@botiverse/porthole 0.2.4 → 0.3.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 (85) hide show
  1. package/README.md +17 -11
  2. package/dist/check/check.d.ts +100 -0
  3. package/dist/check/check.js +247 -0
  4. package/dist/check/drivers.d.ts +43 -0
  5. package/dist/check/drivers.js +181 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/lint.d.ts +21 -0
  11. package/dist/check/lint.js +131 -0
  12. package/dist/check/page-source.d.ts +2 -0
  13. package/dist/check/page-source.js +2 -0
  14. package/dist/check/page.d.ts +13 -0
  15. package/dist/check/page.js +170 -0
  16. package/dist/check/tools.d.ts +61 -0
  17. package/dist/check/tools.js +140 -0
  18. package/dist/conformance/host-kit.d.ts +26 -5
  19. package/dist/conformance/host-kit.js +46 -22
  20. package/dist/conformance/index.d.ts +1 -1
  21. package/dist/conformance/reporter.d.ts +14 -0
  22. package/dist/conformance/reporter.js +28 -0
  23. package/dist/displays/displays.d.ts +61 -0
  24. package/dist/displays/displays.js +113 -0
  25. package/dist/host/client.d.ts +110 -0
  26. package/dist/host/client.js +274 -0
  27. package/dist/index.d.ts +4 -0
  28. package/dist/index.js +6 -0
  29. package/dist/node/index.d.ts +26 -1
  30. package/dist/node/index.js +91 -1
  31. package/dist/react/frame.d.ts +79 -3
  32. package/dist/react/frame.js +183 -42
  33. package/dist/react/index.d.ts +2 -1
  34. package/dist/react/index.js +1 -0
  35. package/dist/react/view.d.ts +54 -0
  36. package/dist/react/view.js +151 -0
  37. package/dist/server/bootstrap.d.ts +27 -0
  38. package/dist/server/bootstrap.js +63 -0
  39. package/dist/server/host.d.ts +77 -8
  40. package/dist/server/host.js +268 -11
  41. package/dist/server/index.d.ts +4 -2
  42. package/dist/server/index.js +3 -1
  43. package/dist/server/pages.d.ts +19 -0
  44. package/dist/server/pages.js +8 -0
  45. package/dist/server/proxy.d.ts +24 -0
  46. package/dist/server/proxy.js +67 -0
  47. package/dist/server/server.js +14 -1
  48. package/dist/server/types.d.ts +8 -0
  49. package/docs/ADOPTING.md +278 -108
  50. package/docs/DECISIONS.md +280 -0
  51. package/docs/DESIGN.md +84 -2
  52. package/examples/app.mjs +82 -78
  53. package/examples/conformance/page.spec.mjs +23 -0
  54. package/examples/conformance/playwright.config.mjs +3 -2
  55. package/examples/conformance/porthole.spec.mjs +6 -3
  56. package/examples/displays.mjs +21 -0
  57. package/examples/mcp/server.mjs +121 -0
  58. package/examples/node/server.mjs +16 -34
  59. package/examples/workers/worker.mjs +19 -7
  60. package/package.json +13 -1
  61. package/src/check/check.ts +386 -0
  62. package/src/check/drivers.ts +242 -0
  63. package/src/check/index.ts +22 -0
  64. package/src/check/instrument.ts +138 -0
  65. package/src/check/lint.ts +238 -0
  66. package/src/check/page-source.ts +19 -0
  67. package/src/check/page.ts +230 -0
  68. package/src/check/tools.ts +206 -0
  69. package/src/conformance/host-kit.ts +82 -27
  70. package/src/conformance/index.ts +1 -0
  71. package/src/conformance/reporter.ts +38 -0
  72. package/src/displays/displays.ts +191 -0
  73. package/src/host/client.ts +395 -0
  74. package/src/index.ts +25 -0
  75. package/src/node/index.ts +112 -2
  76. package/src/react/frame.tsx +271 -57
  77. package/src/react/index.ts +9 -0
  78. package/src/react/view.tsx +237 -0
  79. package/src/server/bootstrap.ts +97 -0
  80. package/src/server/host.ts +372 -18
  81. package/src/server/index.ts +11 -1
  82. package/src/server/pages.ts +28 -0
  83. package/src/server/proxy.ts +86 -0
  84. package/src/server/server.ts +26 -2
  85. package/src/server/types.ts +5 -0
@@ -0,0 +1,2 @@
1
+ const source = "\"use strict\";(()=>{var Me=[\"sendPrompt\",\"openLink\",\"downloadFile\",\"callTool\",\"readData\",\"setModelContext\",\"reportError\",\"resize\",\"copyText\",\"annotate\"],te=e=>({rateLimit:{perMinute:e}});var le={sendPrompt:{defaultGates:[\"user-activation\",\"confirm\"],served:\"handler\",global:\"sendPrompt\",request:{method:\"ui/message\",sdk:\"app.sendMessage\"}},openLink:{defaultGates:[\"user-activation\",\"confirm\"],served:\"handler\",global:\"openLink\",request:{method:\"ui/open-link\",sdk:\"app.openLink\"}},downloadFile:{defaultGates:[\"user-activation\",\"confirm\"],served:\"handler\",request:{method:\"ui/download-file\",sdk:\"app.downloadFile\"}},callTool:{defaultGates:[\"confirm\"],served:\"handler\",request:{method:\"tools/call\",sdk:\"app.callServerTool\"}},readData:{defaultGates:[te(120)],served:\"handler\",request:{method:\"resources/read\",sdk:\"app.readServerResource\"}},setModelContext:{defaultGates:[te(30)],served:\"handler\",request:{method:\"ui/update-model-context\",sdk:\"app.updateModelContext\"}},reportError:{defaultGates:[te(10)],served:\"event\"},resize:{defaultGates:[],served:\"event\"},copyText:{defaultGates:[\"user-activation\",te(30)],served:\"handler\",global:\"copyText\",request:{method:\"porthole/copy-text\"}},annotate:{defaultGates:[te(120)],served:\"event\"}};function H(e){return le[e]}function ce(e){return typeof e==\"string\"&&Me.includes(e)}var N={start:\"porthole/annotate.start\",stop:\"porthole/annotate.stop\",show:\"porthole/annotate.show\",focus:\"porthole/annotate.focus\",clear:\"porthole/annotate.clear\",selected:\"porthole/annotate.selected\",unselected:\"porthole/annotate.unselected\",cancelled:\"porthole/annotate.cancelled\",anchored:\"porthole/annotate.anchored\"},L={label:120,cssSelector:1e3,exact:4e3,context:64,marks:500,id:128,position:5e7,coordinate:1e7};var ne=e=>e!==null&&typeof e==\"object\"&&!Array.isArray(e),G=(e,t,n=0)=>typeof e==\"string\"&&e.length>=n&&e.length<=t,We=(e,t)=>typeof e==\"number\"&&Number.isInteger(e)&&e>=0&&e<=t;function Bt(e){if(!ne(e))return null;switch(e.type){case\"CssSelector\":return G(e.value,L.cssSelector,1)?{type:\"CssSelector\",value:e.value}:null;case\"TextQuoteSelector\":{let{exact:t,prefix:n,suffix:o}=e;return!G(t,L.exact,1)||n!==void 0&&!G(n,L.context)||o!==void 0&&!G(o,L.context)?null:{type:\"TextQuoteSelector\",exact:t,...n===void 0||n===\"\"?{}:{prefix:n},...o===void 0||o===\"\"?{}:{suffix:o}}}case\"TextPositionSelector\":return We(e.start,L.position)&&We(e.end,L.position)&&e.start<=e.end?{type:\"TextPositionSelector\",start:e.start,end:e.end}:null;default:return null}}function qe(e){if(!ne(e)||e.kind!==\"element\"&&e.kind!==\"text\"||!Array.isArray(e.selectors)||e.selectors.length===0||e.selectors.length>3||!G(e.label,L.label))return null;let t=[];for(let r of e.selectors){let a=Bt(r);if(a===null||t.some(s=>s.type===a.type))return null;t.push(a)}let n=t.some(r=>r.type===\"TextQuoteSelector\"),o=t.some(r=>r.type===\"CssSelector\");return(e.kind===\"text\"||!o)&&!n?null:{kind:e.kind,selectors:t,label:e.label}}var de=e=>typeof e==\"number\"&&Number.isFinite(e)&&Math.abs(e)<=L.coordinate;function Ue(e){if(!ne(e))return null;let{x:t,y:n,width:o,height:r}=e;return!de(t)||!de(n)||!de(o)||!de(r)||o<0||r<0?null:{x:t,y:n,width:o,height:r}}var Be=e=>G(e,L.id,1);function Vt(e){if(!Array.isArray(e)||e.length>L.marks)return null;let t=[];for(let n of e){if(!ne(n)||!Be(n.id))return null;if(n.state===\"orphaned\"){t.push({id:n.id,state:\"orphaned\"});continue}if(n.state!==\"attached\")return null;let o=n.rect===void 0?void 0:Ue(n.rect);if(o===null)return null;t.push({id:n.id,state:\"attached\",...o===void 0?{}:{rect:o}})}return t}function ue(e){if(!ne(e))return null;switch(e.type){case\"selected\":{let t=qe(e.anchor),n=Ue(e.rect);return t===null||n===null?null:{type:\"selected\",anchor:t,rect:n}}case\"unselected\":return{type:\"unselected\"};case\"cancelled\":return{type:\"cancelled\"};case\"anchored\":{let t=Vt(e.results);return t===null?null:{type:\"anchored\",results:t}}default:return null}}function Ve(e){let t=e?.elements??!0,n=e?.text??!0;if(typeof t!=\"boolean\"||typeof n!=\"boolean\"||!t&&!n)throw new TypeError(\"annotations.start: elements, text, or both\");return{elements:t,text:n}}function Ge(e){if(!Array.isArray(e)||e.length>L.marks)throw new TypeError(`annotations.show: at most ${L.marks} marks`);let t=new Set;return e.map((n,o)=>{let r=qe(n?.anchor);if(!Be(n?.id)||t.has(n.id)||r===null)throw new TypeError(`annotations.show: mark ${o} needs a unique id (1 to ${L.id} characters) and a valid anchor`);return t.add(n.id),{id:n.id,anchor:r}})}function pe(e,t){return(e.egress.anyHttps??[]).some(n=>n===t)}function I(e){return Object.keys(le).filter(t=>e.capabilities[t]!==void 0)}function J(e,t){return e.capabilities[t]?.gates??le[t].defaultGates}var Je=e=>[...new Set(e)];function F(e,t){let n=I(e).flatMap(o=>{let r=e.capabilities[o];return(t===\"connect\"?r?.connect:r?.resource)??[]});return Je([...e.egress[t]??[],...n])}var Gt=e=>e.length===0?[\"'none'\"]:[...e];function Ke(e){if(e.mode===\"url\")return[];let t=o=>F(e,o),n=o=>pe(e,o)?[\"https:\"]:[];return[[\"default-src\",\"'none'\"],[\"script-src\",\"'unsafe-inline'\",\"'unsafe-eval'\",\"blob:\",...t(\"script\")],[\"style-src\",\"'unsafe-inline'\",...t(\"style\")],[\"font-src\",\"data:\",...n(\"font\"),...t(\"font\")],[\"img-src\",\"data:\",\"blob:\",...n(\"img\"),...t(\"img\")],[\"media-src\",\"data:\",\"blob:\",...n(\"media\"),...t(\"media\")],[\"connect-src\",...Gt(t(\"connect\"))],[\"worker-src\",\"blob:\"],[\"child-src\",\"blob:\"],[\"frame-src\",\"'none'\"],[\"object-src\",\"'none'\"],[\"base-uri\",\"'none'\"],[\"form-action\",\"'none'\"],[\"webrtc\",\"'block'\"]]}function Xe(e){return e.map(t=>t.join(\" \")).join(\"; \")}function me(e){switch(e.isolation){case\"opaque\":return[\"allow-scripts\"];case\"domain\":return[\"allow-scripts\",\"allow-same-origin\"];case\"external\":return[\"allow-scripts\",\"allow-same-origin\",\"allow-forms\",...e.sandbox??[]]}}function Ye(e){return e.mode===\"url\"?(e.permissions??[]).join(\"; \"):\"clipboard-read 'none'; clipboard-write 'none'\"}function Qe(e){return Je([...e.contentOrigins,...e.embedder.frameSrc??[]])}var D=e=>e!==null&&typeof e==\"object\"&&!Array.isArray(e),Ze=4096;function Jt(e){if(typeof e!=\"string\"||e.length===0||e.length>Ze)return null;let t;try{t=new URL(e.trim())}catch{return null}return t.protocol!==\"https:\"&&t.protocol!==\"http:\"||t.username!==\"\"||t.password!==\"\"?null:t.href}var Kt={sendPrompt:(e,t)=>{let n=D(e)?e.text:void 0;return typeof n==\"string\"&&n.trim()!==\"\"&&n.length<=t.limits.maxPromptChars?{text:n}:null},openLink:e=>{let t=Jt(D(e)?e.url:void 0);return t===null?null:{url:t}},downloadFile:e=>{let t=D(e)?e.contents:void 0;return Array.isArray(t)&&t.length>0&&t.length<=100?{contents:t}:null},callTool:e=>{if(!D(e)||typeof e.name!=\"string\"||e.name===\"\"||e.name.length>256)return null;let t=e.arguments??{};return D(t)?{name:e.name,arguments:t}:null},readData:e=>{let t=D(e)?e.uri:void 0;return typeof t==\"string\"&&t!==\"\"&&t.length<=Ze?{uri:t}:null},setModelContext:e=>{if(!D(e))return null;let{content:t,structuredContent:n}=e;return t!==void 0&&!Array.isArray(t)||n!==void 0&&!D(n)?null:{...t===void 0?{}:{content:t},...n===void 0?{}:{structuredContent:n}}},reportError:e=>{let t=D(e)?e.message:void 0;return typeof t==\"string\"&&t!==\"\"?{message:t.slice(0,2e3)}:null},copyText:e=>{let t=D(e)?e.text:void 0;return typeof t==\"string\"&&t!==\"\"&&t.length<=2e4?{text:t}:null},annotate:e=>ue(e),resize:e=>{if(!D(e)||typeof e.height!=\"number\"||!Number.isFinite(e.height)||e.height<0)return null;let t=e.width;return typeof t==\"number\"&&Number.isFinite(t)&&t>=0?{height:e.height,width:t}:{height:e.height}}};function et(e){let{config:t,display:n,handlers:o,onEvent:r}=e,a=e.now??(()=>Date.now()),s=new Map,i=0,d=!1,m=(p,v,u)=>(r({type:\"refused\",capability:p,refusal:v}),{ok:!1,refusal:v,...u===void 0?{}:{message:u}}),f=(p,v)=>{let u=a(),g=(s.get(p)??[]).filter(l=>u-l<6e4);return g.length>=v?(s.set(p,g),!1):(g.push(u),s.set(p,g),!0)};return{declared:p=>t.capabilities[p]!==void 0,async call(p,v,u){if(t.capabilities[p]===void 0)return m(p,\"not-declared\");let g=Kt[p](v,t);if(g===null)return m(p,\"invalid\");let l=J(t,p),c=l.includes(\"confirm\");if(c&&d)return m(p,\"muted\");for(let A of l)if(typeof A==\"object\"&&!f(p,A.rateLimit.perMinute))return m(p,\"rate-limited\");if(l.includes(\"user-activation\")&&(u?.userActivated??e.userActivation?.())===!1)return m(p,\"no-user-activation\");let y=null,C=()=>y??=k(p,g);if(c){if(e.confirm===void 0)return m(p,\"no-confirm\");let A=!1;try{A=await e.confirm({capability:p,args:g,display:n},()=>{C()})}catch{A=y===null?!1:\"accepted\"}if(y===null&&A!==!0&&A!==\"accepted\")return A===\"redirected\"?m(p,\"redirected\"):(i+=1,i>=t.limits.declinesBeforeMute&&!d&&(d=!0,r({type:\"muted\"})),m(p,\"declined\"));i=0}return C()}};async function k(p,v){{if(H(p).served===\"event\")return r(p===\"resize\"?{type:\"resize\",...v}:p===\"annotate\"?{type:\"annotation\",report:v}:{type:\"error\",message:v.message}),{ok:!0,value:void 0};let u=o[p];if(u===void 0)return m(p,\"not-declared\");try{return{ok:!0,value:await u(v,{displayId:n.id,title:n.title,capability:p})}}catch(g){return m(p,\"failed\",g instanceof Error?g.message:String(g))}}}}var $e=[\"img\",\"media\",\"font\"],Le=[\"allow-popups\",\"allow-popups-to-escape-sandbox\",\"allow-modals\",\"allow-downloads\"],Ne=[\"clipboard-write\",\"fullscreen\"];var Oe=class extends Error{path;constructor(t,n){super(`${t}: ${n}`),this.name=\"ConfigError\",this.path=t}},Ie=[\"widget\",\"chart\",\"interactive\"],Xt=/^(localhost|127\\.0\\.0\\.1|\\[::1\\])$|\\.localhost$/u,Yt=new Set([...[\"co\",\"org\",\"ac\",\"gov\",\"me\",\"net\",\"ltd\",\"plc\",\"sch\",\"nhs\",\"police\"].map(e=>`${e}.uk`),...[\"com\",\"net\",\"org\",\"edu\",\"gov\",\"asn\",\"id\"].map(e=>`${e}.au`),...[\"co\",\"org\",\"net\",\"ac\",\"govt\",\"geek\",\"school\"].map(e=>`${e}.nz`),...[\"co\",\"ne\",\"or\",\"ac\",\"go\",\"ad\",\"ed\",\"gr\",\"lg\"].map(e=>`${e}.jp`),...[\"co\",\"or\",\"ne\",\"ac\",\"go\",\"re\"].map(e=>`${e}.kr`),...[\"com\",\"net\",\"org\",\"gov\",\"edu\"].flatMap(e=>[\"br\",\"cn\",\"hk\",\"tw\",\"sg\",\"my\",\"mx\",\"ar\",\"tr\",\"ua\",\"pl\",\"ph\",\"pk\",\"ng\",\"eg\",\"sa\",\"vn\",\"co\"].map(t=>`${e}.${t}`)),...[\"co\",\"net\",\"org\",\"gen\",\"firm\",\"ind\",\"ac\",\"edu\",\"gov\",\"res\"].map(e=>`${e}.in`),...[\"co\",\"org\",\"ac\",\"gov\",\"net\",\"web\"].map(e=>`${e}.za`),...[\"co\",\"org\",\"ac\",\"gov\",\"net\",\"muni\"].map(e=>`${e}.il`),\"co.id\",\"or.id\",\"ac.id\",\"co.th\",\"or.th\",\"ac.th\",\"co.ke\",\"co.tz\",\"co.ug\",\"com.de\",\"co.at\",\"or.at\",\"ac.at\",\"co.it\",\"com.es\",\"nom.es\",\"com.fr\",\"asso.fr\",\"eu.org\",\"us.com\",\"uk.com\",\"eu.com\",\"uk.net\",\"gb.net\",\"jpn.com\",\"kr.com\",\"github.io\",\"githubusercontent.com\",\"gitlab.io\",\"bitbucket.io\",\"pages.dev\",\"workers.dev\",\"r2.dev\",\"vercel.app\",\"now.sh\",\"netlify.app\",\"netlify.com\",\"herokuapp.com\",\"herokussl.com\",\"appspot.com\",\"web.app\",\"firebaseapp.com\",\"cloudfunctions.net\",\"run.app\",\"googleusercontent.com\",\"blogspot.com\",\"azurewebsites.net\",\"azurestaticapps.net\",\"azureedge.net\",\"blob.core.windows.net\",\"cloudapp.net\",\"trafficmanager.net\",\"cloudfront.net\",\"amazonaws.com\",\"s3.amazonaws.com\",\"elasticbeanstalk.com\",\"awsapprunner.com\",\"amplifyapp.com\",\"fly.dev\",\"onrender.com\",\"railway.app\",\"up.railway.app\",\"glitch.me\",\"repl.co\",\"replit.app\",\"replit.dev\",\"surge.sh\",\"deno.dev\",\"ngrok.io\",\"ngrok-free.app\",\"ngrok.app\",\"loca.lt\",\"trycloudflare.com\",\"codesandbox.io\",\"csb.app\",\"stackblitz.io\",\"webcontainer.io\",\"neocities.org\",\"wordpress.com\",\"tumblr.com\",\"wixsite.com\",\"squarespace.com\",\"myshopify.com\",\"carrd.co\",\"notion.site\",\"framer.app\",\"webflow.io\",\"readthedocs.io\",\"gitbook.io\",\"sourceforge.net\",\"digitaloceanspaces.com\",\"ondigitalocean.app\",\"b-cdn.net\",\"jsdelivr.net\"]);function Qt(e){return e===\"localhost\"?null:!e.includes(\".\")||Yt.has(e)?`is a wildcard over a public suffix (*.${e}): anyone can serve a site under it; name a domain of your own (https://*.cdn.example.com)`:null}var Zt=/^(\\*\\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/u;function en(e){let t=\"is not an origin (scheme://host[:port], lowercase, no path)\";if(typeof e!=\"string\"||e.length>269)return`${JSON.stringify(e)} ${t}`;let n=/^(https|http|wss|ws):\\/\\/([^/:]+|\\[::1\\])(:(\\d{1,5}))?$/u.exec(e);if(n===null)return`${JSON.stringify(e)} ${t}`;let[,o,r=\"\",,a]=n;if(a!==void 0&&(Number(a)<1||Number(a)>65535))return`${JSON.stringify(e)} has no valid port`;if(r!==\"[::1]\"&&!Zt.test(r))return`${JSON.stringify(e)} ${t}`;if(r.startsWith(\"*.\")){let s=Qt(r.slice(2));if(s!==null)return`${JSON.stringify(e)} ${s}`}return(o===\"http\"||o===\"ws\")&&!Xt.test(r.replace(/^\\*\\./u,\"x.\"))?`${JSON.stringify(e)} uses ${o} off loopback: ${o} is allowed only for localhost, *.localhost, 127.0.0.1 and [::1] (loopback development); use ${o===\"http\"?\"https\":\"wss\"}`:null}var x=(e,t)=>{throw new Oe(e,t)},re=e=>e!==null&&typeof e==\"object\"&&!Array.isArray(e);function O(e,t){return re(e)?e:x(t,\"must be an object\")}function _(e,t,n){for(let o of Object.keys(e))t.includes(o)||x(`${n}.${o}`,\"is not a known field\")}function oe(e,t){if(e!==void 0){if(!Array.isArray(e)){x(t,\"must be an array of origins\");return}e.forEach((n,o)=>{let r=en(n);r!==null&&x(`${t}[${o}]`,r)})}}function he(e,t,n=Number.MAX_SAFE_INTEGER){(typeof e!=\"number\"||!Number.isInteger(e)||e<1||e>n)&&x(t,`must be an integer from 1 to ${n}`)}function tn(e,t){if(e===\"user-activation\"||e===\"confirm\")return;let n=re(e)&&re(e.rateLimit)?e.rateLimit:null;if(n===null||Object.keys(e).length!==1){x(t,'must be \"user-activation\", \"confirm\" or { rateLimit: { perMinute } }');return}_(n,[\"perMinute\"],`${t}.rateLimit`),he(n.perMinute,`${t}.rateLimit.perMinute`,1e4)}var tt=[\"inline\",\"artifact\",\"mcp-app\",\"url\"],nt=[\"opaque\",\"domain\",\"external\"];function ot(e){let t=O(e,\"config\");_(t,[\"mode\",\"isolation\",\"capabilities\",\"egress\",\"theme\",\"limits\",\"layout\",\"guide\",\"contentOrigins\",\"embedder\",\"sandbox\",\"permissions\",\"storage\",\"errors\"],\"config\"),tt.includes(t.mode)||x(\"config.mode\",`must be one of ${tt.join(\", \")}`),nt.includes(t.isolation)||x(\"config.isolation\",`must be one of ${nt.join(\", \")}`),t.mode===\"url\"!=(t.isolation===\"external\")&&x(\"config.isolation\",'url mode, and only url mode, is \"external\"');let n=O(t.capabilities,\"config.capabilities\");for(let[u,g]of Object.entries(n)){let l=`config.capabilities.${u}`;ce(u)||x(l,`is not a capability (${Me.join(\", \")})`);let c=O(g,l);_(c,[\"gates\",\"connect\",\"resource\",\"guide\"],l),c.gates!==void 0&&(Array.isArray(c.gates)||x(`${l}.gates`,\"must be an array\"),c.gates.forEach((y,C)=>tn(y,`${l}.gates[${C}]`))),oe(c.connect,`${l}.connect`),oe(c.resource,`${l}.resource`),c.guide!==void 0&&typeof c.guide!=\"string\"&&x(`${l}.guide`,\"must be a string\")}t.mode===\"url\"&&Object.keys(n).length>0&&x(\"config.capabilities\",\"url mode has no shell, so it can declare no capabilities\");let o=O(t.egress,\"config.egress\"),r=[\"connect\",\"script\",\"style\",\"img\",\"font\",\"media\"];_(o,[...r,\"anyHttps\"],\"config.egress\");for(let u of r)oe(o[u],`config.egress.${u}`);o.anyHttps!==void 0&&(Array.isArray(o.anyHttps)||x(\"config.egress.anyHttps\",`must be a list of ${$e.join(\", \")}`),o.anyHttps.forEach((u,g)=>{$e.includes(u)||x(`config.egress.anyHttps[${g}]`,`${JSON.stringify(u)}: only images, media and fonts may load from any https site (P059), never scripts, styles or data`)}),t.mode===\"url\"&&x(\"config.egress.anyHttps\",\"url mode has no egress control\"));let a=O(t.theme,\"config.theme\");_(a,[\"variables\",\"event\",\"documents\"],\"config.theme\"),a.documents!==void 0&&a.documents!==\"declared\"&&a.documents!==\"always\"&&a.documents!==\"never\"&&x(\"config.theme.documents\",'must be \"declared\", \"always\" or \"never\"'),a.documents===\"never\"&&t.mode!==\"artifact\"&&x(\"config.theme.documents\",'\"never\" is for whole pages: a fragment takes the theme it is drawn in');let s=O(a.variables,\"config.theme.variables\");for(let[u,g]of Object.entries(s)){let l=`config.theme.variables[${JSON.stringify(u)}]`;/^--[a-z0-9]+(-[a-z0-9]+)*$/u.test(u)||x(l,\"must be a CSS custom property name (--lowercase-words)\");let c=re(g)?[g.light,g.dark]:[g];re(g)&&_(g,[\"light\",\"dark\"],l);for(let y of c)(typeof y!=\"string\"||y.length===0||y.length>500||/[;{}<>]/u.test(y))&&x(l,\"must be a CSS value (1\\u2013500 characters, no ; { } < >), or { light, dark } of them\")}(typeof a.event!=\"string\"||!/^[a-z][a-z0-9]*([:.-][a-z0-9]+)*$/u.test(a.event))&&x(\"config.theme.event\",'must be an event name such as \"porthole:theme\"');let i=O(t.limits,\"config.limits\"),d=[\"maxHeightPx\",\"minHeightPx\",\"maxBytes\",\"maxLiveFrames\",\"declinesBeforeMute\",\"maxPromptChars\",\"maxErrorReports\"];_(i,[...d,\"loadTimeoutMs\"],\"config.limits\");for(let u of d)he(i[u],`config.limits.${u}`);i.loadTimeoutMs!==void 0&&he(i.loadTimeoutMs,\"config.limits.loadTimeoutMs\",6e5),i.minHeightPx>i.maxHeightPx&&x(\"config.limits.minHeightPx\",\"must not exceed maxHeightPx\");let m=O(t.layout,\"config.layout\");_(m,[\"minWidthPx\",\"narrowWidthPx\",\"wideWidthPx\",\"kind\"],\"config.layout\"),m.kind!==void 0&&m.kind!==\"flow\"&&m.kind!==\"fill\"&&x(\"config.layout.kind\",'must be \"flow\" or \"fill\"');for(let u of[\"minWidthPx\",\"narrowWidthPx\",\"wideWidthPx\"])he(m[u],`config.layout.${u}`,1e4);(m.minWidthPx>m.narrowWidthPx||m.narrowWidthPx>m.wideWidthPx)&&x(\"config.layout\",\"must hold minWidthPx \\u2264 narrowWidthPx \\u2264 wideWidthPx\");let f=O(t.guide,\"config.guide\");_(f,[\"toolName\",\"guideToolName\",\"topics\"],\"config.guide\");for(let u of[\"toolName\",\"guideToolName\"]){let g=f[u];g!==void 0&&(typeof g!=\"string\"||!/^[A-Za-z0-9_.-]{1,64}$/u.test(g))&&x(`config.guide.${u}`,\"must be a tool name (letters, digits, _ . -)\")}if(f.topics!==void 0)for(let[u,g]of Object.entries(O(f.topics,\"config.guide.topics\"))){let l=`config.guide.topics.${u}`;(!/^[a-z][a-z0-9-]{0,31}$/u.test(u)||Ie.includes(u))&&x(l,\"must be a new topic name (lowercase), not a built-in one\"),(typeof g!=\"string\"||g.trim()===\"\")&&x(l,\"must be the topic's text\")}oe(t.contentOrigins,\"config.contentOrigins\");let k=t.isolation===\"domain\"||t.isolation===\"external\",p=t.contentOrigins;k!==p.length>0&&x(\"config.contentOrigins\",k?`${String(t.isolation)} isolation needs the origins its content is served from`:\"opaque isolation serves nothing: leave it empty\");let v=O(t.embedder,\"config.embedder\");if(_(v,[\"frameSrc\"],\"config.embedder\"),oe(Array.isArray(v.frameSrc)?v.frameSrc.filter(u=>u!==\"'self'\"):v.frameSrc,\"config.embedder.frameSrc\"),t.sandbox!==void 0&&(t.mode!==\"url\"&&x(\"config.sandbox\",\"only url mode may add sandbox tokens\"),Array.isArray(t.sandbox)||x(\"config.sandbox\",\"must be an array of sandbox tokens\"),t.sandbox.forEach((u,g)=>{Le.includes(u)||x(`config.sandbox[${g}]`,/top-navigation|same-origin/u.test(String(u))?`${JSON.stringify(u)} is never granted (P037)`:`must be one of ${Le.join(\", \")}`)})),t.storage!==void 0){let u=O(t.storage,\"config.storage\");_(u,[\"shared\",\"scope\"],\"config.storage\"),u.shared!==void 0&&u.scope!==void 0&&x(\"config.storage\",\"shared (several displays at once) or scope (one at a time), not both\"),u.scope!==void 0&&(typeof u.scope!=\"string\"||!/^[a-z][a-z ,'-]{0,59}$/u.test(u.scope))&&x(\"config.storage.scope\",'must be short lowercase words (\"this artifact, across its versions\")'),t.isolation!==\"domain\"&&x(\"config.storage\",\"only domain isolation keeps storage across displays\"),u.shared!==void 0&&(typeof u.shared!=\"string\"||!/^[a-z][a-z -]{0,39}$/u.test(u.shared))&&x(\"config.storage.shared\",'must be a short lowercase noun (\"conversation\")')}return t.errors!==void 0&&(t.errors!==\"agent\"&&t.errors!==\"host\"&&t.errors!==\"none\"&&x(\"config.errors\",'must be \"agent\", \"host\" or \"none\"'),t.errors===\"none\"!=(n.reportError===void 0)&&x(\"config.errors\",t.errors===\"none\"?'\"none\" means no reportError: drop the capability':`${JSON.stringify(t.errors)} needs the reportError capability, which carries them`)),t.permissions!==void 0&&(t.mode!==\"url\"&&x(\"config.permissions\",\"only url mode may be delegated features\"),Array.isArray(t.permissions)||x(\"config.permissions\",\"must be an array of features\"),t.permissions.forEach((u,g)=>{Ne.includes(u)||x(`config.permissions[${g}]`,`must be one of ${Ne.join(\", \")}`)})),e}var fe=\"2026-01-26\",P={initialize:\"ui/initialize\",message:\"ui/message\",openLink:\"ui/open-link\",downloadFile:\"ui/download-file\",requestDisplayMode:\"ui/request-display-mode\",updateModelContext:\"ui/update-model-context\",callTool:\"tools/call\",readResource:\"resources/read\",initialized:\"ui/notifications/initialized\",sizeChanged:\"ui/notifications/size-changed\",requestTeardown:\"ui/notifications/request-teardown\",log:\"notifications/message\",toolInput:\"ui/notifications/tool-input\",toolInputPartial:\"ui/notifications/tool-input-partial\",toolResult:\"ui/notifications/tool-result\",toolCancelled:\"ui/notifications/tool-cancelled\",hostContextChanged:\"ui/notifications/host-context-changed\",resourceTeardown:\"ui/resource-teardown\",sandboxProxyReady:\"ui/notifications/sandbox-proxy-ready\",sandboxResourceReady:\"ui/notifications/sandbox-resource-ready\"},rt=[...[\"background\",\"text\",\"border\",\"ring\"].flatMap(e=>(e===\"background\"?[\"primary\",\"secondary\",\"tertiary\",\"inverse\",\"ghost\",\"info\",\"danger\",\"success\",\"warning\",\"disabled\"]:e===\"text\"?[\"primary\",\"secondary\",\"tertiary\",\"inverse\",\"ghost\",\"info\",\"danger\",\"success\",\"warning\",\"disabled\"]:e===\"border\"?[\"primary\",\"secondary\",\"tertiary\",\"inverse\",\"ghost\",\"info\",\"danger\",\"success\",\"warning\",\"disabled\"]:[\"primary\",\"secondary\",\"inverse\",\"info\",\"danger\",\"success\",\"warning\"]).map(t=>`--color-${e}-${t}`)),\"--font-sans\",\"--font-mono\",...[\"normal\",\"medium\",\"semibold\",\"bold\"].map(e=>`--font-weight-${e}`),...[\"xs\",\"sm\",\"md\",\"lg\"].map(e=>`--font-text-${e}-size`),...[\"xs\",\"sm\",\"md\",\"lg\",\"xl\",\"2xl\",\"3xl\"].map(e=>`--font-heading-${e}-size`),...[\"xs\",\"sm\",\"md\",\"lg\"].map(e=>`--font-text-${e}-line-height`),...[\"xs\",\"sm\",\"md\",\"lg\",\"xl\",\"2xl\",\"3xl\"].map(e=>`--font-heading-${e}-line-height`),...[\"xs\",\"sm\",\"md\",\"lg\",\"xl\",\"full\"].map(e=>`--border-radius-${e}`),\"--border-width-regular\",...[\"hairline\",\"sm\",\"md\",\"lg\"].map(e=>`--shadow-${e}`)],at=\"porthole/styles\",st=\"porthole/copy-text\";function X(e){if(e.mode===\"url\")return null;let t=e.mode===\"mcp-app\"?\"none\":\"shell\",n=I(e),o={};for(let a of n)o[a]={userActivation:J(e,a).includes(\"user-activation\")};let r=t===\"shell\"?n.flatMap(a=>{let s=H(a);return s.global===void 0?[]:[s.global]}):[];return{protocol:t,content:e.mode===\"artifact\"?\"document\":\"fragment\",capabilities:o,globals:r,themeVariables:Object.keys(e.theme.variables),themeEvent:e.theme.event,themeDocuments:e.theme.documents??\"declared\",storage:e.isolation===\"opaque\"?\"memory\":\"native\",maxErrorReports:e.limits.maxErrorReports,maxPromptChars:e.limits.maxPromptChars,maxCopyChars:2e4,protocolVersion:fe}}var S=e=>e,w=(e,t)=>({light:e,dark:t}),ge={categorical:[{hue:\"blue\",light:\"#2a78d6\",dark:\"#3987e5\"},{hue:\"orange\",light:\"#eb6834\",dark:\"#d95926\"},{hue:\"aqua\",light:\"#1baf7a\",dark:\"#199e70\"},{hue:\"yellow\",light:\"#eda100\",dark:\"#c98500\"},{hue:\"magenta\",light:\"#e87ba4\",dark:\"#d55181\"},{hue:\"green\",light:\"#008300\",dark:\"#008300\"},{hue:\"violet\",light:\"#4a3aa7\",dark:\"#9085e9\"},{hue:\"red\",light:\"#e34948\",dark:\"#e66767\"}],sequential:{light:[\"#cde2fb\",\"#9ec5f4\",\"#6da7ec\",\"#3987e5\",\"#256abf\",\"#184f95\",\"#0d366b\"],dark:[\"#0d366b\",\"#184f95\",\"#256abf\",\"#3987e5\",\"#6da7ec\",\"#9ec5f4\",\"#cde2fb\"]},diverging:{neg:{light:\"#e34948\",dark:\"#e66767\"},mid:{light:\"#f0efec\",dark:\"#383835\"},pos:{light:\"#2a78d6\",dark:\"#3987e5\"}}},ye=(e,t)=>Object.entries(t).map(([n,o])=>[`--color-${e}-${n}`,o]),B=(e,t,n)=>[[`--font-heading-${e}-size`,S(`${t}px`)],[`--font-heading-${e}-line-height`,S(`${n}px`)]],ao=Object.fromEntries([[\"--color-background-primary\",w(\"#f9f9f7\",\"#191918\")],[\"--color-background-secondary\",w(\"#ffffff\",\"#232321\")],[\"--color-background-tertiary\",w(\"#f3f3f1\",\"#2b2b29\")],[\"--color-background-inverse\",w(\"#1a1a19\",\"#f4f4f2\")],[\"--color-background-ghost\",w(\"rgba(11, 11, 11, 0.04)\",\"rgba(255, 255, 255, 0.05)\")],[\"--color-background-disabled\",w(\"#efefec\",\"#2e2e2c\")],...ye(\"background\",{info:w(\"#e8f1fc\",\"#16283d\"),success:w(\"#e7f5ec\",\"#15301f\"),warning:w(\"#fdf3e1\",\"#3a2a10\"),danger:w(\"#fdecec\",\"#3a1a18\")}),[\"--color-text-primary\",w(\"#0b0b0b\",\"#f4f4f2\")],[\"--color-text-secondary\",w(\"#52514e\",\"#b5b4ae\")],[\"--color-text-tertiary\",w(\"#898781\",\"#8f8e88\")],[\"--color-text-inverse\",w(\"#ffffff\",\"#0b0b0b\")],[\"--color-text-ghost\",w(\"#a3a29c\",\"#6e6d68\")],[\"--color-text-disabled\",w(\"#b5b4ae\",\"#5c5b57\")],...ye(\"text\",{info:w(\"#1f5fae\",\"#8cbcf5\"),success:w(\"#1d7a3e\",\"#86d3a2\"),warning:w(\"#8a5a00\",\"#e8b85c\"),danger:w(\"#b42318\",\"#f19a92\")}),[\"--color-border-primary\",w(\"#c3c2b7\",\"#4a4a46\")],[\"--color-border-secondary\",w(\"#e1e0d9\",\"#393936\")],[\"--color-border-tertiary\",w(\"#ebeae5\",\"#2f2f2d\")],[\"--color-border-inverse\",w(\"#3a3a37\",\"#d6d5cf\")],[\"--color-border-ghost\",w(\"rgba(11, 11, 11, 0.06)\",\"rgba(255, 255, 255, 0.08)\")],[\"--color-border-disabled\",w(\"#e6e5e0\",\"#333331\")],...ye(\"border\",{info:w(\"#a9c8f0\",\"#2e5584\"),success:w(\"#a6d9b8\",\"#2c6141\"),warning:w(\"#f0cf8c\",\"#6e5221\"),danger:w(\"#f1b0ab\",\"#7a2f29\")}),[\"--color-ring-primary\",w(\"#2a78d6\",\"#3987e5\")],[\"--color-ring-secondary\",w(\"#898781\",\"#8f8e88\")],[\"--color-ring-inverse\",w(\"#ffffff\",\"#0b0b0b\")],...ye(\"ring\",{info:w(\"#2a78d6\",\"#3987e5\"),success:w(\"#1d7a3e\",\"#86d3a2\"),warning:w(\"#b07400\",\"#e8b85c\"),danger:w(\"#d92d20\",\"#f19a92\")}),[\"--color-accent\",w(\"#2a78d6\",\"#3987e5\")],[\"--color-accent-soft\",w(\"#e8f1fc\",\"#16283d\")],...ge.categorical.map((e,t)=>[`--color-chart-${t+1}`,w(e.light,e.dark)]),...ge.sequential.light.map((e,t)=>[`--color-chart-seq-${t+1}`,w(e,ge.sequential.dark[t]??e)]),...[\"neg\",\"mid\",\"pos\"].map(e=>[`--color-chart-${e}`,ge.diverging[e]]),[\"--font-sans\",S('system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif')],[\"--font-mono\",S('ui-monospace, \"SF Mono\", Menlo, Consolas, monospace')],[\"--font-weight-normal\",S(\"400\")],[\"--font-weight-medium\",S(\"500\")],[\"--font-weight-semibold\",S(\"600\")],[\"--font-weight-bold\",S(\"700\")],[\"--font-text-xs-size\",S(\"12px\")],[\"--font-text-xs-line-height\",S(\"16px\")],[\"--font-text-sm-size\",S(\"13px\")],[\"--font-text-sm-line-height\",S(\"18px\")],[\"--font-text-md-size\",S(\"14px\")],[\"--font-text-md-line-height\",S(\"20px\")],[\"--font-text-lg-size\",S(\"16px\")],[\"--font-text-lg-line-height\",S(\"24px\")],...B(\"xs\",14,20),...B(\"sm\",16,24),...B(\"md\",20,28),...B(\"lg\",24,32),...B(\"xl\",28,36),...B(\"2xl\",32,40),...B(\"3xl\",40,48),[\"--border-radius-xs\",S(\"4px\")],[\"--border-radius-sm\",S(\"6px\")],[\"--border-radius-md\",S(\"8px\")],[\"--border-radius-lg\",S(\"12px\")],[\"--border-radius-xl\",S(\"16px\")],[\"--border-radius-full\",S(\"9999px\")],[\"--border-width-regular\",S(\"1px\")],[\"--shadow-hairline\",w(\"0 0 0 1px rgba(11, 11, 11, 0.06)\",\"0 0 0 1px rgba(255, 255, 255, 0.08)\")],[\"--shadow-sm\",w(\"0 1px 2px rgba(11, 11, 11, 0.06)\",\"0 1px 2px rgba(0, 0, 0, 0.4)\")],[\"--shadow-md\",w(\"0 2px 8px rgba(11, 11, 11, 0.08)\",\"0 2px 8px rgba(0, 0, 0, 0.45)\")],[\"--shadow-lg\",w(\"0 8px 24px rgba(11, 11, 11, 0.12)\",\"0 8px 24px rgba(0, 0, 0, 0.5)\")]]);function De(e,t){return typeof e==\"string\"?e:e[t]}function it(e,t,n){let o={};for(let[r,a]of Object.entries(e.variables)){let s=n?.[r]?.trim();o[r]=s===void 0||s===\"\"||/[;{}<>]/u.test(s)?De(a,t):s}return o}var W={stats:`<style>\n .stats { display: flex; flex-wrap: wrap; gap: 8px; }\n .stat { flex: 1 1 100px; background: var(--color-background-secondary); border: var(--border-width-regular) solid var(--color-border-tertiary); border-radius: var(--border-radius-lg); padding: 12px 16px; }\n .stat div { font-size: var(--font-text-sm-size); color: var(--color-text-secondary); }\n .stat b { font-size: var(--font-heading-md-size); font-weight: var(--font-weight-semibold); }\n</style>\n<div class=\"stats\">\n <div class=\"stat\"><div>Monthly cost</div><b>$1,240</b></div>\n <div class=\"stat\"><div>Failed builds</div><b>2.4%</b></div>\n</div>`,diagram:`<div style=\"font-weight: var(--font-weight-semibold); margin-bottom: 8px\">Uploads reach storage only through the API</div>\n<svg viewBox=\"0 0 320 260\" width=\"100%\" style=\"max-width: 400px\" font-size=\"13\" role=\"img\" aria-label=\"Uploads reach storage only through the API\">\n <defs><marker id=\"arrow\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"6\" markerHeight=\"6\" orient=\"auto-start-reverse\"><path d=\"M0 0L10 5L0 10z\" fill=\"var(--color-text-tertiary)\"/></marker></defs>\n <g fill=\"none\" stroke=\"var(--color-border-secondary)\" stroke-width=\"1.25\"><rect x=\"16\" y=\"8\" width=\"136\" height=\"52\" rx=\"8\"/><rect x=\"168\" y=\"8\" width=\"136\" height=\"52\" rx=\"8\"/><rect x=\"16\" y=\"200\" width=\"136\" height=\"52\" rx=\"8\"/><rect x=\"168\" y=\"200\" width=\"136\" height=\"52\" rx=\"8\"/></g>\n <rect x=\"16\" y=\"104\" width=\"288\" height=\"52\" rx=\"8\" fill=\"var(--color-chart-1)\" fill-opacity=\"0.12\" stroke=\"var(--color-chart-1)\" stroke-width=\"2\"/>\n <g fill=\"none\" stroke=\"var(--color-text-tertiary)\" stroke-width=\"1.25\" marker-end=\"url(#arrow)\"><path d=\"M84 60V102\"/><path d=\"M236 60V102\"/><path d=\"M84 156V198\"/><path d=\"M236 156V198\"/></g>\n <g text-anchor=\"middle\" font-size=\"14\" font-weight=\"600\" fill=\"var(--color-text-primary)\"><text x=\"84\" y=\"30\">Phone app</text><text x=\"236\" y=\"30\">Web app</text><text x=\"160\" y=\"126\">API server</text><text x=\"84\" y=\"222\">Object storage</text><text x=\"236\" y=\"222\">Database</text></g>\n <g text-anchor=\"middle\" fill=\"var(--color-text-secondary)\"><text x=\"84\" y=\"48\">iOS, Android</text><text x=\"236\" y=\"48\">any browser</text><text x=\"160\" y=\"144\">checks every upload</text><text x=\"84\" y=\"240\">the files</text><text x=\"236\" y=\"240\">who sent what</text></g>\n <g fill=\"var(--color-text-secondary)\"><text x=\"92\" y=\"86\">HTTPS</text><text x=\"244\" y=\"86\">HTTPS</text><text x=\"92\" y=\"182\">writes</text><text x=\"244\" y=\"182\">records</text></g>\n</svg>`,line:'<style>\\n .note { font-size: var(--font-text-sm-size); color: var(--color-text-secondary); }\\n</style>\\n<div style=\"font-weight: var(--font-weight-semibold)\">Failed builds fell from 9 to 2 a week</div>\\n<div class=\"note\">Builds per week, last 8 weeks</div>\\n<div class=\"note\"><b style=\"color: var(--color-chart-1)\">\\u2501</b> Failed &nbsp; <b style=\"color: var(--color-text-disabled)\">\\u2501</b> All builds</div>\\n<div id=\"plot\" style=\"height: 200px\"></div>\\n<div class=\"note\" id=\"readout\"></div>\\n<script>\\n const rows = [[\"W1\", 41, 9], [\"W2\", 44, 8], [\"W3\", 39, 7], [\"W4\", 47, 6], [\"W5\", 52, 4], [\"W6\", 49, 3], [\"W7\", 55, 3], [\"W8\", 58, 2]];\\n const series = [[1, \"builds\", \"var(--color-text-disabled)\"], [2, \"failed\", \"var(--color-chart-1)\"]];\\n const plot = document.getElementById(\"plot\");\\n const show = (i) => (document.getElementById(\"readout\").textContent = `${rows[i][0]}: ${series.map(([at, name]) => `${rows[i][at]} ${name}`).join(\", \")}`);\\n function draw() {\\n const w = plot.clientWidth, h = plot.clientHeight, left = 36, base = h - 24;\\n const x = (i) => left + 12 + (i * (w - left - 36)) / (rows.length - 1);\\n const y = (v) => base - (v / 60) * (base - 8);\\n const step = Math.ceil((rows.length * 44) / w); // x labels at least 44 px apart\\n let svg = `<svg width=\"${w}\" height=\"${h}\" font-size=\"12\" fill=\"var(--color-text-secondary)\">`;\\n for (const v of [0, 30, 60]) svg += `<line x1=\"${left}\" x2=\"${w}\" y1=\"${y(v)}\" y2=\"${y(v)}\" stroke=\"var(--color-border-tertiary)\"/><text x=\"${left - 6}\" y=\"${y(v) + 4}\" text-anchor=\"end\">${v}</text>`;\\n rows.forEach((row, i) => { if (i % step === 0) svg += `<text x=\"${x(i)}\" y=\"${h - 6}\" text-anchor=\"middle\">${row[0]}</text>`; });\\n for (const [at, , color] of series) svg += `<polyline points=\"${rows.map((row, i) => `${x(i)},${y(row[at])}`).join(\" \")}\" fill=\"none\" stroke=\"${color}\" stroke-width=\"2\"/>`;\\n // The two values the title rests on; then a column per week to tap.\\n for (const i of [0, rows.length - 1]) svg += `<text x=\"${x(i)}\" y=\"${y(rows[i][2]) - 10}\" text-anchor=\"middle\" fill=\"var(--color-text-primary)\">${rows[i][2]}</text>`;\\n const band = (w - left) / rows.length;\\n rows.forEach((row, i) => (svg += `<rect data-i=\"${i}\" x=\"${x(i) - band / 2}\" width=\"${band}\" height=\"${base}\" fill=\"transparent\"/>`));\\n plot.innerHTML = svg + \"</svg>\";\\n }\\n plot.addEventListener(\"click\", (event) => event.target.dataset.i && show(Number(event.target.dataset.i)));\\n show(rows.length - 1);\\n new ResizeObserver(draw).observe(plot);\\n<\\/script>',bars:`<div style=\"display: grid; grid-template-columns: 5em 1fr 3em; gap: 8px; align-items: center; font-size: var(--font-text-sm-size)\">\n <span>Web</span><div style=\"height: 12px; width: 100%; background: var(--color-chart-1)\"></div><span>412</span>\n <span>iOS</span><div style=\"height: 12px; width: 77%; background: var(--color-text-disabled)\"></div><span>318</span>\n <span>Docs</span><div style=\"height: 12px; width: 16%; background: var(--color-text-disabled)\"></div><span>64</span>\n</div>`};var nn={layout:\"where\",theme:\"where\",storage:\"interactive\",errors:\"interactive\",silent:\"sandbox\",network:\"sandbox\",\"inline-assets\":\"sandbox\",dialogs:\"sandbox\",print:\"sandbox\",downloads:\"sandbox\",forms:\"sandbox\",\"link-schemes\":\"sandbox\",windows:\"sandbox\",devices:\"sandbox\",workers:\"sandbox\",sound:\"sandbox\",address:\"sandbox\",shell:\"sandbox\"},on=e=>e.mode===\"artifact\"?\"page\":e.mode===\"mcp-app\"?\"view\":\"widget\",we=(e,t)=>F(e,t).length>0||(e.egress.anyHttps??[]).some(n=>n===t);function be(e,t){if(e.mode===\"url\")return[];let n=me(e),o=new Set(I(e)),r=new Set(X(e)?.globals??[]),a=on(e),s=[],i=(c,y)=>{y!==null&&s.push({id:c,text:y,topic:nn[c]})};i(\"layout\",e.layout.kind===\"fill\"?\"It is as tall as the viewer, not the window: the page scrolls itself, and position: fixed and sticky work.\":o.has(\"resize\")?`Its height follows its content, at most ${e.limits.maxHeightPx.toLocaleString(\"en-US\")} px (then it scrolls inside).`:\"Its height is fixed by the app: keep it short, or let it scroll inside.\");let d=e.theme.documents??\"declared\";i(\"theme\",e.mode!==\"artifact\"||d===\"always\"?\"It runs in the person's light or dark theme.\":d===\"never\"?\"It always shows in light: the app doesn't theme it, so style it yourself; prefers-color-scheme may report the reader's system setting, so don't rely on it.\":`It shows in light, as you style it; to follow the person's light or dark theme, declare it in its head (<meta name=\"color-scheme\" content=\"light dark\">) and draw with the variables below.`);let m=\"a blocked script, style or image just doesn't load and a blocked fetch rejects\";i(\"silent\",o.has(\"reportError\")?e.errors===\"agent\"?`What the sandbox blocks shows nothing on the page: ${m}. Each block comes back to you as an error, so check them.`:e.errors===\"host\"?`What the sandbox blocks shows nothing on the page: ${m}. The app is told of each block, but you aren't: test what you write.`:`What the sandbox blocks shows nothing on the page: ${m}. Each block is reported to the app.`:\"What the sandbox blocks fails silently: a blocked script, style or image just doesn't load, a blocked fetch rejects, and nothing shows an error.\"),i(\"network\",t);let f=c=>(e.egress.anyHttps??[]).some(y=>y===c),k=[\"img\",\"font\",\"media\"].filter(c=>!f(c));if(k.some(c=>we(e,c))||we(e,\"style\")||F(e,\"script\").length>0||F(e,\"connect\").length>0||k.length<3){let c=k.length===0?null:k.every(A=>!we(e,A))?\"images, icons, fonts and sound go inline (data: URLs or SVG)\":\"images, fonts and sound from anywhere not listed go inline (data: URLs or SVG)\",y=we(e,\"style\")?\"other CSS goes in a <style>\":\"CSS goes in a <style>\",C=[c,y].filter(A=>A!==null).join(\"; \");i(\"inline-assets\",`${C.charAt(0).toUpperCase()}${C.slice(1)}.`)}n.includes(\"allow-modals\")||(i(\"dialogs\",\"alert, confirm and prompt show nothing: confirm returns false and prompt null. Draw your own dialogs.\"),i(\"print\",\"window.print() does nothing.\")),n.includes(\"allow-downloads\")||i(\"downloads\",`Downloads don't work: <a download>, data: and blob: links, saves from script.${o.has(\"downloadFile\")?\" To give the person a file, ask the app (ui/download-file; with the App SDK, app.downloadFile).\":\"\"}`),n.includes(\"allow-forms\")||i(\"forms\",'Forms never submit, and some browsers fire no submit event: use them as UI, give buttons type=\"button\" and handle their click.'),i(\"link-schemes\",`mailto:, tel: and sms: links open nothing: show the address or number as text${r.has(\"copyText\")?\" (with a copy button)\":\"\"}.`),n.includes(\"allow-popups\")||i(\"windows\",r.has(\"openLink\")||o.has(\"openLink\")?\"window.open and target=_blank open no window (window.open returns null or throws): links open in a new tab through the app (openLink; a click on <a href> does it).\":\"Links to other pages, window.open and target=_blank open nothing (window.open returns null or throws).\"),i(\"devices\",\"Camera, microphone, location and sharing are denied without asking (they reject, or aren't there); file inputs and FileReader work.\"),i(\"workers\",\"Web Workers from blob: URLs work; service workers can't be registered (even reading navigator.serviceWorker can throw), and WebRTC is gone.\"),i(\"sound\",\"Sound (and video with sound) plays only from a click: call play() in its handler.\"),i(\"address\",e.isolation===\"opaque\"?`The ${a}'s address is about:srcdoc: it has no query string or hash to read.`:`The ${a}'s address is its own (with Porthole's one-time ticket), never the app's: read no parameters from it.`),i(\"shell\",`document.write and document.open throw; nested frames (iframe, object, embed) are removed; full screen and the clipboard are closed${r.has(\"copyText\")?\" (copy buttons call copyText)\":\"\"}.`),i(\"storage\",e.isolation===\"opaque\"?`State isn't saved: localStorage works but lasts only while the ${a} is on screen, and a reload or another device starts fresh. Keep what matters in the ${a}'s code.`:e.storage?.scope!==void 0?`localStorage is kept for ${e.storage.scope}, in this browser; another browser or device starts fresh. Reads and writes can throw (private windows, strict settings): wrap them in try/catch and keep only what can be lost.`:e.storage?.shared===void 0?`localStorage is kept for this ${a} in this browser; another device starts fresh. Reads and writes can throw (private windows, strict settings): wrap them in try/catch and keep only what can be lost.`:`localStorage is shared by every ${a} in this ${e.storage.shared}, in this browser (another device starts fresh): prefix your keys with a name of this ${a}'s own (\"budget:filters\", not \"filters\"), or ${a}s overwrite each other. Reads and writes can throw (private windows, strict settings): wrap them in try/catch and keep only what can be lost.`);let u=e.limits.maxErrorReports,g=(e.capabilities.reportError?.gates??[{rateLimit:{perMinute:10}}]).find(c=>typeof c==\"object\"),l=g===void 0?\"\":` At most ${g.rateLimit.perMinute} a minute.`;return i(\"errors\",o.has(\"reportError\")?e.errors===\"agent\"?`Errors: what your code throws, and anything the sandbox blocks, comes back to you (at most ${u} a run), so you can fix it.${l}`:e.errors===\"host\"?`Errors: what your code throws, and anything the sandbox blocks, goes to the app (at most ${u} a run), not to you: test what you write.${l}`:`Errors: what your code throws, and anything the sandbox blocks, is reported to the app (at most ${u} a run).${l}`:\"Errors: nothing reports what your code throws, to you or the app: test what you write.\"),s}function lt(e){return e<1e6?`${Math.floor(e/1e3)} KB`:`${Math.round(e/1048576*10)/10} MB`}var ut=/--[a-z0-9]+(?:-[a-z0-9]+)*/gu;function pt(e){let t=Object.keys(e.theme.variables),n=(...a)=>a.every(s=>t.includes(s)),o=new Set(I(e)),r=new Set(X(e)?.globals??[]);return{config:e,noun:e.mode===\"artifact\"?\"page\":e.mode===\"mcp-app\"?\"view\":\"widget\",has:n,when:a=>n(...a.match(ut)??[])?a:null,names:(a,s=[])=>t.filter(i=>i.startsWith(a)&&!s.some(d=>i.startsWith(d))).join(\", \"),declared:a=>o.has(a),global:a=>r.has(a)}}var He=(...e)=>e.filter(t=>t!==null).join(`\n`).replace(/\\n{3,}/gu,`\n\n`).trim(),mt={script:\"scripts\",style:\"styles\",font:\"fonts\",img:\"images\",media:\"audio and video\",connect:\"data (fetch, WebSocket)\"},ht=\"any https site\",rn=(e,t)=>[...pe(e,t)?[ht]:[],...F(e,t)];function an(e){let n=[\"script\",\"style\",\"font\",\"img\",\"media\",\"connect\"].map(s=>[s,rn(e,s)]).filter(([,s])=>s.length>0);if(n.length===0)return\"Network: none. Nothing loads from outside (no scripts, styles, fonts, images or data from any server) and any fetch fails, so write everything inline: SVG and CSS draw charts well.\";let o=new Map;for(let[s,i]of n)for(let d of i)o.set(d,[...o.get(d)??[],s]);let r=new Map;for(let[s,i]of o){let d=i.map(f=>mt[f]),m=d.length===1?d[0]??\"\":`${d.slice(0,-1).join(\", \")} and ${d.at(-1)}`;r.set(m,[...r.get(m)??[],s])}return`Network: only ${[...r].map(([s,i])=>`${s} from ${i.join(\", \")}`).join(\"; \")}. Anything else fails.`}var sn=e=>e.mode===\"artifact\"&&(e.theme.documents??\"declared\")===\"declared\",_e=e=>F(e,\"script\").length>0;function ln(e){let{config:t,noun:n}=e,{layout:o,limits:r}=t,a=n===\"page\"?\"Pages\":n===\"view\"?\"Views\":\"Widgets\",s=t.guide.toolName===void 0?\"\":` (${t.guide.toolName})`,i=t.mode===\"artifact\"?\"What you pass: a whole HTML document (<!doctype html>, <head>, <body>). It is written into its frame once all of it has arrived, then its scripts run in order.\":t.mode===\"mcp-app\"?\"What you pass: an MCP Apps view, a whole HTML document that talks to its host through the official App SDK (@modelcontextprotocol/ext-apps) or the protocol's own messages.\":\"What you pass: SVG that starts with <svg, or an HTML fragment: no <!doctype>, <html>, <head> or <body>. Order it styles, then markup, then scripts: people see the styled markup as you write it, and scripts run once all of it is written, in order, each external one loaded before the next runs.\",d=be(t,an(t)),m=l=>d.find(c=>c.id===l)?.text??\"\",f=o.kind===\"fill\",k=t.theme.documents===\"never\",p=o.narrowWidthPx+20,v=Math.round(13*o.minWidthPx/p*10)/10,u=Math.round(13*400/p*10)/10,g=De(t.theme.variables[\"--font-text-md-size\"]??\"14px\",\"light\").replace(/^(\\d+(?:\\.\\d+)?)px$/u,\"$1 px\");return He(`# ${a}${s}`,\"\",i,\"\",`Where it runs: ${f?`in a sandboxed frame that fills the app's viewer (often smaller than the window: toolbars and side panels take room), about ${o.narrowWidthPx} px wide on a phone (${o.minWidthPx} on a small one) and wider on a desktop`:`in a sandboxed frame as wide as the column it sits in, about ${o.narrowWidthPx} px on a phone (${o.minWidthPx} on a small one) and ${o.wideWidthPx} on a desktop`}; the same ${n} is read on both, so never write for one of them. Design for ${o.narrowWidthPx} first; where the layout depends on the width, read it as it runs (the ${f?\"frame's own innerWidth, again on resize\":\"box's clientWidth, again from a ResizeObserver\"}). ${m(\"layout\")} ${m(\"theme\")} It runs again each time it is shown${_e(t)?\": pin library versions\":\"\"}.`,\"\",\"Sizes that read on a phone:\",e.when(`- Words go in HTML (titles, notes, legends, readouts): it keeps its size and wraps. The frame's text is already ${g} --font-sans in --color-text-primary; notes --font-text-sm-size, never under 12 px.`),`- An SVG scales with the frame: its text shows at font-size \\xD7 frame width \\xF7 viewBox width, so a 680-wide viewBox turns 12 into 5 px on a phone. Draw it for the phone: viewBox=\"0 0 ${p} H\", no text under 13, width=\"100%\" style=\"max-width: 400px\"; its text then shows at ${v} to ${u} px on every screen. Or draw it 1 unit = 1 px with a script (topic chart).`,`- The frame never scrolls sideways: nothing fixed wider than ${o.minWidthPx} px; images max-width: 100%; a grid or flex child with long text min-width: 0; a wide table or code block in its own box with overflow-x: auto.`,\"- Cards in a row wrap (flex-wrap: wrap; flex: 1 1 100px), or a grid of repeat(auto-fit, minmax(160px, 1fr)): at most 2 columns under 500 px, never a fixed repeat(3, \\u2026).\",\"- Touch: anything clickable is at least 44 px tall. Phones don't hover: what a hover shows, a tap (click) shows too.\",f?null:\"- No position: fixed: the frame grows with its content, so a fixed element covers it.\",\"\",\"The sandbox:\",...d.filter(l=>l.topic===\"sandbox\").map(l=>`- ${l.text}`),`Keep it under ${lt(r.maxBytes)}.`,_e(t)?`\nLibraries: pin an exact version at least two weeks old (chart.js@4.4.1 in its URL), never @latest or a range, so the code can't be swapped under you and draws the same every time.`:null,\"\",k?`Colors: these variables hold the app's palette; use them, or colors of your own. Give the ${n} its own background.`:sn(t)?`Colors, for a ${n} that declares light and dark: every color from these variables, never hard-coded, so both work; its own background then stays transparent (it sits on the app's surface).`:`Colors: every color from these variables, never hard-coded, so light and dark both work. The ${n}'s own background is transparent (it sits on the app's surface).`,e.names(\"--color-background-\")===\"\"?null:`- Surfaces: ${e.names(\"--color-background-\")}`,e.names(\"--color-text-\")===\"\"?null:`- Text: ${e.names(\"--color-text-\")}`,e.names(\"--color-border-\")===\"\"?null:`- Borders: ${e.names(\"--color-border-\")}${e.names(\"--color-ring-\")===\"\"?\"\":`; focus rings: ${e.names(\"--color-ring-\")}`}`,e.names(\"--color-accent\")===\"\"?null:`- Accent: ${[e.when(\"--color-accent (a button)\"),e.when(\"--color-accent-soft (a selected item's fill)\"),e.when(\"in a figure, --color-chart-1 (topic chart)\")].filter(l=>l!==null).join(\"; \")}`,e.names(\"--font-\")===\"\"?null:`- Type: ${e.names(\"--font-\")}`,e.names(\"--border-\")===\"\"&&e.names(\"--shadow-\")===\"\"?null:`- Shape: ${[e.names(\"--border-\"),e.names(\"--shadow-\")].filter(l=>l!==\"\").join(\", \")}`,ct(e)===\"\"?null:`- Also: ${ct(e)}`,\"\",xe(e,W.stats)?`Cards that ${k?\"\":\"read in both themes, and \"}wrap on a phone:\n${W.stats}\n`:null,e.when(\"Don't use --color-background-primary as a card's fill: it is the app's own surface, so a card on it vanishes.\"),k?null:`A theme change updates the variables in place and fires window \"${t.theme.event}\": CSS that uses var(...) follows by itself; a canvas or a library you gave colors to must redraw.`,t.mode===\"inline\"?\"Buttons and inputs already match the app (its borders, radius, colors and focus ring, 44 px tall): use them as they are, or restyle them with your own CSS.\":null,\"\",\"Diagrams (boxes and arrows): show the mechanism asked about (what calls what, where data goes), only the parts the ask names; label each arrow with what moves.\",\"- Top to bottom, at most 2 boxes a row, in the phone viewBox; the title in HTML above. Too much for one glance on a phone: make two.\",\"- SVG doesn't wrap: break lines yourself. A box is its longest line + 24 wide (13 px text takes about 7 units a character, a 14 px bold name 8.5: a 136-wide box holds 16); a name and a line, 52 tall; 16 between boxes.\",e.when(\"- Boxes fill none, stroke --color-border-secondary; at most one stands out: stroke --color-chart-1, 2 wide, fill --color-chart-1 at fill-opacity 0.12. Arrows --color-text-tertiary, in the gaps, never across a box, their labels beside them. Every <text> sets fill: names --color-text-primary, the rest --color-text-secondary.\"),xe(e,W.diagram)?`\n${W.diagram}`:null)}function ct(e){let t=[\"--color-background-\",\"--color-text-\",\"--color-border-\",\"--color-ring-\",\"--color-accent\",\"--color-chart-\",\"--font-\",\"--border-\",\"--shadow-\"];return Object.keys(e.config.theme.variables).filter(n=>!t.some(o=>n.startsWith(o))).join(\", \")}function xe(e,t){return e.has(...t.match(ut)??[])&&!/https?:\\/\\//u.test(t)}function cn(e){let{config:t}=e,n=Object.keys(t.theme.variables).filter(a=>/^--color-chart-\\d+$/u.test(a)),o=Object.keys(t.theme.variables).filter(a=>/^--color-chart-seq-\\d+$/u.test(a)),r=_e(t)?`Libraries (Chart.js, ECharts, d3) draw in px too, in a box with a set height (Chart.js responsive: true, maintainAspectRatio: false). They don't read CSS variables: pass in getComputedStyle(document.documentElement).getPropertyValue(\"${n[0]??\"--color-text-primary\"}\").trim()${t.theme.documents===\"never\"?\"\":`, redraw on window \"${t.theme.event}\"`}, and override their palette and white background.`:\"No chart library loads here: draw the SVG yourself, from a script, as below.\";return He(`# Charts (a chart is a ${e.noun})`,\"\",\"Pick the form first: a trend over time \\u2192 line; compare categories \\u2192 horizontal bars; x against y \\u2192 scatter; one number \\u2192 a big number, not a chart; a few numbers \\u2192 a table, not a chart.\",\"\",\"The look:\",'- The title states the finding, with its number (\"Failed builds fell from 9 to 2 a week\"), not the topic; a line under it says what is measured, in what unit.',e.when(\"- Grey first: the data in a quiet grey (--color-text-disabled), one accent (--color-chart-1) on what the title is about. More hues only for series that differ in kind and must each be found.\"),\"- Values on the marks or a light axis, not both; label only the points the finding rests on. Bars start at zero.\",\"- Write the numbers once, as rows, and draw marks, labels and readout from them.\",\"\",\"Size: draw it at the frame's width, 1 unit = 1 px: read the box's clientWidth, draw an <svg> that wide with 12 px text, and again from a ResizeObserver. Its text stays 12 px on every screen; keep x labels 44 px apart. No script: the phone viewBox (topic widget). Bars need no SVG: an HTML grid row per category.\",\"\",r,\"\",n.length===0?null:\"Colors:\",n.length===0?null:`- Series of different kinds: ${n[0]} \\u2026 ${n.at(-1)}, in this order, never cycled, at most ${n.length} (fold the rest into \"Other\"); a series keeps its color when a filter hides others.`,o.length===0?null:`- Magnitude (a heatmap): ${o[0]} \\u2026 ${o.at(-1)}, 1 nearest zero.${e.has(\"--color-chart-neg\",\"--color-chart-mid\",\"--color-chart-pos\")?\" Above or below a midpoint: --color-chart-neg, --color-chart-mid, --color-chart-pos.\":\"\"}`,e.when(\"- Never a rainbow. Status (good, bad) uses --color-text-success, --color-text-warning, --color-text-danger with a word, never as a series color.\"),e.when(\"- Text is never in a series color: --color-text-primary or --color-text-secondary; the mark beside it carries identity.\"),\"\",e.when(\"Marks: 2 px lines, bars with a 2 px gap; grid lines --color-border-tertiary, 1 px; one y axis (two scales: two charts); the legend in HTML.\"),\"\",`Reading values: a readout line in HTML that a tap on a column fills (each column a hit area the plot's height), the latest values shown before any tap; a \"Table\" toggle for the numbers.`,xe(e,W.line)?`\nA line chart drawn at the frame's width, its numbers on a tap:\n${W.line}`:null,xe(e,W.bars)?`\nBars in HTML, under a title like the line chart's:\n${W.bars}`:null)}function j(e,t){let n=[];e.includes(\"confirm\")&&n.push(`The app shows the person ${t} first, and nothing happens unless they confirm.`),e.includes(\"user-activation\")&&n.push(\"Call it from a click (it needs one).\");for(let o of e)typeof o==\"object\"&&n.push(`At most ${o.rateLimit.perMinute} a minute.`);return n.join(\" \")}var dn={sendPrompt:(e,t)=>e.global(\"sendPrompt\")?`- sendPrompt(text): asks to send text to you as the person's message (at most ${e.config.limits.maxPromptChars.toLocaleString(\"en-US\")} characters). Use it for \"explain this point\", \"try these settings\". ${j(t,\"the whole text\")} It returns a promise: true if it was sent.`:`- Messages: the MCP Apps request ui/message (with the App SDK, app.sendMessage) asks to send text to you as the person's message. ${j(t,\"the whole text\")}`,openLink:(e,t)=>e.global(\"openLink\")?`- openLink(url): asks to open an http(s) link in a new tab; a click on an <a href> does the same for you. ${j(t,\"the link\")} It returns a promise: true if it opened.`:`- Links: the MCP Apps request ui/open-link (with the App SDK, app.openLink) asks to open an http(s) link in a new tab. ${j(t,\"the link\")}`,downloadFile:(e,t)=>`- Downloads: the MCP Apps request ui/download-file (with the App SDK, app.downloadFile). ${j(t,\"the file\")}`,callTool:(e,t)=>`- Tools: the MCP Apps request tools/call (with the App SDK, app.callServerTool). ${j(t,\"the call\")}`,readData:(e,t)=>`- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${j(t,\"the request\")}`,setModelContext:(e,t)=>`- Context for the agent: the MCP Apps request ui/update-model-context (with the App SDK, app.updateModelContext). ${j(t,\"it\")}`,copyText:(e,t)=>e.global(\"copyText\")?`- copyText(text): copies text to the person's clipboard (at most ${2e4.toLocaleString(\"en-US\")} characters), and the app shows them what was copied. Use it for every copy button: nothing else in the ${e.noun} can write the clipboard. ${j(t,\"the text\")} It returns a promise: true if it was copied.`:`- Copying: the request porthole/copy-text with { text } (at most ${2e4.toLocaleString(\"en-US\")} characters) copies text to the person's clipboard, and the app shows them what was copied; nothing else in the ${e.noun} can write the clipboard. ${j(t,\"the text\")}`,annotate:e=>`- Comments: the person may point at parts of the ${e.noun} to comment on them. Give headings and the parts that matter stable ids (id=\"revenue\"), so comments stay on them when the ${e.noun} is written again.`,reportError:e=>`- ${be(e.config,\"\").find(t=>t.id===\"errors\")?.text??\"\"}`,resize:()=>\"\"};function un(e){let{config:t,noun:n}=e,o=I(t).map(m=>{let f=t.capabilities[m]?.guide;return f===void 0?dn[m](e,J(t,m)):`- ${f}`}).filter(m=>m!==\"\"),r=be(t,\"\"),a=r.find(m=>m.id===\"storage\"),s=a===void 0?null:`- ${a.text}`,i=e.declared(\"reportError\")?null:`- ${r.find(m=>m.id===\"errors\")?.text??\"\"}`,d=o.length===0?\"- It can only draw: it has no way to send anything to you or the app.\":null;return He(`# Interactive ${n}s`,\"\",...o,i,d,s)}var dt={widget:ln,chart:cn,interactive:un};function ft(e,t){let n=pt(e),o=e.guide.topics??{};return(t??Ie).map(r=>{if(Object.hasOwn(dt,r))return dt[r](n);let a=o[r];if(a===void 0)throw new RangeError(`No guide topic ${JSON.stringify(r)}`);return a}).join(`\n\n`)}function gt(e){let t=pt(e),{layout:n}=e,o=e.mode===\"artifact\"?\"Show a whole HTML page you write: a report, a document, a small app.\":e.mode===\"mcp-app\"?\"Show an MCP Apps view.\":\"Render an SVG or an HTML fragment you write, shown inline: charts, diagrams, explainers, small interactive tools.\",r=[...new Set([\"script\",\"style\",\"font\",\"img\",\"media\",\"connect\"].flatMap(p=>F(e,p)))],a=[\"img\",\"media\",\"font\"].filter(p=>pe(e,p)).map(p=>mt[p]),s=a.length===0?\"\":`${a.length===1?a[0]:`${a.slice(0,-1).join(\", \")} and ${a.at(-1)}`} from ${ht}`,i=r.length===0&&s===\"\"?\"with no network (nothing loads from outside)\":r.length===0?`loading only ${s}`:`loading only from ${r.join(\", \")}${s===\"\"?\"\":`, and ${s}`}`,d=I(e).flatMap(p=>{let v=H(p);return v.global===void 0||!t.global(v.global)?[]:v.global===\"sendPrompt\"?[\"sendPrompt(text) asks the person to send text to you as their message.\"]:v.global===\"openLink\"?[\"openLink(url) asks the person to open a link.\"]:[]}),m=e.guide.guideToolName===void 0?\"\":` Call ${e.guide.guideToolName} once before your first ${t.noun}${e.mode===\"inline\"?\" (topic chart before your first chart)\":\"\"}.`,f=n.kind===\"fill\"?`It fills the viewer in a sandbox about ${n.narrowWidthPx} px wide on a phone, from the same code on every screen`:`It runs in a sandbox about ${n.narrowWidthPx} px wide on a phone and ${n.wideWidthPx} on a desktop, from the same code${t.declared(\"resize\")?\" (its height follows the content)\":\"\"}`,k=e.theme.documents===\"never\"?\"always in light (the app doesn't theme it)\":\"in the person's light or dark theme through CSS variables\";return`${o} ${f}, ${k}, ${i}. ${d.join(\" \")}${m} Each time it is shown it runs again from this code.`.replace(/ {2,}/gu,\" \")}var pn=/^(https?):\\/\\/([a-z0-9.-]+|\\[[0-9a-f:.]+\\])(?::(\\d{1,5}))?$/u,yt=/^\\d{1,3}(\\.\\d{1,3}){3}$/u,wt={http:\"80\",https:\"443\"};function ve(e){let t=pn.exec(e);if(t===null)return null;let[,n=\"\",o=\"\",r]=t;return{scheme:n,host:o,port:r??wt[n]??\"\"}}var mn=/^[a-z][a-z0-9+.-]*:\\/\\/([a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*|\\[[0-9a-f:.]+\\])(:\\d{1,5})?$/u;function hn(e){return typeof e==\"string\"&&e.length<=300&&mn.test(e)}function bt(e){return hn(e)?null:e===\"null\"?`the host page's origin is opaque (\"null\"): serve it from a real origin (an Electron custom protocol must be registered as standard, and file: pages have none)`:`${JSON.stringify(e)} is not an exact origin (scheme://host[:port], lowercase, no path)`}function fn(e,t){let n=e.toLowerCase().replace(/\\.$/u,\"\"),o=t.toLowerCase().replace(/\\.$/u,\"\");if(n===o)return!0;if(yt.test(n)||yt.test(o)||n.startsWith(\"[\")||o.startsWith(\"[\"))return!1;let r=n.split(\".\").toReversed(),a=o.split(\".\").toReversed(),s=0;for(;s<r.length&&s<a.length&&r[s]===a[s];)s+=1;return s>=2}function gn(e,t){let n=ve(e),o=/^(https?):\\/\\/\\*\\.([a-z0-9.-]+)(?::(\\d{1,5}))?$/u.exec(t);if(n===null)return!1;if(o===null){let i=ve(t);return i!==null&&i.scheme===n.scheme&&i.host===n.host&&i.port===n.port}let[,r=\"\",a=\"\",s]=o;return r===n.scheme&&(s??wt[r])===n.port&&n.host.endsWith(`.${a}`)&&n.host.length>a.length+1}function xt(e,t,n){let o=ve(e.origin),r;try{r=new URL(e.url)}catch{throw new TypeError(\"The located URL is not a URL\")}if(o===null||r.origin!==e.origin)throw new TypeError(`The located URL is not on its origin ${JSON.stringify(e.origin)} (it is on ${JSON.stringify(yn(e.url))})`);if(!t.some(s=>gn(e.origin,s)))throw new TypeError(`The located origin ${e.origin} is not one of the config's content origins`);let a=ve(n);if(a!==null&&fn(o.host,a.host))throw new TypeError(`The located origin ${e.origin} may be the same site as the host (${n}): content must be served from a registrable domain the host uses for nothing else`)}function yn(e){try{return new URL(e).origin}catch{return\"an unparsable address\"}}var vt=String.raw`if (declared(\"annotate\")) {\n (() => {\n const LIMIT = { exact: 4000, quote: 300, context: 32, label: 120, css: 1000, marks: 500, boxes: 200 };\n const M = {\n start: \"porthole/annotate.start\",\n stop: \"porthole/annotate.stop\",\n show: \"porthole/annotate.show\",\n focus: \"porthole/annotate.focus\",\n clear: \"porthole/annotate.clear\",\n selected: \"porthole/annotate.selected\",\n unselected: \"porthole/annotate.unselected\",\n cancelled: \"porthole/annotate.cancelled\",\n anchored: \"porthole/annotate.anchored\",\n };\n // The DOM's own functions, taken before content runs.\n const elementFromPoint = Document.prototype.elementFromPoint;\n const querySelector = Document.prototype.querySelector;\n const createRange = Document.prototype.createRange;\n const createTreeWalker = Document.prototype.createTreeWalker;\n const createElement = Document.prototype.createElement;\n const selectionOf = Document.prototype.getSelection;\n const elementRect = Element.prototype.getBoundingClientRect;\n const rangeRect = Range.prototype.getBoundingClientRect;\n const rangeRects = Range.prototype.getClientRects;\n const attachShadow = Element.prototype.attachShadow;\n const post = window.parent.postMessage.bind(window.parent);\n const tell = (method, params) => {\n if (window.parent !== window) {\n post({ jsonrpc: \"2.0\", method, params }, \"*\");\n }\n };\n const squash = (text) => String(text).replace(/\\s+/g, \" \").trim();\n const box = (rect) => ({ x: rect.left, y: rect.top, width: rect.width, height: rect.height });\n\n // The document's text: the body's text nodes in order, without scripts, styles, templates.\n const SKIPPED = { script: 1, style: 1, noscript: 1, template: 1 };\n const textIndex = () => {\n const nodes = [];\n const starts = [];\n const at = new Map();\n let text = \"\";\n const body = document.body;\n if (body) {\n const walker = createTreeWalker.call(document, body, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {\n acceptNode: (node) => (node.nodeType === 1 ? (SKIPPED[node.localName] ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_SKIP) : NodeFilter.FILTER_ACCEPT),\n });\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n at.set(node, nodes.length);\n nodes.push(node);\n starts.push(text.length);\n text += node.nodeValue;\n }\n }\n return { nodes, starts, at, text };\n };\n // A boundary point as an offset into the text: in a text node, where it is; elsewhere, the\n // first text at or after it.\n const offsetOf = (index, container, offset) => {\n if (container.nodeType === 3 && index.at.has(container)) {\n return index.starts[index.at.get(container)] + Math.min(offset, container.nodeValue.length);\n }\n const point = createRange.call(document);\n try {\n point.setStart(container, offset);\n } catch (_) {\n return index.text.length;\n }\n point.collapse(true);\n let low = 0;\n let high = index.nodes.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if (point.comparePoint(index.nodes[middle], 0) >= 0) {\n high = middle;\n } else {\n low = middle + 1;\n }\n }\n return low < index.nodes.length ? index.starts[low] : index.text.length;\n };\n const pointAt = (index, at, end) => {\n let low = 0;\n let high = index.nodes.length - 1;\n let found = -1;\n while (low <= high) {\n const middle = (low + high) >> 1;\n if (index.starts[middle] <= at) {\n found = middle;\n low = middle + 1;\n } else {\n high = middle - 1;\n }\n }\n if (found === -1) {\n return null;\n }\n let node = index.nodes[found];\n let offset = at - index.starts[found];\n if (end) {\n // An end at a node's very start belongs to the text before it.\n while (offset === 0 && found > 0) {\n found -= 1;\n node = index.nodes[found];\n offset = node.nodeValue.length;\n }\n } else {\n while (offset >= node.nodeValue.length && found + 1 < index.nodes.length) {\n found += 1;\n node = index.nodes[found];\n offset = 0;\n }\n }\n return { node, offset: Math.min(offset, node.nodeValue.length) };\n };\n const rangeAt = (index, start, end) => {\n const from = pointAt(index, start, false);\n const to = pointAt(index, end, true);\n if (from === null || to === null) {\n return null;\n }\n const range = createRange.call(document);\n try {\n range.setStart(from.node, from.offset);\n range.setEnd(to.node, to.offset);\n } catch (_) {\n return null;\n }\n return range;\n };\n const spanOf = (index, node) => {\n const range = createRange.call(document);\n range.selectNodeContents(node);\n return [offsetOf(index, range.startContainer, range.startOffset), offsetOf(index, range.endContainer, range.endOffset)];\n };\n\n // A CSS selector that matches this element and no other: from the nearest id, else the body.\n const escape = typeof CSS === \"object\" && CSS !== null && typeof CSS.escape === \"function\" ? CSS.escape : (value) => String(value).replace(/[^a-zA-Z0-9_-]/g, (each) => \"\\\\\" + each);\n const only = (selector, element) => {\n try {\n return querySelector.call(document, selector) === element;\n } catch (_) {\n return false;\n }\n };\n const cssPath = (element) => {\n const steps = [];\n for (let node = element; node !== null && node.nodeType === 1 && steps.length < 16; node = node.parentElement) {\n if (node.id && only(\"#\" + escape(node.id), node)) {\n steps.unshift(\"#\" + escape(node.id));\n break;\n }\n if (node.localName === \"body\" || node.localName === \"html\") {\n steps.unshift(node.localName);\n break;\n }\n let step = escape(node.localName);\n const parent = node.parentElement;\n if (parent !== null) {\n const same = Array.from(parent.children).filter((child) => child.localName === node.localName);\n if (same.length > 1) {\n step += \":nth-of-type(\" + (same.indexOf(node) + 1) + \")\";\n }\n }\n steps.unshift(step);\n }\n const selector = steps.join(\" > \");\n return selector.length <= LIMIT.css && only(selector, element) ? selector : null;\n };\n const describe = (element) => {\n let name = element.localName + (element.id ? \"#\" + element.id : \"\");\n const classes = typeof element.className === \"string\" ? element.className.trim().split(/\\s+/).filter(Boolean).slice(0, 2) : [];\n for (const each of classes) {\n name += \".\" + each;\n }\n const words = squash(element.textContent || \"\").slice(0, 40);\n return (words ? name + \" \" + words : name).slice(0, LIMIT.label);\n };\n const quoteOf = (index, start, end) => {\n const quote = { type: \"TextQuoteSelector\", exact: index.text.slice(start, end) };\n const prefix = index.text.slice(Math.max(0, start - LIMIT.context), start);\n const suffix = index.text.slice(end, end + LIMIT.context);\n if (prefix) {\n quote.prefix = prefix;\n }\n if (suffix) {\n quote.suffix = suffix;\n }\n return quote;\n };\n const elementAnchor = (element, index) => {\n const selectors = [];\n const css = cssPath(element);\n if (css !== null) {\n selectors.push({ type: \"CssSelector\", value: css });\n }\n const span = spanOf(index, element);\n const end = Math.min(span[1], span[0] + LIMIT.quote);\n if (index.text.slice(span[0], end).trim() !== \"\") {\n selectors.push(quoteOf(index, span[0], end), { type: \"TextPositionSelector\", start: span[0], end });\n }\n return selectors.length === 0 ? null : { kind: \"element\", selectors, label: describe(element) };\n };\n const textAnchor = (range, index) => {\n const start = offsetOf(index, range.startContainer, range.startOffset);\n const end = Math.min(offsetOf(index, range.endContainer, range.endOffset), start + LIMIT.exact);\n const exact = index.text.slice(start, end);\n if (exact.trim() === \"\") {\n return null;\n }\n const selectors = [quoteOf(index, start, end), { type: \"TextPositionSelector\", start, end }];\n let container = range.commonAncestorContainer;\n if (container.nodeType !== 1) {\n container = container.parentElement;\n }\n const css = container !== null && container !== document.body ? cssPath(container) : null;\n if (css !== null) {\n selectors.push({ type: \"CssSelector\", value: css });\n }\n return { kind: \"text\", selectors, label: squash(exact).slice(0, LIMIT.label) };\n };\n\n // Finding an anchor again, best-effort: where it was, its words anywhere (the occurrence\n // whose surroundings match best), then its words with any spacing.\n const shared = (a, b, fromEnd) => {\n let n = 0;\n while (n < a.length && n < b.length && (fromEnd ? a.charAt(a.length - 1 - n) === b.charAt(b.length - 1 - n) : a.charAt(n) === b.charAt(n))) {\n n += 1;\n }\n return n;\n };\n const locate = (index, quote, position) => {\n const text = index.text;\n const length = quote.exact.length;\n if (position && text.slice(position.start, position.start + length) === quote.exact) {\n return [position.start, position.start + length];\n }\n let best = null;\n let bestScore = -1;\n let seen = 0;\n for (let at = text.indexOf(quote.exact); at !== -1 && seen < 1000; at = text.indexOf(quote.exact, at + 1)) {\n seen += 1;\n const score =\n shared(text.slice(Math.max(0, at - LIMIT.context), at), quote.prefix || \"\", true) +\n shared(text.slice(at + length, at + length + LIMIT.context), quote.suffix || \"\", false) -\n (position ? Math.min(1, Math.abs(at - position.start) / 1e6) : 0);\n if (score > bestScore) {\n bestScore = score;\n best = [at, at + length];\n }\n }\n if (best !== null) {\n return best;\n }\n const wanted = squash(quote.exact);\n if (wanted === \"\") {\n return null;\n }\n const map = [];\n let loose = \"\";\n let space = false;\n for (let i = 0; i < text.length; i += 1) {\n const each = text.charAt(i);\n if (/\\s/.test(each)) {\n if (!space && loose !== \"\") {\n loose += \" \";\n map.push(i);\n }\n space = true;\n } else {\n loose += each;\n map.push(i);\n space = false;\n }\n }\n const at = loose.indexOf(wanted);\n return at === -1 ? null : [map[at], map[at + wanted.length - 1] + 1];\n };\n const find = (anchor, index) => {\n const of = (type) => anchor.selectors.filter((each) => each && each.type === type)[0];\n const css = of(\"CssSelector\");\n const quote = of(\"TextQuoteSelector\");\n const position = of(\"TextPositionSelector\");\n if (anchor.kind === \"text\") {\n const span = quote ? locate(index, quote, position) : null;\n const range = span === null ? null : rangeAt(index, span[0], span[1]);\n return range === null ? null : { range };\n }\n let element = null;\n if (css && typeof css.value === \"string\") {\n try {\n element = querySelector.call(document, css.value);\n } catch (_) {\n element = null;\n }\n }\n if (element !== null && quote) {\n const span = spanOf(index, element);\n if (index.text.slice(span[0], span[1]).indexOf(quote.exact) === 0) {\n return { element };\n }\n }\n // Without words to check, or by an id, the selector is enough.\n if (element !== null && (!quote || css.value.charAt(0) === \"#\")) {\n return { element };\n }\n const span = quote ? locate(index, quote, position) : null;\n const range = span === null ? null : rangeAt(index, span[0], span[1]);\n if (range !== null) {\n let node = range.commonAncestorContainer;\n if (node.nodeType !== 1) {\n node = node.parentElement;\n }\n if (node !== null) {\n return { element: node };\n }\n }\n return null;\n };\n const rectOf = (found) => (found.range ? rangeRect.call(found.range) : elementRect.call(found.element));\n\n // The shell's own layer, over the content: marks, the outline of what would be picked.\n let layer = null;\n let shadow = null;\n const STYLE = \".mark{position:absolute;border-radius:2px;background:rgba(250,204,21,.3);box-shadow:inset 0 -2px 0 rgba(202,138,4,.8)}.mark.element{background:rgba(250,204,21,.12);box-shadow:none;outline:2px solid rgba(202,138,4,.85);outline-offset:1px}.mark.active{background:rgba(250,204,21,.5)}.mark.element.active{background:rgba(250,204,21,.22);outline-width:3px}.mark.flash{animation:flash 1.8s ease-out}@keyframes flash{from{background:rgba(250,204,21,.9)}}.hover{position:absolute;outline:2px solid #2563eb;outline-offset:1px;background:rgba(37,99,235,.12)}.tag{position:absolute;max-width:70vw;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:12px/18px ui-monospace,SFMono-Regular,Menlo,monospace;padding:0 6px;border-radius:4px;background:#1e293b;color:#fff}\";\n const ensureLayer = () => {\n if (layer === null) {\n layer = createElement.call(document, \"div\");\n layer.setAttribute(\"aria-hidden\", \"true\");\n layer.setAttribute(\"data-porthole-annotations\", \"\");\n // Inline and important: the content's own styles can't hide or move it by accident.\n layer.style.cssText = \"position:fixed!important;inset:0!important;display:block!important;visibility:visible!important;opacity:1!important;pointer-events:none!important;z-index:2147483647!important;overflow:hidden!important;margin:0!important;padding:0!important;border:0!important;background:none!important;transform:none!important\";\n shadow = attachShadow.call(layer, { mode: \"closed\" });\n }\n if (!layer.isConnected) {\n document.documentElement.appendChild(layer);\n }\n return shadow;\n };\n\n let mode = { elements: false, text: false };\n let hover = null;\n let marks = [];\n let active = null;\n let flashing = null;\n let flashUntil = 0;\n const draw = () => {\n if (marks.length === 0 && hover === null && layer === null) {\n return;\n }\n const root = ensureLayer();\n const parts = [];\n const style = createElement.call(document, \"style\");\n if (nonce !== \"\") {\n style.nonce = nonce;\n }\n style.textContent = STYLE;\n parts.push(style);\n const flashOn = Date.now() < flashUntil;\n for (const mark of marks) {\n if (mark.found === null) {\n continue;\n }\n const rects = mark.found.range ? Array.from(rangeRects.call(mark.found.range)) : [elementRect.call(mark.found.element)];\n for (const rect of rects.slice(0, LIMIT.boxes)) {\n if (rect.width === 0 && rect.height === 0) {\n continue;\n }\n const each = createElement.call(document, \"div\");\n each.className = \"mark \" + (mark.found.range ? \"text\" : \"element\") + (mark.id === active ? \" active\" : \"\") + (flashOn && mark.id === flashing ? \" flash\" : \"\");\n each.style.cssText = \"left:\" + rect.left + \"px;top:\" + rect.top + \"px;width:\" + rect.width + \"px;height:\" + rect.height + \"px\";\n parts.push(each);\n }\n }\n if (hover !== null && hover.isConnected) {\n const rect = elementRect.call(hover);\n const outline = createElement.call(document, \"div\");\n outline.className = \"hover\";\n outline.style.cssText = \"left:\" + rect.left + \"px;top:\" + rect.top + \"px;width:\" + rect.width + \"px;height:\" + rect.height + \"px\";\n const tag = createElement.call(document, \"div\");\n tag.className = \"tag\";\n tag.textContent = describe(hover).slice(0, 80);\n tag.style.cssText = \"left:\" + Math.max(4, rect.left) + \"px;top:\" + (rect.top >= 24 ? rect.top - 22 : Math.max(4, rect.bottom + 4)) + \"px\";\n parts.push(outline, tag);\n }\n root.replaceChildren(...parts);\n };\n let drawing = false;\n const redraw = () => {\n if (!drawing) {\n drawing = true;\n requestAnimationFrame(() => {\n drawing = false;\n draw();\n });\n }\n };\n\n const resultOf = (mark) => (mark.found === null ? { id: mark.id, state: \"orphaned\" } : { id: mark.id, state: \"attached\", rect: box(rectOf(mark.found)) });\n // Finds every mark again; tells the host every result (after show) or only when one changed.\n const anchorAll = (all) => {\n const index = textIndex();\n let changed = false;\n for (const mark of marks) {\n let found = null;\n try {\n found = find(mark.anchor, index);\n } catch (_) {\n found = null;\n }\n const state = found === null ? \"orphaned\" : \"attached\";\n if (state !== mark.state) {\n changed = true;\n }\n mark.found = found;\n mark.state = state;\n }\n if (all || changed) {\n tell(M.anchored, { results: marks.map(resultOf) });\n }\n draw();\n };\n // Once the content has been quiet a moment (it may still be drawing), at most a second late.\n let anchorTimer = 0;\n let deadline = 0;\n let reportAll = false;\n // Nothing is reported before the content is in place (an empty shell would orphan every\n // mark), nor before a run of changes settles; a focus asked for meanwhile waits for it.\n let waitingForContent = false;\n let pendingFocus = null;\n const settling = () => anchorTimer !== 0 || waitingForContent || marks.some((mark) => mark.state === null);\n const scheduleAnchor = (all) => {\n if (all) {\n reportAll = true;\n }\n if (!contentIsIn()) {\n if (!waitingForContent) {\n waitingForContent = true;\n whenContentIsIn(() => {\n waitingForContent = false;\n scheduleAnchor(false);\n });\n }\n return;\n }\n const now = Date.now();\n if (deadline === 0) {\n deadline = now + 1000;\n }\n clearTimeout(anchorTimer);\n anchorTimer = setTimeout(() => {\n anchorTimer = 0;\n deadline = 0;\n const every = reportAll;\n reportAll = false;\n anchorAll(every);\n if (pendingFocus !== null) {\n const id = pendingFocus;\n pendingFocus = null;\n focus(id);\n }\n }, Math.max(0, Math.min(150, deadline - now)));\n };\n new MutationObserver((records) => {\n if (marks.length === 0) {\n return;\n }\n for (const record of records) {\n if (record.target === layer || (record.addedNodes.length + record.removedNodes.length === 1 && (record.addedNodes[0] === layer || record.removedNodes[0] === layer))) {\n continue;\n }\n scheduleAnchor(false);\n return;\n }\n }).observe(document, { childList: true, subtree: true, characterData: true });\n window.addEventListener(\"resize\", redraw);\n window.addEventListener(\"scroll\", redraw, true);\n\n const focus = (id) => {\n const mark = marks.filter((each) => each.id === id)[0];\n if (!mark) {\n return;\n }\n if (settling()) {\n // Where it is isn't known yet: focus it once anchoring has settled, then say where.\n pendingFocus = id;\n active = id;\n return;\n }\n active = id;\n if (mark.found !== null) {\n const rect = rectOf(mark.found);\n if (rect.top < 0 || rect.bottom > window.innerHeight) {\n window.scrollBy(0, rect.top - (window.innerHeight - Math.min(rect.height, window.innerHeight)) / 2);\n }\n flashing = id;\n flashUntil = Date.now() + 1800;\n setTimeout(redraw, 1850);\n }\n draw();\n tell(M.anchored, { results: [resultOf(mark)] });\n };\n\n // Picking an element: what is under the pointer, never the page itself or the shell's layer.\n let cursor = null;\n const setCursor = (on) => {\n if (typeof CSSStyleSheet !== \"function\" || !Array.isArray(document.adoptedStyleSheets)) {\n return;\n }\n if (cursor === null) {\n cursor = new CSSStyleSheet();\n cursor.replaceSync(\"*, *::before, *::after { cursor: crosshair !important; }\");\n }\n const others = document.adoptedStyleSheets.filter((sheet) => sheet !== cursor);\n document.adoptedStyleSheets = on ? others.concat([cursor]) : others;\n };\n const pickable = (element) => (element && element.nodeType === 1 && element !== document.documentElement && element !== document.body && element !== layer ? element : null);\n const under = (x, y) => pickable(elementFromPoint.call(document, x, y));\n const stop = () => {\n mode = { elements: false, text: false };\n hover = null;\n reported = null;\n setCursor(false);\n draw();\n };\n // The content's own handlers never see the pointer while an element is being picked; a\n // finger outlines what it is on as it goes down.\n let pressed = null;\n const swallow = (event) => {\n if (mode.elements) {\n if (event.type === \"pointerdown\") {\n pressed = { x: event.clientX, y: event.clientY };\n hover = under(event.clientX, event.clientY);\n redraw();\n }\n event.stopImmediatePropagation();\n if (!mode.text && (event.type === \"mousedown\" || event.type === \"mouseup\")) {\n event.preventDefault();\n }\n }\n };\n for (const type of [\"pointerdown\", \"pointerup\", \"mousedown\", \"mouseup\", \"dblclick\", \"auxclick\", \"touchstart\", \"touchend\"]) {\n window.addEventListener(type, swallow, true);\n }\n window.addEventListener(\"pointermove\", (event) => {\n if (mode.elements) {\n hover = under(event.clientX, event.clientY);\n redraw();\n }\n }, true);\n window.addEventListener(\"click\", (event) => {\n if (!mode.elements) {\n return;\n }\n event.preventDefault();\n event.stopImmediatePropagation();\n // A drag that selected text: the selection is what was meant. A press and release in\n // one place is a pick.\n const selection = selectionOf.call(document);\n const dragged = pressed !== null && event.detail !== 0 && Math.abs(event.clientX - pressed.x) + Math.abs(event.clientY - pressed.y) > 4;\n if (mode.text && dragged && selection !== null && !selection.isCollapsed) {\n return;\n }\n const element = event.detail === 0 ? pickable(event.target) : under(event.clientX, event.clientY);\n if (element === null) {\n return;\n }\n const anchor = elementAnchor(element, textIndex());\n if (anchor === null) {\n return;\n }\n mode = { elements: false, text: mode.text };\n hover = null;\n setCursor(false);\n draw();\n tell(M.selected, { anchor, rect: box(elementRect.call(element)) });\n }, true);\n window.addEventListener(\"keydown\", (event) => {\n if (mode.elements && event.key === \"Escape\") {\n event.preventDefault();\n event.stopImmediatePropagation();\n mode = { elements: false, text: mode.text };\n hover = null;\n setCursor(false);\n draw();\n tell(M.cancelled, {});\n }\n }, true);\n\n // Selecting text: each selection that settles, and its clearing; again after a scroll.\n let reported = null;\n let selectionTimer = 0;\n const reportSelection = (again) => {\n if (!mode.text) {\n return;\n }\n const selection = selectionOf.call(document);\n if (selection === null || selection.isCollapsed || selection.rangeCount === 0) {\n if (reported !== null) {\n reported = null;\n tell(M.unselected, {});\n }\n return;\n }\n const range = selection.getRangeAt(0);\n if (!document.body || !document.body.contains(range.commonAncestorContainer)) {\n return;\n }\n const anchor = textAnchor(range, textIndex());\n if (anchor === null) {\n return;\n }\n const key = anchor.selectors[1].start + \":\" + anchor.selectors[1].end;\n if (key === reported && !again) {\n return;\n }\n reported = key;\n tell(M.selected, { anchor, rect: box(rangeRect.call(range)) });\n };\n document.addEventListener(\"selectionchange\", () => {\n if (mode.text) {\n clearTimeout(selectionTimer);\n selectionTimer = setTimeout(() => reportSelection(false), 250);\n }\n });\n let scrollTimer = 0;\n window.addEventListener(\"scroll\", () => {\n if (reported !== null) {\n clearTimeout(scrollTimer);\n scrollTimer = setTimeout(() => reportSelection(true), 150);\n }\n }, true);\n\n window.addEventListener(\"message\", (event) => {\n if (event.source !== window.parent || plan.origins.indexOf(event.origin) === -1) {\n return;\n }\n const data = event.data;\n if (data === null || typeof data !== \"object\" || data.jsonrpc !== \"2.0\" || typeof data.method !== \"string\") {\n return;\n }\n const params = data.params !== null && typeof data.params === \"object\" ? data.params : {};\n switch (data.method) {\n case M.start:\n mode = { elements: params.elements === true, text: params.text === true };\n hover = null;\n reported = null;\n setCursor(mode.elements);\n draw();\n reportSelection(false);\n break;\n case M.stop:\n stop();\n break;\n case M.show:\n marks = (Array.isArray(params.marks) ? params.marks : [])\n .slice(0, LIMIT.marks)\n .filter((mark) => mark && typeof mark.id === \"string\" && mark.anchor && Array.isArray(mark.anchor.selectors))\n .map((mark) => ({ id: mark.id, anchor: mark.anchor, found: null, state: null }));\n if (typeof params.active === \"string\") {\n active = params.active;\n }\n if (!marks.some((mark) => mark.id === active)) {\n active = null;\n }\n scheduleAnchor(true);\n break;\n case M.focus:\n focus(String(params.id));\n break;\n case M.clear:\n pendingFocus = null;\n marks = [];\n active = null;\n draw();\n break;\n default:\n break;\n }\n });\n })();\n }`;var kt=String.raw`(() => {\n \"use strict\";\n const plan = __PLAN__;\n // The embedding page's nonce, where it gave one (a srcdoc frame inherits its policy): every\n // script the shell runs for the content carries it.\n const nonce = document.currentScript && document.currentScript.nonce ? document.currentScript.nonce : \"\";\n const declared = (name) => Object.prototype.hasOwnProperty.call(plan.capabilities, name);\n // Fixed in place: content can neither restore what is removed nor replace what is wrapped.\n const lock = (target, name, value) => {\n try {\n Object.defineProperty(target, name, { configurable: false, writable: false, value });\n } catch (_) {}\n };\n\n if (plan.storage === \"memory\") {\n // An opaque origin has no storage: a map stands in, for as long as the frame lives.\n const store = () => {\n const items = new Map();\n return {\n getItem: (key) => (items.has(String(key)) ? items.get(String(key)) : null),\n setItem: (key, value) => void items.set(String(key), String(value)),\n removeItem: (key) => void items.delete(String(key)),\n clear: () => items.clear(),\n key: (index) => Array.from(items.keys())[index] ?? null,\n get length() {\n return items.size;\n },\n };\n };\n for (const name of [\"localStorage\", \"sessionStorage\"]) {\n try {\n Object.defineProperty(window, name, { configurable: true, value: store() });\n } catch (_) {}\n }\n }\n\n // WebRTC leaves the frame outside connect-src. Only RTCPeerConnection (and its prefixed alias)\n // opens a connection; the rest are value types, removed too so nothing is assembled from them.\n for (const name of Object.getOwnPropertyNames(window)) {\n if (/^(RTC|webkitRTC)/.test(name)) {\n lock(window, name, undefined);\n }\n }\n\n // No nested frames (each would be a fresh realm with WebRTC intact), no resource hints and no\n // refreshes (they reach the network outside the CSP's fetch directives). Removed as they are\n // added: a mutation observer's microtask runs before a child frame's document loads.\n const FRAMES = \"iframe,frame,frameset,object,embed,portal,fencedframe\";\n const HINTS = 'link[rel~=\"dns-prefetch\" i],link[rel~=\"preconnect\" i],link[rel~=\"prefetch\" i],link[rel~=\"prerender\" i],script[type=\"speculationrules\" i],meta[http-equiv=\"refresh\" i],meta[http-equiv=\"x-dns-prefetch-control\" i]';\n const GUARDED = FRAMES + \",\" + HINTS;\n const guardedRoots = new WeakSet();\n let guardRoot = null;\n const strip = (node) => {\n if (node === null || (node.nodeType !== 1 && node.nodeType !== 9 && node.nodeType !== 11)) {\n return;\n }\n if (node.nodeType === 1 && node.matches(GUARDED)) {\n node.remove();\n return;\n }\n for (const element of Array.from(node.querySelectorAll(GUARDED))) {\n element.remove();\n }\n // Open shadow roots made without attachShadow (declarative ones the parser built elsewhere).\n if (node.nodeType === 1 && node.shadowRoot) {\n guardRoot(node.shadowRoot);\n }\n for (const element of Array.from(node.querySelectorAll(\"*\"))) {\n if (element.shadowRoot) {\n guardRoot(element.shadowRoot);\n }\n }\n };\n const frameGuard = new MutationObserver((records) => {\n for (const record of records) {\n for (const node of Array.from(record.addedNodes)) {\n strip(node);\n }\n }\n });\n guardRoot = (root) => {\n if (guardedRoots.has(root)) {\n return;\n }\n guardedRoots.add(root);\n strip(root);\n frameGuard.observe(root, { childList: true, subtree: true });\n };\n guardRoot(document);\n\n // Every shadow root content makes, open or closed, is guarded as it is made.\n const attachShadow = Element.prototype.attachShadow;\n lock(Element.prototype, \"attachShadow\", function (init) {\n const root = attachShadow.call(this, init);\n guardRoot(root);\n return root;\n });\n\n // The parser builds declarative shadow roots (template shadowrootmode) without attachShadow, and\n // a closed one is out of the guard's reach. Fragment parsing doesn't build them, so the entry\n // points that would are given fragment parsing's behavior, and a document can't be rewritten.\n const parseInert = (html) => {\n const template = document.createElement(\"template\");\n template.innerHTML = String(html);\n return template.content;\n };\n for (const proto of [Element.prototype, typeof ShadowRoot === \"function\" ? ShadowRoot.prototype : null]) {\n if (proto !== null && \"setHTMLUnsafe\" in proto) {\n lock(proto, \"setHTMLUnsafe\", function (html) {\n this.innerHTML = String(html);\n });\n }\n }\n if (typeof Document.parseHTMLUnsafe === \"function\") {\n lock(Document, \"parseHTMLUnsafe\", (html) => new DOMParser().parseFromString(String(html), \"text/html\"));\n }\n const noRewrite = function () {\n throw new Error(\"document.open and document.write aren't available here: build the page with DOM methods\");\n };\n for (const name of [\"open\", \"write\", \"writeln\"]) {\n lock(Document.prototype, name, noRewrite);\n }\n\n // Some engines act on a hint the moment its element is connected or changed (WebKit opens a\n // preconnect then, outside the CSP), before the observer's microtask. So every way to connect a\n // node drops guarded elements first, synchronously, and a connected link or meta can't be\n // changed into one. The observer stays as the backstop for anything these miss.\n const admit = (node) => {\n if (node === null || typeof node !== \"object\" || typeof node.nodeType !== \"number\") {\n return true;\n }\n if (node.nodeType === 1 && node.matches(GUARDED)) {\n return false;\n }\n strip(node);\n return true;\n };\n const admitted = (args) => args.map((arg) => (admit(arg) ? arg : document.createTextNode(\"\")));\n const wrapInsert = (proto, name, positions) => {\n const original = proto && proto[name];\n if (typeof original !== \"function\") {\n return;\n }\n lock(proto, name, function (...args) {\n const checked = positions === \"all\" ? admitted(args) : args.map((arg, index) => (positions.indexOf(index) !== -1 && !admit(arg) ? document.createTextNode(\"\") : arg));\n return original.apply(this, checked);\n });\n };\n for (const proto of [Node.prototype]) {\n wrapInsert(proto, \"appendChild\", [0]);\n wrapInsert(proto, \"insertBefore\", [0]);\n wrapInsert(proto, \"replaceChild\", [0]);\n }\n for (const proto of [Element.prototype, Document.prototype, DocumentFragment.prototype]) {\n for (const name of [\"append\", \"prepend\", \"replaceChildren\"]) {\n wrapInsert(proto, name, \"all\");\n }\n }\n for (const proto of [Element.prototype, CharacterData.prototype, DocumentType.prototype]) {\n for (const name of [\"before\", \"after\", \"replaceWith\"]) {\n wrapInsert(proto, name, \"all\");\n }\n }\n wrapInsert(Element.prototype, \"insertAdjacentElement\", [1]);\n wrapInsert(Range.prototype, \"insertNode\", [0]);\n wrapInsert(Range.prototype, \"surroundContents\", [0]);\n\n // Markup parsed in place: parsed first in a detached element of the same kind (so it parses as it\n // would in place, and nothing in it is connected yet), guarded, then moved in.\n const accessor = (proto, name) => (proto ? Object.getOwnPropertyDescriptor(proto, name) : undefined);\n const contextFor = (element) => {\n if (element === null || element.nodeType !== 1) {\n return document.createElement(\"div\");\n }\n // A fresh element of the same kind; a custom element's own class is not run again.\n const name = element.localName.indexOf(\"-\") === -1 ? element.localName : \"div\";\n return document.createElementNS(element.namespaceURI, name);\n };\n const innerHTMLs = [accessor(Element.prototype, \"innerHTML\"), accessor(typeof ShadowRoot === \"function\" ? ShadowRoot.prototype : null, \"innerHTML\")];\n const setInner = (innerHTMLs[0] || innerHTMLs[1]).set;\n const parseIn = (contextElement, html) => {\n const box = contextFor(contextElement);\n setInner.call(box, String(html));\n strip(box);\n return Array.from(box.childNodes);\n };\n [Element.prototype, typeof ShadowRoot === \"function\" ? ShadowRoot.prototype : null].forEach((proto, index) => {\n const descriptor = innerHTMLs[index];\n if (!proto || !descriptor || !descriptor.set) {\n return;\n }\n Object.defineProperty(proto, \"innerHTML\", {\n configurable: false,\n enumerable: descriptor.enumerable,\n get: descriptor.get,\n set(html) {\n if (this.nodeType === 1 && this.localName === \"template\") {\n descriptor.set.call(this, html);\n return;\n }\n this.replaceChildren(...parseIn(this.nodeType === 11 ? this.host || null : this, html));\n },\n });\n });\n const outer = accessor(Element.prototype, \"outerHTML\");\n if (outer && outer.set) {\n Object.defineProperty(Element.prototype, \"outerHTML\", {\n configurable: false,\n enumerable: outer.enumerable,\n get: outer.get,\n set(html) {\n const parent = this.parentNode;\n if (parent === null || parent.nodeType === 9) {\n outer.set.call(this, html);\n return;\n }\n this.replaceWith(...parseIn(parent.nodeType === 1 ? parent : null, html));\n },\n });\n }\n const insertAdjacentHTML = Element.prototype.insertAdjacentHTML;\n lock(Element.prototype, \"insertAdjacentHTML\", function (position, html) {\n insertAdjacentHTML.call(this, position, \"\");\n const where = String(position).toLowerCase();\n const outside = where === \"beforebegin\" || where === \"afterend\";\n const nodes = parseIn(outside ? this.parentElement : this, html);\n if (where === \"beforebegin\") {\n this.before(...nodes);\n } else if (where === \"afterbegin\") {\n this.prepend(...nodes);\n } else if (where === \"beforeend\") {\n this.append(...nodes);\n } else {\n this.after(...nodes);\n }\n });\n if (typeof Element.prototype.setHTML === \"function\") {\n lock(Element.prototype, \"setHTML\", function (html) {\n this.innerHTML = String(html);\n });\n }\n // insertHTML parses markup outside these guards; copy, cut and paste reach the clipboard (P051).\n const REFUSED_COMMANDS = [\"inserthtml\", \"copy\", \"cut\", \"paste\"];\n const execCommand = Document.prototype.execCommand;\n if (typeof execCommand === \"function\") {\n lock(Document.prototype, \"execCommand\", function (command, ...rest) {\n return REFUSED_COMMANDS.indexOf(String(command).toLowerCase()) !== -1 ? false : execCommand.call(this, command, ...rest);\n });\n }\n\n // The clipboard is the host's to write (P051): content can neither write nor read it. A copy\n // the person makes (their keys, their menu) copies their selection as the browser makes it: no\n // copy or cut listener of the content's runs, so none can swap what goes on the clipboard.\n const noClipboard = function () {\n return Promise.reject(new DOMException(\"Content can't use the clipboard here\" + (declared(\"copyText\") ? \": call copyText(text) from a click\" : \"\"), \"NotAllowedError\"));\n };\n if (typeof Clipboard === \"function\") {\n for (const name of [\"write\", \"writeText\", \"read\", \"readText\"]) {\n if (typeof Clipboard.prototype[name] === \"function\") {\n lock(Clipboard.prototype, name, noClipboard);\n }\n }\n }\n for (const type of [\"copy\", \"cut\"]) {\n window.addEventListener(type, (event) => event.stopImmediatePropagation(), true);\n }\n\n // A connected link or meta can't become a guarded one: the change is tried on a detached copy\n // first, and if the copy would be guarded, the element leaves the document before it changes.\n const watched = (element) => element && element.nodeType === 1 && (element.localName === \"link\" || element.localName === \"meta\");\n const beforeChange = (element, change) => {\n if (!watched(element) || !element.isConnected) {\n return;\n }\n const copy = element.cloneNode(false);\n try {\n change(copy);\n } catch (_) {\n return;\n }\n if (copy.matches(GUARDED)) {\n element.remove();\n }\n };\n const guardMethod = (proto, name, change) => {\n const original = proto && proto[name];\n if (typeof original !== \"function\") {\n return;\n }\n lock(proto, name, function (...args) {\n beforeChange(this, (copy) => change(copy, args, original));\n return original.apply(this, args);\n });\n };\n for (const name of [\"setAttribute\", \"setAttributeNS\", \"toggleAttribute\", \"removeAttribute\", \"removeAttributeNS\"]) {\n guardMethod(Element.prototype, name, (copy, args, original) => original.apply(copy, args));\n }\n for (const name of [\"setAttributeNode\", \"setAttributeNodeNS\"]) {\n guardMethod(Element.prototype, name, (copy, args) => copy.setAttributeNS(args[0].namespaceURI, args[0].name, args[0].value));\n }\n for (const [proto, name] of [[Attr.prototype, \"value\"], [Node.prototype, \"nodeValue\"], [Node.prototype, \"textContent\"]]) {\n const descriptor = accessor(proto, name);\n if (!descriptor || !descriptor.set) {\n continue;\n }\n Object.defineProperty(proto, name, {\n configurable: false,\n enumerable: descriptor.enumerable,\n get: descriptor.get,\n set(value) {\n if (this.nodeType === 2 && this.ownerElement) {\n const attribute = this;\n beforeChange(attribute.ownerElement, (copy) => copy.setAttributeNS(attribute.namespaceURI, attribute.name, String(value)));\n }\n descriptor.set.call(this, value);\n },\n });\n }\n // Attribute maps and token lists don't name their element: remember it when content gets one.\n const owners = new WeakMap();\n const remember = (proto, name) => {\n const descriptor = accessor(proto, name);\n if (!descriptor || !descriptor.get) {\n return;\n }\n Object.defineProperty(proto, name, {\n configurable: false,\n enumerable: descriptor.enumerable,\n get() {\n const value = descriptor.get.call(this);\n if (value !== null && typeof value === \"object\") {\n owners.set(value, this);\n }\n return value;\n },\n // relList = \"…\" forwards to the list's value, natively: guarded here instead.\n set: descriptor.set\n ? function (value) {\n beforeChange(this, (copy) => descriptor.set.call(copy, value));\n descriptor.set.call(this, value);\n }\n : undefined,\n });\n };\n remember(Element.prototype, \"attributes\");\n for (const proto of [\n typeof HTMLLinkElement === \"function\" ? HTMLLinkElement.prototype : null,\n typeof HTMLMetaElement === \"function\" ? HTMLMetaElement.prototype : null,\n ]) {\n remember(proto, \"relList\");\n for (const name of Object.getOwnPropertyNames(proto || {})) {\n const descriptor = accessor(proto, name);\n if (descriptor && descriptor.set && name !== \"relList\") {\n Object.defineProperty(proto, name, {\n configurable: false,\n enumerable: descriptor.enumerable,\n get: descriptor.get,\n set(value) {\n beforeChange(this, (copy) => descriptor.set.call(copy, value));\n descriptor.set.call(this, value);\n },\n });\n }\n }\n }\n for (const name of [\"setNamedItem\", \"setNamedItemNS\", \"removeNamedItem\", \"removeNamedItemNS\"]) {\n const original = NamedNodeMap.prototype[name];\n if (typeof original !== \"function\") {\n continue;\n }\n lock(NamedNodeMap.prototype, name, function (...args) {\n beforeChange(owners.get(this), (copy) => {\n if (name.indexOf(\"set\") === 0) {\n copy.setAttributeNS(args[0].namespaceURI, args[0].name, args[0].value);\n } else {\n copy.removeAttribute(args[args.length - 1]);\n }\n });\n return original.apply(this, args);\n });\n }\n const tokens = typeof DOMTokenList === \"function\" ? DOMTokenList.prototype : null;\n for (const name of [\"add\", \"remove\", \"replace\", \"toggle\"]) {\n const original = tokens && tokens[name];\n if (typeof original === \"function\") {\n lock(tokens, name, function (...args) {\n const element = owners.get(this);\n beforeChange(element, (copy) => original.apply(copy.relList, args));\n return original.apply(this, args);\n });\n }\n }\n const tokenValue = accessor(tokens, \"value\");\n if (tokenValue && tokenValue.set) {\n Object.defineProperty(tokens, \"value\", {\n configurable: false,\n enumerable: tokenValue.enumerable,\n get: tokenValue.get,\n set(value) {\n beforeChange(owners.get(this), (copy) => tokenValue.set.call(copy.relList, value));\n tokenValue.set.call(this, value);\n },\n });\n }\n\n let root = document.getElementById(\"porthole-root\");\n let reported = 0;\n const report = (message) => {\n if (!declared(\"reportError\") || reported >= plan.maxErrorReports) {\n return;\n }\n reported += 1;\n send({ method: \"notifications/message\", params: { level: \"error\", logger: \"porthole\", data: String(message).slice(0, 2000) } });\n };\n const send = (message) => {\n if (plan.protocol === \"shell\" && window.parent !== window) {\n // Nothing secret is ever said from here, so any parent may hear it; what it hears is the\n // content's word, which the host gates before it acts on it.\n window.parent.postMessage(Object.assign({ jsonrpc: \"2.0\" }, message), \"*\");\n }\n };\n\n // A parsed tree's scripts are held (each replaced by a numbered marker) and run later, in order,\n // as the page's parser would run them: each made again, live, in its marker's place, and each\n // external one loaded before the next runs. Markers are found in the live document by number, so\n // this works the same for a fragment that was moved in and a document that was imported.\n let held = 0;\n const holdScripts = (tree, owner) => {\n const scripts = [];\n for (const script of Array.from(tree.querySelectorAll(\"script\"))) {\n const marker = owner.createComment(\"porthole-script:\" + held);\n held += 1;\n script.replaceWith(marker);\n scripts.push({ script, id: marker.data });\n }\n return scripts;\n };\n const markers = () => {\n const found = new Map();\n const walker = document.createTreeWalker(document, NodeFilter.SHOW_COMMENT);\n for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {\n if (node.data.indexOf(\"porthole-script:\") === 0) {\n found.set(node.data, node);\n }\n }\n return found;\n };\n const runScripts = async (scripts) => {\n const placed = markers();\n for (const { script, id } of scripts) {\n const marker = placed.get(id);\n if (marker === undefined) {\n continue;\n }\n const live = document.createElement(\"script\");\n for (const attribute of Array.from(script.attributes)) {\n live.setAttribute(attribute.name, attribute.value);\n }\n // A script made by a script is async unless told otherwise: keep the page's order.\n live.async = script.hasAttribute(\"async\");\n if (nonce !== \"\") {\n live.nonce = nonce;\n }\n live.textContent = script.textContent;\n const external = live.hasAttribute(\"src\") && !live.async && live.type !== \"module\";\n const loaded = external\n ? new Promise((resolve) => {\n live.addEventListener(\"load\", resolve);\n live.addEventListener(\"error\", () => {\n report(\"Couldn't load \" + live.src);\n resolve();\n });\n })\n : null;\n marker.replaceWith(live);\n if (loaded !== null) {\n await loaded;\n }\n }\n };\n // The page's own load events, for code that waits for them: its scripts ran after the shell's\n // document had loaded, so they fire again, once, after them.\n const announceLoaded = () => {\n document.dispatchEvent(new Event(\"DOMContentLoaded\", { bubbles: true }));\n window.dispatchEvent(new Event(\"load\"));\n };\n\n // Whether the content is in place: a fragment or page the shell draws, once drawn whole; a\n // view the plan carries, once rendered; a view that is the document itself, from the start.\n const contentHooks = [];\n let contentIn = typeof plan.document !== \"string\" && plan.protocol !== \"shell\";\n const contentIsIn = () => contentIn;\n const whenContentIsIn = (run) => {\n if (contentIn) {\n run();\n } else {\n contentHooks.push(run);\n }\n };\n const contentArrived = () => {\n if (!contentIn) {\n contentIn = true;\n for (const run of contentHooks.splice(0)) {\n run();\n }\n }\n };\n\n // A fragment takes the person's scheme; a whole document only if it declares that it supports\n // both (or the config says always), else it shows as its author styled it (P039).\n let lastContext = null;\n let themed = plan.content !== \"document\";\n const schemeFollows = () => {\n const root = document.documentElement;\n const theme = lastContext && lastContext.theme;\n if (themed && (theme === \"light\" || theme === \"dark\")) {\n root.style.colorScheme = theme;\n root.setAttribute(\"data-theme\", theme);\n } else {\n root.style.removeProperty(\"color-scheme\");\n root.removeAttribute(\"data-theme\");\n }\n };\n // A whole document, parsed inert (no scripts run, no declarative shadow roots built), guarded,\n // imported in place of the shell's, then its scripts run in order. The theme on the root stays.\n const renderDocument = async (html) => {\n const parsed = new DOMParser().parseFromString(String(html), \"text/html\");\n strip(parsed);\n const scripts = holdScripts(parsed, parsed);\n const element = document.documentElement;\n for (const attribute of Array.from(parsed.documentElement.attributes)) {\n if (attribute.name !== \"style\") {\n element.setAttribute(attribute.name, attribute.value);\n }\n }\n document.head.replaceChildren(...Array.from(parsed.head.childNodes, (node) => document.importNode(node, true)));\n document.body.replaceWith(document.importNode(parsed.body, true));\n root = null;\n const declaredScheme = parsed.querySelector('meta[name=\"color-scheme\" i]');\n themed = plan.themeDocuments !== \"never\" && (plan.themeDocuments === \"always\" || (declaredScheme !== null && /\\bdark\\b/i.test(declaredScheme.getAttribute(\"content\") || \"\")));\n schemeFollows();\n await runScripts(scripts);\n announceLoaded();\n contentArrived();\n };\n\n // A document the plan carries (a served page, an MCP Apps view) is rendered once the shell's own\n // document has loaded, whichever protocol the frame speaks.\n const whenLoaded = (run) => {\n if (document.readyState === \"complete\") {\n run();\n } else {\n window.addEventListener(\"load\", run, { once: true });\n }\n };\n\n __ANNOTATE__\n\n if (plan.protocol !== \"shell\") {\n // A view that speaks for itself.\n if (typeof plan.document === \"string\") {\n whenLoaded(() => void renderDocument(plan.document));\n }\n return;\n }\n\n // Content in this window may speak MCP Apps too (the official App SDK numbers its requests):\n // the shell's ids are its own strings, so neither takes the other's answers.\n let nextId = 1;\n const pending = new Map();\n const request = (method, params) =>\n new Promise((resolve, reject) => {\n const id = \"porthole-shell-\" + nextId++;\n pending.set(id, { resolve, reject });\n send({ id, method, params });\n });\n const notify = (method, params) => send({ method, params });\n\n const themeNames = new Set(plan.themeVariables);\n // What the content was last told of (its scheme and values): the theme it starts with is no\n // change, and a host context that changes neither (a host re-sending it) is none either.\n let announced = null;\n const applyTheme = (context) => {\n if (context === null || typeof context !== \"object\") {\n return;\n }\n // The spec's variables, and Porthole's own beside them (its own-prefixed field).\n const own = context[\"porthole/styles\"];\n const applied = [];\n for (const variables of [context.styles && context.styles.variables, own && own.variables]) {\n if (variables === null || typeof variables !== \"object\") {\n continue;\n }\n for (const name of Object.keys(variables)) {\n const value = variables[name];\n if (themeNames.has(name) && typeof value === \"string\") {\n document.documentElement.style.setProperty(name, value);\n applied.push(name + \":\" + value);\n }\n }\n }\n lastContext = context;\n schemeFollows();\n const now = JSON.stringify([context.theme, applied.sort()]);\n if (announced === null) {\n announced = now;\n return;\n }\n if (now !== announced) {\n announced = now;\n window.dispatchEvent(new CustomEvent(plan.themeEvent, { detail: { theme: context.theme } }));\n }\n };\n\n // No size before there is something to size: an empty shell's height would make the host\n // forget the height it remembered for this display, and the frame would jump.\n let drawn = false;\n let lastHeight = -1;\n const measure = () => {\n if (!declared(\"resize\") || !drawn) {\n return;\n }\n const box = root !== null && root.isConnected ? root : document.documentElement;\n const rect = box.getBoundingClientRect();\n const height = Math.ceil(box === root ? Math.max(rect.height, root.scrollHeight) : rect.height);\n if (height !== lastHeight) {\n lastHeight = height;\n notify(\"ui/notifications/size-changed\", { width: Math.ceil(rect.width), height });\n }\n };\n let scheduled = false;\n const schedule = () => {\n if (!scheduled) {\n scheduled = true;\n requestAnimationFrame(() => {\n scheduled = false;\n measure();\n });\n }\n };\n\n const gestured = (name) => {\n const capability = plan.capabilities[name];\n const activation = navigator.userActivation;\n return !(capability && capability.userActivation) || !activation || activation.isActive;\n };\n const refuse = (message) => Promise.reject(new Error(message));\n if (declared(\"sendPrompt\")) {\n lock(window, \"sendPrompt\", (text) => {\n if (!gestured(\"sendPrompt\")) {\n return refuse(\"sendPrompt needs a click: call it from a button's handler\");\n }\n const words = String(text);\n if (words.trim() === \"\" || words.length > plan.maxPromptChars) {\n return refuse(\"sendPrompt takes 1 to \" + plan.maxPromptChars + \" characters\");\n }\n return request(\"ui/message\", { role: \"user\", content: [{ type: \"text\", text: words }] }).then(\n (result) => !(result && result.isError),\n );\n });\n }\n if (declared(\"copyText\")) {\n lock(window, \"copyText\", (text) => {\n if (!gestured(\"copyText\")) {\n return refuse(\"copyText needs a click: call it from a button's handler\");\n }\n const words = String(text);\n if (words === \"\" || words.length > plan.maxCopyChars) {\n return refuse(\"copyText takes 1 to \" + plan.maxCopyChars + \" characters\");\n }\n return request(\"porthole/copy-text\", { text: words }).then((result) => !(result && result.isError));\n });\n }\n if (declared(\"openLink\")) {\n lock(window, \"openLink\", (url) => {\n if (!gestured(\"openLink\")) {\n return refuse(\"openLink needs a click: call it from a link's or button's handler\");\n }\n return request(\"ui/open-link\", { url: String(url) }).then((result) => !(result && result.isError));\n });\n }\n\n window.addEventListener(\"error\", (event) => {\n const error = event.error;\n const where = event.lineno ? \" (line \" + event.lineno + \")\" : \"\";\n // V8's stack starts with the message; WebKit's and Firefox's don't, so it goes first there.\n const stack = error && error.stack ? String(error.stack).split(\"\\n\").slice(0, 3).join(\" \") : \"\";\n const said = error && error.message !== undefined ? String(error.name || \"Error\") + \": \" + String(error.message) : event.message;\n report(stack === \"\" ? said + where : stack.indexOf(String(error.message)) === -1 ? said + \" \" + stack : stack);\n });\n window.addEventListener(\"unhandledrejection\", (event) => {\n const reason = event.reason;\n report(\"Unhandled rejection: \" + (reason && reason.message ? reason.message : String(reason)));\n });\n document.addEventListener(\"securitypolicyviolation\", (event) => {\n report(\"Blocked by the sandbox: \" + (event.blockedURI || \"inline\") + \" (\" + event.effectiveDirective + \")\");\n });\n // A link never navigates this frame: an http(s) one opens outside, through the host, and an\n // in-page anchor still jumps. SVG links (href or xlink:href) and image-map areas too.\n document.addEventListener(\n \"click\",\n (event) => {\n const target = event.target;\n const link = target && target.closest ? target.closest(\"a, area\") : null;\n if (link === null) {\n return;\n }\n const href = link.getAttribute(\"href\") || link.getAttributeNS(\"http://www.w3.org/1999/xlink\", \"href\") || \"\";\n if (href === \"\" || href.charAt(0) === \"#\") {\n return;\n }\n event.preventDefault();\n let url = \"\";\n try {\n url = new URL(href, document.baseURI).href;\n } catch (_) {}\n if (/^https?:/i.test(url) && typeof window.openLink === \"function\") {\n window.openLink(url).catch(() => {});\n }\n },\n true,\n );\n if (typeof ResizeObserver === \"function\") {\n const sizes = new ResizeObserver(schedule);\n sizes.observe(document.documentElement);\n if (root !== null) {\n sizes.observe(root);\n }\n }\n window.addEventListener(\"load\", schedule);\n\n let rendered = false;\n\n // The content so far, drawn inert: what runs, loads a frame or navigates is left out, and every\n // attribute that runs code (on…) or names a javascript: URL. Parsed in a template, where nothing\n // runs; its scripts run only in the whole content, once (render).\n const INERT = \"script,iframe,frame,frameset,object,embed,applet,portal,fencedframe,meta,base,noscript,link:not([rel~=stylesheet i])\";\n const inert = (fragment) => {\n for (const element of Array.from(fragment.querySelectorAll(INERT))) {\n element.remove();\n }\n for (const element of Array.from(fragment.querySelectorAll(\"*\"))) {\n for (const attribute of Array.from(element.attributes)) {\n const name = attribute.name.toLowerCase();\n if (name.startsWith(\"on\") || /^\\s*javascript:/i.test(attribute.value)) {\n element.removeAttributeNode(attribute);\n }\n }\n }\n return fragment;\n };\n // Change only what changed: what was drawn stays (an image doesn't load again, an animation\n // doesn't start over) as the content grows at its end.\n const morph = (into, from) => {\n const wanted = Array.from(from.childNodes);\n wanted.forEach((want, index) => {\n const have = into.childNodes[index];\n if (have === undefined) {\n into.appendChild(want);\n } else if (have.nodeType !== want.nodeType || have.nodeName !== want.nodeName || have.namespaceURI !== want.namespaceURI) {\n into.replaceChild(want, have);\n } else if (want.nodeType === 1) {\n for (const attribute of Array.from(have.attributes)) {\n if (!want.hasAttributeNS(attribute.namespaceURI, attribute.localName)) {\n have.removeAttributeNode(attribute);\n }\n }\n for (const attribute of Array.from(want.attributes)) {\n if (have.getAttributeNS(attribute.namespaceURI, attribute.localName) !== attribute.value) {\n have.setAttributeNS(attribute.namespaceURI, attribute.name, attribute.value);\n }\n }\n morph(have, want);\n } else if (have.nodeValue !== want.nodeValue) {\n have.nodeValue = want.nodeValue;\n }\n });\n while (into.childNodes.length > wanted.length) {\n into.removeChild(into.lastChild);\n }\n };\n let drafted = false;\n const draft = (input) => {\n if (rendered || root === null || input === null || typeof input !== \"object\" || plan.content === \"document\") {\n return;\n }\n morph(root, inert(parseInert(input.html || \"\")));\n drafted = true;\n drawn = true;\n schedule();\n };\n\n const SVG = /^\\s*(<\\?xml[\\s\\S]*?\\?>\\s*)?(<!--[\\s\\S]*?-->\\s*)*<svg[\\s>]/i;\n const render = async (input) => {\n if (rendered || input === null || typeof input !== \"object\") {\n return;\n }\n rendered = true;\n drawn = true;\n const html = String(input.html || \"\");\n if (plan.content === \"document\") {\n await renderDocument(html);\n schedule();\n return;\n }\n if (root === null) {\n return;\n }\n if (drafted) {\n // The whole content replaces its draft, and runs as if drawn first.\n root.textContent = \"\";\n }\n // SVG goes in as drawn: its scripts, if any, stay inert.\n const fragment = parseInert(html);\n strip(fragment);\n const scripts = SVG.test(html) ? [] : holdScripts(fragment, document);\n root.appendChild(fragment);\n schedule();\n await runScripts(scripts);\n announceLoaded();\n contentArrived();\n schedule();\n };\n\n const receive = (data) => {\n if (data === null || typeof data !== \"object\" || data.jsonrpc !== \"2.0\") {\n return;\n }\n if (data.id !== undefined && data.method === undefined) {\n const waiting = pending.get(data.id);\n if (waiting !== undefined) {\n pending.delete(data.id);\n if (data.error) {\n waiting.reject(new Error(String(data.error.message || \"refused\")));\n } else {\n waiting.resolve(data.result);\n }\n }\n return;\n }\n const params = data.params !== null && typeof data.params === \"object\" ? data.params : {};\n switch (data.method) {\n case \"ui/notifications/tool-input-partial\":\n draft(params.arguments);\n break;\n case \"ui/notifications/tool-input\":\n void render(params.arguments);\n break;\n case \"ui/notifications/host-context-changed\":\n applyTheme(params);\n break;\n case \"ui/resource-teardown\":\n case \"ping\":\n if (data.id !== undefined) {\n send({ id: data.id, result: {} });\n }\n break;\n default:\n if (data.id !== undefined) {\n send({ id: data.id, error: { code: -32601, message: String(data.method) + \" isn't offered here\" } });\n }\n break;\n }\n };\n window.addEventListener(\"message\", (event) => {\n if (event.source !== window.parent || plan.origins.indexOf(event.origin) === -1) {\n return;\n }\n receive(event.data);\n });\n if (typeof plan.document === \"string\") {\n whenLoaded(() => void render({ html: plan.document }));\n }\n\n // Ask until answered: the host may start listening after this runs.\n let initialized = false;\n let tries = 0;\n const initialize = () => {\n if (initialized || tries >= 40) {\n return;\n }\n tries += 1;\n request(\"ui/initialize\", {\n protocolVersion: plan.protocolVersion,\n appInfo: { name: \"porthole-shell\", version: \"1\" },\n appCapabilities: {},\n }).then((result) => {\n if (initialized) {\n return;\n }\n initialized = true;\n applyTheme(result && result.hostContext);\n notify(\"ui/notifications/initialized\", {});\n schedule();\n }, () => {});\n setTimeout(initialize, 250);\n };\n initialize();\n})();`;var wn=/^[A-Za-z0-9+/_=-]{8,256}$/u,bn=e=>e.replace(/&/gu,\"&amp;\").replace(/\"/gu,\"&quot;\").replace(/</gu,\"&lt;\"),xn=e=>e.replace(/&/gu,\"&amp;\").replace(/</gu,\"&lt;\").replace(/>/gu,\"&gt;\"),vn=e=>JSON.stringify(e).replace(/</gu,\"\\\\u003c\").replace(/\\u2028/gu,\"\\\\u2028\").replace(/\\u2029/gu,\"\\\\u2029\"),kn=`:root { color-scheme: light dark; }\nhtml, body { margin: 0; padding: 0; background: transparent; }\nbody {\n font-family: var(--font-sans, system-ui, sans-serif);\n font-size: var(--font-text-md-size, 14px);\n line-height: var(--font-text-md-line-height, 20px);\n color: var(--color-text-primary, CanvasText);\n overflow-wrap: anywhere;\n -webkit-text-size-adjust: 100%;\n}\n#porthole-root { display: flow-root; }\n#porthole-root > svg { display: block; max-width: 100%; height: auto; }\n:where(button, input, select, textarea) { font: inherit; color: inherit; box-sizing: border-box; }\n:where(button, select, input:is([type=\"button\" i], [type=\"submit\" i], [type=\"reset\" i])) {\n min-height: 44px;\n padding: 0 14px;\n border: var(--border-width-regular, 1px) solid var(--color-border-primary, ButtonBorder);\n border-radius: var(--border-radius-md, 8px);\n background: var(--color-background-secondary, ButtonFace);\n color: var(--color-text-primary, ButtonText);\n cursor: pointer;\n}\n:where(input:not([type]), input:is([type=\"text\" i], [type=\"search\" i], [type=\"number\" i], [type=\"email\" i], [type=\"url\" i], [type=\"tel\" i], [type=\"password\" i], [type=\"date\" i], [type=\"time\" i]), textarea) {\n min-height: 44px;\n padding: 0 10px;\n border: var(--border-width-regular, 1px) solid var(--color-border-primary, FieldText);\n border-radius: var(--border-radius-md, 8px);\n background: var(--color-background-secondary, Field);\n}\n:where(textarea) { padding: 8px 10px; }\n:where(input:is([type=\"checkbox\" i], [type=\"radio\" i], [type=\"range\" i])) { accent-color: var(--color-accent, auto); }\n:where(button, input, select, textarea):focus-visible { outline: 2px solid var(--color-ring-primary, Highlight); outline-offset: 1px; }\n:where(button, input, select, textarea):disabled { color: var(--color-text-disabled, GrayText); cursor: default; }`;function St(e,t,n){for(let s of n.origins){let i=bt(s);if(i!==null)throw new TypeError(`shellDocument: ${i}`)}if(n.nonce!==void 0&&!wn.test(n.nonce))throw new TypeError(\"shellDocument: a nonce is 8 to 256 base64 characters\");let o=n.nonce===void 0?\"\":` nonce=\"${n.nonce}\"`,r=kt.replace(\"__ANNOTATE__\",()=>e.capabilities.annotate===void 0?\"\":vt).replace(\"__PLAN__\",()=>vn({...e,origins:n.origins,...n.document===void 0?{}:{document:n.document}}));return`<!doctype html>\n<html lang=\"en\">\n<head>\n${['<meta charset=\"utf-8\">',n.cspMeta===!1?null:`<meta http-equiv=\"Content-Security-Policy\" content=\"${bn(t)}\">`,'<meta name=\"referrer\" content=\"no-referrer\">','<meta http-equiv=\"x-dns-prefetch-control\" content=\"off\">'].filter(s=>s!==null).join(`\n`)}\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${xn(n.title??\"Content\")}</title>\n<style${o}>\n${kn}\n</style>\n</head>\n<body>\n<div id=\"porthole-root\"></div>\n<script${o}>${r}<\\/script>\n</body>\n</html>\n`}function Ct(e){ot(e);let t=Ke(e),n=Xe(t),o=X(e);return{config:e,cspDirectives:t,csp:n,sandbox:me(e).join(\" \"),allow:Ye(e),referrerPolicy:\"no-referrer\",embedderFrameSources:Qe(e),shell:o,shellDocument:r=>{if(o===null)throw new TypeError(\"url mode has no shell: the frame loads the app's own document\");return St(o,n,r)},guide:r=>ft(e,r),toolDescription:()=>gt(e)}}async function Tt(e,t,n,o,r){let a=await e.locate(t,r);return xt(a,n.contentOrigins,o),{kind:\"url\",url:new URL(a.url).href,origin:a.origin,...a.reports===!0?{reports:!0}:{}}}var ke=\"porthole/notifications/frame-status\";var At=400,Sn=[\"framing\",\"cookies\",\"sign-in\",\"session\",\"upstream\",\"denied\",\"not-found\",\"error\"];function Cn(e){if(e===null||typeof e!=\"object\")return null;let t=e;if(t.jsonrpc!==\"2.0\"||t.method!==ke)return null;let n=t.params;return n===null||typeof n!=\"object\"?null:n.state===\"entering\"?{state:\"entering\"}:n.state!==\"blocked\"?null:{state:\"blocked\",reason:Sn.includes(n.reason)?n.reason:\"error\",...typeof n.status==\"number\"&&Number.isInteger(n.status)?{status:n.status}:{},...typeof n.code==\"string\"&&/^[a-z0-9-]{1,40}$/u.test(n.code)?{code:n.code}:{}}}function Et(e){let{surface:t,source:n,speaks:o}=e,r=n.kind===\"url\"&&n.reports===!0,a=null,s=!1,i=!1,d=0,m=new Set,f=(c,y)=>{let C=setTimeout(()=>{m.delete(C),y()},c);m.add(C)},k=()=>{for(let c of m)clearTimeout(c);m.clear()},p=()=>{k(),u(),l()},v=c=>{a===null?(a=c.state,k(),e.onOutcome(c)):a===\"loaded\"&&c.state===\"blocked\"&&(a=\"blocked\",e.onOutcome(c))},u=t.transport.listen(c=>{s=!0;let y=Cn(c);y?.state===\"entering\"?i=!0:y?.state===\"blocked\"&&v({state:\"blocked\",reason:y.reason??\"error\",...y.status===void 0?{}:{status:y.status},...y.code===void 0?{}:{code:y.code}})}),g=()=>f(At,()=>{s||v({state:\"blocked\",reason:\"framing\"})}),l=t.onLoad(()=>{if(d+=1,a===null){if(o){n.kind===\"url\"&&g();return}if(!r){f(At,()=>v({state:\"loaded\"}));return}i&&d>=2?v({state:\"loaded\"}):i||g()}});return f(e.timeoutMs,()=>v({state:\"timeout\"})),{initialized:()=>v({state:\"loaded\"}),stop:p}}function Rt(e,t,n=window,o){let r=new Set,a=!1,s=d=>{let m=e();if(!(a||m===null||d.source!==m)&&!(d.origin!==t&&(o===void 0||d.origin!==o.origin||!o.accept(d.data))))for(let f of r)f(d.data)};n.addEventListener(\"message\",s);let i=t===\"null\"?\"*\":t;return{send(d){a||e()?.postMessage(d,i)},listen(d){return r.add(d),()=>r.delete(d)},close(){a=!0,r.clear(),n.removeEventListener(\"message\",s)}}}var Tn=e=>e!==null&&typeof e==\"object\"&&e.jsonrpc===\"2.0\"&&e.method===ke,Pt={name:\"web\",createSurface(e,t){let n=e.ownerDocument.createElement(\"iframe\");n.setAttribute(\"sandbox\",t.sandbox),n.setAttribute(\"allow\",t.allow),n.setAttribute(\"referrerpolicy\",t.referrerPolicy),n.setAttribute(\"loading\",\"eager\"),n.title=t.title,n.dataset.portholeFrame=\"\",Object.assign(n.style,{display:\"block\",width:\"100%\",border:\"0\",background:\"transparent\",colorScheme:t.colorScheme,...t.fill===!0?{height:\"100%\",minHeight:`${Math.max(0,Math.round(t.initialHeightPx))}px`}:{height:`${Math.max(0,Math.round(t.initialHeightPx))}px`}});let o=t.source.kind===\"srcdoc\"?\"null\":t.source.origin;t.source.kind===\"srcdoc\"?n.srcdoc=t.source.html:n.src=t.source.url;let r=new Set,a=new Set,s=0;n.addEventListener(\"load\",()=>{s+=1;for(let f of a)f();if(s>1)for(let f of r)f()}),e.append(n);let i=e.ownerDocument.defaultView??window,d=i.origin,m=Rt(()=>n.contentWindow,o,i,o===\"null\"||d===\"null\"||d===o?void 0:{origin:d,accept:Tn});return{transport:m,element:n,setHeight(f){t.fill!==!0&&(n.style.height=`${Math.max(0,Math.round(f))}px`)},setColorScheme(f){n.style.colorScheme=f},userActivation(){let f=i.navigator.userActivation;return f===void 0?void 0:f.isActive},onLoad(f){return a.add(f),()=>a.delete(f)},onNavigated(f){return r.add(f),()=>r.delete(f)},destroy(){r.clear(),a.clear(),m.close(),n.remove()}}}};var $t={invalidRequest:-32600,methodNotFound:-32601,invalidParams:-32602,internal:-32603},je=e=>e!==null&&typeof e==\"object\"&&!Array.isArray(e),Mt=e=>typeof e==\"string\"&&e.length<=256||typeof e==\"number\"&&Number.isSafeInteger(e);function Lt(e){if(!je(e)||e.jsonrpc!==\"2.0\"||e.params!==void 0&&!je(e.params))return null;if(typeof e.method==\"string\")return e.method.length===0||e.method.length>256?null:e.id===void 0||Mt(e.id)?e:null;if(!Mt(e.id)||e.method!==void 0)return null;let t=\"result\"in e,n=\"error\"in e;if(t===n)return null;if(n){let o=e.error;if(!je(o)||typeof o.code!=\"number\"||typeof o.message!=\"string\")return null}return e}var An=new Set([\"error\",\"critical\",\"alert\",\"emergency\"]),En={[P.message]:{capability:\"sendPrompt\",args:e=>({text:Array.isArray(e.content)?e.content.map(t=>{let n=t;return n!==null&&typeof n==\"object\"&&n.type===\"text\"&&typeof n.text==\"string\"?n.text:\"\"}).join(\"\"):void 0})},[P.openLink]:{capability:\"openLink\",args:e=>({url:e.url})},[st]:{capability:\"copyText\",args:e=>({text:e.text})},[P.downloadFile]:{capability:\"downloadFile\",args:e=>({contents:e.contents})},[P.callTool]:{capability:\"callTool\",args:e=>({name:e.name,arguments:e.arguments})},[P.readResource]:{capability:\"readData\",args:e=>({uri:e.uri})},[P.updateModelContext]:{capability:\"setModelContext\",args:e=>({content:e.content,structuredContent:e.structuredContent})}};function Rn(e,t){let n=e===\"sendPrompt\"||e===\"openLink\"||e===\"downloadFile\"||e===\"copyText\";return t.ok?n?{result:t.value===!0?{}:{isError:!0}}:{result:t.value??{}}:n?{result:{isError:!0}}:{error:{code:-32e3,message:`Refused (${t.refusal})`}}}function Pn(e){let t={};return e(\"openLink\")&&(t.openLinks={}),e(\"sendPrompt\")&&(t.message={text:{}}),e(\"downloadFile\")&&(t.downloadFile={}),e(\"callTool\")&&(t.serverTools={}),e(\"readData\")&&(t.serverResources={}),e(\"setModelContext\")&&(t.updateModelContext={text:{}}),e(\"reportError\")&&(t.logging={}),t}var Nt={name:\"porthole-shell\",connect(e){let{transport:t,bridge:n}=e,o=!1,r=!1,a=null,s=null,i=!1,d=1,m=new Map,f=(l,c)=>t.send({jsonrpc:\"2.0\",id:l,...c}),k=(l,c)=>t.send({jsonrpc:\"2.0\",method:l,params:c}),p=()=>{if(!(!o||r||s===null||i)){if(s.partial){a!==s.html&&(a=s.html,k(P.toolInputPartial,{arguments:{html:s.html}}));return}i=!0,k(P.toolInput,{arguments:{html:s.html}})}},v=async l=>{let c=l.params??{};if(l.method===P.initialize){f(l.id,{result:{protocolVersion:fe,hostInfo:e.hostInfo,hostCapabilities:Pn(A=>n.declared(A)),hostContext:e.hostContext()}});return}if(l.method===\"ping\"){f(l.id,{result:{}});return}if(l.method===P.requestDisplayMode){f(l.id,{result:{mode:\"inline\"}});return}let y=En[l.method];if(y===void 0){f(l.id,{error:{code:$t.methodNotFound,message:`${l.method} isn't offered here`}});return}let C=await n.call(y.capability,y.args(c));r||f(l.id,Rn(y.capability,C))},u=(l,c)=>{switch(l){case P.initialized:o||(o=!0,e.emit({type:\"initialized\"}),p());return;case P.sizeChanged:n.call(\"resize\",{height:c.height,width:c.width});return;case P.log:if(An.has(String(c.level))){let y=c.data;n.call(\"reportError\",{message:typeof y==\"string\"?y:JSON.stringify(y??null).slice(0,2e3)})}return;case P.requestTeardown:e.emit({type:\"teardown-requested\"});return;default:return}},g=t.listen(l=>{let c=Lt(l);if(!(c===null||r)){if(\"method\"in c){\"id\"in c?v(c):u(c.method,c.params??{});return}m.get(c.id)?.(c),m.delete(c.id)}});return{setContent(l,c){i||(s={html:l,partial:c?.partial===!0},p())},hostContextChanged(l){o&&!r&&k(P.hostContextChanged,{...l})},teardown(){if(!o||r)return Promise.resolve();let l=`teardown-${d++}`;return new Promise(c=>{let y=setTimeout(()=>{m.delete(l),c()},500);m.set(l,()=>{clearTimeout(y),c()}),t.send({jsonrpc:\"2.0\",id:l,method:P.resourceTeardown,params:{}})})},close(){r=!0,g(),m.clear()}}}};var Mn=15e3,$n=3,Ln=new Set([\"hostContextChanged\",\"teardown\",\"close\"]),Nn={[N.selected]:\"selected\",[N.unselected]:\"unselected\",[N.cancelled]:\"cancelled\",[N.anchored]:\"anchored\"},Ot=e=>e!==null&&typeof e==\"object\"&&!Array.isArray(e),On=new Set(rt);function It(e,t={}){let n=Ct(e);if((e.isolation===\"domain\"||e.isolation===\"external\")&&t.locator===void 0)throw new TypeError(`${e.isolation} isolation needs a locator (HostOptions.locator)`);let o=e.mode!==\"url\",r=t.adapter??Nt,a=t.platform??Pt,s=t.hostInfo??{name:\"porthole\",version:\"0\"};return{compiled:n,mount(i,d){let m={...t.handlers,...d.handlers},f=I(e).filter(h=>H(h).served===\"handler\"&&m[h]===void 0);if(f.length>0)throw new TypeError(`No handler for the declared capabilities: ${f.join(\", \")}`);if(e.isolation!==\"opaque\"&&d.instance===void 0)throw new TypeError(`${e.isolation} isolation needs MountOptions.instance`);let k=new Map,p=(h,b)=>{for(let E of k.get(h)??[])E(b)},v=h=>{p(\"contentError\",{message:h}),p(\"error\",{message:h,source:\"content\"})},u=(h,b)=>{p(\"hostError\",{message:h,kind:b}),p(\"error\",{message:h,source:\"host\"})},g=e.theme.documents===\"never\",l=g?\"light\":d.scheme,c=d.initialHeightPx??0,y=null,C=null,A=!1,Ce=0,ae=0,Te=null,Ae=null,Q=null,V=i.ownerDocument.defaultView,Ee=new Map,ze=e.capabilities.annotate!==void 0,$=null,q=[],z=null,se=!1,U=(h,b)=>{se&&y!==null&&y.transport.send({jsonrpc:\"2.0\",method:h,params:b})},zt=()=>{q.length>0&&U(N.show,{marks:q,...z===null?{}:{active:z}}),$!==null&&U(N.start,{...$})},Ft=(h,b)=>{if(!Ot(h)||h.jsonrpc!==\"2.0\"||\"id\"in h||typeof h.method!=\"string\")return;let E=Nn[h.method];if(E===void 0)return;let R=ue({...Ot(h.params)?h.params:{},type:E});if(R===null){b.call(\"annotate\",null);return}switch(R.type){case\"selected\":{let M=R.anchor.kind;if($===null||!(M===\"element\"?$.elements:$.text))return;M===\"element\"&&($=$.text?{elements:!1,text:!0}:null);break}case\"unselected\":if($?.text!==!0)return;break;case\"cancelled\":if($?.elements!==!0)return;$=$.text?{elements:!1,text:!0}:null;break;case\"anchored\":{let M=new Set(q.map(ee=>ee.id)),T=R.results.filter(ee=>M.has(ee.id));if(T.length===0)return;R={type:\"anchored\",results:T};break}}b.call(\"annotate\",R)},Z=h=>{if(!ze)throw new TypeError(`annotations.${h}: the config doesn't declare annotate`)},Wt={start(h){Z(\"start\"),$=Ve(h),U(N.start,{...$})},stop(){Z(\"stop\"),$=null,U(N.stop,{})},show(h){Z(\"show\"),q=Ge(h),z!==null&&!q.some(b=>b.id===z)&&(z=null),U(N.show,{marks:q,...z===null?{}:{active:z}})},focus(h){if(Z(\"focus\"),!q.some(b=>b.id===h))throw new TypeError(`annotations.focus: no mark ${JSON.stringify(h)} is shown`);z=h,U(N.focus,{id:h})},clear(){Z(\"clear\"),q=[],z=null,U(N.clear,{})}},ie=()=>{let h=i.getBoundingClientRect().width,b=it(e.theme,l,t.theme?.(l)),E={},R={};for(let[M,T]of Object.entries(b))(On.has(M)?E:R)[M]=T;return{theme:l,styles:{variables:E},...Object.keys(R).length===0?{}:{[at]:{variables:R}},displayMode:\"inline\",availableDisplayModes:[\"inline\"],...h>0?{containerDimensions:{maxWidth:Math.round(h)}}:{},...V===null?{}:{locale:V.navigator.language,timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,platform:\"web\"},...t.hostContext?.()}},qt=h=>{switch(h.type){case\"resize\":{let b=Math.min(e.limits.maxHeightPx,Math.max(e.limits.minHeightPx,Math.ceil(h.height)));c=b,y?.setHeight(b),p(\"resize\",{height:b,...h.width===void 0?{}:{width:h.width}});return}case\"error\":v(h.message);return;case\"refused\":p(\"refused\",{capability:h.capability,refusal:h.refusal});return;case\"muted\":p(\"muted\",void 0);return;case\"annotation\":p(\"annotation\",h.report);return}},Re=()=>{se=!1,Te?.abort(),Te=null,Ae?.stop(),Ae=null,C?.close(),C=null,y?.destroy(),y=null},Fe=h=>{let b=a.createSurface(i,{source:h,title:d.title,sandbox:n.sandbox,allow:n.allow,referrerPolicy:n.referrerPolicy,colorScheme:l,...o&&d.fill!==!0&&e.layout.kind!==\"fill\"?{initialHeightPx:c}:{fill:!0,initialHeightPx:e.limits.minHeightPx}});y=b;let E=Et({surface:b,source:h,speaks:o,timeoutMs:e.limits.loadTimeoutMs??Mn,onOutcome:T=>p(\"outcome\",T)});if(Ae=E,!o){let T=!1;b.onLoad(()=>{T||(T=!0,p(\"initialized\",void 0))});return}let R=et({config:e,display:{id:d.displayId,title:d.title},handlers:m,...t.confirm===void 0?{}:{confirm:t.confirm},userActivation:()=>b.userActivation(),onEvent:qt});ze&&b.transport.listen(T=>Ft(T,R));let M=r.connect({display:{id:d.displayId,title:d.title},compiled:n,transport:b.transport,bridge:R,hostInfo:s,hostContext:ie,emit:T=>{T.type===\"initialized\"&&(E.initialized(),se||(se=!0,zt()),p(\"initialized\",void 0))},...d.document===void 0?{}:{document:d.document}});C=M;for(let[T,ee]of Ee)M[T]?.(...ee);b.onNavigated(()=>{p(\"navigated\",void 0),Ce<$n?(Ce+=1,Pe()):(Re(),v(\"The content kept navigating its frame away; it was stopped.\"))})},Pe=()=>{if(Re(),A)return;if(ae+=1,e.isolation===\"opaque\"){Fe({kind:\"srcdoc\",html:n.shellDocument({origins:[i.ownerDocument.defaultView?.location.origin??\"\"],title:d.title,...In(t.nonce),...d.document===void 0?{}:{document:d.document}})});return}let h=ae,b=new AbortController;Te=b;let E=t.locator,R=d.instance;if(E===void 0||R===void 0)return;let M=i.ownerDocument.defaultView?.location.origin??\"\";Tt(E,R,e,M,b.signal).then(T=>{h===ae&&!A&&Fe(T)},T=>{h===ae&&!b.signal.aborted&&(u(T instanceof Error?T.message:String(T),\"locate\"),p(\"outcome\",{state:\"blocked\",reason:\"locate\"}))})};Pe();let Ut={displayId:d.displayId,annotations:Wt,setTheme(h){if(!g){if(l=h,y?.setColorScheme(h),V===null){C?.hostContextChanged(ie());return}Q!==null&&V.cancelAnimationFrame(Q),Q=V.requestAnimationFrame(()=>{Q=V.requestAnimationFrame(()=>{Q=null,C?.hostContextChanged(ie())})})}},refreshTheme(){C?.hostContextChanged(ie())},on(h,b){let E=k.get(h)??new Set;return E.add(b),k.set(h,E),()=>E.delete(b)},reload(){Ce=0,Pe()},destroy(){A=!0,Re(),k.clear()}};return new Proxy(Ut,{get(h,b,E){return typeof b==\"string\"&&!(b in h)&&!Ln.has(b)?(...R)=>{Ee.delete(b),Ee.set(b,R);let M=C?.[b];return typeof M==\"function\"?M.apply(C,R):void 0}:Reflect.get(h,b,E)}})}}}function In(e){let t=typeof e==\"function\"?e():e;return t===void 0||t===\"\"?{}:{nonce:t}}var Dn=\"porthole-script-\",Se=`<script>(() => {\n const send = (kind, data) => { try { parent.postMessage({ portholeCheck: kind, data }, \"*\"); } catch (_) {} };\n const text = (value) => { try { return String(value && value.stack ? value.message || value : value); } catch (_) { return \"?\"; } };\n for (const [method, level] of [[\"error\", \"error\"], [\"warn\", \"warning\"]]) {\n const original = console[method];\n console[method] = (...args) => { send(\"console\", { level, text: args.map(text).join(\" \").slice(0, 400) }); return original.apply(console, args); };\n }\n addEventListener(\"error\", (event) => {\n const target = event.target;\n if (target && target !== window && (target.src || target.href)) {\n send(\"load\", { url: String(target.src || target.href).slice(0, 400), tag: String(target.tagName || \"\").toLowerCase() });\n } else if (event.message || event.error) {\n const error = event.error;\n send(\"error\", {\n message: (error && error.message ? (error.name || \"Error\") + \": \" + error.message : String(event.message)).slice(0, 400),\n file: String(event.filename || \"\"),\n line: event.lineno || 0,\n stack: error && error.stack ? String(error.stack).slice(0, 1000) : \"\",\n });\n }\n }, true);\n addEventListener(\"unhandledrejection\", (event) => send(\"error\", {\n message: (\"Unhandled rejection: \" + text(event.reason)).slice(0, 400),\n file: \"\", line: 0,\n stack: event.reason && event.reason.stack ? String(event.reason.stack).slice(0, 1000) : \"\",\n }));\n addEventListener(\"securitypolicyviolation\", (event) => send(\"blocked\", { url: String(event.blockedURI || \"inline\").slice(0, 400), directive: String(event.effectiveDirective) }));\n addEventListener(\"message\", (event) => {\n if (event.source === parent && event.data && event.data.portholeCheck === \"measure\") {\n const root = document.documentElement;\n send(\"measure\", { scrollWidth: Math.max(root.scrollWidth, document.body ? document.body.scrollWidth : 0), clientWidth: root.clientWidth });\n }\n });\n})();<\\/script>`;function Dt(e){let t=/<head[^>]*>/iu.exec(e);if(t!==null){let o=t.index+t[0].length;return`${e.slice(0,o)}${Se}${e.slice(o)}`}let n=/<html[^>]*>/iu.exec(e);if(n!==null){let o=n.index+n[0].length;return`${e.slice(0,o)}<head>${Se}</head>${e.slice(o)}`}return/^\\s*<!doctype/iu.test(e)?e.replace(/^(\\s*<!doctype[^>]*>)/iu,`$1${Se}`):`${Se}${e}`}function _t(e,t){let n=new RegExp(`${Dn}(\\\\d+)(?::(\\\\d+))?`,\"u\"),o=n.exec(e.file);if(o?.[1]!==void 0&&e.line>0){let a=t[Number(o[1])];return a===void 0?null:a+e.line-1}let r=n.exec(e.stack);if(r?.[1]!==void 0&&r[2]!==void 0){let a=t[Number(r[1])];return a===void 0?null:a+Number(r[2])-1}return null}var _n={sendPrompt:()=>!1,openLink:()=>!1,downloadFile:()=>!1,copyText:()=>!1,setModelContext:()=>{},callTool:()=>{throw new Error(\"The host declined the tool call\")},readData:()=>{throw new Error(\"The host declined the read\")}};function Hn(e,t){let n={};for(let o of e)if(ce(o)&&H(o).served===\"handler\"){let r=_n[o];n[o]=()=>(t.push({capability:o,outcome:\"answered\"}),r())}return n}var Y=new Map,Ht=0,jt=e=>e.box.querySelector(\"iframe\");addEventListener(\"message\",e=>{let t=e.data;if(!(t===null||typeof t!=\"object\"||typeof t.portholeCheck!=\"string\"))for(let n of Y.values()){if(jt(n)?.contentWindow!==e.source)continue;let o=t.data;switch(t.portholeCheck){case\"error\":{let r=t.data,a=_t({file:typeof r.file==\"string\"?r.file:\"\",line:typeof r.line==\"number\"?r.line:0,stack:typeof r.stack==\"string\"?r.stack:\"\"},n.scriptLines),s=typeof r.message==\"string\"?r.message:\"Error\";n.data.errors.push(`${s}${a===null?\"\":` (line ${a})`}`);break}case\"blocked\":n.data.blocked.push({url:String(o.url),directive:String(o.directive)});break;case\"load\":n.data.failedLoads.push({url:String(o.url),tag:String(o.tag)});break;case\"console\":n.data.console.push({level:o.level===\"warning\"?\"warning\":\"error\",text:String(o.text)});break;case\"measure\":n.data.scrollWidth=Number(o.scrollWidth),n.data.clientWidth=Number(o.clientWidth);break;default:break}}});var jn={run(e){let t=Ht;Ht+=1;let n=document.createElement(\"section\");n.id=`porthole-check-${t}`,n.style.cssText=`width:${e.widthPx}px;${e.heightPx===void 0?\"\":`height:${e.heightPx}px;`}`,document.body.append(n);let o=e.hostTheme??{},r=[],a=It(e.config,{theme:()=>o,hostInfo:{name:\"porthole-check\",version:\"1\"},handlers:Hn(Object.keys(e.config.capabilities),r),confirm:()=>Promise.resolve(\"declined\"),locator:{locate:async i=>await(await fetch(\"/issue\",{method:\"POST\",body:JSON.stringify({instance:i})})).json()}}).mount(n,{displayId:`check-${t}`,title:\"Check\",scheme:e.scheme,...e.instance===void 0?{}:{instance:e.instance}}),s={display:a,box:n,scriptLines:e.scriptLines,data:{errors:[],calls:r,blocked:[],failedLoads:[],console:[],height:null,scrollWidth:null,clientWidth:null,outcome:null}};return a.on(\"resize\",({height:i})=>{s.data.height=i}),a.on(\"refused\",({capability:i,refusal:d})=>{d!==\"failed\"&&r.push({capability:i,outcome:d})}),a.on(\"outcome\",i=>{s.data.outcome=i.state===\"blocked\"?`blocked: ${i.reason}`:i.state}),Y.set(t,s),e.instance?.document.kind!==\"artifact\"&&a.on(\"initialized\",()=>a.setContent(Dt(e.content))),t},async measure(e){let t=Y.get(e),n=t===void 0?null:jt(t);if(t===void 0||n?.contentWindow===null||n===null)return;n.contentWindow.postMessage({portholeCheck:\"measure\"},\"*\");let o=Date.now();for(;t.data.scrollWidth===null&&Date.now()-o<1e3;)await new Promise(r=>setTimeout(r,50))},result(e){return Y.get(e)?.data??null},end(e){let t=Y.get(e);t?.display.destroy(),t?.box.remove(),Y.delete(e)}};window.portholeCheck=jn;document.documentElement.dataset.portholeCheck=\"ready\";})();\n";
2
+ export default source;
@@ -0,0 +1,13 @@
1
+ import { type CheckRunData, type CheckRunSpec } from "./instrument.ts";
2
+ export type { CheckCall, CheckRunData, CheckRunSpec } from "./instrument.ts";
3
+ declare const check: {
4
+ /** Shows the content at one width and scheme; returns its run id. */
5
+ run(spec: CheckRunSpec): number;
6
+ /** Asks the frame for its width; resolves when it answers (or after a second). */
7
+ measure(id: number): Promise<void>;
8
+ /** What the run saw. */
9
+ result(id: number): CheckRunData | null;
10
+ /** Removes a run's display. */
11
+ end(id: number): void;
12
+ };
13
+ export type CheckPageApi = typeof check;
@@ -0,0 +1,170 @@
1
+ import { capabilitySpec, isCapabilityName, } from "../config/capabilities.js";
2
+ import { createHost } from "../host/create-host.js";
3
+ import { contentLine, instrumented, } from "./instrument.js";
4
+ /**
5
+ * What a host that declines answers each host function with (P074): no prompt sent, no link
6
+ * opened, nothing downloaded or copied; a tool call or a read refused.
7
+ */
8
+ const DECLINED = {
9
+ sendPrompt: () => false,
10
+ openLink: () => false,
11
+ downloadFile: () => false,
12
+ copyText: () => false,
13
+ setModelContext: () => undefined,
14
+ callTool: () => {
15
+ throw new Error("The host declined the tool call");
16
+ },
17
+ readData: () => {
18
+ throw new Error("The host declined the read");
19
+ },
20
+ };
21
+ /** A handler for each host function the config declares: it notes the call and answers no. */
22
+ function declining(capabilities, calls) {
23
+ const handlers = {};
24
+ for (const name of capabilities) {
25
+ if (isCapabilityName(name) && capabilitySpec(name).served === "handler") {
26
+ const answer = DECLINED[name];
27
+ handlers[name] = () => {
28
+ calls.push({ capability: name, outcome: "answered" });
29
+ return answer();
30
+ };
31
+ }
32
+ }
33
+ return handlers;
34
+ }
35
+ const runs = new Map();
36
+ let next = 0;
37
+ const frameOf = (run) => run.box.querySelector("iframe");
38
+ addEventListener("message", (event) => {
39
+ const data = event.data;
40
+ if (data === null || typeof data !== "object" || typeof data.portholeCheck !== "string") {
41
+ return;
42
+ }
43
+ for (const run of runs.values()) {
44
+ if (frameOf(run)?.contentWindow !== event.source) {
45
+ continue;
46
+ }
47
+ const said = data.data;
48
+ switch (data.portholeCheck) {
49
+ case "error": {
50
+ const error = data.data;
51
+ const line = contentLine({
52
+ file: typeof error.file === "string" ? error.file : "",
53
+ line: typeof error.line === "number" ? error.line : 0,
54
+ stack: typeof error.stack === "string" ? error.stack : "",
55
+ }, run.scriptLines);
56
+ const message = typeof error.message === "string" ? error.message : "Error";
57
+ run.data.errors.push(`${message}${line === null ? "" : ` (line ${line})`}`);
58
+ break;
59
+ }
60
+ case "blocked":
61
+ run.data.blocked.push({ url: String(said.url), directive: String(said.directive) });
62
+ break;
63
+ case "load":
64
+ run.data.failedLoads.push({ url: String(said.url), tag: String(said.tag) });
65
+ break;
66
+ case "console":
67
+ run.data.console.push({
68
+ level: said.level === "warning" ? "warning" : "error",
69
+ text: String(said.text),
70
+ });
71
+ break;
72
+ case "measure":
73
+ run.data.scrollWidth = Number(said.scrollWidth);
74
+ run.data.clientWidth = Number(said.clientWidth);
75
+ break;
76
+ default:
77
+ break;
78
+ }
79
+ }
80
+ });
81
+ const check = {
82
+ /** Shows the content at one width and scheme; returns its run id. */
83
+ run(spec) {
84
+ const id = next;
85
+ next += 1;
86
+ const box = document.createElement("section");
87
+ box.id = `porthole-check-${id}`;
88
+ box.style.cssText = `width:${spec.widthPx}px;${spec.heightPx === undefined ? "" : `height:${spec.heightPx}px;`}`;
89
+ document.body.append(box);
90
+ const theme = spec.hostTheme ?? {};
91
+ const calls = [];
92
+ const display = createHost(spec.config, {
93
+ theme: () => theme,
94
+ hostInfo: { name: "porthole-check", version: "1" },
95
+ // Every host function the config declares, answered as a host that declines (P074): a
96
+ // person asked to confirm says no, a handler says no, and each call is noted.
97
+ handlers: declining(Object.keys(spec.config.capabilities), calls),
98
+ confirm: () => Promise.resolve("declined"),
99
+ // A served config's instance, issued by the check's own server on this page's origin.
100
+ locator: {
101
+ locate: async (instance) => (await (await fetch("/issue", { method: "POST", body: JSON.stringify({ instance }) })).json()),
102
+ },
103
+ }).mount(box, {
104
+ displayId: `check-${id}`,
105
+ title: "Check",
106
+ scheme: spec.scheme,
107
+ ...(spec.instance === undefined ? {} : { instance: spec.instance }),
108
+ });
109
+ const run = {
110
+ display,
111
+ box,
112
+ scriptLines: spec.scriptLines,
113
+ data: {
114
+ errors: [],
115
+ calls,
116
+ blocked: [],
117
+ failedLoads: [],
118
+ console: [],
119
+ height: null,
120
+ scrollWidth: null,
121
+ clientWidth: null,
122
+ outcome: null,
123
+ },
124
+ };
125
+ display.on("resize", ({ height }) => {
126
+ run.data.height = height;
127
+ });
128
+ display.on("refused", ({ capability, refusal }) => {
129
+ // "failed": the declining handler's own no, already noted.
130
+ if (refusal !== "failed") {
131
+ calls.push({ capability, outcome: refusal });
132
+ }
133
+ });
134
+ display.on("outcome", (outcome) => {
135
+ run.data.outcome = outcome.state === "blocked" ? `blocked: ${outcome.reason}` : outcome.state;
136
+ });
137
+ runs.set(id, run);
138
+ // A stored page comes from the check's server; a shell (served or opaque) gets the content.
139
+ if (spec.instance?.document.kind !== "artifact") {
140
+ display.on("initialized", () => display.setContent(instrumented(spec.content)));
141
+ }
142
+ return id;
143
+ },
144
+ /** Asks the frame for its width; resolves when it answers (or after a second). */
145
+ async measure(id) {
146
+ const run = runs.get(id);
147
+ const frame = run === undefined ? null : frameOf(run);
148
+ if (run === undefined || frame?.contentWindow === null || frame === null) {
149
+ return;
150
+ }
151
+ frame.contentWindow.postMessage({ portholeCheck: "measure" }, "*");
152
+ const started = Date.now();
153
+ while (run.data.scrollWidth === null && Date.now() - started < 1_000) {
154
+ await new Promise((resolve) => setTimeout(resolve, 50));
155
+ }
156
+ },
157
+ /** What the run saw. */
158
+ result(id) {
159
+ return runs.get(id)?.data ?? null;
160
+ },
161
+ /** Removes a run's display. */
162
+ end(id) {
163
+ const run = runs.get(id);
164
+ run?.display.destroy();
165
+ run?.box.remove();
166
+ runs.delete(id);
167
+ },
168
+ };
169
+ window.portholeCheck = check;
170
+ document.documentElement.dataset.portholeCheck = "ready";