diacode 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,122 @@
1
+ import{M as m1,N as b1,O as w1,P as fc,Q as zd,R as x1,T as zy,U as v1,V as k1,W as Py,X as _r,Y as Dy,Z as S1,L as yi,_ as jt,$ as xt,a0 as Vr,a1 as mr,a2 as jy,S as _a,a3 as Ma,a4 as Mo,a5 as $1,a6 as Wy,F as qr,a7 as _1,a8 as qy,a9 as Hy,aa,ab as of,ac as M1,ad as la,z as sf,k as E1,I as By,ae as A1,l as Eo,a as Uy,af as T1,ag as af,v as Pd,A as Ea,ah as O1,ai as C1,aj as N1,ak as I1,al as Ky,am as L1,an as F1,ao as R1,ap as z1,K as Yy,aq as Dd,t as P1,D as D1,ar as j1,as as Ni,at as W1,d as Gy,au as q1,y as H1,av as B1,aw as U1,B as K1,ax as Vy,c as Y1,i as Xy,p as G1,ay as V1,az as X1,aA as jd,n as J1,aB as Z1,C as Q1,aC as ew,o as Wd,r as tw,q as nw,x as Jy,aD as rw,aE as ow,aF as Zy,H as iw,aG as sw,aH as aw,m as lw,J as dc,aI as Qy,aJ as cw,aK as uw,aL as fw,aM as dw}from"./fonts-C71K6yRy.js";const qd=e=>e.kind==="context"||e.status==="done"||e.status==="cancelled",hw=(e,t)=>e.edges.filter(n=>n.to===t&&zy.has(n.kind??"needs")&&!n.passed),eg=e=>e.phase==="executing"||e.phase==="paused";function pw(e){return e.kind==="approve"?`the person to approve ${e.from}'s result`:e.kind==="ask"?e.question?`the person's answer to the question asked before ${e.to}`:`you to ask the person before ${e.to} (step_ask)`:`input from the person${e.label?` (${e.label})`:""}`}const hc=e=>b1.has(e.op)||e.op==="plan.set"&&(e.title!==void 0||e.goal!==void 0);let lf=class extends Error{};const Fe=e=>{throw new lf(e)};function yw(e,t,n){for(let r=0;r<t.length;r++){const o=m1(t[r]);if(o.length)return{kind:"rejected",index:r,op:t[r],why:o.join("; ")}}if((eg(e)||n.propose)&&n.actor!=="you"&&t.some(hc)){const r=t.filter(hc),o=t.filter(u=>!hc(u)),s=pc(e,r,{...n,actor:"you"});if(s.kind==="rejected")return{...s,index:t.indexOf(r[s.index])};const i={id:n.proposalId??`p${e.rev+1}`,by:n.actor,...n.at?{at:n.at}:{},...n.reason?{reason:n.reason}:{},ops:s.ops},a={...structuredClone(e),proposals:[...e.proposals??[],i]};if(!o.length)return{kind:"proposed",plan:{...a,rev:e.rev+1},proposal:i};const l=pc({...a,rev:e.rev},o,n);return l.kind==="rejected"?{...l,index:t.indexOf(o[l.index])}:l.kind==="applied"?{...l,proposal:i}:l}return pc(e,t,n)}function pc(e,t,n){const r=structuredClone(e),o={who:n,you:n.actor==="you",impact:new Map,touched:new Set,placements:[]},s=[];for(let i=0;i<t.length;i++)try{s.push(tg(r,t[i],o))}catch(a){if(a instanceof lf)return{kind:"rejected",index:i,op:t[i],why:a.message};throw a}return r.rev=e.rev+1,r.proposals&&!r.proposals.length&&delete r.proposals,{kind:"applied",plan:r,ops:s,impact:gw(r,o),touched:[...o.touched].filter(i=>r.nodes[i]),placements:o.placements}}function gw(e,t){return[...t.impact].filter(([n])=>e.nodes[n]&&e.nodes[n].kind!=="context"&&!t.touched.has(n)).map(([n,{distance:r,reasons:o}])=>({id:n,distance:r,reasons:[...o],done:e.nodes[n].status==="done"})).sort((n,r)=>n.distance-r.distance||n.id.localeCompare(r.id))}function tg(e,t,n){const{you:r,who:o}=n,s=c=>e.nodes[c]??Fe(`there is no step ${c}`),i=c=>!r&&e.nodes[c]?.status==="done",a=(c,d,f)=>{const p=n.impact.get(c);p?(p.distance=Math.min(p.distance,d),p.reasons.add(f)):n.impact.set(c,{distance:d,reasons:new Set([f])})},l=(c,d)=>{a(c,1,`${c} ${d}`);for(const[f,p]of fc(e,c))a(f,p+1,`${c} ${d}`)},u=(c,d,f)=>{for(const[p,h]of Object.entries(e.nodes))p!==c&&k1(d,h.files)&&a(p,1,`${c} ${f}`)};switch(t.op){case"node.add":{const c=t.id??x1(t.label,e.nodes);e.nodes[c]&&Fe(`step ${c} exists`);const d={label:t.label};t.kind==="context"&&(d.kind="context"),t.detail&&(d.detail=t.detail),t.group!==void 0&&(d.group=t.group),t.files?.length&&(d.files=t.files),t.touches?.length&&(d.touches=t.touches),e.nodes[c]=d;for(const f of t.after??[])Hd(e,f,c);return n.touched.add(c),{...t,id:c}}case"node.set":{const c=s(t.id);i(t.id)&&Fe(`${t.id} is done; only you can change it`);const d={label:c.label,kind:c.kind,detail:c.detail,files:c.files};if(t.label!==void 0&&(c.label=t.label),t.kind==="task"?delete c.kind:t.kind!==void 0&&(c.kind=t.kind),t.detail===""?delete c.detail:t.detail!==void 0&&(c.detail=t.detail),Array.isArray(t.files)&&!t.files.length?delete c.files:t.files!==void 0&&(c.files=t.files),Array.isArray(t.touches)&&!t.touches.length?delete c.touches:t.touches!==void 0&&(c.touches=t.touches),t.group===null?delete c.group:t.group!==void 0&&(c.group=t.group),c.kind==="context")for(const p of["status","statusFrom","statusBy","note","owner"])delete c[p];if(n.touched.add(t.id),c.label!==d.label||c.kind!==d.kind||c.detail!==d.detail||JSON.stringify(c.files)!==JSON.stringify(d.files)){for(const[p,h]of fc(e,t.id,!0))a(p,h,`${t.id} changed`);u(t.id,[...d.files??[],...c.files??[]],"changed")}return t}case"node.remove":{const c=s(t.id);i(t.id)&&Fe(`${t.id} is done; only you can remove it`);for(const d of zd(e,t.id))a(d,1,`${t.id} was removed`);return u(t.id,c.files,"was removed"),delete e.nodes[t.id],e.edges=e.edges.filter(d=>d.from!==t.id&&d.to!==t.id),t}case"edge.add":return i(t.to)&&Fe(`${t.to} is done; what it depended on is history`),Hd(e,t.from,t.to,t.label,t.kind),l(t.to,`now depends on ${t.from}`),t;case"edge.remove":{const c=ca(e,t.from,t.to);return i(c.to)&&Fe(`${c.to} is done; what it depended on is history`),e.edges.splice(e.edges.indexOf(c),1),l(t.to,`no longer depends on ${t.from}`),t}case"edge.rewire":case"edge.reverse":{const c=ca(e,t.from,t.to),d=t.op==="edge.reverse"?c.to:t.newFrom??c.from,f=t.op==="edge.reverse"?c.from:t.newTo??c.to;return(i(c.to)||i(f))&&Fe("a done step's prerequisites are history"),ng(e,d,f,c),c.from=d,c.to=f,ua(c),f===t.to?l(f,`now depends on ${d} instead of ${t.from}`):(l(t.to,`no longer depends on ${t.from}`),l(f,`now depends on ${d}`)),t}case"edge.set":{const c=ca(e,t.from,t.to);return t.label!==void 0&&(c.label=t.label),t.kind!==void 0&&t.kind!==(c.kind??"needs")&&(i(c.to)&&Fe(`${c.to} is done; what it depended on is history`),t.kind==="needs"?delete c.kind:c.kind=t.kind,ua(c)),t}case"gate.pass":{r||Fe("only the person passes a checkpoint");const c=yc(e,t.from,t.to);return c.passed&&Fe(`the checkpoint ${t.from} → ${t.to} is passed already`),c.kind==="approve"&&!qd(s(t.from))&&Fe(`${t.from} is not done: there is no result to approve yet`),c.passed=!0,t.answer&&(c.answer=t.answer),t}case"gate.ask":{const c=yc(e,t.from,t.to);return c.kind!=="ask"&&Fe(`${t.from} → ${t.to} is an "${c.kind}" checkpoint; only an "ask" one takes a question`),c.passed&&Fe(`the checkpoint ${t.from} → ${t.to} is passed already: ${t.to} can start`),c.question=t.question,t}case"gate.reject":{r||Fe("only the person sends a step back");const c=yc(e,t.from,t.to);return c.kind!=="approve"&&Fe(`${t.from} → ${t.to} is an "${c.kind}" checkpoint; only an approval is withheld`),s(t.from).status!=="done"&&Fe(`${t.from} is not done: there is nothing to send back`),Bd(e,t.from,{status:"not_started",note:t.reason?`sent back: ${t.reason}`:"sent back: not approved",who:o}),t}case"status.set":{const c=s(t.id);if(c.kind==="context"&&Fe(`${t.id} is context; it has no status`),i(t.id)&&Fe(`${t.id} is done; only you can reopen it`),!r&&c.owner&&c.owner!==o.actor&&Fe(`${t.id} is ${c.owner}'s`),t.status==="cancelled"&&!r&&Fe("only you cancel a step; an agent proposes removing it"),t.status==="in_progress"&&!r&&e.phase==="paused"&&c.status!=="in_progress"&&Fe("the person paused the plan: start nothing new until they resume it. Finish the step you are on, if any, then end your turn"),(t.status==="in_progress"||t.status==="done")&&!r){const f=w1(e,t.id).filter(h=>!qd(e.nodes[h]));f.length&&Fe(`${t.id} is blocked: ${f.join(", ")} unfinished${t.status==="done"?", so it cannot be finished yet":""}`);const p=hw(e,t.id);p.length&&Fe(`${t.id} waits at a checkpoint: it needs ${p.map(pw).join(", and ")}${t.status==="done"?", so it cannot be finished yet":""}`)}const d=c.status==="done";if(c.status=t.status,c.statusFrom=r?"you":o.via==="plugin"?"observed":"reported",c.statusBy=o.actor,t.note!==void 0?c.note=t.note:delete c.note,d&&t.status!=="done")for(const f of e.edges)f.from===t.id&&f.kind==="approve"&&ua(f);if(t.status==="failed")for(const[f,p]of fc(e,t.id))a(f,p,`${t.id} failed`);if(t.status==="cancelled")for(const f of zd(e,t.id))a(f,1,`${t.id} was cancelled`);return t}case"claim":{const c=s(t.id);return c.kind==="context"&&Fe(`${t.id} is context; nobody works on it`),!r&&c.owner&&c.owner!==o.actor&&Fe(`${t.id} is ${c.owner}'s`),!r&&e.phase==="paused"&&c.owner!==o.actor&&Fe("the person paused the plan: start nothing new until they resume it"),c.owner=o.actor,t}case"release":{const c=s(t.id);return!r&&c.owner&&c.owner!==o.actor&&Fe(`${t.id} is ${c.owner}'s`),delete c.owner,t}case"group.rename":{const c=Object.values(e.nodes).filter(d=>d.group===t.from);c.length||Fe(`there is no group "${t.from}"`);for(const d of c)d.group=t.to;return t}case"plan.set":if(t.phase!==void 0&&t.phase!==e.phase&&!r&&Fe("only you change the phase: approving the plan is yours"),t.phase==="paused"&&e.phase!=="paused"&&e.phase!=="executing"&&Fe("only a plan that is being carried out can be paused"),t.title!==void 0&&(e.title=t.title),t.goal!==void 0&&t.goal!==e.goal){e.goal=t.goal;for(const c of Object.keys(e.nodes))a(c,1,"the goal changed")}return t.phase!==void 0&&(e.phase=t.phase),t;case"plan.stop":r||Fe("only the person stops the plan"),eg(e)||Fe(`the plan is ${e.phase}, not running: there is nothing to stop`),e.phase="planning";for(const[c,d]of Object.entries(e.nodes))d.status==="in_progress"||d.status==="waiting"?Bd(e,c,{status:"not_started",note:"stopped by you",who:o}):d.owner&&delete d.owner;return t;case"layout.place":return r||Fe("only you place a step: the layout is yours"),s(t.id),n.placements.push({id:t.id,x:t.x,y:t.y}),t;case"proposal.accept":{r||Fe("only you accept a proposal");const c=(e.proposals??[]).find(d=>d.id===t.id)??Fe(`there is no proposal ${t.id}`);e.proposals=(e.proposals??[]).filter(d=>d!==c);for(const d of c.ops)try{tg(e,d,n)}catch(f){throw f instanceof lf&&Fe(`proposal ${t.id} no longer applies: ${f.message}`),f}return t}case"proposal.reject":return r||Fe("only you reject a proposal"),(e.proposals??[]).some(c=>c.id===t.id)||Fe(`there is no proposal ${t.id}`),e.proposals=(e.proposals??[]).filter(c=>c.id!==t.id),t;case"review":for(const c of t.ids)s(c).kind==="context"&&Fe(`${c} is context; there is nothing to review`);return t;default:return Fe(`"${t.op}" is not an op`)}}function ca(e,t,n){return e.edges.find(r=>r.from===t&&r.to===n)??Fe(`there is no dependency ${t} → ${n}`)}function ng(e,t,n,r){e.nodes[t]||Fe(`there is no step ${t}`),e.nodes[n]||Fe(`there is no step ${n}`),t===n&&Fe(`${t} cannot depend on itself`),e.edges.some(s=>s!==r&&s.from===t&&s.to===n)&&Fe(`${n} already depends on ${t}`);const o=r?{...e,edges:e.edges.filter(s=>s!==r)}:e;v1(o,n,t)&&Fe(`${t} → ${n} would make a loop`)}function Hd(e,t,n,r,o){ng(e,t,n),e.edges.push({from:t,to:n,...r?{label:r}:{},...o&&o!=="needs"?{kind:o}:{}})}function yc(e,t,n){const r=ca(e,t,n);return zy.has(r.kind??"needs")||Fe(`${t} → ${n} is not a checkpoint`),r}function ua(e){delete e.question,delete e.passed,delete e.answer}function Bd(e,t,{status:n,note:r,who:o}){const s=e.nodes[t];if(s.status==="done")for(const i of e.edges)i.from===t&&i.kind==="approve"&&ua(i);s.status=n,s.statusFrom="you",s.statusBy=o.actor,s.note=r,delete s.owner}const mw=100;function Zc(e){if(Array.isArray(e))return`[${e.map(Zc).join(", ")}]`;if(e&&typeof e=="object"){const t=Object.entries(e).map(([n,r])=>`${JSON.stringify(n)}: ${Zc(r)}`);return t.length?`{ ${t.join(", ")} }`:"{}"}return JSON.stringify(e)}function Qc(e,t="",n=0,r=!1){const o=Zc(e);if(!e||typeof e!="object"||r!==!0&&t.length+n+o.length<=mw&&!Array.isArray(r))return o;const s=`${t} `;if(Array.isArray(e))return e.length?`[
2
+ ${e.map(a=>s+Qc(a,s)).join(`,
3
+ `)}
4
+ ${t}]`:"[]";const i=Object.entries(e);return i.length?`{
5
+ ${i.map(([a,l])=>{const u=`${JSON.stringify(a)}: `;return s+u+Qc(l,s,u.length,Array.isArray(r)&&r.includes(a))}).join(`,
6
+ `)}
7
+ ${t}}`:"{}"}const wo={left:16,right:16,top:32,bottom:14},Aa={LR:{gap:74,cross:34,pad:40},TD:{gap:44,cross:60,pad:40}},gc={chars:26,fontSize:10.5,pad:26},bw=e=>Math.min(String(e??"").length,gc.chars)*gc.fontSize*rg+gc.pad,nr={padding:9,maxWidth:168,minWidth:66,minHeight:34,fontSize:12.5},rg=.55,Ud=24,ww=1.28,xw=e=>{const t=vw(e);return{w:t.width,h:t.height}};function vw(e){const t=String(e??""),n=nr.maxWidth-nr.padding*2,r=t.length*nr.fontSize*rg,o=Math.max(nr.minWidth,Math.min(nr.maxWidth,r+nr.padding*2)),s=Math.max(1,Math.ceil(r/n)),i=Math.max(nr.minHeight,s*nr.fontSize*ww+nr.padding*2);return{width:o,height:i}}function kw(e,t){const n=new Map(e.map(s=>[s.id,[]]));for(const s of t)n.has(s.source)&&n.has(s.target)&&n.get(s.source).push(s);const r=new Map(e.map(s=>[s.id,0])),o=new Set;for(const s of e){if(r.get(s.id)!==0)continue;const i=[{id:s.id,i:0}];for(r.set(s.id,1);i.length;){const a=i[i.length-1],l=n.get(a.id);if(a.i>=l.length){r.set(a.id,2),i.pop();continue}const u=l[a.i++];r.get(u.target)===1?o.add(u):r.get(u.target)===0&&(r.set(u.target,1),i.push({id:u.target,i:0}))}}return t.filter(s=>!o.has(s))}function Kd(e,t){const n=new Map(e.map(l=>[l.id,0])),r=new Map(e.map(l=>[l.id,[]]));for(const l of t)!n.has(l.source)||!n.has(l.target)||(n.set(l.target,n.get(l.target)+1),r.get(l.source).push(l.target));const o=new Map(e.map(l=>[l.id,0])),s=e.filter(l=>n.get(l.id)===0).map(l=>l.id),i=new Map(n),a=[];for(;s.length;){const l=s.shift();a.push(l);for(const u of r.get(l))o.set(u,Math.max(o.get(u),o.get(l)+1)),i.set(u,i.get(u)-1),i.get(u)===0&&s.push(u)}if(a.length!==e.length)throw new Error("the plan loops, so it has no layers");return o}function Sw(e,t,n){const r=new Map;for(const u of e){const c=n.get(u.id);r.has(c)||r.set(c,[]),r.get(c).push(u.id)}const o=[...r.keys()].sort((u,c)=>u-c),s=new Map;for(const u of o)r.get(u).forEach((c,d)=>s.set(c,d));const i=new Map(e.map(u=>[u.id,[]])),a=new Map(e.map(u=>[u.id,[]]));for(const u of t)!i.has(u.target)||!a.has(u.source)||(i.get(u.target).push(u.source),a.get(u.source).push(u.target));const l=(u,c)=>{const d=c==="up"?i.get(u):a.get(u);return d.length?d.reduce((f,p)=>f+s.get(p),0)/d.length:s.get(u)};for(let u=0;u<8;u++){const c=u%2===0?"up":"down",d=c==="up"?o:[...o].reverse();for(const f of d){const p=r.get(f),h=p.map(y=>[y,l(y,c)]);h.sort((y,g)=>y[1]-g[1]||p.indexOf(y[0])-p.indexOf(g[0])),r.set(f,h.map(([y])=>y)),r.get(f).forEach((y,g)=>s.set(y,g))}}return{byRank:r,ranks:o}}function $w(e,t,n,r=!1){let o=e,s=t;if(r){const L=Kd(e.map(T=>({id:T.id,label:T.label})),t),N=[],I=[];for(const T of t){const M=L.get(T.source),$=L.get(T.target);if($-M<=1){I.push(T);continue}let F=T.source;for(let D=M+1;D<$;D++){const P=`\0lane:${T.source}${T.target}${D}`;N.push({id:P,label:"",w:Ud,h:Ud}),I.push({source:F,target:P}),F=P}I.push({source:F,target:T.target,...T.label?{label:T.label}:{}})}o=[...e,...N],s=I}const i=o.map(L=>({id:L.id,label:L.label})),a=Kd(i,s),{byRank:l,ranks:u}=Sw(i,s,a),c=Aa[n]||Aa.LR,d=L=>o.find(N=>N.id===L),f=L=>n==="LR"?L.w:L.h,p=L=>n==="LR"?L.h:L.w,h=Math.max(...e.map(p))+c.cross,y=L=>l.get(L),g=Math.max(...u.map(L=>y(L).length)),m=h*g,b=new Map;for(const L of u)for(const N of y(L))b.set(N,L);const w=L=>Math.max(0,...s.filter(N=>b.get(N.source)===L&&N.label).map(N=>bw(N.label))),x=new Map;let S=0,v=0;for(const L of u){const N=Math.max(...y(L).map(I=>f(d(I))));x.set(L,S+N/2),v=n==="LR"?Math.max(c.gap,w(L)):c.gap,S+=N+v}const k=S-v,_=(L,N)=>m/2-h*(N-1)/2+h*L,A=new Map;for(const L of u){const N=y(L);N.forEach((I,T)=>{const M=x.get(L),$=_(T,N.length);A.set(I,n==="LR"?{x:M,y:$}:{x:$,y:M})})}return n==="LR"?{at:A,width:k,height:m}:{at:A,width:m,height:k}}function og(e,t,n,r,o,s=!1){const i=new Map,a=[],l=new Map,u=new Map;for(const h of e){const y=h.path?.[n];if(y===void 0)a.push({id:h.id,label:h.label,...xw(h.label)}),l.set(h.id,h.id);else{const g=i.get(y);g?g.push(h):i.set(y,[h])}}for(const[h,y]of i){const g=`\0frame:${h}`,m=og(y,t,n+1,r,o,s);u.set(g,m),a.push({id:g,label:h,w:m.width+wo.left+wo.right,h:m.height+wo.top+wo.bottom});for(const b of y)l.set(b.id,g)}let c=[];const d=new Set;for(const h of t){const y=l.get(h.source),g=l.get(h.target);y===void 0||g===void 0||y===g||d.has(`${y}${g}`)||(d.add(`${y}${g}`),c.push({source:y,target:g,...h.label?{label:h.label}:{}}))}o&&(c=kw(a,c));const f=$w(a,c,r,s),p=new Map;for(const h of e){const y=l.get(h.id),g=f.at.get(y),m=u.get(y);if(!m){p.set(h.id,g);continue}const b=a.find(v=>v.id===y),w=g.x-b.w/2+wo.left,x=g.y-b.h/2+wo.top,S=m.at.get(h.id);p.set(h.id,{x:w+S.x,y:x+S.y})}return{at:p,width:f.width,height:f.height}}function _w({steps:e,depends:t,direction:n="LR",loops:r=!1}){if(!e.length)return{canvas:{width:0,height:0},positions:new Map};const o=Aa[n]||Aa.LR,s=og(e,t,0,n,r||e.some(a=>a.path?.length),!0),i=new Map;for(const[a,l]of s.at)i.set(a,{x:Math.round(l.x+o.pad),y:Math.round(l.y+o.pad)});return{canvas:{width:Math.round(s.width+o.pad*2),height:Math.round(s.height+o.pad*2)},positions:i}}const Sr={along:230,across:72},Ds={along:90,across:50},Yd={x:70,y:55},Mw={width:640,height:240};function ig(e,t,{paths:n,loops:r=!1}={}){const o=t.direction==="TD",s=m=>o?{along:m.y,across:m.x}:{along:m.x,across:m.y},i=(m,b)=>o?{x:b,y:m}:{x:m,y:b},a={};for(const[m,b]of Object.entries(t.nodes))e.nodes[m]&&(a[m]=b);const l=[],u=new Set,c=new Set(Object.keys(e.nodes).filter(m=>!a[m])),d=new Map;for(const m of Object.values(e.nodes))m.group&&d.set(m.group,(d.get(m.group)??0)+1);const f=m=>{const b=e.nodes[m]?.group;return b&&d.get(b)>1?b:void 0},p=m=>(n?n[m]?.[0]:f(m))??"",h=new Set(Object.keys(a).map(p)),y=n!==void 0&&[...c].some(m=>p(m)!==""&&!h.has(p(m))),g=Object.values(a).some(m=>m.pinned);if(c.size&&y&&!g)for(const m of Object.keys(a))delete a[m];if(c.size&&!Object.keys(a).length){const{positions:m,canvas:b}=_w({steps:Object.entries(e.nodes).map(([w,x])=>({id:w,label:x.label,path:n?n[w]:f(w)?[f(w)]:[]})),depends:e.edges.map(w=>({source:w.from,target:w.to,label:w.label})),direction:t.direction,loops:r});for(const[w,x]of m)a[w]=x;return{layout:{...t,nodes:a,canvas:Gd(a,b)},placed:[...m.keys()],moved:[]}}for(;c.size;){const m=[...c].find(I=>e.edges.every(T=>T.to!==I||a[T.from]))??[...c][0];c.delete(m);const b=e.edges.filter(I=>I.to===m&&a[I.from]).map(I=>s(a[I.from])),w=e.edges.filter(I=>I.from===m&&a[I.to]).map(I=>I.to);let x=b.length?Math.max(...b.map(I=>I.along))+Sr.along:Ds.along;!b.length&&w.length&&(x=Math.max(Ds.along,Math.min(...w.map(I=>s(a[I]).along))-Sr.along));const S=b.length?b:w.map(I=>s(a[I])),v=S.length?S.reduce((I,T)=>I+T.across,0)/S.length:Ds.across,k=new Set,_=(I,T)=>{const M=s(a[I]);if(!(M.along>=T||a[I].pinned||k.has(I))){k.add(I),a[I]={...a[I],...i(T,M.across)},u.add(I);for(const $ of e.edges)$.from===I&&a[$.to]&&!c.has($.to)&&_($.to,T+Sr.along)}};for(const I of w)_(I,x+Sr.along);const A=p(m),L=Object.entries(a).filter(([,I])=>Math.abs(s(I).along-x)<Sr.along/2).map(([I,T])=>({across:s(T).across,gap:p(I)===A?Sr.across*.9:Sr.across*1.9}));let N=v;for(let I=0;L.some(T=>Math.abs(T.across-N)<T.gap);I++){const T=Math.ceil((I+1)/2)*(I%2===0?1:-1)*Sr.across;N=Math.max(Ds.across,v+T)}a[m]={...i(Math.round(x),Math.round(N))},l.push(m)}for(const m of l)u.delete(m);return{layout:{...t,nodes:a,canvas:Gd(a,t.canvas)},placed:l,moved:[...u]}}function Gd(e,t=Mw){const n=Object.values(e),r=Math.max(t.width,...n.map(s=>s.x+Yd.x)),o=Math.max(t.height,...n.map(s=>s.y+Yd.y));return{width:Math.round(r),height:Math.round(o)}}function sg(e,t,n){const r={applies:!0,addedNodes:[],addedEdges:[],removedNodes:[],removedEdges:[],changedNodes:[]},o=yw(e,n,{actor:"you",via:"editor"});if(o.kind!=="applied")return{...r,applies:!1,why:o.kind==="rejected"?`${o.why}`:"it is not a change you can apply"};const s=o.plan,{layout:i}=ig(s,t);for(const[c,d]of Object.entries(s.nodes)){const f=e.nodes[c];if(!f){const h=i.nodes[c]??{x:0,y:0};r.addedNodes.push({id:c,label:d.label,...d.kind==="context"?{kind:"context"}:{},x:h.x,y:h.y});continue}const p=[];f.label!==d.label&&p.push("label"),f.detail!==d.detail&&p.push("detail"),JSON.stringify(f.files)!==JSON.stringify(d.files)&&p.push("files"),JSON.stringify(f.touches)!==JSON.stringify(d.touches)&&p.push("touches"),f.group!==d.group&&p.push("group"),f.kind!==d.kind&&p.push("kind"),p.length&&r.changedNodes.push({id:c,...p.includes("label")?{label:d.label}:{},what:p})}for(const c of Object.keys(e.nodes))s.nodes[c]||r.removedNodes.push(c);const a=c=>`${c.from}\0${c.to}`,l=new Set(e.edges.map(a)),u=new Set(s.edges.map(a));for(const c of s.edges)l.has(a(c))||r.addedEdges.push(c.label?{from:c.from,to:c.to,label:c.label}:{from:c.from,to:c.to});for(const c of e.edges)!u.has(a(c))&&s.nodes[c.from]&&s.nodes[c.to]&&r.removedEdges.push({from:c.from,to:c.to});return r}const xo={arch:["schema","title","goal","rev","phase","source","nodes","edges","flows","proposals"],box:["label","kind","external","in","tech","detail","files","planned","retiring"],arrow:["from","to","label","tech","async","via","planned","retiring"],flow:["id","title","steps"],step:["from","to","label"],proposal:["id","by","at","reason","ops"]};function vo(e,t){const n={};for(const r of t)e[r]!==void 0&&(n[r]=e[r]);for(const r of Object.keys(e))!(r in n)&&e[r]!==void 0&&(n[r]=e[r]);return n}function Ew(e){return vo({...e,nodes:Object.fromEntries(Object.entries(e.nodes).map(([t,n])=>[t,vo(n,xo.box)])),edges:e.edges.map(t=>vo(t,xo.arrow)),flows:e.flows.map(t=>vo({...t,steps:t.steps.map(n=>vo(n,xo.step))},xo.flow)),proposals:e.proposals?.length?e.proposals.map(t=>vo(t,xo.proposal)):void 0},xo.arch)}const Aw=e=>`${Qc(Ew(e),"",0,["nodes","edges","flows","proposals"])}
8
+ `,js=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Vd=e=>`${e.from}\0${e.to}`;function Ws(e){return Object.fromEntries(Object.entries(e).filter(([,t])=>t!==void 0))}function mc(e,t){const n={};return(e.label??"")!==(t.label??"")&&(n.label=t.label??""),(e.tech??"")!==(t.tech??"")&&(n.tech=t.tech??""),!!e.async!=!!t.async&&(n.async=!!t.async),e.via!==t.via&&(n.via=t.via??null),e.planned!==t.planned&&(n.planned=t.planned??null),e.retiring!==t.retiring&&(n.retiring=t.retiring??null),Object.keys(n).length?{op:"arrow.set",from:t.from,to:t.to,...n}:null}function ag(e,t){const n=[],r=[],o={};for(const h of["title","goal","phase"])e[h]!==t[h]&&(t[h]!==void 0||h==="goal")&&(o[h]=t[h]??"");Object.keys(o).length&&n.push({op:"arch.set",...o}),t.rev!==e.rev&&r.push("rev (the server counts revisions)"),js(e.proposals??[],t.proposals??[])||r.push("proposals (accept or reject them instead)");const s=Object.keys(t.nodes).filter(h=>!(h in e.nodes)),i=Object.keys(e.nodes).filter(h=>!(h in t.nodes)),a=Object.keys(t.nodes).filter(h=>h in e.nodes);for(const h of s){const y=t.nodes[h];n.push(Ws({op:"box.add",id:h,label:y.label,kind:y.kind,external:y.external,tech:y.tech,detail:y.detail,files:y.files,planned:y.planned,retiring:y.retiring}))}for(const h of a)e.nodes[h].in!==void 0&&e.nodes[h].in!==t.nodes[h].in&&n.push({op:"box.set",id:h,in:null});const l=new Map(e.edges.map(h=>[Vd(h),h])),u=new Map(t.edges.map(h=>[Vd(h),h])),c=[...l].filter(([h,y])=>!u.has(h)&&y.from in t.nodes&&y.to in t.nodes).map(([,h])=>h),d=[...u].filter(([h])=>!l.has(h)).map(([,h])=>h);for(const h of[...c]){const y=d.find(m=>m.from===h.to&&m.to===h.from);if(!y)continue;n.push({op:"arrow.reverse",from:h.from,to:h.to});const g=mc({...h,from:y.from,to:y.to},y);g&&n.push(g),c.splice(c.indexOf(h),1),d.splice(d.indexOf(y),1)}for(const h of[...c]){const y=d.find(m=>m.from===h.from||m.to===h.to);if(!y)continue;n.push(Ws({op:"arrow.rewire",from:h.from,to:h.to,newFrom:y.from!==h.from?y.from:void 0,newTo:y.to!==h.to?y.to:void 0}));const g=mc({...h,from:y.from,to:y.to},y);g&&n.push(g),c.splice(c.indexOf(h),1),d.splice(d.indexOf(y),1)}for(const h of c)n.push({op:"arrow.remove",from:h.from,to:h.to});for(const h of i)n.push({op:"box.remove",id:h});for(const h of a){const y=e.nodes[h],g=t.nodes[h],m={};y.label!==g.label&&(m.label=g.label),y.kind!==g.kind&&(m.kind=g.kind),(y.tech??"")!==(g.tech??"")&&(m.tech=g.tech??""),(y.detail??"")!==(g.detail??"")&&(m.detail=g.detail??""),js(y.files??[],g.files??[])||(m.files=g.files??[]),!!y.external!=!!g.external&&(m.external=!!g.external),y.retiring!==g.retiring&&g.retiring===void 0&&(m.retiring=null),y.planned!==g.planned&&g.planned===void 0&&(m.planned=null),Object.keys(m).length&&n.push({op:"box.set",id:h,...m});const b={};y.planned!==g.planned&&g.planned!==void 0&&(b.planned=g.planned),y.retiring!==g.retiring&&g.retiring!==void 0&&(b.retiring=g.retiring),Object.keys(b).length&&n.push({op:"box.set",id:h,...b})}for(const h of[...a,...s]){const y=t.nodes[h].in,g=s.includes(h)?void 0:e.nodes[h].in;y!==void 0&&y!==g&&n.push({op:"box.set",id:h,in:y})}for(const h of d)n.push(Ws({op:"arrow.add",from:h.from,to:h.to,label:h.label,tech:h.tech,async:h.async,via:h.via,planned:h.planned,retiring:h.retiring}));for(const[h,y]of u){const g=l.get(h),m=g&&mc(g,y);m&&n.push(m)}const f=new Map(e.flows.map(h=>[h.id,h])),p=new Map(t.flows.map(h=>[h.id,h]));for(const[h,y]of p){const g=f.get(h),m=g?g.steps.filter(b=>!i.includes(b.from)&&!i.includes(b.to)):[];!g||!m.length?n.push({op:"flow.add",id:h,title:y.title,steps:y.steps}):(g.title!==y.title||!js(m,y.steps))&&n.push(Ws({op:"flow.set",id:h,title:g.title!==y.title?y.title:void 0,steps:js(m,y.steps)?void 0:y.steps}))}for(const[h,y]of f)!p.has(h)&&y.steps.some(g=>!i.includes(g.from)&&!i.includes(g.to))&&n.push({op:"flow.remove",id:h});return{ops:n,ignored:r}}const Tw=e=>Object.keys(e.nodes).filter(t=>!_r(e,t));function eu(e,t){const n=Tw(e),r={nodes:Object.fromEntries(n.map(a=>[a,e.nodes[a]])),edges:e.edges},o=Object.fromEntries(n.map(a=>[a,Py(e,a).reverse()])),s=ig(r,t,{paths:o,loops:!0}),i=(t.collapsed??[]).filter(a=>_r(e,a));return{...s,layout:{...s.layout,...i.length?{collapsed:i}:{}}}}function Xd(e,t,n){const r={applies:!0,addedNodes:[],addedEdges:[],removedNodes:[],removedEdges:[],changedNodes:[]},o=Dy(e,n,{actor:"you",via:"editor"});if(o.kind!=="applied")return{...r,applies:!1,why:o.kind==="rejected"?o.why:"it is not a change you can apply"};const s=o.arch,{layout:i}=eu(s,t);for(const[c,d]of Object.entries(s.nodes)){const f=e.nodes[c];if(!f){const h=i.nodes[c]??{x:0,y:0};r.addedNodes.push({id:c,label:d.label,kind:d.kind,x:h.x,y:h.y});continue}const p=[];f.label!==d.label&&p.push("label"),f.kind!==d.kind&&p.push("kind"),f.tech!==d.tech&&p.push("tech"),f.detail!==d.detail&&p.push("detail"),JSON.stringify(f.files)!==JSON.stringify(d.files)&&p.push("files"),f.in!==d.in&&p.push("place"),!!f.external!=!!d.external&&p.push("external"),(f.planned!==d.planned||f.retiring!==d.retiring)&&p.push("plan"),p.length&&r.changedNodes.push({id:c,...p.includes("label")?{label:d.label}:{},what:p})}for(const c of Object.keys(e.nodes))s.nodes[c]||r.removedNodes.push(c);const a=c=>`${c.from}\0${c.to}`,l=new Set(e.edges.map(a)),u=new Set(s.edges.map(a));for(const c of s.edges)l.has(a(c))||r.addedEdges.push(c.label?{from:c.from,to:c.to,label:c.label}:{from:c.from,to:c.to});for(const c of e.edges)!u.has(a(c))&&s.nodes[c.from]&&s.nodes[c.to]&&r.removedEdges.push({from:c.from,to:c.to});return r}const Xr=[],Jd={id:"",title:"",plan:"",repo:"",source:"",direction:"LR",note:"",canvas:{width:640,height:360},steps:[],depends:[]},Sl=e=>Xr.find(t=>t.id===e)||Xr[0],Ii=e=>({steps:e.steps.map(t=>({...t})),depends:e.depends.map(t=>({...t}))}),Vi=[],cf=e=>Vi.find(t=>t.id===e)||Vi[0];function Ow(e){const t=o=>e()?.plan.nodes[o.id],n=o=>t(o)?.kind==="context"?"context":t(o)?.status??"not_started",r=o=>yi[n(o)];return{stroke:o=>r(o)?.edge?r(o).colour:void 0,strokeWidth:o=>r(o)?.edge?3:void 0,opacity:o=>n(o)==="context"?.55:1,look:o=>{const s=r(o),i=o.id;return{status:n(o),...s?{colour:s.colour,icon:s.icon,word:s.word,strike:s.strike}:{},review:i in(e()?.review??{}),atRisk:i in(e()?.derived.atRisk??{})}},owner:o=>S1(t(o)&&{status:"not_started",...t(o)},{stalled:e()?.derived.stalled?.[o.id]?.state,blockedOn:e()?.derived.blocked?.[o.id],held:e()?.derived.held?.[o.id]}),arrow:o=>(e()?.derived.gates??[]).some(s=>s.from===o.source&&s.to===o.target&&s.turn==="you")?"yours":"",frozen:(o,s)=>s==="depends"?n({id:o.target})==="done":n(o)==="done"}}class Cw{constructor(){this.children=[]}add(t){this.children.push(t)}clear(){this.children=[]}}const Zd=e=>[e.hit?0:1,typeof e.index=="number"?e.index:-1];function Qd(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n].glyph;if(!r){t.push(...e[n].nodes);continue}const o=[];let s=n;for(;s<e.length&&e[s].glyph===r;)o.push(...e[s].nodes),s++;n=s-1,o.sort((i,a)=>{const[l,u]=Zd(i),[c,d]=Zd(a);return l!==c?l-c:u-d}),t.push(...o)}return t.some(n=>n&&n.raise)?[...t.filter(n=>!(n&&n.raise)),...t.filter(n=>n&&n.raise)]:t}function fa(e,t){return e==null||t==null?NaN:e<t?-1:e>t?1:e>=t?0:NaN}function Nw(e,t){return e==null||t==null?NaN:t<e?-1:t>e?1:t>=e?0:NaN}function uf(e){let t,n,r;e.length!==2?(t=fa,n=(a,l)=>fa(e(a),l),r=(a,l)=>e(a)-l):(t=e===fa||e===Nw?e:Iw,n=e,r=e);function o(a,l,u=0,c=a.length){if(u<c){if(t(l,l)!==0)return c;do{const d=u+c>>>1;n(a[d],l)<0?u=d+1:c=d}while(u<c)}return u}function s(a,l,u=0,c=a.length){if(u<c){if(t(l,l)!==0)return c;do{const d=u+c>>>1;n(a[d],l)<=0?u=d+1:c=d}while(u<c)}return u}function i(a,l,u=0,c=a.length){const d=o(a,l,u,c-1);return d>u&&r(a[d-1],l)>-r(a[d],l)?d-1:d}return{left:o,center:i,right:s}}function Iw(){return 0}function Lw(e){return e===null?NaN:+e}const Fw=uf(fa),Rw=Fw.right;uf(Lw).center;class Ln{constructor(){this._partials=new Float64Array(32),this._n=0}add(t){const n=this._partials;let r=0;for(let o=0;o<this._n&&o<32;o++){const s=n[o],i=t+s,a=Math.abs(t)<Math.abs(s)?t-(i-s):s-(i-t);a&&(n[r++]=a),t=i}return n[r]=t,this._n=r+1,this}valueOf(){const t=this._partials;let n=this._n,r,o,s,i=0;if(n>0){for(i=t[--n];n>0&&(r=i,o=t[--n],i=r+o,s=o-(i-r),!s););n>0&&(s<0&&t[n-1]<0||s>0&&t[n-1]>0)&&(o=s*2,r=i+o,o==r-i&&(i=r))}return i}}class eh extends Map{constructor(t,n=Dw){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),t!=null)for(const[r,o]of t)this.set(r,o)}get(t){return super.get(th(this,t))}has(t){return super.has(th(this,t))}set(t,n){return super.set(zw(this,t),n)}delete(t){return super.delete(Pw(this,t))}}function th({_intern:e,_key:t},n){const r=t(n);return e.has(r)?e.get(r):n}function zw({_intern:e,_key:t},n){const r=t(n);return e.has(r)?e.get(r):(e.set(r,n),n)}function Pw({_intern:e,_key:t},n){const r=t(n);return e.has(r)&&(n=e.get(r),e.delete(r)),n}function Dw(e){return e!==null&&typeof e=="object"?e.valueOf():e}const jw=Math.sqrt(50),Ww=Math.sqrt(10),qw=Math.sqrt(2);function Ta(e,t,n){const r=(t-e)/Math.max(0,n),o=Math.floor(Math.log10(r)),s=r/Math.pow(10,o),i=s>=jw?10:s>=Ww?5:s>=qw?2:1;let a,l,u;return o<0?(u=Math.pow(10,-o)/i,a=Math.round(e*u),l=Math.round(t*u),a/u<e&&++a,l/u>t&&--l,u=-u):(u=Math.pow(10,o)*i,a=Math.round(e/u),l=Math.round(t/u),a*u<e&&++a,l*u>t&&--l),l<a&&.5<=n&&n<2?Ta(e,t,n*2):[a,l,u]}function tu(e,t,n){if(t=+t,e=+e,n=+n,!(n>0))return[];if(e===t)return[e];const r=t<e,[o,s,i]=r?Ta(t,e,n):Ta(e,t,n);if(!(s>=o))return[];const a=s-o+1,l=new Array(a);if(r)if(i<0)for(let u=0;u<a;++u)l[u]=(s-u)/-i;else for(let u=0;u<a;++u)l[u]=(s-u)*i;else if(i<0)for(let u=0;u<a;++u)l[u]=(o+u)/-i;else for(let u=0;u<a;++u)l[u]=(o+u)*i;return l}function nu(e,t,n){return t=+t,e=+e,n=+n,Ta(e,t,n)[2]}function ru(e,t,n){t=+t,e=+e,n=+n;const r=t<e,o=r?nu(t,e,n):nu(e,t,n);return(r?-1:1)*(o<0?1/-o:o)}function*Hw(e){for(const t of e)yield*t}function lg(e){return Array.from(Hw(e))}function Bw(e,t,n){e=+e,t=+t,n=(o=arguments.length)<2?(t=e,e=0,1):o<3?1:+n;for(var r=-1,o=Math.max(0,Math.ceil((t-e)/n))|0,s=new Array(o);++r<o;)s[r]=e+r*n;return s}var Uw={value:()=>{}};function ff(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new da(n)}function da(e){this._=e}function Kw(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",o=n.indexOf(".");if(o>=0&&(r=n.slice(o+1),n=n.slice(0,o)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}da.prototype=ff.prototype={constructor:da,on:function(e,t){var n=this._,r=Kw(e+"",n),o,s=-1,i=r.length;if(arguments.length<2){for(;++s<i;)if((o=(e=r[s]).type)&&(o=Yw(n[o],e.name)))return o;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++s<i;)if(o=(e=r[s]).type)n[o]=nh(n[o],e.name,t);else if(t==null)for(o in n)n[o]=nh(n[o],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new da(e)},call:function(e,t){if((o=arguments.length-2)>0)for(var n=new Array(o),r=0,o,s;r<o;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(s=this._[e],r=0,o=s.length;r<o;++r)s[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],o=0,s=r.length;o<s;++o)r[o].value.apply(t,n)}};function Yw(e,t){for(var n=0,r=e.length,o;n<r;++n)if((o=e[n]).name===t)return o.value}function nh(e,t,n){for(var r=0,o=e.length;r<o;++r)if(e[r].name===t){e[r]=Uw,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var ou="http://www.w3.org/1999/xhtml";const rh={svg:"http://www.w3.org/2000/svg",xhtml:ou,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function $l(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),rh.hasOwnProperty(t)?{space:rh[t],local:e}:e}function Gw(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===ou&&t.documentElement.namespaceURI===ou?t.createElement(e):t.createElementNS(n,e)}}function Vw(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function cg(e){var t=$l(e);return(t.local?Vw:Gw)(t)}function Xw(){}function df(e){return e==null?Xw:function(){return this.querySelector(e)}}function Jw(e){typeof e!="function"&&(e=df(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,a=r[o]=new Array(i),l,u,c=0;c<i;++c)(l=s[c])&&(u=e.call(l,l.__data__,c,s))&&("__data__"in l&&(u.__data__=l.__data__),a[c]=u);return new gn(r,this._parents)}function Zw(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function Qw(){return[]}function ug(e){return e==null?Qw:function(){return this.querySelectorAll(e)}}function ex(e){return function(){return Zw(e.apply(this,arguments))}}function tx(e){typeof e=="function"?e=ex(e):e=ug(e);for(var t=this._groups,n=t.length,r=[],o=[],s=0;s<n;++s)for(var i=t[s],a=i.length,l,u=0;u<a;++u)(l=i[u])&&(r.push(e.call(l,l.__data__,u,i)),o.push(l));return new gn(r,o)}function fg(e){return function(){return this.matches(e)}}function dg(e){return function(t){return t.matches(e)}}var nx=Array.prototype.find;function rx(e){return function(){return nx.call(this.children,e)}}function ox(){return this.firstElementChild}function ix(e){return this.select(e==null?ox:rx(typeof e=="function"?e:dg(e)))}var sx=Array.prototype.filter;function ax(){return Array.from(this.children)}function lx(e){return function(){return sx.call(this.children,e)}}function cx(e){return this.selectAll(e==null?ax:lx(typeof e=="function"?e:dg(e)))}function ux(e){typeof e!="function"&&(e=fg(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,a=r[o]=[],l,u=0;u<i;++u)(l=s[u])&&e.call(l,l.__data__,u,s)&&a.push(l);return new gn(r,this._parents)}function hg(e){return new Array(e.length)}function fx(){return new gn(this._enter||this._groups.map(hg),this._parents)}function Oa(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Oa.prototype={constructor:Oa,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function dx(e){return function(){return e}}function hx(e,t,n,r,o,s){for(var i=0,a,l=t.length,u=s.length;i<u;++i)(a=t[i])?(a.__data__=s[i],r[i]=a):n[i]=new Oa(e,s[i]);for(;i<l;++i)(a=t[i])&&(o[i]=a)}function px(e,t,n,r,o,s,i){var a,l,u=new Map,c=t.length,d=s.length,f=new Array(c),p;for(a=0;a<c;++a)(l=t[a])&&(f[a]=p=i.call(l,l.__data__,a,t)+"",u.has(p)?o[a]=l:u.set(p,l));for(a=0;a<d;++a)p=i.call(e,s[a],a,s)+"",(l=u.get(p))?(r[a]=l,l.__data__=s[a],u.delete(p)):n[a]=new Oa(e,s[a]);for(a=0;a<c;++a)(l=t[a])&&u.get(f[a])===l&&(o[a]=l)}function yx(e){return e.__data__}function gx(e,t){if(!arguments.length)return Array.from(this,yx);var n=t?px:hx,r=this._parents,o=this._groups;typeof e!="function"&&(e=dx(e));for(var s=o.length,i=new Array(s),a=new Array(s),l=new Array(s),u=0;u<s;++u){var c=r[u],d=o[u],f=d.length,p=mx(e.call(c,c&&c.__data__,u,r)),h=p.length,y=a[u]=new Array(h),g=i[u]=new Array(h),m=l[u]=new Array(f);n(c,d,y,g,m,p,t);for(var b=0,w=0,x,S;b<h;++b)if(x=y[b]){for(b>=w&&(w=b+1);!(S=g[w])&&++w<h;);x._next=S||null}}return i=new gn(i,r),i._enter=a,i._exit=l,i}function mx(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function bx(){return new gn(this._exit||this._groups.map(hg),this._parents)}function wx(e,t,n){var r=this.enter(),o=this,s=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(o=t(o),o&&(o=o.selection())),n==null?s.remove():n(s),r&&o?r.merge(o).order():o}function xx(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,o=n.length,s=r.length,i=Math.min(o,s),a=new Array(o),l=0;l<i;++l)for(var u=n[l],c=r[l],d=u.length,f=a[l]=new Array(d),p,h=0;h<d;++h)(p=u[h]||c[h])&&(f[h]=p);for(;l<o;++l)a[l]=n[l];return new gn(a,this._parents)}function vx(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],o=r.length-1,s=r[o],i;--o>=0;)(i=r[o])&&(s&&i.compareDocumentPosition(s)^4&&s.parentNode.insertBefore(i,s),s=i);return this}function kx(e){e||(e=Sx);function t(d,f){return d&&f?e(d.__data__,f.__data__):!d-!f}for(var n=this._groups,r=n.length,o=new Array(r),s=0;s<r;++s){for(var i=n[s],a=i.length,l=o[s]=new Array(a),u,c=0;c<a;++c)(u=i[c])&&(l[c]=u);l.sort(t)}return new gn(o,this._parents).order()}function Sx(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function $x(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function _x(){return Array.from(this)}function Mx(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,s=r.length;o<s;++o){var i=r[o];if(i)return i}return null}function Ex(){let e=0;for(const t of this)++e;return e}function Ax(){return!this.node()}function Tx(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var o=t[n],s=0,i=o.length,a;s<i;++s)(a=o[s])&&e.call(a,a.__data__,s,o);return this}function Ox(e){return function(){this.removeAttribute(e)}}function Cx(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Nx(e,t){return function(){this.setAttribute(e,t)}}function Ix(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function Lx(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function Fx(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function Rx(e,t){var n=$l(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?Cx:Ox:typeof t=="function"?n.local?Fx:Lx:n.local?Ix:Nx)(n,t))}function pg(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function zx(e){return function(){this.style.removeProperty(e)}}function Px(e,t,n){return function(){this.style.setProperty(e,t,n)}}function Dx(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function jx(e,t,n){return arguments.length>1?this.each((t==null?zx:typeof t=="function"?Dx:Px)(e,t,n??"")):Po(this.node(),e)}function Po(e,t){return e.style.getPropertyValue(t)||pg(e).getComputedStyle(e,null).getPropertyValue(t)}function Wx(e){return function(){delete this[e]}}function qx(e,t){return function(){this[e]=t}}function Hx(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function Bx(e,t){return arguments.length>1?this.each((t==null?Wx:typeof t=="function"?Hx:qx)(e,t)):this.node()[e]}function yg(e){return e.trim().split(/^|\s+/)}function hf(e){return e.classList||new gg(e)}function gg(e){this._node=e,this._names=yg(e.getAttribute("class")||"")}gg.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function mg(e,t){for(var n=hf(e),r=-1,o=t.length;++r<o;)n.add(t[r])}function bg(e,t){for(var n=hf(e),r=-1,o=t.length;++r<o;)n.remove(t[r])}function Ux(e){return function(){mg(this,e)}}function Kx(e){return function(){bg(this,e)}}function Yx(e,t){return function(){(t.apply(this,arguments)?mg:bg)(this,e)}}function Gx(e,t){var n=yg(e+"");if(arguments.length<2){for(var r=hf(this.node()),o=-1,s=n.length;++o<s;)if(!r.contains(n[o]))return!1;return!0}return this.each((typeof t=="function"?Yx:t?Ux:Kx)(n,t))}function Vx(){this.textContent=""}function Xx(e){return function(){this.textContent=e}}function Jx(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function Zx(e){return arguments.length?this.each(e==null?Vx:(typeof e=="function"?Jx:Xx)(e)):this.node().textContent}function Qx(){this.innerHTML=""}function ev(e){return function(){this.innerHTML=e}}function tv(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function nv(e){return arguments.length?this.each(e==null?Qx:(typeof e=="function"?tv:ev)(e)):this.node().innerHTML}function rv(){this.nextSibling&&this.parentNode.appendChild(this)}function ov(){return this.each(rv)}function iv(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function sv(){return this.each(iv)}function av(e){var t=typeof e=="function"?e:cg(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function lv(){return null}function cv(e,t){var n=typeof e=="function"?e:cg(e),r=t==null?lv:typeof t=="function"?t:df(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function uv(){var e=this.parentNode;e&&e.removeChild(this)}function fv(){return this.each(uv)}function dv(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function hv(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function pv(e){return this.select(e?hv:dv)}function yv(e){return arguments.length?this.property("__data__",e):this.node().__data__}function gv(e){return function(t){e.call(this,t,this.__data__)}}function mv(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function bv(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,o=t.length,s;n<o;++n)s=t[n],(!e.type||s.type===e.type)&&s.name===e.name?this.removeEventListener(s.type,s.listener,s.options):t[++r]=s;++r?t.length=r:delete this.__on}}}function wv(e,t,n){return function(){var r=this.__on,o,s=gv(t);if(r){for(var i=0,a=r.length;i<a;++i)if((o=r[i]).type===e.type&&o.name===e.name){this.removeEventListener(o.type,o.listener,o.options),this.addEventListener(o.type,o.listener=s,o.options=n),o.value=t;return}}this.addEventListener(e.type,s,n),o={type:e.type,name:e.name,value:t,listener:s,options:n},r?r.push(o):this.__on=[o]}}function xv(e,t,n){var r=mv(e+""),o,s=r.length,i;if(arguments.length<2){var a=this.node().__on;if(a){for(var l=0,u=a.length,c;l<u;++l)for(o=0,c=a[l];o<s;++o)if((i=r[o]).type===c.type&&i.name===c.name)return c.value}return}for(a=t?wv:bv,o=0;o<s;++o)this.each(a(r[o],t,n));return this}function wg(e,t,n){var r=pg(e),o=r.CustomEvent;typeof o=="function"?o=new o(t,n):(o=r.document.createEvent("Event"),n?(o.initEvent(t,n.bubbles,n.cancelable),o.detail=n.detail):o.initEvent(t,!1,!1)),e.dispatchEvent(o)}function vv(e,t){return function(){return wg(this,e,t)}}function kv(e,t){return function(){return wg(this,e,t.apply(this,arguments))}}function Sv(e,t){return this.each((typeof t=="function"?kv:vv)(e,t))}function*$v(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],o=0,s=r.length,i;o<s;++o)(i=r[o])&&(yield i)}var xg=[null];function gn(e,t){this._groups=e,this._parents=t}function bs(){return new gn([[document.documentElement]],xg)}function _v(){return this}gn.prototype=bs.prototype={constructor:gn,select:Jw,selectAll:tx,selectChild:ix,selectChildren:cx,filter:ux,data:gx,enter:fx,exit:bx,join:wx,merge:xx,selection:_v,order:vx,sort:kx,call:$x,nodes:_x,node:Mx,size:Ex,empty:Ax,each:Tx,attr:Rx,style:jx,property:Bx,classed:Gx,text:Zx,html:nv,raise:ov,lower:sv,append:av,insert:cv,remove:fv,clone:pv,datum:yv,on:xv,dispatch:Sv,[Symbol.iterator]:$v};function ir(e){return typeof e=="string"?new gn([[document.querySelector(e)]],[document.documentElement]):new gn([[e]],xg)}function Mv(e){let t;for(;t=e.sourceEvent;)e=t;return e}function iu(e,t){if(e=Mv(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}}return[e.pageX,e.pageY]}const Ev={passive:!1},Xi={capture:!0,passive:!1};function bc(e){e.stopImmediatePropagation()}function Io(e){e.preventDefault(),e.stopImmediatePropagation()}function Av(e){var t=e.document.documentElement,n=ir(e).on("dragstart.drag",Io,Xi);"onselectstart"in t?n.on("selectstart.drag",Io,Xi):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function Tv(e,t){var n=e.document.documentElement,r=ir(e).on("dragstart.drag",null);t&&(r.on("click.drag",Io,Xi),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const qs=e=>()=>e;function su(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:s,x:i,y:a,dx:l,dy:u,dispatch:c}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:s,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:a,enumerable:!0,configurable:!0},dx:{value:l,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:c}})}su.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function Ov(e){return!e.ctrlKey&&!e.button}function Cv(){return this.parentNode}function Nv(e,t){return t??{x:e.x,y:e.y}}function Iv(){return navigator.maxTouchPoints||"ontouchstart"in this}function Lv(){var e=Ov,t=Cv,n=Nv,r=Iv,o={},s=ff("start","drag","end"),i=0,a,l,u,c,d=0;function f(x){x.on("mousedown.drag",p).filter(r).on("touchstart.drag",g).on("touchmove.drag",m,Ev).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(x,S){if(!(c||!e.call(this,x,S))){var v=w(this,t.call(this,x,S),x,S,"mouse");v&&(ir(x.view).on("mousemove.drag",h,Xi).on("mouseup.drag",y,Xi),Av(x.view),bc(x),u=!1,a=x.clientX,l=x.clientY,v("start",x))}}function h(x){if(Io(x),!u){var S=x.clientX-a,v=x.clientY-l;u=S*S+v*v>d}o.mouse("drag",x)}function y(x){ir(x.view).on("mousemove.drag mouseup.drag",null),Tv(x.view,u),Io(x),o.mouse("end",x)}function g(x,S){if(e.call(this,x,S)){var v=x.changedTouches,k=t.call(this,x,S),_=v.length,A,L;for(A=0;A<_;++A)(L=w(this,k,x,S,v[A].identifier,v[A]))&&(bc(x),L("start",x,v[A]))}}function m(x){var S=x.changedTouches,v=S.length,k,_;for(k=0;k<v;++k)(_=o[S[k].identifier])&&(Io(x),_("drag",x,S[k]))}function b(x){var S=x.changedTouches,v=S.length,k,_;for(c&&clearTimeout(c),c=setTimeout(function(){c=null},500),k=0;k<v;++k)(_=o[S[k].identifier])&&(bc(x),_("end",x,S[k]))}function w(x,S,v,k,_,A){var L=s.copy(),N=iu(A||v,S),I,T,M;if((M=n.call(x,new su("beforestart",{sourceEvent:v,target:f,identifier:_,active:i,x:N[0],y:N[1],dx:0,dy:0,dispatch:L}),k))!=null)return I=M.x-N[0]||0,T=M.y-N[1]||0,function $(F,D,P){var j=N,G;switch(F){case"start":o[_]=$,G=i++;break;case"end":delete o[_],--i;case"drag":N=iu(P||D,S),G=i;break}L.call(F,x,new su(F,{sourceEvent:D,subject:M,target:f,identifier:_,active:G,x:N[0]+I,y:N[1]+T,dx:N[0]-j[0],dy:N[1]-j[1],dispatch:L}),k)}}return f.filter=function(x){return arguments.length?(e=typeof x=="function"?x:qs(!!x),f):e},f.container=function(x){return arguments.length?(t=typeof x=="function"?x:qs(x),f):t},f.subject=function(x){return arguments.length?(n=typeof x=="function"?x:qs(x),f):n},f.touchable=function(x){return arguments.length?(r=typeof x=="function"?x:qs(!!x),f):r},f.on=function(){var x=s.on.apply(s,arguments);return x===s?f:x},f.clickDistance=function(x){return arguments.length?(d=(x=+x)*x,f):Math.sqrt(d)},f}function _l(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function pf(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function Zo(){}var Jr=.7,Do=1/Jr,Lo="\\s*([+-]?\\d+)\\s*",Ji="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",Un="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",Fv=/^#([0-9a-f]{3,8})$/,Rv=new RegExp(`^rgb\\(${Lo},${Lo},${Lo}\\)$`),zv=new RegExp(`^rgb\\(${Un},${Un},${Un}\\)$`),Pv=new RegExp(`^rgba\\(${Lo},${Lo},${Lo},${Ji}\\)$`),Dv=new RegExp(`^rgba\\(${Un},${Un},${Un},${Ji}\\)$`),jv=new RegExp(`^hsl\\(${Ji},${Un},${Un}\\)$`),Wv=new RegExp(`^hsla\\(${Ji},${Un},${Un},${Ji}\\)$`),oh={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};_l(Zo,Zr,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:ih,formatHex:ih,formatHex8:qv,formatHsl:Hv,formatRgb:sh,toString:sh});function ih(){return this.rgb().formatHex()}function qv(){return this.rgb().formatHex8()}function Hv(){return kg(this).formatHsl()}function sh(){return this.rgb().formatRgb()}function Zr(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=Fv.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?ah(t):n===3?new Yt(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?Hs(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?Hs(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=Rv.exec(e))?new Yt(t[1],t[2],t[3],1):(t=zv.exec(e))?new Yt(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Pv.exec(e))?Hs(t[1],t[2],t[3],t[4]):(t=Dv.exec(e))?Hs(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=jv.exec(e))?uh(t[1],t[2]/100,t[3]/100,1):(t=Wv.exec(e))?uh(t[1],t[2]/100,t[3]/100,t[4]):oh.hasOwnProperty(e)?ah(oh[e]):e==="transparent"?new Yt(NaN,NaN,NaN,0):null}function ah(e){return new Yt(e>>16&255,e>>8&255,e&255,1)}function Hs(e,t,n,r){return r<=0&&(e=t=n=NaN),new Yt(e,t,n,r)}function vg(e){return e instanceof Zo||(e=Zr(e)),e?(e=e.rgb(),new Yt(e.r,e.g,e.b,e.opacity)):new Yt}function Ca(e,t,n,r){return arguments.length===1?vg(e):new Yt(e,t,n,r??1)}function Yt(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}_l(Yt,Ca,pf(Zo,{brighter(e){return e=e==null?Do:Math.pow(Do,e),new Yt(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Jr:Math.pow(Jr,e),new Yt(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Yt(Br(this.r),Br(this.g),Br(this.b),Na(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:lh,formatHex:lh,formatHex8:Bv,formatRgb:ch,toString:ch}));function lh(){return`#${Hr(this.r)}${Hr(this.g)}${Hr(this.b)}`}function Bv(){return`#${Hr(this.r)}${Hr(this.g)}${Hr(this.b)}${Hr((isNaN(this.opacity)?1:this.opacity)*255)}`}function ch(){const e=Na(this.opacity);return`${e===1?"rgb(":"rgba("}${Br(this.r)}, ${Br(this.g)}, ${Br(this.b)}${e===1?")":`, ${e})`}`}function Na(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Br(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Hr(e){return e=Br(e),(e<16?"0":"")+e.toString(16)}function uh(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Cn(e,t,n,r)}function kg(e){if(e instanceof Cn)return new Cn(e.h,e.s,e.l,e.opacity);if(e instanceof Zo||(e=Zr(e)),!e)return new Cn;if(e instanceof Cn)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,o=Math.min(t,n,r),s=Math.max(t,n,r),i=NaN,a=s-o,l=(s+o)/2;return a?(t===s?i=(n-r)/a+(n<r)*6:n===s?i=(r-t)/a+2:i=(t-n)/a+4,a/=l<.5?s+o:2-s-o,i*=60):a=l>0&&l<1?0:i,new Cn(i,a,l,e.opacity)}function Uv(e,t,n,r){return arguments.length===1?kg(e):new Cn(e,t,n,r??1)}function Cn(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}_l(Cn,Uv,pf(Zo,{brighter(e){return e=e==null?Do:Math.pow(Do,e),new Cn(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Jr:Math.pow(Jr,e),new Cn(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,o=2*n-r;return new Yt(wc(e>=240?e-240:e+120,o,r),wc(e,o,r),wc(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new Cn(fh(this.h),Bs(this.s),Bs(this.l),Na(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Na(this.opacity);return`${e===1?"hsl(":"hsla("}${fh(this.h)}, ${Bs(this.s)*100}%, ${Bs(this.l)*100}%${e===1?")":`, ${e})`}`}}));function fh(e){return e=(e||0)%360,e<0?e+360:e}function Bs(e){return Math.max(0,Math.min(1,e||0))}function wc(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const Kv=Math.PI/180,Yv=180/Math.PI;var Sg=-.14861,yf=1.78277,gf=-.29227,Ml=-.90649,Zi=1.97294,dh=Zi*Ml,hh=Zi*yf,ph=yf*gf-Ml*Sg;function Gv(e){if(e instanceof Ur)return new Ur(e.h,e.s,e.l,e.opacity);e instanceof Yt||(e=vg(e));var t=e.r/255,n=e.g/255,r=e.b/255,o=(ph*r+dh*t-hh*n)/(ph+dh-hh),s=r-o,i=(Zi*(n-o)-gf*s)/Ml,a=Math.sqrt(i*i+s*s)/(Zi*o*(1-o)),l=a?Math.atan2(i,s)*Yv-120:NaN;return new Ur(l<0?l+360:l,a,o,e.opacity)}function Ar(e,t,n,r){return arguments.length===1?Gv(e):new Ur(e,t,n,r??1)}function Ur(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}_l(Ur,Ar,pf(Zo,{brighter(e){return e=e==null?Do:Math.pow(Do,e),new Ur(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Jr:Math.pow(Jr,e),new Ur(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=isNaN(this.h)?0:(this.h+120)*Kv,t=+this.l,n=isNaN(this.s)?0:this.s*t*(1-t),r=Math.cos(e),o=Math.sin(e);return new Yt(255*(t+n*(Sg*r+yf*o)),255*(t+n*(gf*r+Ml*o)),255*(t+n*(Zi*r)),this.opacity)}}));function Vv(e,t,n,r,o){var s=e*e,i=s*e;return((1-3*e+3*s-i)*t+(4-6*s+3*i)*n+(1+3*e+3*s-3*i)*r+i*o)/6}function Xv(e){var t=e.length-1;return function(n){var r=n<=0?n=0:n>=1?(n=1,t-1):Math.floor(n*t),o=e[r],s=e[r+1],i=r>0?e[r-1]:2*o-s,a=r<t-1?e[r+2]:2*s-o;return Vv((n-r/t)*t,i,o,s,a)}}const El=e=>()=>e;function $g(e,t){return function(n){return e+n*t}}function Jv(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function Zv(e,t){var n=t-e;return n?$g(e,n>180||n<-180?n-360*Math.round(n/360):n):El(isNaN(e)?t:e)}function Qv(e){return(e=+e)==1?Fo:function(t,n){return n-t?Jv(t,n,e):El(isNaN(t)?n:t)}}function Fo(e,t){var n=t-e;return n?$g(e,n):El(isNaN(e)?t:e)}const Qr=(function e(t){var n=Qv(t);function r(o,s){var i=n((o=Ca(o)).r,(s=Ca(s)).r),a=n(o.g,s.g),l=n(o.b,s.b),u=Fo(o.opacity,s.opacity);return function(c){return o.r=i(c),o.g=a(c),o.b=l(c),o.opacity=u(c),o+""}}return r.gamma=e,r})(1);function ek(e){return function(t){var n=t.length,r=new Array(n),o=new Array(n),s=new Array(n),i,a;for(i=0;i<n;++i)a=Ca(t[i]),r[i]=a.r||0,o[i]=a.g||0,s[i]=a.b||0;return r=e(r),o=e(o),s=e(s),a.opacity=1,function(l){return a.r=r(l),a.g=o(l),a.b=s(l),a+""}}}var tk=ek(Xv);function nk(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),o;return function(s){for(o=0;o<n;++o)r[o]=e[o]*(1-s)+t[o]*s;return r}}function rk(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function ok(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,o=new Array(r),s=new Array(n),i;for(i=0;i<r;++i)o[i]=Al(e[i],t[i]);for(;i<n;++i)s[i]=t[i];return function(a){for(i=0;i<r;++i)s[i]=o[i](a);return s}}function ik(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function Tn(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function sk(e,t){var n={},r={},o;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(o in t)o in e?n[o]=Al(e[o],t[o]):r[o]=t[o];return function(s){for(o in n)r[o]=n[o](s);return r}}var au=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,xc=new RegExp(au.source,"g");function ak(e){return function(){return e}}function lk(e){return function(t){return e(t)+""}}function _g(e,t){var n=au.lastIndex=xc.lastIndex=0,r,o,s,i=-1,a=[],l=[];for(e=e+"",t=t+"";(r=au.exec(e))&&(o=xc.exec(t));)(s=o.index)>n&&(s=t.slice(n,s),a[i]?a[i]+=s:a[++i]=s),(r=r[0])===(o=o[0])?a[i]?a[i]+=o:a[++i]=o:(a[++i]=null,l.push({i,x:Tn(r,o)})),n=xc.lastIndex;return n<t.length&&(s=t.slice(n),a[i]?a[i]+=s:a[++i]=s),a.length<2?l[0]?lk(l[0].x):ak(t):(t=l.length,function(u){for(var c=0,d;c<t;++c)a[(d=l[c]).i]=d.x(u);return a.join("")})}function Al(e,t){var n=typeof t,r;return t==null||n==="boolean"?El(t):(n==="number"?Tn:n==="string"?(r=Zr(t))?(t=r,Qr):_g:t instanceof Zr?Qr:t instanceof Date?ik:rk(t)?nk:Array.isArray(t)?ok:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?sk:Tn)(e,t)}function ck(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var yh=180/Math.PI,lu={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Mg(e,t,n,r,o,s){var i,a,l;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(l=e*n+t*r)&&(n-=e*l,r-=t*l),(a=Math.sqrt(n*n+r*r))&&(n/=a,r/=a,l/=a),e*r<t*n&&(e=-e,t=-t,l=-l,i=-i),{translateX:o,translateY:s,rotate:Math.atan2(t,e)*yh,skewX:Math.atan(l)*yh,scaleX:i,scaleY:a}}var Us;function uk(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?lu:Mg(t.a,t.b,t.c,t.d,t.e,t.f)}function fk(e){return e==null||(Us||(Us=document.createElementNS("http://www.w3.org/2000/svg","g")),Us.setAttribute("transform",e),!(e=Us.transform.baseVal.consolidate()))?lu:(e=e.matrix,Mg(e.a,e.b,e.c,e.d,e.e,e.f))}function Eg(e,t,n,r){function o(u){return u.length?u.pop()+" ":""}function s(u,c,d,f,p,h){if(u!==d||c!==f){var y=p.push("translate(",null,t,null,n);h.push({i:y-4,x:Tn(u,d)},{i:y-2,x:Tn(c,f)})}else(d||f)&&p.push("translate("+d+t+f+n)}function i(u,c,d,f){u!==c?(u-c>180?c+=360:c-u>180&&(u+=360),f.push({i:d.push(o(d)+"rotate(",null,r)-2,x:Tn(u,c)})):c&&d.push(o(d)+"rotate("+c+r)}function a(u,c,d,f){u!==c?f.push({i:d.push(o(d)+"skewX(",null,r)-2,x:Tn(u,c)}):c&&d.push(o(d)+"skewX("+c+r)}function l(u,c,d,f,p,h){if(u!==d||c!==f){var y=p.push(o(p)+"scale(",null,",",null,")");h.push({i:y-4,x:Tn(u,d)},{i:y-2,x:Tn(c,f)})}else(d!==1||f!==1)&&p.push(o(p)+"scale("+d+","+f+")")}return function(u,c){var d=[],f=[];return u=e(u),c=e(c),s(u.translateX,u.translateY,c.translateX,c.translateY,d,f),i(u.rotate,c.rotate,d,f),a(u.skewX,c.skewX,d,f),l(u.scaleX,u.scaleY,c.scaleX,c.scaleY,d,f),u=c=null,function(p){for(var h=-1,y=f.length,g;++h<y;)d[(g=f[h]).i]=g.x(p);return d.join("")}}}var dk=Eg(uk,"px, ","px)","deg)"),hk=Eg(fk,", ",")",")");function Ag(e){return(function t(n){n=+n;function r(o,s){var i=e((o=Ar(o)).h,(s=Ar(s)).h),a=Fo(o.s,s.s),l=Fo(o.l,s.l),u=Fo(o.opacity,s.opacity);return function(c){return o.h=i(c),o.s=a(c),o.l=l(Math.pow(c,n)),o.opacity=u(c),o+""}}return r.gamma=t,r})(1)}Ag(Zv);var Tg=Ag(Fo);function Og(e,t){t===void 0&&(t=e,e=Al);for(var n=0,r=t.length-1,o=t[0],s=new Array(r<0?0:r);n<r;)s[n]=e(o,o=t[++n]);return function(i){var a=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return s[a](i-a)}}function Cg(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e(r/(t-1));return n}var jo=0,gi=0,ci=0,Ng=1e3,Ia,mi,La=0,eo=0,Tl=0,Qi=typeof performance=="object"&&performance.now?performance:Date,Ig=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function mf(){return eo||(Ig(pk),eo=Qi.now()+Tl)}function pk(){eo=0}function Fa(){this._call=this._time=this._next=null}Fa.prototype=Lg.prototype={constructor:Fa,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?mf():+n)+(t==null?0:+t),!this._next&&mi!==this&&(mi?mi._next=this:Ia=this,mi=this),this._call=e,this._time=n,cu()},stop:function(){this._call&&(this._call=null,this._time=1/0,cu())}};function Lg(e,t,n){var r=new Fa;return r.restart(e,t,n),r}function yk(){mf(),++jo;for(var e=Ia,t;e;)(t=eo-e._time)>=0&&e._call.call(void 0,t),e=e._next;--jo}function gh(){eo=(La=Qi.now())+Tl,jo=gi=0;try{yk()}finally{jo=0,mk(),eo=0}}function gk(){var e=Qi.now(),t=e-La;t>Ng&&(Tl-=t,La=e)}function mk(){for(var e,t=Ia,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Ia=n);mi=e,cu(r)}function cu(e){if(!jo){gi&&(gi=clearTimeout(gi));var t=e-eo;t>24?(e<1/0&&(gi=setTimeout(gh,e-Qi.now()-Tl)),ci&&(ci=clearInterval(ci))):(ci||(La=Qi.now(),ci=setInterval(gk,Ng)),jo=1,Ig(gh))}}function mh(e,t,n){var r=new Fa;return t=t==null?0:+t,r.restart(o=>{r.stop(),e(o+t)},t,n),r}var bk=ff("start","end","cancel","interrupt"),wk=[],Fg=0,bh=1,uu=2,ha=3,wh=4,fu=5,pa=6;function Ol(e,t,n,r,o,s){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;xk(e,n,{name:t,index:r,group:o,on:bk,tween:wk,time:s.time,delay:s.delay,duration:s.duration,ease:s.ease,timer:null,state:Fg})}function bf(e,t){var n=zn(e,t);if(n.state>Fg)throw new Error("too late; already scheduled");return n}function Xn(e,t){var n=zn(e,t);if(n.state>ha)throw new Error("too late; already running");return n}function zn(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function xk(e,t,n){var r=e.__transition,o;r[t]=n,n.timer=Lg(s,0,n.time);function s(u){n.state=bh,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var c,d,f,p;if(n.state!==bh)return l();for(c in r)if(p=r[c],p.name===n.name){if(p.state===ha)return mh(i);p.state===wh?(p.state=pa,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[c]):+c<t&&(p.state=pa,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[c])}if(mh(function(){n.state===ha&&(n.state=wh,n.timer.restart(a,n.delay,n.time),a(u))}),n.state=uu,n.on.call("start",e,e.__data__,n.index,n.group),n.state===uu){for(n.state=ha,o=new Array(f=n.tween.length),c=0,d=-1;c<f;++c)(p=n.tween[c].value.call(e,e.__data__,n.index,n.group))&&(o[++d]=p);o.length=d+1}}function a(u){for(var c=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(l),n.state=fu,1),d=-1,f=o.length;++d<f;)o[d].call(e,c);n.state===fu&&(n.on.call("end",e,e.__data__,n.index,n.group),l())}function l(){n.state=pa,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function vk(e,t){var n=e.__transition,r,o,s=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){s=!1;continue}o=r.state>uu&&r.state<fu,r.state=pa,r.timer.stop(),r.on.call(o?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}s&&delete e.__transition}}function kk(e){return this.each(function(){vk(this,e)})}function Sk(e,t){var n,r;return function(){var o=Xn(this,e),s=o.tween;if(s!==n){r=n=s;for(var i=0,a=r.length;i<a;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}o.tween=r}}function $k(e,t,n){var r,o;if(typeof n!="function")throw new Error;return function(){var s=Xn(this,e),i=s.tween;if(i!==r){o=(r=i).slice();for(var a={name:t,value:n},l=0,u=o.length;l<u;++l)if(o[l].name===t){o[l]=a;break}l===u&&o.push(a)}s.tween=o}}function _k(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=zn(this.node(),n).tween,o=0,s=r.length,i;o<s;++o)if((i=r[o]).name===e)return i.value;return null}return this.each((t==null?Sk:$k)(n,e,t))}function wf(e,t,n){var r=e._id;return e.each(function(){var o=Xn(this,r);(o.value||(o.value={}))[t]=n.apply(this,arguments)}),function(o){return zn(o,r).value[t]}}function Rg(e,t){var n;return(typeof t=="number"?Tn:t instanceof Zr?Qr:(n=Zr(t))?(t=n,Qr):_g)(e,t)}function Mk(e){return function(){this.removeAttribute(e)}}function Ek(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Ak(e,t,n){var r,o=n+"",s;return function(){var i=this.getAttribute(e);return i===o?null:i===r?s:s=t(r=i,n)}}function Tk(e,t,n){var r,o=n+"",s;return function(){var i=this.getAttributeNS(e.space,e.local);return i===o?null:i===r?s:s=t(r=i,n)}}function Ok(e,t,n){var r,o,s;return function(){var i,a=n(this),l;return a==null?void this.removeAttribute(e):(i=this.getAttribute(e),l=a+"",i===l?null:i===r&&l===o?s:(o=l,s=t(r=i,a)))}}function Ck(e,t,n){var r,o,s;return function(){var i,a=n(this),l;return a==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),l=a+"",i===l?null:i===r&&l===o?s:(o=l,s=t(r=i,a)))}}function Nk(e,t){var n=$l(e),r=n==="transform"?hk:Rg;return this.attrTween(e,typeof t=="function"?(n.local?Ck:Ok)(n,r,wf(this,"attr."+e,t)):t==null?(n.local?Ek:Mk)(n):(n.local?Tk:Ak)(n,r,t))}function Ik(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function Lk(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function Fk(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&Lk(e,s)),n}return o._value=t,o}function Rk(e,t){var n,r;function o(){var s=t.apply(this,arguments);return s!==r&&(n=(r=s)&&Ik(e,s)),n}return o._value=t,o}function zk(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=$l(e);return this.tween(n,(r.local?Fk:Rk)(r,t))}function Pk(e,t){return function(){bf(this,e).delay=+t.apply(this,arguments)}}function Dk(e,t){return t=+t,function(){bf(this,e).delay=t}}function jk(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Pk:Dk)(t,e)):zn(this.node(),t).delay}function Wk(e,t){return function(){Xn(this,e).duration=+t.apply(this,arguments)}}function qk(e,t){return t=+t,function(){Xn(this,e).duration=t}}function Hk(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Wk:qk)(t,e)):zn(this.node(),t).duration}function Bk(e,t){if(typeof t!="function")throw new Error;return function(){Xn(this,e).ease=t}}function Uk(e){var t=this._id;return arguments.length?this.each(Bk(t,e)):zn(this.node(),t).ease}function Kk(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Xn(this,e).ease=n}}function Yk(e){if(typeof e!="function")throw new Error;return this.each(Kk(this._id,e))}function Gk(e){typeof e!="function"&&(e=fg(e));for(var t=this._groups,n=t.length,r=new Array(n),o=0;o<n;++o)for(var s=t[o],i=s.length,a=r[o]=[],l,u=0;u<i;++u)(l=s[u])&&e.call(l,l.__data__,u,s)&&a.push(l);return new br(r,this._parents,this._name,this._id)}function Vk(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,o=n.length,s=Math.min(r,o),i=new Array(r),a=0;a<s;++a)for(var l=t[a],u=n[a],c=l.length,d=i[a]=new Array(c),f,p=0;p<c;++p)(f=l[p]||u[p])&&(d[p]=f);for(;a<r;++a)i[a]=t[a];return new br(i,this._parents,this._name,this._id)}function Xk(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function Jk(e,t,n){var r,o,s=Xk(t)?bf:Xn;return function(){var i=s(this,e),a=i.on;a!==r&&(o=(r=a).copy()).on(t,n),i.on=o}}function Zk(e,t){var n=this._id;return arguments.length<2?zn(this.node(),n).on.on(e):this.each(Jk(n,e,t))}function Qk(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function e2(){return this.on("end.remove",Qk(this._id))}function t2(e){var t=this._name,n=this._id;typeof e!="function"&&(e=df(e));for(var r=this._groups,o=r.length,s=new Array(o),i=0;i<o;++i)for(var a=r[i],l=a.length,u=s[i]=new Array(l),c,d,f=0;f<l;++f)(c=a[f])&&(d=e.call(c,c.__data__,f,a))&&("__data__"in c&&(d.__data__=c.__data__),u[f]=d,Ol(u[f],t,n,f,u,zn(c,n)));return new br(s,this._parents,t,n)}function n2(e){var t=this._name,n=this._id;typeof e!="function"&&(e=ug(e));for(var r=this._groups,o=r.length,s=[],i=[],a=0;a<o;++a)for(var l=r[a],u=l.length,c,d=0;d<u;++d)if(c=l[d]){for(var f=e.call(c,c.__data__,d,l),p,h=zn(c,n),y=0,g=f.length;y<g;++y)(p=f[y])&&Ol(p,t,n,y,f,h);s.push(f),i.push(c)}return new br(s,i,t,n)}var r2=bs.prototype.constructor;function o2(){return new r2(this._groups,this._parents)}function i2(e,t){var n,r,o;return function(){var s=Po(this,e),i=(this.style.removeProperty(e),Po(this,e));return s===i?null:s===n&&i===r?o:o=t(n=s,r=i)}}function zg(e){return function(){this.style.removeProperty(e)}}function s2(e,t,n){var r,o=n+"",s;return function(){var i=Po(this,e);return i===o?null:i===r?s:s=t(r=i,n)}}function a2(e,t,n){var r,o,s;return function(){var i=Po(this,e),a=n(this),l=a+"";return a==null&&(l=a=(this.style.removeProperty(e),Po(this,e))),i===l?null:i===r&&l===o?s:(o=l,s=t(r=i,a))}}function l2(e,t){var n,r,o,s="style."+t,i="end."+s,a;return function(){var l=Xn(this,e),u=l.on,c=l.value[s]==null?a||(a=zg(t)):void 0;(u!==n||o!==c)&&(r=(n=u).copy()).on(i,o=c),l.on=r}}function c2(e,t,n){var r=(e+="")=="transform"?dk:Rg;return t==null?this.styleTween(e,i2(e,r)).on("end.style."+e,zg(e)):typeof t=="function"?this.styleTween(e,a2(e,r,wf(this,"style."+e,t))).each(l2(this._id,e)):this.styleTween(e,s2(e,r,t),n).on("end.style."+e,null)}function u2(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function f2(e,t,n){var r,o;function s(){var i=t.apply(this,arguments);return i!==o&&(r=(o=i)&&u2(e,i,n)),r}return s._value=t,s}function d2(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,f2(e,t,n??""))}function h2(e){return function(){this.textContent=e}}function p2(e){return function(){var t=e(this);this.textContent=t??""}}function y2(e){return this.tween("text",typeof e=="function"?p2(wf(this,"text",e)):h2(e==null?"":e+""))}function g2(e){return function(t){this.textContent=e.call(this,t)}}function m2(e){var t,n;function r(){var o=e.apply(this,arguments);return o!==n&&(t=(n=o)&&g2(o)),t}return r._value=e,r}function b2(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,m2(e))}function w2(){for(var e=this._name,t=this._id,n=Pg(),r=this._groups,o=r.length,s=0;s<o;++s)for(var i=r[s],a=i.length,l,u=0;u<a;++u)if(l=i[u]){var c=zn(l,t);Ol(l,e,n,u,i,{time:c.time+c.delay+c.duration,delay:0,duration:c.duration,ease:c.ease})}return new br(r,this._parents,e,n)}function x2(){var e,t,n=this,r=n._id,o=n.size();return new Promise(function(s,i){var a={value:i},l={value:function(){--o===0&&s()}};n.each(function(){var u=Xn(this,r),c=u.on;c!==e&&(t=(e=c).copy(),t._.cancel.push(a),t._.interrupt.push(a),t._.end.push(l)),u.on=t}),o===0&&s()})}var v2=0;function br(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function Pg(){return++v2}var rr=bs.prototype;br.prototype={constructor:br,select:t2,selectAll:n2,selectChild:rr.selectChild,selectChildren:rr.selectChildren,filter:Gk,merge:Vk,selection:o2,transition:w2,call:rr.call,nodes:rr.nodes,node:rr.node,size:rr.size,empty:rr.empty,each:rr.each,on:Zk,attr:Nk,attrTween:zk,style:c2,styleTween:d2,text:y2,textTween:b2,remove:e2,tween:_k,delay:jk,duration:Hk,ease:Uk,easeVarying:Yk,end:x2,[Symbol.iterator]:rr[Symbol.iterator]};function k2(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var S2={time:null,delay:0,duration:250,ease:k2};function $2(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function _2(e){var t,n;e instanceof br?(t=e._id,e=e._name):(t=Pg(),(n=S2).time=mf(),e=e==null?null:e+"");for(var r=this._groups,o=r.length,s=0;s<o;++s)for(var i=r[s],a=i.length,l,u=0;u<a;++u)(l=i[u])&&Ol(l,e,t,u,i,n||$2(l,t));return new br(r,this._parents,e,t)}bs.prototype.interrupt=kk;bs.prototype.transition=_2;const du=Math.PI,hu=2*du,jr=1e-6,M2=hu-jr;function Dg(e){this._+=e[0];for(let t=1,n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function E2(e){let t=Math.floor(e);if(!(t>=0))throw new Error(`invalid digits: ${e}`);if(t>15)return Dg;const n=10**t;return function(r){this._+=r[0];for(let o=1,s=r.length;o<s;++o)this._+=Math.round(arguments[o]*n)/n+r[o]}}class A2{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?Dg:E2(t)}moveTo(t,n){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(t,n){this._append`L${this._x1=+t},${this._y1=+n}`}quadraticCurveTo(t,n,r,o){this._append`Q${+t},${+n},${this._x1=+r},${this._y1=+o}`}bezierCurveTo(t,n,r,o,s,i){this._append`C${+t},${+n},${+r},${+o},${this._x1=+s},${this._y1=+i}`}arcTo(t,n,r,o,s){if(t=+t,n=+n,r=+r,o=+o,s=+s,s<0)throw new Error(`negative radius: ${s}`);let i=this._x1,a=this._y1,l=r-t,u=o-n,c=i-t,d=a-n,f=c*c+d*d;if(this._x1===null)this._append`M${this._x1=t},${this._y1=n}`;else if(f>jr)if(!(Math.abs(d*l-u*c)>jr)||!s)this._append`L${this._x1=t},${this._y1=n}`;else{let p=r-i,h=o-a,y=l*l+u*u,g=p*p+h*h,m=Math.sqrt(y),b=Math.sqrt(f),w=s*Math.tan((du-Math.acos((y+f-g)/(2*m*b)))/2),x=w/b,S=w/m;Math.abs(x-1)>jr&&this._append`L${t+x*c},${n+x*d}`,this._append`A${s},${s},0,0,${+(d*p>c*h)},${this._x1=t+S*l},${this._y1=n+S*u}`}}arc(t,n,r,o,s,i){if(t=+t,n=+n,r=+r,i=!!i,r<0)throw new Error(`negative radius: ${r}`);let a=r*Math.cos(o),l=r*Math.sin(o),u=t+a,c=n+l,d=1^i,f=i?o-s:s-o;this._x1===null?this._append`M${u},${c}`:(Math.abs(this._x1-u)>jr||Math.abs(this._y1-c)>jr)&&this._append`L${u},${c}`,r&&(f<0&&(f=f%hu+hu),f>M2?this._append`A${r},${r},0,1,${d},${t-a},${n-l}A${r},${r},0,1,${d},${this._x1=u},${this._y1=c}`:f>jr&&this._append`A${r},${r},0,${+(f>=du)},${d},${this._x1=t+r*Math.cos(s)},${this._y1=n+r*Math.sin(s)}`)}rect(t,n,r,o){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${r=+r}v${+o}h${-r}Z`}toString(){return this._}}function T2(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Ra(e,t){if(!isFinite(e)||e===0)return null;var n=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"),r=e.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+e.slice(n+1)]}function Wo(e){return e=Ra(Math.abs(e)),e?e[1]:NaN}function O2(e,t){return function(n,r){for(var o=n.length,s=[],i=0,a=e[0],l=0;o>0&&a>0&&(l+a+1>r&&(a=Math.max(1,r-l)),s.push(n.substring(o-=a,o+a)),!((l+=a+1)>r));)a=e[i=(i+1)%e.length];return s.reverse().join(t)}}function C2(e){return function(t){return t.replace(/[0-9]/g,function(n){return e[+n]})}}var N2=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function es(e){if(!(t=N2.exec(e)))throw new Error("invalid format: "+e);var t;return new xf({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}es.prototype=xf.prototype;function xf(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}xf.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function I2(e){e:for(var t=e.length,n=1,r=-1,o;n<t;++n)switch(e[n]){case".":r=o=n;break;case"0":r===0&&(r=n),o=n;break;default:if(!+e[n])break e;r>0&&(r=0);break}return r>0?e.slice(0,r)+e.slice(o+1):e}var za;function L2(e,t){var n=Ra(e,t);if(!n)return za=void 0,e.toPrecision(t);var r=n[0],o=n[1],s=o-(za=Math.max(-8,Math.min(8,Math.floor(o/3)))*3)+1,i=r.length;return s===i?r:s>i?r+new Array(s-i+1).join("0"):s>0?r.slice(0,s)+"."+r.slice(s):"0."+new Array(1-s).join("0")+Ra(e,Math.max(0,t+s-1))[0]}function xh(e,t){var n=Ra(e,t);if(!n)return e+"";var r=n[0],o=n[1];return o<0?"0."+new Array(-o).join("0")+r:r.length>o+1?r.slice(0,o+1)+"."+r.slice(o+1):r+new Array(o-r.length+2).join("0")}const vh={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:T2,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>xh(e*100,t),r:xh,s:L2,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function kh(e){return e}var Sh=Array.prototype.map,$h=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function F2(e){var t=e.grouping===void 0||e.thousands===void 0?kh:O2(Sh.call(e.grouping,Number),e.thousands+""),n=e.currency===void 0?"":e.currency[0]+"",r=e.currency===void 0?"":e.currency[1]+"",o=e.decimal===void 0?".":e.decimal+"",s=e.numerals===void 0?kh:C2(Sh.call(e.numerals,String)),i=e.percent===void 0?"%":e.percent+"",a=e.minus===void 0?"−":e.minus+"",l=e.nan===void 0?"NaN":e.nan+"";function u(d,f){d=es(d);var p=d.fill,h=d.align,y=d.sign,g=d.symbol,m=d.zero,b=d.width,w=d.comma,x=d.precision,S=d.trim,v=d.type;v==="n"?(w=!0,v="g"):vh[v]||(x===void 0&&(x=12),S=!0,v="g"),(m||p==="0"&&h==="=")&&(m=!0,p="0",h="=");var k=(f&&f.prefix!==void 0?f.prefix:"")+(g==="$"?n:g==="#"&&/[boxX]/.test(v)?"0"+v.toLowerCase():""),_=(g==="$"?r:/[%p]/.test(v)?i:"")+(f&&f.suffix!==void 0?f.suffix:""),A=vh[v],L=/[defgprs%]/.test(v);x=x===void 0?6:/[gprs]/.test(v)?Math.max(1,Math.min(21,x)):Math.max(0,Math.min(20,x));function N(I){var T=k,M=_,$,F,D;if(v==="c")M=A(I)+M,I="";else{I=+I;var P=I<0||1/I<0;if(I=isNaN(I)?l:A(Math.abs(I),x),S&&(I=I2(I)),P&&+I==0&&y!=="+"&&(P=!1),T=(P?y==="("?y:a:y==="-"||y==="("?"":y)+T,M=(v==="s"&&!isNaN(I)&&za!==void 0?$h[8+za/3]:"")+M+(P&&y==="("?")":""),L){for($=-1,F=I.length;++$<F;)if(D=I.charCodeAt($),48>D||D>57){M=(D===46?o+I.slice($+1):I.slice($))+M,I=I.slice(0,$);break}}}w&&!m&&(I=t(I,1/0));var j=T.length+I.length+M.length,G=j<b?new Array(b-j+1).join(p):"";switch(w&&m&&(I=t(G+I,G.length?b-M.length:1/0),G=""),h){case"<":I=T+I+M+G;break;case"=":I=T+G+I+M;break;case"^":I=G.slice(0,j=G.length>>1)+T+I+M+G.slice(j);break;default:I=G+T+I+M;break}return s(I)}return N.toString=function(){return d+""},N}function c(d,f){var p=Math.max(-8,Math.min(8,Math.floor(Wo(f)/3)))*3,h=Math.pow(10,-p),y=u((d=es(d),d.type="f",d),{suffix:$h[8+p/3]});return function(g){return y(h*g)}}return{format:u,formatPrefix:c}}var Ks,Qo,jg;R2({thousands:",",grouping:[3],currency:["$",""]});function R2(e){return Ks=F2(e),Qo=Ks.format,jg=Ks.formatPrefix,Ks}function z2(e){return Math.max(0,-Wo(Math.abs(e)))}function P2(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(Wo(t)/3)))*3-Wo(Math.abs(e)))}function D2(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,Wo(t)-Wo(e))+1}var Be=1e-6,Wg=1e-12,Ye=Math.PI,St=Ye/2,Pa=Ye/4,en=Ye*2,Kt=180/Ye,ut=Ye/180,ot=Math.abs,ei=Math.atan,Kn=Math.atan2,qe=Math.cos,qg=Math.exp,Da=Math.log,vc=Math.pow,De=Math.sin,kn=Math.sign||function(e){return e>0?1:e<0?-1:0},fn=Math.sqrt,vf=Math.tan;function Hg(e){return e>1?0:e<-1?Ye:Math.acos(e)}function Mn(e){return e>1?St:e<-1?-St:Math.asin(e)}function Gt(){}function ja(e,t){e&&Mh.hasOwnProperty(e.type)&&Mh[e.type](e,t)}var _h={Feature:function(e,t){ja(e.geometry,t)},FeatureCollection:function(e,t){for(var n=e.features,r=-1,o=n.length;++r<o;)ja(n[r].geometry,t)}},Mh={Sphere:function(e,t){t.sphere()},Point:function(e,t){e=e.coordinates,t.point(e[0],e[1],e[2])},MultiPoint:function(e,t){for(var n=e.coordinates,r=-1,o=n.length;++r<o;)e=n[r],t.point(e[0],e[1],e[2])},LineString:function(e,t){pu(e.coordinates,t,0)},MultiLineString:function(e,t){for(var n=e.coordinates,r=-1,o=n.length;++r<o;)pu(n[r],t,0)},Polygon:function(e,t){Eh(e.coordinates,t)},MultiPolygon:function(e,t){for(var n=e.coordinates,r=-1,o=n.length;++r<o;)Eh(n[r],t)},GeometryCollection:function(e,t){for(var n=e.geometries,r=-1,o=n.length;++r<o;)ja(n[r],t)}};function pu(e,t,n){var r=-1,o=e.length-n,s;for(t.lineStart();++r<o;)s=e[r],t.point(s[0],s[1],s[2]);t.lineEnd()}function Eh(e,t){var n=-1,r=e.length;for(t.polygonStart();++n<r;)pu(e[n],t,1);t.polygonEnd()}function Wr(e,t){e&&_h.hasOwnProperty(e.type)?_h[e.type](e,t):ja(e,t)}var yu=new Ln,Wa=new Ln,Bg,Ug,gu,mu,bu,ts={point:Gt,lineStart:Gt,lineEnd:Gt,polygonStart:function(){yu=new Ln,ts.lineStart=j2,ts.lineEnd=W2},polygonEnd:function(){var e=+yu;Wa.add(e<0?en+e:e),this.lineStart=this.lineEnd=this.point=Gt},sphere:function(){Wa.add(en)}};function j2(){ts.point=q2}function W2(){Kg(Bg,Ug)}function q2(e,t){ts.point=Kg,Bg=e,Ug=t,e*=ut,t*=ut,gu=e,mu=qe(t=t/2+Pa),bu=De(t)}function Kg(e,t){e*=ut,t*=ut,t=t/2+Pa;var n=e-gu,r=n>=0?1:-1,o=r*n,s=qe(t),i=De(t),a=bu*i,l=mu*s+a*qe(o),u=a*r*De(o);yu.add(Kn(u,l)),gu=e,mu=s,bu=i}function H2(e){return Wa=new Ln,Wr(e,ts),Wa*2}function wu(e){return[Kn(e[1],e[0]),Mn(e[2])]}function qo(e){var t=e[0],n=e[1],r=qe(n);return[r*qe(t),r*De(t),De(n)]}function Ys(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function qa(e,t){return[e[1]*t[2]-e[2]*t[1],e[2]*t[0]-e[0]*t[2],e[0]*t[1]-e[1]*t[0]]}function kc(e,t){e[0]+=t[0],e[1]+=t[1],e[2]+=t[2]}function Gs(e,t){return[e[0]*t,e[1]*t,e[2]*t]}function xu(e){var t=fn(e[0]*e[0]+e[1]*e[1]+e[2]*e[2]);e[0]/=t,e[1]/=t,e[2]/=t}function vu(e,t){function n(r,o){return r=e(r,o),t(r[0],r[1])}return e.invert&&t.invert&&(n.invert=function(r,o){return r=t.invert(r,o),r&&e.invert(r[0],r[1])}),n}function ku(e,t){return ot(e)>Ye&&(e-=Math.round(e/en)*en),[e,t]}ku.invert=ku;function Yg(e,t,n){return(e%=en)?t||n?vu(Th(e),Oh(t,n)):Th(e):t||n?Oh(t,n):ku}function Ah(e){return function(t,n){return t+=e,ot(t)>Ye&&(t-=Math.round(t/en)*en),[t,n]}}function Th(e){var t=Ah(e);return t.invert=Ah(-e),t}function Oh(e,t){var n=qe(e),r=De(e),o=qe(t),s=De(t);function i(a,l){var u=qe(l),c=qe(a)*u,d=De(a)*u,f=De(l),p=f*n+c*r;return[Kn(d*o-p*s,c*n-f*r),Mn(p*o+d*s)]}return i.invert=function(a,l){var u=qe(l),c=qe(a)*u,d=De(a)*u,f=De(l),p=f*o-d*s;return[Kn(d*o+f*s,c*n+p*r),Mn(p*n-c*r)]},i}function B2(e){e=Yg(e[0]*ut,e[1]*ut,e.length>2?e[2]*ut:0);function t(n){return n=e(n[0]*ut,n[1]*ut),n[0]*=Kt,n[1]*=Kt,n}return t.invert=function(n){return n=e.invert(n[0]*ut,n[1]*ut),n[0]*=Kt,n[1]*=Kt,n},t}function U2(e,t,n,r,o,s){if(n){var i=qe(t),a=De(t),l=r*n;o==null?(o=t+r*en,s=t-l/2):(o=Ch(i,o),s=Ch(i,s),(r>0?o<s:o>s)&&(o+=r*en));for(var u,c=o;r>0?c>s:c<s;c-=l)u=wu([i,-a*qe(c),-a*De(c)]),e.point(u[0],u[1])}}function Ch(e,t){t=qo(t),t[0]-=e,xu(t);var n=Hg(-t[1]);return((-t[2]<0?-n:n)+en-Be)%en}function Gg(){var e=[],t;return{point:function(n,r,o){t.push([n,r,o])},lineStart:function(){e.push(t=[])},lineEnd:Gt,rejoin:function(){e.length>1&&e.push(e.pop().concat(e.shift()))},result:function(){var n=e;return e=[],t=null,n}}}function ya(e,t){return ot(e[0]-t[0])<Be&&ot(e[1]-t[1])<Be}function Vs(e,t,n,r){this.x=e,this.z=t,this.o=n,this.e=r,this.v=!1,this.n=this.p=null}function Vg(e,t,n,r,o){var s=[],i=[],a,l;if(e.forEach(function(h){if(!((y=h.length-1)<=0)){var y,g=h[0],m=h[y],b;if(ya(g,m)){if(!g[2]&&!m[2]){for(o.lineStart(),a=0;a<y;++a)o.point((g=h[a])[0],g[1]);o.lineEnd();return}m[0]+=2*Be}s.push(b=new Vs(g,h,null,!0)),i.push(b.o=new Vs(g,null,b,!1)),s.push(b=new Vs(m,h,null,!1)),i.push(b.o=new Vs(m,null,b,!0))}}),!!s.length){for(i.sort(t),Nh(s),Nh(i),a=0,l=i.length;a<l;++a)i[a].e=n=!n;for(var u=s[0],c,d;;){for(var f=u,p=!0;f.v;)if((f=f.n)===u)return;c=f.z,o.lineStart();do{if(f.v=f.o.v=!0,f.e){if(p)for(a=0,l=c.length;a<l;++a)o.point((d=c[a])[0],d[1]);else r(f.x,f.n.x,1,o);f=f.n}else{if(p)for(c=f.p.z,a=c.length-1;a>=0;--a)o.point((d=c[a])[0],d[1]);else r(f.x,f.p.x,-1,o);f=f.p}f=f.o,c=f.z,p=!p}while(!f.v);o.lineEnd()}}}function Nh(e){if(t=e.length){for(var t,n=0,r=e[0],o;++n<t;)r.n=o=e[n],o.p=r,r=o;r.n=o=e[0],o.p=r}}function Sc(e){return ot(e[0])<=Ye?e[0]:kn(e[0])*((ot(e[0])+Ye)%en-Ye)}function K2(e,t){var n=Sc(t),r=t[1],o=De(r),s=[De(n),-qe(n),0],i=0,a=0,l=new Ln;o===1?r=St+Be:o===-1&&(r=-St-Be);for(var u=0,c=e.length;u<c;++u)if(f=(d=e[u]).length)for(var d,f,p=d[f-1],h=Sc(p),y=p[1]/2+Pa,g=De(y),m=qe(y),b=0;b<f;++b,h=x,g=v,m=k,p=w){var w=d[b],x=Sc(w),S=w[1]/2+Pa,v=De(S),k=qe(S),_=x-h,A=_>=0?1:-1,L=A*_,N=L>Ye,I=g*v;if(l.add(Kn(I*A*De(L),m*k+I*qe(L))),i+=N?_+A*en:_,N^h>=n^x>=n){var T=qa(qo(p),qo(w));xu(T);var M=qa(s,T);xu(M);var $=(N^_>=0?-1:1)*Mn(M[2]);(r>$||r===$&&(T[0]||T[1]))&&(a+=N^_>=0?1:-1)}}return(i<-Be||i<Be&&l<-Wg)^a&1}function Xg(e,t,n,r){return function(o){var s=t(o),i=Gg(),a=t(i),l=!1,u,c,d,f={point:p,lineStart:y,lineEnd:g,polygonStart:function(){f.point=m,f.lineStart=b,f.lineEnd=w,c=[],u=[]},polygonEnd:function(){f.point=p,f.lineStart=y,f.lineEnd=g,c=lg(c);var x=K2(u,r);c.length?(l||(o.polygonStart(),l=!0),Vg(c,G2,x,n,o)):x&&(l||(o.polygonStart(),l=!0),o.lineStart(),n(null,null,1,o),o.lineEnd()),l&&(o.polygonEnd(),l=!1),c=u=null},sphere:function(){o.polygonStart(),o.lineStart(),n(null,null,1,o),o.lineEnd(),o.polygonEnd()}};function p(x,S){e(x,S)&&o.point(x,S)}function h(x,S){s.point(x,S)}function y(){f.point=h,s.lineStart()}function g(){f.point=p,s.lineEnd()}function m(x,S){d.push([x,S]),a.point(x,S)}function b(){a.lineStart(),d=[]}function w(){m(d[0][0],d[0][1]),a.lineEnd();var x=a.clean(),S=i.result(),v,k=S.length,_,A,L;if(d.pop(),u.push(d),d=null,!!k){if(x&1){if(A=S[0],(_=A.length-1)>0){for(l||(o.polygonStart(),l=!0),o.lineStart(),v=0;v<_;++v)o.point((L=A[v])[0],L[1]);o.lineEnd()}return}k>1&&x&2&&S.push(S.pop().concat(S.shift())),c.push(S.filter(Y2))}}return f}}function Y2(e){return e.length>1}function G2(e,t){return((e=e.x)[0]<0?e[1]-St-Be:St-e[1])-((t=t.x)[0]<0?t[1]-St-Be:St-t[1])}const Ih=Xg(function(){return!0},V2,J2,[-Ye,-St]);function V2(e){var t=NaN,n=NaN,r=NaN,o;return{lineStart:function(){e.lineStart(),o=1},point:function(s,i){var a=s>0?Ye:-Ye,l=ot(s-t);ot(l-Ye)<Be?(e.point(t,n=(n+i)/2>0?St:-St),e.point(r,n),e.lineEnd(),e.lineStart(),e.point(a,n),e.point(s,n),o=0):r!==a&&l>=Ye&&(ot(t-r)<Be&&(t-=r*Be),ot(s-a)<Be&&(s-=a*Be),n=X2(t,n,s,i),e.point(r,n),e.lineEnd(),e.lineStart(),e.point(a,n),o=0),e.point(t=s,n=i),r=a},lineEnd:function(){e.lineEnd(),t=n=NaN},clean:function(){return 2-o}}}function X2(e,t,n,r){var o,s,i=De(e-n);return ot(i)>Be?ei((De(t)*(s=qe(r))*De(n)-De(r)*(o=qe(t))*De(e))/(o*s*i)):(t+r)/2}function J2(e,t,n,r){var o;if(e==null)o=n*St,r.point(-Ye,o),r.point(0,o),r.point(Ye,o),r.point(Ye,0),r.point(Ye,-o),r.point(0,-o),r.point(-Ye,-o),r.point(-Ye,0),r.point(-Ye,o);else if(ot(e[0]-t[0])>Be){var s=e[0]<t[0]?Ye:-Ye;o=n*s/2,r.point(-s,o),r.point(0,o),r.point(s,o)}else r.point(t[0],t[1])}function Z2(e){var t=qe(e),n=2*ut,r=t>0,o=ot(t)>Be;function s(c,d,f,p){U2(p,e,n,f,c,d)}function i(c,d){return qe(c)*qe(d)>t}function a(c){var d,f,p,h,y;return{lineStart:function(){h=p=!1,y=1},point:function(g,m){var b=[g,m],w,x=i(g,m),S=r?x?0:u(g,m):x?u(g+(g<0?Ye:-Ye),m):0;if(!d&&(h=p=x)&&c.lineStart(),x!==p&&(w=l(d,b),(!w||ya(d,w)||ya(b,w))&&(b[2]=1)),x!==p)y=0,x?(c.lineStart(),w=l(b,d),c.point(w[0],w[1])):(w=l(d,b),c.point(w[0],w[1],2),c.lineEnd()),d=w;else if(o&&d&&r^x){var v;!(S&f)&&(v=l(b,d,!0))&&(y=0,r?(c.lineStart(),c.point(v[0][0],v[0][1]),c.point(v[1][0],v[1][1]),c.lineEnd()):(c.point(v[1][0],v[1][1]),c.lineEnd(),c.lineStart(),c.point(v[0][0],v[0][1],3)))}x&&(!d||!ya(d,b))&&c.point(b[0],b[1]),d=b,p=x,f=S},lineEnd:function(){p&&c.lineEnd(),d=null},clean:function(){return y|(h&&p)<<1}}}function l(c,d,f){var p=qo(c),h=qo(d),y=[1,0,0],g=qa(p,h),m=Ys(g,g),b=g[0],w=m-b*b;if(!w)return!f&&c;var x=t*m/w,S=-t*b/w,v=qa(y,g),k=Gs(y,x),_=Gs(g,S);kc(k,_);var A=v,L=Ys(k,A),N=Ys(A,A),I=L*L-N*(Ys(k,k)-1);if(!(I<0)){var T=fn(I),M=Gs(A,(-L-T)/N);if(kc(M,k),M=wu(M),!f)return M;var $=c[0],F=d[0],D=c[1],P=d[1],j;F<$&&(j=$,$=F,F=j);var G=F-$,J=ot(G-Ye)<Be,re=J||G<Be;if(!J&&P<D&&(j=D,D=P,P=j),re?J?D+P>0^M[1]<(ot(M[0]-$)<Be?D:P):D<=M[1]&&M[1]<=P:G>Ye^($<=M[0]&&M[0]<=F)){var Q=Gs(A,(-L+T)/N);return kc(Q,k),[M,wu(Q)]}}}function u(c,d){var f=r?e:Ye-e,p=0;return c<-f?p|=1:c>f&&(p|=2),d<-f?p|=4:d>f&&(p|=8),p}return Xg(i,a,s,r?[0,-e]:[-Ye,e-Ye])}function Q2(e,t,n,r,o,s){var i=e[0],a=e[1],l=t[0],u=t[1],c=0,d=1,f=l-i,p=u-a,h;if(h=n-i,!(!f&&h>0)){if(h/=f,f<0){if(h<c)return;h<d&&(d=h)}else if(f>0){if(h>d)return;h>c&&(c=h)}if(h=o-i,!(!f&&h<0)){if(h/=f,f<0){if(h>d)return;h>c&&(c=h)}else if(f>0){if(h<c)return;h<d&&(d=h)}if(h=r-a,!(!p&&h>0)){if(h/=p,p<0){if(h<c)return;h<d&&(d=h)}else if(p>0){if(h>d)return;h>c&&(c=h)}if(h=s-a,!(!p&&h<0)){if(h/=p,p<0){if(h>d)return;h>c&&(c=h)}else if(p>0){if(h<c)return;h<d&&(d=h)}return c>0&&(e[0]=i+c*f,e[1]=a+c*p),d<1&&(t[0]=i+d*f,t[1]=a+d*p),!0}}}}}var bi=1e9,Xs=-bi;function Jg(e,t,n,r){function o(u,c){return e<=u&&u<=n&&t<=c&&c<=r}function s(u,c,d,f){var p=0,h=0;if(u==null||(p=i(u,d))!==(h=i(c,d))||l(u,c)<0^d>0)do f.point(p===0||p===3?e:n,p>1?r:t);while((p=(p+d+4)%4)!==h);else f.point(c[0],c[1])}function i(u,c){return ot(u[0]-e)<Be?c>0?0:3:ot(u[0]-n)<Be?c>0?2:1:ot(u[1]-t)<Be?c>0?1:0:c>0?3:2}function a(u,c){return l(u.x,c.x)}function l(u,c){var d=i(u,1),f=i(c,1);return d!==f?d-f:d===0?c[1]-u[1]:d===1?u[0]-c[0]:d===2?u[1]-c[1]:c[0]-u[0]}return function(u){var c=u,d=Gg(),f,p,h,y,g,m,b,w,x,S,v,k={point:_,lineStart:I,lineEnd:T,polygonStart:L,polygonEnd:N};function _($,F){o($,F)&&c.point($,F)}function A(){for(var $=0,F=0,D=p.length;F<D;++F)for(var P=p[F],j=1,G=P.length,J=P[0],re,Q,ve=J[0],Ce=J[1];j<G;++j)re=ve,Q=Ce,J=P[j],ve=J[0],Ce=J[1],Q<=r?Ce>r&&(ve-re)*(r-Q)>(Ce-Q)*(e-re)&&++$:Ce<=r&&(ve-re)*(r-Q)<(Ce-Q)*(e-re)&&--$;return $}function L(){c=d,f=[],p=[],v=!0}function N(){var $=A(),F=v&&$,D=(f=lg(f)).length;(F||D)&&(u.polygonStart(),F&&(u.lineStart(),s(null,null,1,u),u.lineEnd()),D&&Vg(f,a,$,s,u),u.polygonEnd()),c=u,f=p=h=null}function I(){k.point=M,p&&p.push(h=[]),S=!0,x=!1,b=w=NaN}function T(){f&&(M(y,g),m&&x&&d.rejoin(),f.push(d.result())),k.point=_,x&&c.lineEnd()}function M($,F){var D=o($,F);if(p&&h.push([$,F]),S)y=$,g=F,m=D,S=!1,D&&(c.lineStart(),c.point($,F));else if(D&&x)c.point($,F);else{var P=[b=Math.max(Xs,Math.min(bi,b)),w=Math.max(Xs,Math.min(bi,w))],j=[$=Math.max(Xs,Math.min(bi,$)),F=Math.max(Xs,Math.min(bi,F))];Q2(P,j,e,t,n,r)?(x||(c.lineStart(),c.point(P[0],P[1])),c.point(j[0],j[1]),D||c.lineEnd(),v=!1):D&&(c.lineStart(),c.point($,F),v=!1)}b=$,w=F,x=D}return k}}const ns=e=>e;var $c=new Ln,Su=new Ln,Zg,Qg,$u,_u,sr={point:Gt,lineStart:Gt,lineEnd:Gt,polygonStart:function(){sr.lineStart=eS,sr.lineEnd=nS},polygonEnd:function(){sr.lineStart=sr.lineEnd=sr.point=Gt,$c.add(ot(Su)),Su=new Ln},result:function(){var e=$c/2;return $c=new Ln,e}};function eS(){sr.point=tS}function tS(e,t){sr.point=em,Zg=$u=e,Qg=_u=t}function em(e,t){Su.add(_u*e-$u*t),$u=e,_u=t}function nS(){em(Zg,Qg)}var Ho=1/0,Ha=Ho,rs=-Ho,Ba=rs,Ua={point:rS,lineStart:Gt,lineEnd:Gt,polygonStart:Gt,polygonEnd:Gt,result:function(){var e=[[Ho,Ha],[rs,Ba]];return rs=Ba=-(Ha=Ho=1/0),e}};function rS(e,t){e<Ho&&(Ho=e),e>rs&&(rs=e),t<Ha&&(Ha=t),t>Ba&&(Ba=t)}var Mu=0,Eu=0,wi=0,Ka=0,Ya=0,Ao=0,Au=0,Tu=0,xi=0,tm,nm,Wn,qn,vn={point:to,lineStart:Lh,lineEnd:Fh,polygonStart:function(){vn.lineStart=sS,vn.lineEnd=aS},polygonEnd:function(){vn.point=to,vn.lineStart=Lh,vn.lineEnd=Fh},result:function(){var e=xi?[Au/xi,Tu/xi]:Ao?[Ka/Ao,Ya/Ao]:wi?[Mu/wi,Eu/wi]:[NaN,NaN];return Mu=Eu=wi=Ka=Ya=Ao=Au=Tu=xi=0,e}};function to(e,t){Mu+=e,Eu+=t,++wi}function Lh(){vn.point=oS}function oS(e,t){vn.point=iS,to(Wn=e,qn=t)}function iS(e,t){var n=e-Wn,r=t-qn,o=fn(n*n+r*r);Ka+=o*(Wn+e)/2,Ya+=o*(qn+t)/2,Ao+=o,to(Wn=e,qn=t)}function Fh(){vn.point=to}function sS(){vn.point=lS}function aS(){rm(tm,nm)}function lS(e,t){vn.point=rm,to(tm=Wn=e,nm=qn=t)}function rm(e,t){var n=e-Wn,r=t-qn,o=fn(n*n+r*r);Ka+=o*(Wn+e)/2,Ya+=o*(qn+t)/2,Ao+=o,o=qn*e-Wn*t,Au+=o*(Wn+e),Tu+=o*(qn+t),xi+=o*3,to(Wn=e,qn=t)}function om(e){this._context=e}om.prototype={_radius:4.5,pointRadius:function(e){return this._radius=e,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){this._line===0&&this._context.closePath(),this._point=NaN},point:function(e,t){switch(this._point){case 0:{this._context.moveTo(e,t),this._point=1;break}case 1:{this._context.lineTo(e,t);break}default:{this._context.moveTo(e+this._radius,t),this._context.arc(e,t,this._radius,0,en);break}}},result:Gt};var Ou=new Ln,_c,im,sm,vi,ki,os={point:Gt,lineStart:function(){os.point=cS},lineEnd:function(){_c&&am(im,sm),os.point=Gt},polygonStart:function(){_c=!0},polygonEnd:function(){_c=null},result:function(){var e=+Ou;return Ou=new Ln,e}};function cS(e,t){os.point=am,im=vi=e,sm=ki=t}function am(e,t){vi-=e,ki-=t,Ou.add(fn(vi*vi+ki*ki)),vi=e,ki=t}let Rh,Ga,zh,Ph;class Dh{constructor(t){this._append=t==null?lm:uS(t),this._radius=4.5,this._=""}pointRadius(t){return this._radius=+t,this}polygonStart(){this._line=0}polygonEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){this._line===0&&(this._+="Z"),this._point=NaN}point(t,n){switch(this._point){case 0:{this._append`M${t},${n}`,this._point=1;break}case 1:{this._append`L${t},${n}`;break}default:{if(this._append`M${t},${n}`,this._radius!==zh||this._append!==Ga){const r=this._radius,o=this._;this._="",this._append`m0,${r}a${r},${r} 0 1,1 0,${-2*r}a${r},${r} 0 1,1 0,${2*r}z`,zh=r,Ga=this._append,Ph=this._,this._=o}this._+=Ph;break}}}result(){const t=this._;return this._="",t.length?t:null}}function lm(e){let t=1;this._+=e[0];for(const n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function uS(e){const t=Math.floor(e);if(!(t>=0))throw new RangeError(`invalid digits: ${e}`);if(t>15)return lm;if(t!==Rh){const n=10**t;Rh=t,Ga=function(o){let s=1;this._+=o[0];for(const i=o.length;s<i;++s)this._+=Math.round(arguments[s]*n)/n+o[s]}}return Ga}function fS(e,t){let n=3,r=4.5,o,s;function i(a){return a&&(typeof r=="function"&&s.pointRadius(+r.apply(this,arguments)),Wr(a,o(s))),s.result()}return i.area=function(a){return Wr(a,o(sr)),sr.result()},i.measure=function(a){return Wr(a,o(os)),os.result()},i.bounds=function(a){return Wr(a,o(Ua)),Ua.result()},i.centroid=function(a){return Wr(a,o(vn)),vn.result()},i.projection=function(a){return arguments.length?(o=a==null?(e=null,ns):(e=a).stream,i):e},i.context=function(a){return arguments.length?(s=a==null?(t=null,new Dh(n)):new om(t=a),typeof r!="function"&&s.pointRadius(r),i):t},i.pointRadius=function(a){return arguments.length?(r=typeof a=="function"?a:(s.pointRadius(+a),+a),i):r},i.digits=function(a){if(!arguments.length)return n;if(a==null)n=null;else{const l=Math.floor(a);if(!(l>=0))throw new RangeError(`invalid digits: ${a}`);n=l}return t===null&&(s=new Dh(n)),i},i.projection(e).digits(n).context(t)}function Cl(e){return function(t){var n=new Cu;for(var r in e)n[r]=e[r];return n.stream=t,n}}function Cu(){}Cu.prototype={constructor:Cu,point:function(e,t){this.stream.point(e,t)},sphere:function(){this.stream.sphere()},lineStart:function(){this.stream.lineStart()},lineEnd:function(){this.stream.lineEnd()},polygonStart:function(){this.stream.polygonStart()},polygonEnd:function(){this.stream.polygonEnd()}};function kf(e,t,n){var r=e.clipExtent&&e.clipExtent();return e.scale(150).translate([0,0]),r!=null&&e.clipExtent(null),Wr(n,e.stream(Ua)),t(Ua.result()),r!=null&&e.clipExtent(r),e}function Nl(e,t,n){return kf(e,function(r){var o=t[1][0]-t[0][0],s=t[1][1]-t[0][1],i=Math.min(o/(r[1][0]-r[0][0]),s/(r[1][1]-r[0][1])),a=+t[0][0]+(o-i*(r[1][0]+r[0][0]))/2,l=+t[0][1]+(s-i*(r[1][1]+r[0][1]))/2;e.scale(150*i).translate([a,l])},n)}function Sf(e,t,n){return Nl(e,[[0,0],t],n)}function $f(e,t,n){return kf(e,function(r){var o=+t,s=o/(r[1][0]-r[0][0]),i=(o-s*(r[1][0]+r[0][0]))/2,a=-s*r[0][1];e.scale(150*s).translate([i,a])},n)}function _f(e,t,n){return kf(e,function(r){var o=+t,s=o/(r[1][1]-r[0][1]),i=-s*r[0][0],a=(o-s*(r[1][1]+r[0][1]))/2;e.scale(150*s).translate([i,a])},n)}var jh=16,dS=qe(30*ut);function Wh(e,t){return+t?pS(e,t):hS(e)}function hS(e){return Cl({point:function(t,n){t=e(t,n),this.stream.point(t[0],t[1])}})}function pS(e,t){function n(r,o,s,i,a,l,u,c,d,f,p,h,y,g){var m=u-r,b=c-o,w=m*m+b*b;if(w>4*t&&y--){var x=i+f,S=a+p,v=l+h,k=fn(x*x+S*S+v*v),_=Mn(v/=k),A=ot(ot(v)-1)<Be||ot(s-d)<Be?(s+d)/2:Kn(S,x),L=e(A,_),N=L[0],I=L[1],T=N-r,M=I-o,$=b*T-m*M;($*$/w>t||ot((m*T+b*M)/w-.5)>.3||i*f+a*p+l*h<dS)&&(n(r,o,s,i,a,l,N,I,A,x/=k,S/=k,v,y,g),g.point(N,I),n(N,I,A,x,S,v,u,c,d,f,p,h,y,g))}}return function(r){var o,s,i,a,l,u,c,d,f,p,h,y,g={point:m,lineStart:b,lineEnd:x,polygonStart:function(){r.polygonStart(),g.lineStart=S},polygonEnd:function(){r.polygonEnd(),g.lineStart=b}};function m(_,A){_=e(_,A),r.point(_[0],_[1])}function b(){d=NaN,g.point=w,r.lineStart()}function w(_,A){var L=qo([_,A]),N=e(_,A);n(d,f,c,p,h,y,d=N[0],f=N[1],c=_,p=L[0],h=L[1],y=L[2],jh,r),r.point(d,f)}function x(){g.point=m,r.lineEnd()}function S(){b(),g.point=v,g.lineEnd=k}function v(_,A){w(o=_,A),s=d,i=f,a=p,l=h,u=y,g.point=w}function k(){n(d,f,c,p,h,y,s,i,o,a,l,u,jh,r),g.lineEnd=x,x()}return g}}var yS=Cl({point:function(e,t){this.stream.point(e*ut,t*ut)}});function gS(e){return Cl({point:function(t,n){var r=e(t,n);return this.stream.point(r[0],r[1])}})}function mS(e,t,n,r,o){function s(i,a){return i*=r,a*=o,[t+e*i,n-e*a]}return s.invert=function(i,a){return[(i-t)/e*r,(n-a)/e*o]},s}function qh(e,t,n,r,o,s){if(!s)return mS(e,t,n,r,o);var i=qe(s),a=De(s),l=i*e,u=a*e,c=i/e,d=a/e,f=(a*n-i*t)/e,p=(a*t+i*n)/e;function h(y,g){return y*=r,g*=o,[l*y-u*g+t,n-u*y-l*g]}return h.invert=function(y,g){return[r*(c*y-d*g+f),o*(p-d*y-c*g)]},h}function Ir(e){return cm(function(){return e})()}function cm(e){var t,n=150,r=480,o=250,s=0,i=0,a=0,l=0,u=0,c,d=0,f=1,p=1,h=null,y=Ih,g=null,m,b,w,x=ns,S=.5,v,k,_,A,L;function N($){return _($[0]*ut,$[1]*ut)}function I($){return $=_.invert($[0],$[1]),$&&[$[0]*Kt,$[1]*Kt]}N.stream=function($){return A&&L===$?A:A=yS(gS(c)(y(v(x(L=$)))))},N.preclip=function($){return arguments.length?(y=$,h=void 0,M()):y},N.postclip=function($){return arguments.length?(x=$,g=m=b=w=null,M()):x},N.clipAngle=function($){return arguments.length?(y=+$?Z2(h=$*ut):(h=null,Ih),M()):h*Kt},N.clipExtent=function($){return arguments.length?(x=$==null?(g=m=b=w=null,ns):Jg(g=+$[0][0],m=+$[0][1],b=+$[1][0],w=+$[1][1]),M()):g==null?null:[[g,m],[b,w]]},N.scale=function($){return arguments.length?(n=+$,T()):n},N.translate=function($){return arguments.length?(r=+$[0],o=+$[1],T()):[r,o]},N.center=function($){return arguments.length?(s=$[0]%360*ut,i=$[1]%360*ut,T()):[s*Kt,i*Kt]},N.rotate=function($){return arguments.length?(a=$[0]%360*ut,l=$[1]%360*ut,u=$.length>2?$[2]%360*ut:0,T()):[a*Kt,l*Kt,u*Kt]},N.angle=function($){return arguments.length?(d=$%360*ut,T()):d*Kt},N.reflectX=function($){return arguments.length?(f=$?-1:1,T()):f<0},N.reflectY=function($){return arguments.length?(p=$?-1:1,T()):p<0},N.precision=function($){return arguments.length?(v=Wh(k,S=$*$),M()):fn(S)},N.fitExtent=function($,F){return Nl(N,$,F)},N.fitSize=function($,F){return Sf(N,$,F)},N.fitWidth=function($,F){return $f(N,$,F)},N.fitHeight=function($,F){return _f(N,$,F)};function T(){var $=qh(n,0,0,f,p,d).apply(null,t(s,i)),F=qh(n,r-$[0],o-$[1],f,p,d);return c=Yg(a,l,u),k=vu(t,F),_=vu(c,k),v=Wh(k,S),M()}function M(){return A=L=null,N}return function(){return t=e.apply(this,arguments),N.invert=t.invert&&I,T()}}function Mf(e){var t=0,n=Ye/3,r=cm(e),o=r(t,n);return o.parallels=function(s){return arguments.length?r(t=s[0]*ut,n=s[1]*ut):[t*Kt,n*Kt]},o}function bS(e){var t=qe(e);function n(r,o){return[r*t,De(o)/t]}return n.invert=function(r,o){return[r/t,Mn(o*t)]},n}function wS(e,t){var n=De(e),r=(n+De(t))/2;if(ot(r)<Be)return bS(e);var o=1+n*(2*r-n),s=fn(o)/r;function i(a,l){var u=fn(o-2*r*De(l))/r;return[u*De(a*=r),s-u*qe(a)]}return i.invert=function(a,l){var u=s-l,c=Kn(a,ot(u))*kn(u);return u*r<0&&(c-=Ye*kn(a)*kn(u)),[c/r,Mn((o-(a*a+u*u)*r*r)/(2*r))]},i}function Va(){return Mf(wS).scale(155.424).center([0,33.6442])}function um(){return Va().parallels([29.5,45.5]).scale(1070).translate([480,250]).rotate([96,0]).center([-.6,38.7])}function xS(e){var t=e.length;return{point:function(n,r){for(var o=-1;++o<t;)e[o].point(n,r)},sphere:function(){for(var n=-1;++n<t;)e[n].sphere()},lineStart:function(){for(var n=-1;++n<t;)e[n].lineStart()},lineEnd:function(){for(var n=-1;++n<t;)e[n].lineEnd()},polygonStart:function(){for(var n=-1;++n<t;)e[n].polygonStart()},polygonEnd:function(){for(var n=-1;++n<t;)e[n].polygonEnd()}}}function vS(){var e,t,n=um(),r,o=Va().rotate([154,0]).center([-2,58.5]).parallels([55,65]),s,i=Va().rotate([157,0]).center([-3,19.9]).parallels([8,18]),a,l,u={point:function(f,p){l=[f,p]}};function c(f){var p=f[0],h=f[1];return l=null,r.point(p,h),l||(s.point(p,h),l)||(a.point(p,h),l)}c.invert=function(f){var p=n.scale(),h=n.translate(),y=(f[0]-h[0])/p,g=(f[1]-h[1])/p;return(g>=.12&&g<.234&&y>=-.425&&y<-.214?o:g>=.166&&g<.234&&y>=-.214&&y<-.115?i:n).invert(f)},c.stream=function(f){return e&&t===f?e:e=xS([n.stream(t=f),o.stream(f),i.stream(f)])},c.precision=function(f){return arguments.length?(n.precision(f),o.precision(f),i.precision(f),d()):n.precision()},c.scale=function(f){return arguments.length?(n.scale(f),o.scale(f*.35),i.scale(f),c.translate(n.translate())):n.scale()},c.translate=function(f){if(!arguments.length)return n.translate();var p=n.scale(),h=+f[0],y=+f[1];return r=n.translate(f).clipExtent([[h-.455*p,y-.238*p],[h+.455*p,y+.238*p]]).stream(u),s=o.translate([h-.307*p,y+.201*p]).clipExtent([[h-.425*p+Be,y+.12*p+Be],[h-.214*p-Be,y+.234*p-Be]]).stream(u),a=i.translate([h-.205*p,y+.212*p]).clipExtent([[h-.214*p+Be,y+.166*p+Be],[h-.115*p-Be,y+.234*p-Be]]).stream(u),d()},c.fitExtent=function(f,p){return Nl(c,f,p)},c.fitSize=function(f,p){return Sf(c,f,p)},c.fitWidth=function(f,p){return $f(c,f,p)},c.fitHeight=function(f,p){return _f(c,f,p)};function d(){return e=t=null,c}return c.scale(1070)}function fm(e){return function(t,n){var r=qe(t),o=qe(n),s=e(r*o);return s===1/0?[2,0]:[s*o*De(t),s*De(n)]}}function ws(e){return function(t,n){var r=fn(t*t+n*n),o=e(r),s=De(o),i=qe(o);return[Kn(t*s,r*i),Mn(r&&n*s/r)]}}var dm=fm(function(e){return fn(2/(1+e))});dm.invert=ws(function(e){return 2*Mn(e/2)});function kS(){return Ir(dm).scale(124.75).clipAngle(180-.001)}var hm=fm(function(e){return(e=Hg(e))&&e/De(e)});hm.invert=ws(function(e){return e});function SS(){return Ir(hm).scale(79.4188).clipAngle(180-.001)}function Il(e,t){return[e,Da(vf((St+t)/2))]}Il.invert=function(e,t){return[e,2*ei(qg(t))-St]};function $S(){return pm(Il).scale(961/en)}function pm(e){var t=Ir(e),n=t.center,r=t.scale,o=t.translate,s=t.clipExtent,i=null,a,l,u;t.scale=function(d){return arguments.length?(r(d),c()):r()},t.translate=function(d){return arguments.length?(o(d),c()):o()},t.center=function(d){return arguments.length?(n(d),c()):n()},t.clipExtent=function(d){return arguments.length?(d==null?i=a=l=u=null:(i=+d[0][0],a=+d[0][1],l=+d[1][0],u=+d[1][1]),c()):i==null?null:[[i,a],[l,u]]};function c(){var d=Ye*r(),f=t(B2(t.rotate()).invert([0,0]));return s(i==null?[[f[0]-d,f[1]-d],[f[0]+d,f[1]+d]]:e===Il?[[Math.max(f[0]-d,i),a],[Math.min(f[0]+d,l),u]]:[[i,Math.max(f[1]-d,a)],[l,Math.min(f[1]+d,u)]])}return c()}function Js(e){return vf((St+e)/2)}function _S(e,t){var n=qe(e),r=e===t?De(e):Da(n/qe(t))/Da(Js(t)/Js(e)),o=n*vc(Js(e),r)/r;if(!r)return Il;function s(i,a){o>0?a<-St+Be&&(a=-St+Be):a>St-Be&&(a=St-Be);var l=o/vc(Js(a),r);return[l*De(r*i),o-l*qe(r*i)]}return s.invert=function(i,a){var l=o-a,u=kn(r)*fn(i*i+l*l),c=Kn(i,ot(l))*kn(l);return l*r<0&&(c-=Ye*kn(i)*kn(l)),[c/r,2*ei(vc(o/u,1/r))-St]},s}function MS(){return Mf(_S).scale(109.5).parallels([30,30])}function Xa(e,t){return[e,t]}Xa.invert=Xa;function ES(){return Ir(Xa).scale(152.63)}function AS(e,t){var n=qe(e),r=e===t?De(e):(n-qe(t))/(t-e),o=n/r+e;if(ot(r)<Be)return Xa;function s(i,a){var l=o-a,u=r*i;return[l*De(u),o-l*qe(u)]}return s.invert=function(i,a){var l=o-a,u=Kn(i,ot(l))*kn(l);return l*r<0&&(u-=Ye*kn(i)*kn(l)),[u/r,o-kn(r)*fn(i*i+l*l)]},s}function TS(){return Mf(AS).scale(131.154).center([0,13.9389])}var Li=1.340264,Fi=-.081106,Ri=893e-6,zi=.003796,Ja=fn(3)/2,OS=12;function ym(e,t){var n=Mn(Ja*De(t)),r=n*n,o=r*r*r;return[e*qe(n)/(Ja*(Li+3*Fi*r+o*(7*Ri+9*zi*r))),n*(Li+Fi*r+o*(Ri+zi*r))]}ym.invert=function(e,t){for(var n=t,r=n*n,o=r*r*r,s=0,i,a,l;s<OS&&(a=n*(Li+Fi*r+o*(Ri+zi*r))-t,l=Li+3*Fi*r+o*(7*Ri+9*zi*r),n-=i=a/l,r=n*n,o=r*r*r,!(ot(i)<Wg));++s);return[Ja*e*(Li+3*Fi*r+o*(7*Ri+9*zi*r))/qe(n),Mn(De(n)/Ja)]};function CS(){return Ir(ym).scale(177.158)}function gm(e,t){var n=qe(t),r=qe(e)*n;return[n*De(e)/r,De(t)/r]}gm.invert=ws(ei);function NS(){return Ir(gm).scale(144.049).clipAngle(60)}function IS(){var e=1,t=0,n=0,r=1,o=1,s=0,i,a,l=null,u,c,d,f=1,p=1,h=Cl({point:function(x,S){var v=w([x,S]);this.stream.point(v[0],v[1])}}),y=ns,g,m;function b(){return f=e*r,p=e*o,g=m=null,w}function w(x){var S=x[0]*f,v=x[1]*p;if(s){var k=v*i-S*a;S=S*i+v*a,v=k}return[S+t,v+n]}return w.invert=function(x){var S=x[0]-t,v=x[1]-n;if(s){var k=v*i+S*a;S=S*i-v*a,v=k}return[S/f,v/p]},w.stream=function(x){return g&&m===x?g:g=h(y(m=x))},w.postclip=function(x){return arguments.length?(y=x,l=u=c=d=null,b()):y},w.clipExtent=function(x){return arguments.length?(y=x==null?(l=u=c=d=null,ns):Jg(l=+x[0][0],u=+x[0][1],c=+x[1][0],d=+x[1][1]),b()):l==null?null:[[l,u],[c,d]]},w.scale=function(x){return arguments.length?(e=+x,b()):e},w.translate=function(x){return arguments.length?(t=+x[0],n=+x[1],b()):[t,n]},w.angle=function(x){return arguments.length?(s=x%360*ut,a=De(s),i=qe(s),b()):s*Kt},w.reflectX=function(x){return arguments.length?(r=x?-1:1,b()):r<0},w.reflectY=function(x){return arguments.length?(o=x?-1:1,b()):o<0},w.fitExtent=function(x,S){return Nl(w,x,S)},w.fitSize=function(x,S){return Sf(w,x,S)},w.fitWidth=function(x,S){return $f(w,x,S)},w.fitHeight=function(x,S){return _f(w,x,S)},w}function mm(e,t){return[qe(t)*De(e),De(t)]}mm.invert=ws(Mn);function LS(){return Ir(mm).scale(249.5).clipAngle(90+Be)}function bm(e,t){var n=qe(t),r=1+qe(e)*n;return[n*De(e)/r,De(t)/r]}bm.invert=ws(function(e){return 2*ei(e)});function FS(){return Ir(bm).scale(250).clipAngle(142)}function wm(e,t){return[Da(vf((St+t)/2)),-e]}wm.invert=function(e,t){return[-t,2*ei(qg(e))-St]};function RS(){var e=pm(wm),t=e.center,n=e.rotate;return e.center=function(r){return arguments.length?t([-r[1],r[0]]):(r=t(),[r[1],-r[0]])},e.rotate=function(r){return arguments.length?n([r[0],r[1],r.length>2?r[2]+90:90]):(r=n(),[r[0],r[1],r[2]-90])},n([0,0,90]).scale(159.155)}function so(e,t){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(t).domain(e);break}return this}const Hh=Symbol("implicit");function Ef(){var e=new eh,t=[],n=[],r=Hh;function o(s){let i=e.get(s);if(i===void 0){if(r!==Hh)return r;e.set(s,i=t.push(s)-1)}return n[i%n.length]}return o.domain=function(s){if(!arguments.length)return t.slice();t=[],e=new eh;for(const i of s)e.has(i)||e.set(i,t.push(i)-1);return o},o.range=function(s){return arguments.length?(n=Array.from(s),o):n.slice()},o.unknown=function(s){return arguments.length?(r=s,o):r},o.copy=function(){return Ef(t,n).unknown(r)},so.apply(o,arguments),o}function Af(){var e=Ef().unknown(void 0),t=e.domain,n=e.range,r=0,o=1,s,i,a=!1,l=0,u=0,c=.5;delete e.unknown;function d(){var f=t().length,p=o<r,h=p?o:r,y=p?r:o;s=(y-h)/Math.max(1,f-l+u*2),a&&(s=Math.floor(s)),h+=(y-h-s*(f-l))*c,i=s*(1-l),a&&(h=Math.round(h),i=Math.round(i));var g=Bw(f).map(function(m){return h+s*m});return n(p?g.reverse():g)}return e.domain=function(f){return arguments.length?(t(f),d()):t()},e.range=function(f){return arguments.length?([r,o]=f,r=+r,o=+o,d()):[r,o]},e.rangeRound=function(f){return[r,o]=f,r=+r,o=+o,a=!0,d()},e.bandwidth=function(){return i},e.step=function(){return s},e.round=function(f){return arguments.length?(a=!!f,d()):a},e.padding=function(f){return arguments.length?(l=Math.min(1,u=+f),d()):l},e.paddingInner=function(f){return arguments.length?(l=Math.min(1,f),d()):l},e.paddingOuter=function(f){return arguments.length?(u=+f,d()):u},e.align=function(f){return arguments.length?(c=Math.max(0,Math.min(1,f)),d()):c},e.copy=function(){return Af(t(),[r,o]).round(a).paddingInner(l).paddingOuter(u).align(c)},so.apply(d(),arguments)}function xm(e){var t=e.copy;return e.padding=e.paddingOuter,delete e.paddingInner,delete e.paddingOuter,e.copy=function(){return xm(t())},e}function zS(){return xm(Af.apply(null,arguments).paddingInner(1))}function PS(e){return function(){return e}}function DS(e){return+e}var Bh=[0,1];function Hn(e){return e}function Nu(e,t){return(t-=e=+e)?function(n){return(n-e)/t}:PS(isNaN(t)?NaN:.5)}function jS(e,t){var n;return e>t&&(n=e,e=t,t=n),function(r){return Math.max(e,Math.min(t,r))}}function WS(e,t,n){var r=e[0],o=e[1],s=t[0],i=t[1];return o<r?(r=Nu(o,r),s=n(i,s)):(r=Nu(r,o),s=n(s,i)),function(a){return s(r(a))}}function qS(e,t,n){var r=Math.min(e.length,t.length)-1,o=new Array(r),s=new Array(r),i=-1;for(e[r]<e[0]&&(e=e.slice().reverse(),t=t.slice().reverse());++i<r;)o[i]=Nu(e[i],e[i+1]),s[i]=n(t[i],t[i+1]);return function(a){var l=Rw(e,a,1,r)-1;return s[l](o[l](a))}}function xs(e,t){return t.domain(e.domain()).range(e.range()).interpolate(e.interpolate()).clamp(e.clamp()).unknown(e.unknown())}function Ll(){var e=Bh,t=Bh,n=Al,r,o,s,i=Hn,a,l,u;function c(){var f=Math.min(e.length,t.length);return i!==Hn&&(i=jS(e[0],e[f-1])),a=f>2?qS:WS,l=u=null,d}function d(f){return f==null||isNaN(f=+f)?s:(l||(l=a(e.map(r),t,n)))(r(i(f)))}return d.invert=function(f){return i(o((u||(u=a(t,e.map(r),Tn)))(f)))},d.domain=function(f){return arguments.length?(e=Array.from(f,DS),c()):e.slice()},d.range=function(f){return arguments.length?(t=Array.from(f),c()):t.slice()},d.rangeRound=function(f){return t=Array.from(f),n=ck,c()},d.clamp=function(f){return arguments.length?(i=f?!0:Hn,c()):i!==Hn},d.interpolate=function(f){return arguments.length?(n=f,c()):n},d.unknown=function(f){return arguments.length?(s=f,d):s},function(f,p){return r=f,o=p,c()}}function vm(){return Ll()(Hn,Hn)}function HS(e,t,n,r){var o=ru(e,t,n),s;switch(r=es(r??",f"),r.type){case"s":{var i=Math.max(Math.abs(e),Math.abs(t));return r.precision==null&&!isNaN(s=P2(o,i))&&(r.precision=s),jg(r,i)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(s=D2(o,Math.max(Math.abs(e),Math.abs(t))))&&(r.precision=s-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(s=z2(o))&&(r.precision=s-(r.type==="%")*2);break}}return Qo(r)}function Tf(e){var t=e.domain;return e.ticks=function(n){var r=t();return tu(r[0],r[r.length-1],n??10)},e.tickFormat=function(n,r){var o=t();return HS(o[0],o[o.length-1],n??10,r)},e.nice=function(n){n==null&&(n=10);var r=t(),o=0,s=r.length-1,i=r[o],a=r[s],l,u,c=10;for(a<i&&(u=i,i=a,a=u,u=o,o=s,s=u);c-- >0;){if(u=nu(i,a,n),u===l)return r[o]=i,r[s]=a,t(r);if(u>0)i=Math.floor(i/u)*u,a=Math.ceil(a/u)*u;else if(u<0)i=Math.ceil(i*u)/u,a=Math.floor(a*u)/u;else break;l=u}return e},e}function Pi(){var e=vm();return e.copy=function(){return xs(e,Pi())},so.apply(e,arguments),Tf(e)}function km(e,t){e=e.slice();var n=0,r=e.length-1,o=e[n],s=e[r],i;return s<o&&(i=n,n=r,r=i,i=o,o=s,s=i),e[n]=t.floor(o),e[r]=t.ceil(s),e}function Uh(e){return Math.log(e)}function Kh(e){return Math.exp(e)}function BS(e){return-Math.log(-e)}function US(e){return-Math.exp(-e)}function KS(e){return isFinite(e)?+("1e"+e):e<0?0:e}function YS(e){return e===10?KS:e===Math.E?Math.exp:t=>Math.pow(e,t)}function GS(e){return e===Math.E?Math.log:e===10&&Math.log10||e===2&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}function Yh(e){return(t,n)=>-e(-t,n)}function VS(e){const t=e(Uh,Kh),n=t.domain;let r=10,o,s;function i(){return o=GS(r),s=YS(r),n()[0]<0?(o=Yh(o),s=Yh(s),e(BS,US)):e(Uh,Kh),t}return t.base=function(a){return arguments.length?(r=+a,i()):r},t.domain=function(a){return arguments.length?(n(a),i()):n()},t.ticks=a=>{const l=n();let u=l[0],c=l[l.length-1];const d=c<u;d&&([u,c]=[c,u]);let f=o(u),p=o(c),h,y;const g=a==null?10:+a;let m=[];if(!(r%1)&&p-f<g){if(f=Math.floor(f),p=Math.ceil(p),u>0){for(;f<=p;++f)for(h=1;h<r;++h)if(y=f<0?h/s(-f):h*s(f),!(y<u)){if(y>c)break;m.push(y)}}else for(;f<=p;++f)for(h=r-1;h>=1;--h)if(y=f>0?h/s(-f):h*s(f),!(y<u)){if(y>c)break;m.push(y)}m.length*2<g&&(m=tu(u,c,g))}else m=tu(f,p,Math.min(p-f,g)).map(s);return d?m.reverse():m},t.tickFormat=(a,l)=>{if(a==null&&(a=10),l==null&&(l=r===10?"s":","),typeof l!="function"&&(!(r%1)&&(l=es(l)).precision==null&&(l.trim=!0),l=Qo(l)),a===1/0)return l;const u=Math.max(1,r*a/t.ticks().length);return c=>{let d=c/s(Math.round(o(c)));return d*r<r-.5&&(d*=r),d<=u?l(c):""}},t.nice=()=>n(km(n(),{floor:a=>s(Math.floor(o(a))),ceil:a=>s(Math.ceil(o(a)))})),t}function Sm(){const e=VS(Ll()).domain([1,10]);return e.copy=()=>xs(e,Sm()).base(e.base()),so.apply(e,arguments),e}function Gh(e){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/e))}}function Vh(e){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*e}}function XS(e){var t=1,n=e(Gh(t),Vh(t));return n.constant=function(r){return arguments.length?e(Gh(t=+r),Vh(t)):t},Tf(n)}function $m(){var e=XS(Ll());return e.copy=function(){return xs(e,$m()).constant(e.constant())},so.apply(e,arguments)}function Xh(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function JS(e){return e<0?-Math.sqrt(-e):Math.sqrt(e)}function ZS(e){return e<0?-e*e:e*e}function QS(e){var t=e(Hn,Hn),n=1;function r(){return n===1?e(Hn,Hn):n===.5?e(JS,ZS):e(Xh(n),Xh(1/n))}return t.exponent=function(o){return arguments.length?(n=+o,r()):n},Tf(t)}function _m(){var e=QS(Ll());return e.copy=function(){return xs(e,_m()).exponent(e.exponent())},so.apply(e,arguments),e}const Mc=new Date,Ec=new Date;function Ct(e,t,n,r){function o(s){return e(s=arguments.length===0?new Date:new Date(+s)),s}return o.floor=s=>(e(s=new Date(+s)),s),o.ceil=s=>(e(s=new Date(s-1)),t(s,1),e(s),s),o.round=s=>{const i=o(s),a=o.ceil(s);return s-i<a-s?i:a},o.offset=(s,i)=>(t(s=new Date(+s),i==null?1:Math.floor(i)),s),o.range=(s,i,a)=>{const l=[];if(s=o.ceil(s),a=a==null?1:Math.floor(a),!(s<i)||!(a>0))return l;let u;do l.push(u=new Date(+s)),t(s,a),e(s);while(u<s&&s<i);return l},o.filter=s=>Ct(i=>{if(i>=i)for(;e(i),!s(i);)i.setTime(i-1)},(i,a)=>{if(i>=i)if(a<0)for(;++a<=0;)for(;t(i,-1),!s(i););else for(;--a>=0;)for(;t(i,1),!s(i););}),n&&(o.count=(s,i)=>(Mc.setTime(+s),Ec.setTime(+i),e(Mc),e(Ec),Math.floor(n(Mc,Ec))),o.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?o.filter(r?i=>r(i)%s===0:i=>o.count(0,i)%s===0):o)),o}const Za=Ct(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);Za.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?Ct(t=>{t.setTime(Math.floor(t/e)*e)},(t,n)=>{t.setTime(+t+n*e)},(t,n)=>(n-t)/e):Za);Za.range;const ar=1e3,Sn=ar*60,lr=Sn*60,wr=lr*24,Of=wr*7,Jh=wr*30,Ac=wr*365,To=Ct(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*ar)},(e,t)=>(t-e)/ar,e=>e.getUTCSeconds());To.range;const Fl=Ct(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*ar)},(e,t)=>{e.setTime(+e+t*Sn)},(e,t)=>(t-e)/Sn,e=>e.getMinutes());Fl.range;const e$=Ct(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*Sn)},(e,t)=>(t-e)/Sn,e=>e.getUTCMinutes());e$.range;const Rl=Ct(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*ar-e.getMinutes()*Sn)},(e,t)=>{e.setTime(+e+t*lr)},(e,t)=>(t-e)/lr,e=>e.getHours());Rl.range;const t$=Ct(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*lr)},(e,t)=>(t-e)/lr,e=>e.getUTCHours());t$.range;const ti=Ct(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*Sn)/wr,e=>e.getDate()-1);ti.range;const Cf=Ct(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/wr,e=>e.getUTCDate()-1);Cf.range;const n$=Ct(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/wr,e=>Math.floor(e/wr));n$.range;function ao(e){return Ct(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Sn)/Of)}const vs=ao(0),Qa=ao(1),r$=ao(2),o$=ao(3),Bo=ao(4),i$=ao(5),s$=ao(6);vs.range;Qa.range;r$.range;o$.range;Bo.range;i$.range;s$.range;function lo(e){return Ct(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>(n-t)/Of)}const Mm=lo(0),el=lo(1),a$=lo(2),l$=lo(3),Uo=lo(4),c$=lo(5),u$=lo(6);Mm.range;el.range;a$.range;l$.range;Uo.range;c$.range;u$.range;const zl=Ct(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());zl.range;const f$=Ct(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());f$.range;const Yn=Ct(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());Yn.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Ct(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*e)});Yn.range;const no=Ct(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());no.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:Ct(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*e)});no.range;function d$(e,t,n,r,o,s){const i=[[To,1,ar],[To,5,5*ar],[To,15,15*ar],[To,30,30*ar],[s,1,Sn],[s,5,5*Sn],[s,15,15*Sn],[s,30,30*Sn],[o,1,lr],[o,3,3*lr],[o,6,6*lr],[o,12,12*lr],[r,1,wr],[r,2,2*wr],[n,1,Of],[t,1,Jh],[t,3,3*Jh],[e,1,Ac]];function a(u,c,d){const f=c<u;f&&([u,c]=[c,u]);const p=d&&typeof d.range=="function"?d:l(u,c,d),h=p?p.range(u,+c+1):[];return f?h.reverse():h}function l(u,c,d){const f=Math.abs(c-u)/d,p=uf(([,,g])=>g).right(i,f);if(p===i.length)return e.every(ru(u/Ac,c/Ac,d));if(p===0)return Za.every(Math.max(ru(u,c,d),1));const[h,y]=i[f/i[p-1][2]<i[p][2]/f?p-1:p];return h.every(y)}return[a,l]}const[h$,p$]=d$(Yn,zl,vs,ti,Rl,Fl);function Tc(e){if(0<=e.y&&e.y<100){var t=new Date(-1,e.m,e.d,e.H,e.M,e.S,e.L);return t.setFullYear(e.y),t}return new Date(e.y,e.m,e.d,e.H,e.M,e.S,e.L)}function Oc(e){if(0<=e.y&&e.y<100){var t=new Date(Date.UTC(-1,e.m,e.d,e.H,e.M,e.S,e.L));return t.setUTCFullYear(e.y),t}return new Date(Date.UTC(e.y,e.m,e.d,e.H,e.M,e.S,e.L))}function ui(e,t,n){return{y:e,m:t,d:n,H:0,M:0,S:0,L:0}}function y$(e){var t=e.dateTime,n=e.date,r=e.time,o=e.periods,s=e.days,i=e.shortDays,a=e.months,l=e.shortMonths,u=fi(o),c=di(o),d=fi(s),f=di(s),p=fi(i),h=di(i),y=fi(a),g=di(a),m=fi(l),b=di(l),w={a:D,A:P,b:j,B:G,c:null,d:rp,e:rp,f:P$,g:G$,G:X$,H:F$,I:R$,j:z$,L:Em,m:D$,M:j$,p:J,q:re,Q:sp,s:ap,S:W$,u:q$,U:H$,V:B$,w:U$,W:K$,x:null,X:null,y:Y$,Y:V$,Z:J$,"%":ip},x={a:Q,A:ve,b:Ce,B:le,c:null,d:op,e:op,f:t_,g:f_,G:h_,H:Z$,I:Q$,j:e_,L:Tm,m:n_,M:r_,p:be,q:ce,Q:sp,s:ap,S:o_,u:i_,U:s_,V:a_,w:l_,W:c_,x:null,X:null,y:u_,Y:d_,Z:p_,"%":ip},S={a:L,A:N,b:I,B:T,c:M,d:tp,e:tp,f:C$,g:ep,G:Qh,H:np,I:np,j:E$,L:O$,m:M$,M:A$,p:A,q:_$,Q:I$,s:L$,S:T$,u:x$,U:v$,V:k$,w:w$,W:S$,x:$,X:F,y:ep,Y:Qh,Z:$$,"%":N$};w.x=v(n,w),w.X=v(r,w),w.c=v(t,w),x.x=v(n,x),x.X=v(r,x),x.c=v(t,x);function v(Y,ue){return function(ie){var U=[],we=-1,xe=0,z=Y.length,H,oe,de;for(ie instanceof Date||(ie=new Date(+ie));++we<z;)Y.charCodeAt(we)===37&&(U.push(Y.slice(xe,we)),(oe=Zh[H=Y.charAt(++we)])!=null?H=Y.charAt(++we):oe=H==="e"?" ":"0",(de=ue[H])&&(H=de(ie,oe)),U.push(H),xe=we+1);return U.push(Y.slice(xe,we)),U.join("")}}function k(Y,ue){return function(ie){var U=ui(1900,void 0,1),we=_(U,Y,ie+="",0),xe,z;if(we!=ie.length)return null;if("Q"in U)return new Date(U.Q);if("s"in U)return new Date(U.s*1e3+("L"in U?U.L:0));if(ue&&!("Z"in U)&&(U.Z=0),"p"in U&&(U.H=U.H%12+U.p*12),U.m===void 0&&(U.m="q"in U?U.q:0),"V"in U){if(U.V<1||U.V>53)return null;"w"in U||(U.w=1),"Z"in U?(xe=Oc(ui(U.y,0,1)),z=xe.getUTCDay(),xe=z>4||z===0?el.ceil(xe):el(xe),xe=Cf.offset(xe,(U.V-1)*7),U.y=xe.getUTCFullYear(),U.m=xe.getUTCMonth(),U.d=xe.getUTCDate()+(U.w+6)%7):(xe=Tc(ui(U.y,0,1)),z=xe.getDay(),xe=z>4||z===0?Qa.ceil(xe):Qa(xe),xe=ti.offset(xe,(U.V-1)*7),U.y=xe.getFullYear(),U.m=xe.getMonth(),U.d=xe.getDate()+(U.w+6)%7)}else("W"in U||"U"in U)&&("w"in U||(U.w="u"in U?U.u%7:"W"in U?1:0),z="Z"in U?Oc(ui(U.y,0,1)).getUTCDay():Tc(ui(U.y,0,1)).getDay(),U.m=0,U.d="W"in U?(U.w+6)%7+U.W*7-(z+5)%7:U.w+U.U*7-(z+6)%7);return"Z"in U?(U.H+=U.Z/100|0,U.M+=U.Z%100,Oc(U)):Tc(U)}}function _(Y,ue,ie,U){for(var we=0,xe=ue.length,z=ie.length,H,oe;we<xe;){if(U>=z)return-1;if(H=ue.charCodeAt(we++),H===37){if(H=ue.charAt(we++),oe=S[H in Zh?ue.charAt(we++):H],!oe||(U=oe(Y,ie,U))<0)return-1}else if(H!=ie.charCodeAt(U++))return-1}return U}function A(Y,ue,ie){var U=u.exec(ue.slice(ie));return U?(Y.p=c.get(U[0].toLowerCase()),ie+U[0].length):-1}function L(Y,ue,ie){var U=p.exec(ue.slice(ie));return U?(Y.w=h.get(U[0].toLowerCase()),ie+U[0].length):-1}function N(Y,ue,ie){var U=d.exec(ue.slice(ie));return U?(Y.w=f.get(U[0].toLowerCase()),ie+U[0].length):-1}function I(Y,ue,ie){var U=m.exec(ue.slice(ie));return U?(Y.m=b.get(U[0].toLowerCase()),ie+U[0].length):-1}function T(Y,ue,ie){var U=y.exec(ue.slice(ie));return U?(Y.m=g.get(U[0].toLowerCase()),ie+U[0].length):-1}function M(Y,ue,ie){return _(Y,t,ue,ie)}function $(Y,ue,ie){return _(Y,n,ue,ie)}function F(Y,ue,ie){return _(Y,r,ue,ie)}function D(Y){return i[Y.getDay()]}function P(Y){return s[Y.getDay()]}function j(Y){return l[Y.getMonth()]}function G(Y){return a[Y.getMonth()]}function J(Y){return o[+(Y.getHours()>=12)]}function re(Y){return 1+~~(Y.getMonth()/3)}function Q(Y){return i[Y.getUTCDay()]}function ve(Y){return s[Y.getUTCDay()]}function Ce(Y){return l[Y.getUTCMonth()]}function le(Y){return a[Y.getUTCMonth()]}function be(Y){return o[+(Y.getUTCHours()>=12)]}function ce(Y){return 1+~~(Y.getUTCMonth()/3)}return{format:function(Y){var ue=v(Y+="",w);return ue.toString=function(){return Y},ue},parse:function(Y){var ue=k(Y+="",!1);return ue.toString=function(){return Y},ue},utcFormat:function(Y){var ue=v(Y+="",x);return ue.toString=function(){return Y},ue},utcParse:function(Y){var ue=k(Y+="",!0);return ue.toString=function(){return Y},ue}}}var Zh={"-":"",_:" ",0:"0"},Ft=/^\s*\d+/,g$=/^%/,m$=/[\\^$*+?|[\]().{}]/g;function et(e,t,n){var r=e<0?"-":"",o=(r?-e:e)+"",s=o.length;return r+(s<n?new Array(n-s+1).join(t)+o:o)}function b$(e){return e.replace(m$,"\\$&")}function fi(e){return new RegExp("^(?:"+e.map(b$).join("|")+")","i")}function di(e){return new Map(e.map((t,n)=>[t.toLowerCase(),n]))}function w$(e,t,n){var r=Ft.exec(t.slice(n,n+1));return r?(e.w=+r[0],n+r[0].length):-1}function x$(e,t,n){var r=Ft.exec(t.slice(n,n+1));return r?(e.u=+r[0],n+r[0].length):-1}function v$(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.U=+r[0],n+r[0].length):-1}function k$(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.V=+r[0],n+r[0].length):-1}function S$(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.W=+r[0],n+r[0].length):-1}function Qh(e,t,n){var r=Ft.exec(t.slice(n,n+4));return r?(e.y=+r[0],n+r[0].length):-1}function ep(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function $$(e,t,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(e.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function _$(e,t,n){var r=Ft.exec(t.slice(n,n+1));return r?(e.q=r[0]*3-3,n+r[0].length):-1}function M$(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.m=r[0]-1,n+r[0].length):-1}function tp(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.d=+r[0],n+r[0].length):-1}function E$(e,t,n){var r=Ft.exec(t.slice(n,n+3));return r?(e.m=0,e.d=+r[0],n+r[0].length):-1}function np(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.H=+r[0],n+r[0].length):-1}function A$(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.M=+r[0],n+r[0].length):-1}function T$(e,t,n){var r=Ft.exec(t.slice(n,n+2));return r?(e.S=+r[0],n+r[0].length):-1}function O$(e,t,n){var r=Ft.exec(t.slice(n,n+3));return r?(e.L=+r[0],n+r[0].length):-1}function C$(e,t,n){var r=Ft.exec(t.slice(n,n+6));return r?(e.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function N$(e,t,n){var r=g$.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function I$(e,t,n){var r=Ft.exec(t.slice(n));return r?(e.Q=+r[0],n+r[0].length):-1}function L$(e,t,n){var r=Ft.exec(t.slice(n));return r?(e.s=+r[0],n+r[0].length):-1}function rp(e,t){return et(e.getDate(),t,2)}function F$(e,t){return et(e.getHours(),t,2)}function R$(e,t){return et(e.getHours()%12||12,t,2)}function z$(e,t){return et(1+ti.count(Yn(e),e),t,3)}function Em(e,t){return et(e.getMilliseconds(),t,3)}function P$(e,t){return Em(e,t)+"000"}function D$(e,t){return et(e.getMonth()+1,t,2)}function j$(e,t){return et(e.getMinutes(),t,2)}function W$(e,t){return et(e.getSeconds(),t,2)}function q$(e){var t=e.getDay();return t===0?7:t}function H$(e,t){return et(vs.count(Yn(e)-1,e),t,2)}function Am(e){var t=e.getDay();return t>=4||t===0?Bo(e):Bo.ceil(e)}function B$(e,t){return e=Am(e),et(Bo.count(Yn(e),e)+(Yn(e).getDay()===4),t,2)}function U$(e){return e.getDay()}function K$(e,t){return et(Qa.count(Yn(e)-1,e),t,2)}function Y$(e,t){return et(e.getFullYear()%100,t,2)}function G$(e,t){return e=Am(e),et(e.getFullYear()%100,t,2)}function V$(e,t){return et(e.getFullYear()%1e4,t,4)}function X$(e,t){var n=e.getDay();return e=n>=4||n===0?Bo(e):Bo.ceil(e),et(e.getFullYear()%1e4,t,4)}function J$(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+et(t/60|0,"0",2)+et(t%60,"0",2)}function op(e,t){return et(e.getUTCDate(),t,2)}function Z$(e,t){return et(e.getUTCHours(),t,2)}function Q$(e,t){return et(e.getUTCHours()%12||12,t,2)}function e_(e,t){return et(1+Cf.count(no(e),e),t,3)}function Tm(e,t){return et(e.getUTCMilliseconds(),t,3)}function t_(e,t){return Tm(e,t)+"000"}function n_(e,t){return et(e.getUTCMonth()+1,t,2)}function r_(e,t){return et(e.getUTCMinutes(),t,2)}function o_(e,t){return et(e.getUTCSeconds(),t,2)}function i_(e){var t=e.getUTCDay();return t===0?7:t}function s_(e,t){return et(Mm.count(no(e)-1,e),t,2)}function Om(e){var t=e.getUTCDay();return t>=4||t===0?Uo(e):Uo.ceil(e)}function a_(e,t){return e=Om(e),et(Uo.count(no(e),e)+(no(e).getUTCDay()===4),t,2)}function l_(e){return e.getUTCDay()}function c_(e,t){return et(el.count(no(e)-1,e),t,2)}function u_(e,t){return et(e.getUTCFullYear()%100,t,2)}function f_(e,t){return e=Om(e),et(e.getUTCFullYear()%100,t,2)}function d_(e,t){return et(e.getUTCFullYear()%1e4,t,4)}function h_(e,t){var n=e.getUTCDay();return e=n>=4||n===0?Uo(e):Uo.ceil(e),et(e.getUTCFullYear()%1e4,t,4)}function p_(){return"+0000"}function ip(){return"%"}function sp(e){return+e}function ap(e){return Math.floor(+e/1e3)}var ko,Nf;y_({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function y_(e){return ko=y$(e),Nf=ko.format,ko.parse,ko.utcFormat,ko.utcParse,ko}function g_(e){return new Date(e)}function m_(e){return e instanceof Date?+e:+new Date(+e)}function Cm(e,t,n,r,o,s,i,a,l,u){var c=vm(),d=c.invert,f=c.domain,p=u(".%L"),h=u(":%S"),y=u("%I:%M"),g=u("%I %p"),m=u("%a %d"),b=u("%b %d"),w=u("%B"),x=u("%Y");function S(v){return(l(v)<v?p:a(v)<v?h:i(v)<v?y:s(v)<v?g:r(v)<v?o(v)<v?m:b:n(v)<v?w:x)(v)}return c.invert=function(v){return new Date(d(v))},c.domain=function(v){return arguments.length?f(Array.from(v,m_)):f().map(g_)},c.ticks=function(v){var k=f();return e(k[0],k[k.length-1],v??10)},c.tickFormat=function(v,k){return k==null?S:u(k)},c.nice=function(v){var k=f();return(!v||typeof v.range!="function")&&(v=t(k[0],k[k.length-1],v??10)),v?f(km(k,v)):c},c.copy=function(){return xs(c,Cm(e,t,n,r,o,s,i,a,l,u))},c}function b_(){return so.apply(Cm(h$,p$,Yn,zl,vs,ti,Rl,Fl,To,Nf).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)}function ft(e){for(var t=e.length/6|0,n=new Array(t),r=0;r<t;)n[r]="#"+e.slice(r*6,++r*6);return n}const w_=ft("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"),x_=ft("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"),v_=ft("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"),k_=ft("4269d0efb118ff725c6cc5b03ca951ff8ab7a463f297bbf59c6b4e9498a0"),S_=ft("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"),$_=ft("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"),__=ft("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"),M_=ft("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"),E_=ft("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"),A_=ft("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"),T_=ft("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab"),En=e=>tk(e[e.length-1]);var Nm=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(ft);const O_=En(Nm);var Im=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(ft);const C_=En(Im);var Lm=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(ft);const N_=En(Lm);var Fm=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(ft);const I_=En(Fm);var Rm=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(ft);const L_=En(Rm);var zm=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(ft);const F_=En(zm);var Pm=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(ft);const R_=En(Pm);var Dm=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(ft);const z_=En(Dm);var jm=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(ft);const P_=En(jm);var Wm=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(ft);const D_=En(Wm);var qm=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(ft);const j_=En(qm);var Hm=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(ft);const W_=En(Hm);function q_(e){return e=Math.max(0,Math.min(1,e)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-e*(35.34-e*(2381.73-e*(6402.7-e*(7024.72-e*2710.57)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+e*(170.73+e*(52.82-e*(131.46-e*(176.58-e*67.37)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+e*(442.36-e*(2482.43-e*(6167.24-e*(6614.94-e*2475.67)))))))+")"}var H_=Tg(Ar(-100,.75,.35),Ar(80,1.5,.8)),B_=Tg(Ar(260,.75,.35),Ar(80,1.5,.8));Ar();function U_(e){return e=Math.max(0,Math.min(1,e)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+e*(1172.33-e*(10793.56-e*(33300.12-e*(38394.49-e*14825.05)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+e*(557.33+e*(1225.33-e*(3574.96-e*(1073.77+e*707.56)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+e*(3211.1-e*(15327.97-e*(27814-e*(22569.18-e*6838.66)))))))+")"}function Pl(e){var t=e.length;return function(n){return e[Math.max(0,Math.min(t-1,Math.floor(n*t)))]}}const K_=Pl(ft("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725"));var Y_=Pl(ft("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),G_=Pl(ft("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),V_=Pl(ft("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function So(e){return function(){return e}}const lp=1e-12;function X_(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);t=r}return e},()=>new A2(t)}function J_(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Bm(e){this._context=e}Bm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function If(e){return new Bm(e)}function Z_(e){return e[0]}function Q_(e){return e[1]}function Si(e,t){var n=So(!0),r=null,o=If,s=null,i=X_(a);e=typeof e=="function"?e:e===void 0?Z_:So(e),t=typeof t=="function"?t:t===void 0?Q_:So(t);function a(l){var u,c=(l=J_(l)).length,d,f=!1,p;for(r==null&&(s=o(p=i())),u=0;u<=c;++u)!(u<c&&n(d=l[u],u,l))===f&&((f=!f)?s.lineStart():s.lineEnd()),f&&s.point(+e(d,u,l),+t(d,u,l));if(p)return s=null,p+""||null}return a.x=function(l){return arguments.length?(e=typeof l=="function"?l:So(+l),a):e},a.y=function(l){return arguments.length?(t=typeof l=="function"?l:So(+l),a):t},a.defined=function(l){return arguments.length?(n=typeof l=="function"?l:So(!!l),a):n},a.curve=function(l){return arguments.length?(o=l,r!=null&&(s=o(r)),a):o},a.context=function(l){return arguments.length?(l==null?r=s=null:s=o(r=l),a):r},a}function cp(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function Um(e){this._context=e}Um.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:cp(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:cp(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function eM(e){return new Um(e)}function up(e,t,n){e._context.bezierCurveTo(e._x1+e._k*(e._x2-e._x0),e._y1+e._k*(e._y2-e._y0),e._x2+e._k*(e._x1-t),e._y2+e._k*(e._y1-n),e._x2,e._y2)}function Lf(e,t){this._context=e,this._k=(1-t)/6}Lf.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:up(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2,this._x1=e,this._y1=t;break;case 2:this._point=3;default:up(this,e,t);break}this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};const tM=(function e(t){function n(r){return new Lf(r,t)}return n.tension=function(r){return e(+r)},n})(0);function nM(e,t,n){var r=e._x1,o=e._y1,s=e._x2,i=e._y2;if(e._l01_a>lp){var a=2*e._l01_2a+3*e._l01_a*e._l12_a+e._l12_2a,l=3*e._l01_a*(e._l01_a+e._l12_a);r=(r*a-e._x0*e._l12_2a+e._x2*e._l01_2a)/l,o=(o*a-e._y0*e._l12_2a+e._y2*e._l01_2a)/l}if(e._l23_a>lp){var u=2*e._l23_2a+3*e._l23_a*e._l12_a+e._l12_2a,c=3*e._l23_a*(e._l23_a+e._l12_a);s=(s*u+e._x1*e._l23_2a-t*e._l12_2a)/c,i=(i*u+e._y1*e._l23_2a-n*e._l12_2a)/c}e._context.bezierCurveTo(r,o,s,i,e._x2,e._y2)}function Km(e,t){this._context=e,this._alpha=t}Km.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){if(e=+e,t=+t,this._point){var n=this._x2-e,r=this._y2-t;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(n*n+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3;default:nM(this,e,t);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=e,this._y0=this._y1,this._y1=this._y2,this._y2=t}};const rM=(function e(t){function n(r){return t?new Km(r,t):new Lf(r,0)}return n.alpha=function(r){return e(+r)},n})(.5);function fp(e){return e<0?-1:1}function dp(e,t,n){var r=e._x1-e._x0,o=t-e._x1,s=(e._y1-e._y0)/(r||o<0&&-0),i=(n-e._y1)/(o||r<0&&-0),a=(s*o+i*r)/(r+o);return(fp(s)+fp(i))*Math.min(Math.abs(s),Math.abs(i),.5*Math.abs(a))||0}function hp(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function Cc(e,t,n){var r=e._x0,o=e._y0,s=e._x1,i=e._y1,a=(s-r)/3;e._context.bezierCurveTo(r+a,o+a*t,s-a,i-a*n,s,i)}function tl(e){this._context=e}tl.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Cc(this,this._t0,hp(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,Cc(this,hp(this,n=dp(this,e,t)),n);break;default:Cc(this,this._t0,n=dp(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function Ym(e){this._context=new Gm(e)}(Ym.prototype=Object.create(tl.prototype)).point=function(e,t){tl.prototype.point.call(this,t,e)};function Gm(e){this._context=e}Gm.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,o,s){this._context.bezierCurveTo(t,e,r,n,s,o)}};function oM(e){return new tl(e)}function iM(e){return new Ym(e)}function Vm(e){this._context=e}Vm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=pp(e),o=pp(t),s=0,i=1;i<n;++s,++i)this._context.bezierCurveTo(r[0][s],o[0][s],r[1][s],o[1][s],e[i],t[i]);(this._line||this._line!==0&&n===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function pp(e){var t,n=e.length-1,r,o=new Array(n),s=new Array(n),i=new Array(n);for(o[0]=0,s[0]=2,i[0]=e[0]+2*e[1],t=1;t<n-1;++t)o[t]=1,s[t]=4,i[t]=4*e[t]+2*e[t+1];for(o[n-1]=2,s[n-1]=7,i[n-1]=8*e[n-1]+e[n],t=1;t<n;++t)r=o[t]/s[t-1],s[t]-=r,i[t]-=r*i[t-1];for(o[n-1]=i[n-1]/s[n-1],t=n-2;t>=0;--t)o[t]=(i[t]-o[t+1])/s[t];for(s[n-1]=(e[n]+o[n-1])/2,t=0;t<n-1;++t)s[t]=2*e[t+1]-o[t+1];return[o,s]}function sM(e){return new Vm(e)}function Dl(e,t){this._context=e,this._t=t}Dl.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}}this._x=e,this._y=t}};function aM(e){return new Dl(e,.5)}function lM(e){return new Dl(e,0)}function cM(e){return new Dl(e,1)}function $i(e,t,n){this.k=e,this.x=t,this.y=n}$i.prototype={constructor:$i,scale:function(e){return e===1?this:new $i(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new $i(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};$i.prototype;function co(e,t){return t==null?e:`${e}\0${t}`}function Xm(e){return e instanceof Date?e:new Date(e)}function uM(e){return typeof e.bandwidth=="function"?typeof e.paddingInner=="function"?"band":"point":typeof e.invert=="function"?"continuous":"discrete"}function Jm(e,t){e.type=t,e.kind=uM(e);const n=typeof e.domain=="function"?e.domain():[];return e.temporal=n.some(r=>r instanceof Date),e.domainConfig=n,e.invertible=e.kind==="band"||e.kind==="point"||typeof e.invert=="function",e.ramp=e.ramp===!0||typeof e.interpolator=="function",e.encode=(r,o)=>$r(e,r,o),e.invertValue=e.invertible?r=>hM(e,r):()=>{},e}function fM(e,{range:t,positional:n,domain:r}={}){return r&&typeof e.domain=="function"&&!e.domain().length&&e.domain(r),t&&n&&typeof e.range=="function"&&e.range(t),Jm(e)}function Iu(e,t){if(!e)return null;const n=e.type||"linear";let r;if(n==="time")r=b_().domain(e.domain.map(Xm)).range(t);else if(n==="band")r=Af().domain(e.domain).range(t).padding(e.padding!=null?e.padding:.1);else if(n==="point")r=zS().domain(e.domain).range(t).padding(e.padding!=null?e.padding:.5);else if(n==="ordinal")r=Ef().domain(e.domain).range(t);else if(n==="sequential"){const[o,s]=[Math.min(...e.domain),Math.max(...e.domain)],i=Pi().domain([o,s]).range([0,1]).clamp(!0),a=Qr(t[0],t[1]);r=l=>a(i(l)),r.domain=()=>e.domain,r.range=()=>t,r.ramp=!0}else if(n==="diverging"){const[o,s]=[Math.min(...e.domain),Math.max(...e.domain)],i=e.pivot!=null?e.pivot:o<0&&s>0?0:(o+s)/2,a=Pi().domain([o,i,s]).range([0,.5,1]).clamp(!0),l=t.length>=3?[t[0],t[1],t[t.length-1]]:[t[0],"#f7f7f7",t[t.length-1]],u=Og(Qr,l);r=c=>u(a(c)),r.domain=()=>e.domain,r.range=()=>t,r.ramp=!0,r.pivot=()=>i}else n==="log"?(r=Sm().domain(e.domain).range(t),e.base!=null&&r.base(e.base)):n==="symlog"?(r=$m().domain(e.domain).range(t),e.constant!=null&&r.constant(e.constant)):n==="pow"||n==="sqrt"?r=_m().domain(e.domain).range(t).exponent(e.exponent!=null?e.exponent:n==="sqrt"?.5:1):r=Pi().domain(e.domain).range(t);return e.nice&&typeof r.nice=="function"&&r.nice(),e.clamp&&typeof r.clamp=="function"&&r.clamp(!0),Jm(r,n)}function dM({domain:e,localRange:t,origin:n=0,halfSize:r=1,family:o="plain"}){const s=o==="x"?l=>n+l*r:o==="y"?l=>n-l*r:o==="size"?l=>l*r:l=>l,i=e.some(l=>l instanceof Date)?"time":"linear",a=Iu({type:i,domain:e},t.map(s));return a.frameExtent=Math.abs(r)||void 0,a}function Gn(e){return!!e&&e.kind==="band"}function uo(e){return!!e&&(e.kind==="band"||e.kind==="point")}function ro(e){const t=e.range();return[Math.min(t[0],t[1]),Math.max(t[0],t[1])]}function $r(e,t,n){if(!e)return n;if(e.kind==="band"){const o=e(t);return o==null?n:o+e.bandwidth()/2}if(e.kind==="point"){const o=e(t);return o??n}if(e.temporal)return e(Xm(t));if(t==null)return n;const r=e(t);return typeof r=="number"&&!Number.isFinite(r)?n:r}function yn(e,t){return e&&e.bandwidth?e.bandwidth():t}function Kr(e,t,n){if(!e)return n;if(e.kind==="band"||e.kind==="point"){const r=e(t);return r??n}return $r(e,t,n)}function Zm(e,t,n,{inset:r=0,length:o}={}){let s,i;if(Gn(e)){const a=e(t),l=e.bandwidth();s=a,i=a+l}else s=0,i=n;if(o!=null){const a=(s+i)/2;return[a-o/2,a+o/2]}return[s+r,i-r]}function hM(e,t){if(!e||!e.invertible)return;if(uo(e)){const i=e.domain();if(!i.length)return;const a=e.kind==="band"?e.bandwidth()/2:0;let l=i[0],u=1/0;for(const c of i){const d=e(c)+a,f=Math.abs(d-t);f<u&&(u=f,l=c)}return l}const n=e.invert(t),r=e.domain();if(e.temporal){const i=Math.min(...r.map(Number)),a=Math.max(...r.map(Number));return new Date(Math.max(i,Math.min(a,Number(n))))}const o=Math.min(...r),s=Math.max(...r);return Math.max(o,Math.min(s,n))}function yr(e){const[t,n]=ro(e),r=e(0);return Math.max(t,Math.min(n,r))}const is=["#4e79a7","#f28e2b","#e15759","#76b7b2","#59a14f","#edc948","#b07aa1","#ff9da7","#9c755f","#bab0ac"],_i=["#e6f0ff","#08519c"],Lu=["#2166ac","#f7f7f7","#b2182b"],Qm=["●","■","▲","◆","★","✚","▼","◀","▶","⬟"],yp={faces:["😞","😐","🙂"],faces5:["😢","🙁","😐","🙂","😄"],hearts:["🖤","💛","❤️"],weather:["☀️","⛅","☁️","🌧️","⛈️"],arrows:["⬇️","↘️","➡️","↗️","⬆️"],shapes:Qm},gp={category10:w_,tableau10:T_,observable10:k_,accent:x_,dark2:v_,paired:S_,pastel1:$_,pastel2:__,set1:M_,set2:E_,set3:A_},pM={rdbu:N_,rdylbu:I_,rdylgn:L_,brbg:O_,piyg:C_,spectral:F_,blues:R_,greens:z_,greys:P_,oranges:W_,purples:D_,reds:j_,viridis:K_,magma:Y_,inferno:G_,plasma:V_,cividis:q_,turbo:U_,warm:H_,cool:B_},yM={rdbu:Lm,rdylbu:Fm,rdylgn:Rm,brbg:Nm,piyg:Im,spectral:zm,blues:Pm,greens:Dm,greys:jm,oranges:Hm,purples:Wm,reds:qm};function Mi(e,t,n){if(!e||typeof e!="string")return null;const r=e.toLowerCase();if(yp[r])return[...yp[r]];if(gp[r])return[...gp[r]];const o=pM[r];if(!o)return null;if(t==="diverging")return[o(0),o(.5),o(1)];if(t==="sequential")return[o(0),o(1)];const s=Math.max(2,n||2),i=yM[r];if(i){const a=Math.max(3,Math.min(11,s)),l=i[a];if(l)return[...l]}return Cg(o,s)}const e0=new Set(["fill","stroke"]),gM=new Set(["opacity","fillOpacity","strokeOpacity"]),t0=new Set(["symbol"]),mM={x:"x",x1:"x",x2:"x",y:"y",y1:"y",y2:"y",theta:"theta",theta2:"theta",count:"count"};function $t(e){return mM[e]}function Yr(e){if(!e)return null;const t=e.scale;return t==="frame"?{}:t&&typeof t=="object"&&t.type==="frame"?t:null}function bM(e){if(!e||typeof e!="object"||e.frame===void 0)return e;const{frame:t,...n}=e;return n.scale!==void 0?n:Array.isArray(t)?{...n,scale:{type:"frame",range:t}}:typeof t=="number"?{...n,datum:t,scale:"frame"}:{...n,scale:"frame"}}const wM=new Set(["size","rx","ry","strokeWidth"]);function Ff(e){const t=$t(e);return t==="x"||t==="y"?t:wM.has(e)?"size":"plain"}function xM(e){const t=Ff(e);return t==="x"||t==="y"?[-1,1]:t==="size"?[0,1]:null}function Rf(e){const t=e.find(n=>n!=null);return t instanceof Date?"temporal":typeof t=="number"||t===void 0?"quantitative":"categorical"}function vM(e,t,n="band"){const r=t==="quantitative"||t==="temporal";return e0.has(e)?r?"sequential":"ordinal":t0.has(e)?"ordinal":t==="temporal"?"time":t==="quantitative"?"linear":n}function n0(e,t){if(e==="band"||e==="point"||e==="ordinal")return[...new Set(t.filter(r=>r!=null))];const n=t.filter(r=>r!=null);return n.length?[Math.min(...n),Math.max(...n)]:[0,1]}function kM(e,t){if(t.length){if(t.length===1)return t[0];if(e==="quantitative"||e==="temporal"){const n=t.map(i=>Math.min(...i.map(Number))),r=t.map(i=>Math.max(...i.map(Number))),[o,s]=[Math.min(...n),Math.max(...r)];return e==="temporal"?[new Date(o),new Date(s)]:[o,s]}return[...new Set(t.flat())]}}const SM=["tableau10","dark2","set2","accent","paired","set3"],mp=["blues","oranges","greens","purples","greys"];function bp(e,t){if(t<=1)return[e[e.length-1]];const n=Og(Qr,e);return Cg(n,t)}function $M(e,t,n={}){const{measure:r,index:o=0,count:s=2}=n,i=a=>a[o%a.length];return e==="diverging"?o===0?t&&t.diverging||Lu:Mi(i(["rdbu","brbg","piyg","rdylgn"]),"diverging",s)||Lu:e==="sequential"?o===0?t&&t.ramp||_i:Mi(i(mp),"sequential",s)||_i:r==="ordinal"?o===0?bp(t&&t.ramp||_i,Math.max(2,s)):Mi(i(mp),"ordinal",s)||bp(_i,Math.max(2,s)):o===0?t&&t.palette||is:Mi(i(SM),"ordinal",s)||is}function r0(e,t,n,r,o={}){switch(e){case"x":return[0,n.width];case"y":return[n.height,0];case"size":return[3,18];case"rx":return[3,18];case"ry":return[3,18];case"curvature":return[-1,1];case"theta":return[180,0];case"angle":return[180,0];case"count":return o.countAxis==="x"?[0,n.width]:[n.height,0]}return gM.has(e)?[.15,1]:e0.has(e)?$M(t,r,o):t0.has(e)?[...Qm]:e==="strokeWidth"?[1,8]:[0,1]}function _M(e){return e.channels||{}}function zf(e,t){return Math.atan2(-(e.y-t.cy),e.x-t.cx)*180/Math.PI}function MM(e,t,n){const r=Math.min(t,n),o=Math.max(t,n),s=(r+o)/2,i=s+((e-s)%360+540)%360-180;return Math.max(r,Math.min(o,i))}function EM(e,t,n){const r=$t(e);if(r==="x")return t.x;if(r==="y")return t.y;if(e==="size")return n?Math.hypot(t.x-n.cx,t.y-n.cy):void 0;if(e==="theta"||e==="angle")return n?zf(t,n):void 0}function AM(e,t,n=null){const r=$t(e);if(r==="x")return{x:t,y:n?n.cy:0};if(r==="y")return{x:n?n.cx:0,y:t};if(n){if(e==="size")return{x:n.cx+t,y:n.cy};if(e==="theta"||e==="angle"){const o=t*Math.PI/180,s=100;return{x:n.cx+s*Math.cos(o),y:n.cy-s*Math.sin(o)}}}}var TM={};function OM(){try{const e=typeof process<"u"&&TM&&"production";if(e)return e!=="production"}catch{}return!0}let Pf=OM();const Fu=new Set;function CM(e){Pf=!!e,Fu.clear()}function ni(){return Pf}function ge(e,t){!Pf||Fu.has(e)||(Fu.add(e),console.warn(`[elicit] ${t}`))}const o0=200,Ru={table:{roles:["data"],primary:"data"},network:{roles:["nodes","links"],primary:"nodes"}},i0="table",Nc="fields";function NM(e){return!e||typeof e!="object"||Array.isArray(e)?!1:typeof e.type=="string"||"domain"in e||"default"in e||"key"in e||"open"in e}const Df=["directed","multi","selfLoops"],IM=["role","fields",...Df];function LM(e){return!e||typeof e!="object"?!1:typeof e.role=="string"?!0:!e.fields||typeof e.fields!="object"?!1:Object.keys(e).every(t=>IM.includes(t))}function wp(e,t){const n=Object.keys(e).filter(r=>e[r]&&e[r].key===!0);if(n.length>1)throw new Error(`[elicit] table "${t}" declares more than one \`key: true\` field (${n.map(r=>`"${r}"`).join(", ")}). A table has at most one key — it is the identity a \`ref\` points at.`);return n.length?n[0]:null}function s0(e){const t={};for(const n of Df)typeof e[n]=="boolean"&&(t[n]=e[n]);return t}function FM(e,t){if(!t||typeof t!="object")throw new Error(`[elicit] schema.tables.${e} must be a field map, or { role, fields }. Got ${t===null?"null":typeof t}.`);if(LM(t)){if(typeof t.role!="string"&&NM(t.fields))throw new Error(`[elicit] table "${e}" is ambiguous: \`fields\` is its only key and its value looks like a single FieldSchema, so this reads equally as the long form or as a one-column table whose column is called "fields". Say which: ${e}: { fields: { fields: … } } for the column, or add \`role\` for the long form.`);const n=t.fields||{};return{name:e,role:t.role||e,fields:n,key:wp(n,e),...s0(t)}}if(Object.prototype.hasOwnProperty.call(t,Nc))throw new Error(`[elicit] table "${e}" declares a column named "${Nc}", which is reserved in this short form — it is how a table entry says "here are my columns". Use the long form to keep the column: ${e}: { fields: { ${Nc}: … } }.`);return{name:e,role:e,fields:t,key:wp(t,e)}}function RM(e){const t=e&&typeof e=="object"?e:{},n=typeof t.structure=="string",r=n?t.structure:i0,o=Ru[r];if(!o)throw new Error(`[elicit] unknown schema structure "${r}". Known structures: ${Object.keys(Ru).map(u=>`"${u}"`).join(", ")}.`);let s;if(!n)s={[o.primary]:t};else if(t.tables&&typeof t.tables=="object")s=t.tables;else throw t.fields&&typeof t.fields=="object"?new Error(`[elicit] schema declares \`fields\` at the top level. Columns belong to a named TABLE: schema: { structure: "${r}", tables: { ${o.primary}: { … } } }.`):new Error(`[elicit] schema declares structure "${r}" but no \`tables\`. A structure is a set of named tables: tables: { ${o.roles.map(u=>`${u}: { … }`).join(", ")} }.`);const i={},a={};for(const[u,c]of Object.entries(s)){const d=FM(u,c);if(!o.roles.includes(d.role))throw new Error(`[elicit] table "${u}" claims role "${d.role}", which structure "${r}" does not define. Its roles are ${o.roles.map(f=>`"${f}"`).join(", ")}.`);if(a[d.role])throw new Error(`[elicit] tables "${a[d.role]}" and "${u}" both claim role "${d.role}". Each role is filled by exactly one table.`);a[d.role]=u,i[u]=d}const l=o.roles.filter(u=>!a[u]);if(l.length)throw new Error(`[elicit] structure "${r}" needs a table for ${l.map(u=>`"${u}"`).join(", ")}, but the schema declares none. The schema is the contract of the elicited dataset, and a table built entirely by gesture has no rows to infer one from — declare it, even empty.`);for(const[u,c]of Object.entries(i))if(c.role!=="links")for(const d of Df)c[d]!==void 0&&ge(`schema:${d}:${u}`,`table "${u}" declares \`${d}\`, but that describes the pairs of \`ref\` columns in a links table, and this table fills the "${c.role}" role. Move it to the table filling the "links" role, or drop it.`);return{structure:r,tables:i,byRole:a,primary:a[o.primary]}}function ks(e){const t=e&&e.byRole&&e.byRole.links,n=t?e.tables[t]:null;return n?n.directed:void 0}function nl(e){const t=e&&e.byRole&&e.byRole.links,n=t?e.tables[t]:null;return{multi:!!(n&&n.multi),selfLoops:!!(n&&n.selfLoops)}}function ga(e){const t=Ru[e.structure],n=Object.keys(e.tables);return e.structure===i0&&n.length===1&&n[0]===t.primary}function zM(e){if(ga(e))return e.tables[e.primary].fields;const t={};for(const[n,r]of Object.entries(e.tables)){const o=s0(r),s=Object.keys(o).length?o:null;t[n]=r.role===n&&!s?r.fields:{...r.role===n?{}:{role:r.role},...s,fields:r.fields}}return{structure:e.structure,tables:t}}function jf(e,t){const n=t&&typeof t.to=="string"?t.to:null,r=e.byRole.nodes||e.primary;if(n&&n.includes(".")){const i=n.indexOf("."),a=n.slice(0,i),l=n.slice(i+1);return e.tables[a]?{table:a,field:l}:null}const o=e.tables[r];if(!o)return null;const s=n||o.key;return s?{table:r,field:s}:null}function a0(e,t,n){const r=jf(e,t);if(!r)return[];const o=e.tables[r.table].fields[r.field],s=[...o&&o.domain||[]];for(const i of n&&n[r.table]||[]){const a=i?i[r.field]:void 0;a!=null&&!s.includes(a)&&s.push(a)}return s}function Ic(e,t){const n=[];for(const[o,s]of Object.entries(e.tables))for(const[i,a]of Object.entries(s.fields)){if(!a||a.type!=="ref")continue;const l=jf(e,a);l&&n.push({table:o,field:i,target:l})}if(!n.length)return!1;let r=!1;for(let o=0;o<=n.length;o++){let s=!1;for(const i of n){const a=t[i.table];if(!a||!a.length)continue;const l=new Set;for(const c of t[i.target.table]||[]){const d=c?c[i.target.field]:void 0;d!=null&&l.add(d)}const u=a.filter(c=>{const d=c?c[i.field]:void 0;return d==null||l.has(d)});u.length!==a.length&&(t[i.table]=u,s=!0,r=!0)}if(!s)break}return r}function xp(e,t){const n={};for(const r of Object.keys(t.tables))n[r]=[];if(e==null)return n;if(Array.isArray(e))return n[t.primary]=e,n;if(typeof e!="object")throw new Error(`[elicit] data must be an array of rows, or an object keyed by table name (${Object.keys(t.tables).map(r=>`"${r}"`).join(", ")}). Got ${typeof e}.`);for(const[r,o]of Object.entries(e)){if(!n[r]){ge(`data:table:${r}`,`data has a table "${r}" that the schema does not declare. The schema is the contract of the elicited dataset, so every table belongs in it; these rows are ignored. Declared tables: ${Object.keys(t.tables).map(s=>`"${s}"`).join(", ")}.`);continue}if(!Array.isArray(o))throw new Error(`[elicit] data.${r} must be an array of rows. Got ${o===null?"null":typeof o}.`);n[r]=o}return n}function Ss(e){const t={};if(!e)return t;for(const[n,r]of Object.entries(e))t[n]=r&&r.default!==void 0?r.default:null;return t}function l0(e){const t=e||[];return t.some(n=>n instanceof Date)?"temporal":t.every(n=>typeof n=="number")?"quantitative":"categorical"}function c0(e){const t=new Set;for(const n of e.slice(0,o0))if(n&&typeof n=="object")for(const r of Object.keys(n))t.add(r);return[...t]}function rl(e,t){const n=[];for(const r of e.slice(0,o0)){const o=r?r[t]:void 0;o!=null&&n.push(o)}return n}function PM(e){const t={};if(!Array.isArray(e)||!e.length)return t;for(const n of c0(e)){const r=rl(e,n),o=Rf(r),s=o==="categorical"||o==="ordinal";t[n]={type:o,domain:n0(s?"band":"linear",r),...s?{open:!0}:{}}}return t}function DM(e){return`schema: {
9
+ ${Object.entries(e).map(([n,r])=>` ${JSON.stringify(n)}: { type: ${JSON.stringify(r.type)}, domain: ${JSON.stringify(r.domain)}${r.open?", open: true":""} }`).join(`,
10
+ `)}
11
+ }`}function jM(e,t){return t==="quantitative"?typeof e!="number"||!Number.isFinite(e):t==="temporal"?e instanceof Date?Number.isNaN(e.getTime()):typeof e=="number"?!Number.isFinite(e):typeof e=="string"?Number.isNaN(new Date(e).getTime()):!0:!1}function WM(e,t,n){if(!Array.isArray(n)||!n.length)return!1;if(t==="quantitative"||t==="temporal"){if(n.length<2)return!1;const r=e instanceof Date?e.getTime():Number(e);if(!Number.isFinite(r))return!1;const o=n.map(a=>a instanceof Date?a.getTime():Number(a)),s=Math.min(...o),i=Math.max(...o);return!Number.isFinite(s)||!Number.isFinite(i)?!1:r<s||r>i}return!n.includes(e)}function qM(e,t,n="data"){if(!Array.isArray(t)||!t.length)return;const r=e||{};if(!Object.keys(r).length){ge("schema:missing",`${n} was given but the spec declares no schema. The schema is the contract of the elicited dataset — it owns each field's measurement type and domain, and is what a created row is minted from. Inferring both from the data for now; declare it:
12
+ ${DM(PM(t))}`);return}for(const s of c0(t))r[s]||ge(`schema:extra:${s}`,`${n} has a column "${s}" that the schema does not declare. The schema is the contract of the elicited dataset, so every column belongs in it — an undeclared one gets no domain, no type and no creation default, so a row made by an edit will be missing it. Declare it: schema: { ${JSON.stringify(s)}: { type: ${JSON.stringify(Rf(rl(t,s)))} } }.`);for(const[s,i]of Object.entries(r)){if(!i)continue;const a=rl(t,s);if(!i.type){i.domain&&ge(`schema:notype:${s}`,`schema.${s} declares a domain but no \`type\`. A field's measurement type is required — without it the type is inferred from the data and can disagree with the domain you declared. Add type: ${JSON.stringify(l0(i.domain))}.`);continue}const l=a.find(d=>jM(d,i.type));if(l!==void 0){ge(`schema:type:${s}`,`${n} has a value in "${s}" (${JSON.stringify(l)}) that contradicts its declared type "${i.type}". The schema owns the data type; either fix the value or declare the type the data actually has.`);continue}const u=i.domain;if(!u||i.open)continue;const c=a.find(d=>WM(d,i.type,u));c!==void 0&&ge(`schema:domain:${s}`,`${n} has a value in "${s}" (${JSON.stringify(c)}) outside its declared domain ${JSON.stringify(i.domain)}. The domain is what the axis spans, so that row draws clipped or off-plot. Widen the domain or fix the data.`)}}function Lc(e,t,n="data"){const r=Object.keys(e.tables);for(const o of r){const s=r.length>1?`${n}.${o}`:n;qM(e.tables[o].fields,t[o]||[],s),BM(e,t,o,s),e.tables[o].role==="links"&&HM(e,t,o,s)}}function HM(e,t,n,r){const o=e.tables[n];if(o.multi!==!1&&o.selfLoops!==!1)return;const s=Object.keys(o.fields).filter(u=>o.fields[u]&&o.fields[u].type==="ref");if(s.length<2)return;const[i,a]=s,l=new Set;for(const u of t[n]||[]){if(!u)continue;const c=u[i],d=u[a];if(o.selfLoops===!1&&c!=null&&c===d&&ge(`schema:selfLoops:${n}`,`${r} has a link from ${JSON.stringify(c)} to itself, but the "${n}" table declares selfLoops: false. Remove the row, or declare selfLoops: true.`),o.multi===!1){const f=o.directed===!1&&String(d)<String(c)?[d,c]:[c,d],p=JSON.stringify(f);l.has(p)&&ge(`schema:multi:${n}`,`${r} links ${JSON.stringify(c)} and ${JSON.stringify(d)} more than once, but the "${n}" table declares multi: false. Remove the duplicate, or declare multi: true.`),l.add(p)}}}function BM(e,t,n,r){const o=e.tables[n].fields,s=t[n]||[];if(s.length)for(const[i,a]of Object.entries(o)){if(!a||a.type!=="ref")continue;const l=jf(e,a);if(!l){ge(`schema:ref:${n}:${i}`,`schema.${n}.${i} is a \`ref\` but its target cannot be resolved${a.to?` (to: ${JSON.stringify(a.to)})`:""}. A ref points at a table's \`key: true\` column — declare one, or name the column with \`to\`. Nothing references anything until then.`);continue}const u=new Set(a0(e,a,t)),c=rl(s,i).find(d=>!u.has(d));c!==void 0&&ge(`schema:dangling:${n}:${i}`,`${r} has a value in "${i}" (${JSON.stringify(c)}) that names no row of "${l.table}" (its ${JSON.stringify(l.field)}). A \`ref\` must name an existing identity — a link to a node that isn't there connects nothing, and draws nothing.`)}}function vp(e){return e==null?{}:typeof e=="function"?{instance:e}:typeof e=="string"?{type:e}:e}function Fc(e,t,n,r){const o=n.schema||{},s=n.schemaSpec||null,i=n.scales||{},a=m=>t&&(t[m.table]||t[n.schemaSpec?n.schemaSpec.primary:""])||[],l=m=>{const b=s&&s.tables[m.table];return b&&b.fields||o},u={},c=m=>u[m]||(u[m]={fields:[],fieldRefs:[],schemas:[],undeclared:[],values:[]}),d={},f={},p=(m,b)=>{const w=$t(m),x=w||co(m,b&&b.field!=null?b.field:void 0);return(d[x]||(d[x]=new Set)).add(m),f[x]=w||m,x};for(const m of e){const b=_M(m),w=m.discreteScale||"band",x=new Set(m.rawChannels||[]);for(const[S,v]of Object.entries(b)){if(!v||v.scale===null||Yr(v)||x.has(S))continue;if(typeof v.fn=="function"&&v.field==null){(v.scale!==void 0||v.type!==void 0)&&ge(`fnopt:${S}`,`channel "${S}" is derived ({ fn }) — its result is used as-is in visual space, so its "${v.scale!==void 0?"scale":"type"}" is ignored. Drop it, or use a field channel if you want a scale.`);continue}for(const[_,A]of[["domain","the spec's schema"],["range","this channel's `scale`"]])v[_]!==void 0&&ge(`stray:${_}:${S}`,`channel "${S}" declares "${_}", which is ignored. Move it to ${A}: ${_==="range"?"scale: { range: [...] }":"schema: { <field>: { domain: [...] } }"}.`);const k=c(p(S,v));if(k.measure==null&&v.type!=null&&(k.measure=v.type),k.scaleOpt==null&&v.scale!=null&&(k.scaleOpt=v.scale),k.discretePref!=="band"&&(k.discretePref=w),k.countAxis==null&&m.countAxis&&(k.countAxis=m.countAxis),v.field!=null){k.fields.includes(v.field)||k.fields.push(v.field);const _=m.table;_!=null&&!k.fieldRefs.some(L=>L.table===_&&L.field===v.field)&&k.fieldRefs.push({table:_,field:v.field});const A=l(m)[v.field];A&&A.type==="ref"&&s?k.schemas.push({type:"categorical",domain:a0(s,A,t),open:!0}):A?k.schemas.push(A):k.undeclared.includes(v.field)||k.undeclared.push(v.field);for(const L of a(m))k.values.push(L[v.field])}else v.datum!==void 0&&k.values.push(v.datum)}}const h={},y={},g={};for(const m of Object.keys(u)){const b=f[m]||m;y[m]=g[b]||0,g[b]=y[m]+1}for(const[m,b]of Object.entries(u)){const w=f[m]||m,x=b.values.some($=>$!=null);if(!b.fields.length&&!x)continue;const S=b.schemas;for(const $ of b.undeclared)ge(`schema:${$}:${w}`,`field "${$}" is encoded on channel "${w}" but not declared in schema; inferring its type and domain from data. Declare it in the Elicit spec's schema — the schema is the contract of the elicited dataset.`);if(!S.length&&!x)throw new Error(`[elicit] cannot resolve a scale for channel "${w}": field(s) ${b.fields.map($=>`"${$}"`).join(", ")} have no schema entry and there is no data to infer from. Declare them in the Elicit spec's schema.`);const v={...vp(b.scaleOpt),...vp(i[w])},k=S.map($=>$.type).filter(Boolean);new Set(k).size>1&&ge(`measure:${w}`,`fields ${b.fields.map($=>`"${$}"`).join(", ")} share channel "${w}" but declare different schema types (${[...new Set(k)].join(", ")}). Using "${k[0]}".`);const _=b.measure||k[0]||Rf(b.values),A=v.type||vM(w,_,b.discretePref||"band"),L=[];for(const $ of S)$.domain&&L.push($.domain);const N=kM(_,L)||n0(A,b.values),I=!!$t(w);let T=v.range||Mi(v.scheme,A,N.length)||r0(w,A,r,n.theme,{measure:_,index:y[m]||0,count:N.length,countAxis:b.countAxis});v.reverse&&Array.isArray(T)&&(T=[...T].reverse());const M=v.instance?fM(v.instance,{range:v.range?void 0:T,positional:I,domain:N}):Iu({...v,type:A,domain:N},T);if(M){M.fields=b.fields,M.fieldRefs=b.fieldRefs,h[m]=M;for(const $ of d[m]||[])h[$]===void 0&&(h[$]=M)}}if(h.count===void 0){const m=e.find(b=>b&&b.countAxis&&b.countPitch>0);if(m){const b=m.countAxis==="x"?r.width:r.height,w=Math.max(1,Math.floor(b/m.countPitch)),x=w*m.countPitch,S=Iu({type:"linear",domain:[0,w]},m.countAxis==="x"?[0,x]:[r.height,r.height-x]);S&&(h.count=S)}}return h}const UM={"albers-usa":()=>vS(),albers:()=>um(),"azimuthal-equal-area":()=>kS(),"azimuthal-equidistant":()=>SS(),"conic-conformal":()=>MS(),"conic-equal-area":()=>Va(),"conic-equidistant":()=>TS(),"equal-earth":()=>CS(),equirectangular:()=>ES(),gnomonic:()=>NS(),mercator:()=>$S(),orthographic:()=>LS(),stereographic:()=>FS(),"transverse-mercator":()=>RS(),identity:()=>IS()};function KM(e){if(typeof e=="function"&&typeof e.stream!="function")return e();if(typeof e=="string"){const t=e.toLowerCase(),n=UM[t];if(!n)throw new Error(`[elicit] unknown projection type: ${e}`);return n()}return e}const kp=new WeakSet;function YM(e){if(!ni()||!e||typeof e!="object"||kp.has(e))return;kp.add(e);const n=(e.type==="FeatureCollection"&&Array.isArray(e.features)?e.features:[e]).filter(o=>{const s=o&&o.type==="Feature"?o.geometry:o;return!s||s.type!=="Polygon"&&s.type!=="MultiPolygon"?!1:H2(s)>Math.PI});if(!n.length)return;const r=n.map((o,s)=>o.properties&&(o.properties.name||o.properties.NAME)||`feature ${s}`).slice(0,3);ge(`rings:${r.join(",")}`,`projection domain has ${n.length} polygon(s) with reversed ring winding (${r.join(", ")}${n.length>3?", …":""}). d3 reads these as covering the whole globe, so the map fits the world and your features shrink to a dot. Rewind the exterior rings counterclockwise (RFC 7946).`)}function Zs(e){const t=fS(e),n=typeof e.invert=="function";return{apply(r){if(!r||r[0]==null||r[1]==null)return null;const o=e(r);return!o||o[0]==null||o[1]==null||!Number.isFinite(o[0])||!Number.isFinite(o[1])?null:o},invert(r){if(!n||!r||r[0]==null||r[1]==null)return null;const o=e.invert(r);return!o||o[0]==null||o[1]==null||!Number.isFinite(o[0])||!Number.isFinite(o[1])?null:o},path(r){return r==null?null:t(r)},invertible:n,raw:e}}function u0(e,t){if(e==null)return null;if(typeof e=="object"&&typeof e.apply=="function"&&typeof e.invert=="function"&&e.raw)return e;if(typeof e=="function"&&typeof e.stream=="function"||typeof e=="object"&&typeof e.stream=="function")return Zs(e);let n={},r=e,o,s=0,i,a,l,u;if(typeof e=="object"&&e!==null){if({type:r,domain:o,inset:s=0,insetTop:i=s,insetRight:a=s,insetBottom:l=s,insetLeft:u=s,...n}={type:void 0,domain:void 0,...e},r==null&&typeof e.stream=="function")return Zs(e);if(r==null)return null}else i=a=l=u=0;const c=KM(r),{rotate:d,parallels:f,precision:p=.15,clipAngle:h}=n;p!=null&&typeof c.precision=="function"&&c.precision(p),d!=null&&typeof c.rotate=="function"&&c.rotate(d),f!=null&&typeof c.parallels=="function"&&c.parallels(f),h!=null&&typeof c.clipAngle=="function"&&c.clipAngle(h);const y=Math.max(0,t.width-(u||0)-(a||0)),g=Math.max(0,t.height-(i||0)-(l||0));if(o!=null&&typeof c.fitExtent=="function")YM(o),c.fitExtent([[u||0,i||0],[(u||0)+y,(i||0)+g]],o);else if(typeof c.fitSize=="function"){try{c.fitSize([y,g],{type:"Sphere"})}catch{}if(u||i){const m=c.translate();c.translate([m[0]+(u||0),m[1]+(i||0)])}}return Zs(c)}function cr(e,t,n){if(!e||t==null||n==null)return null;const r=e.apply([+t,+n]);return r?{x:r[0],y:r[1]}:null}function Lr(e,t){if(!e||!t)return null;const n=e.invert([t.x,t.y]);return n?{lon:n[0],lat:n[1]}:null}function f0(e,t,n,r,o){if(!e)return null;const s=[cr(e,t,n),cr(e,t,o),cr(e,r,n),cr(e,r,o)];if(s.some(f=>!f))return null;const i=s.map(f=>f.x),a=s.map(f=>f.y),l=Math.min(...i),u=Math.max(...i),c=Math.min(...a),d=Math.max(...a);return{x:l,y:c,width:u-l,height:d-c}}const d0=["channels","id","edits","table"],h0=["fill","stroke","strokeWidth","opacity","fillOpacity","strokeOpacity","size","symbol","text","fontSize","textAnchor","lineAnchor","dx","dy","angle"],p0=["id","edit","edits","field","table"],y0=["id"],st={arc:["outerRadius","innerRadius","padAngle","arc","start","end","handles","handleSize","handleColor"],area:["orientation","curve","handles","handleSize","handleColor","connect"],bar:["orientation","stack","handles","handleSize","handleColor"],composite:["parts","discreteScale"],curve:["orientation","length"],dotStack:["orientation","gap","ghost","label"],ellipse:[],face:["ink"],geoBasemap:["geojson","stroke","strokeWidth","fill"],geoTile:["url","subdomains","tileSize","minZoom","maxZoom","zoomOffset","attribution","attributionSize","opacity"],geoPoint:[],geoPolygon:[],geoLine:["curve","handles","handleSize","handleColor","connect","showVertices"],geoText:["format"],geoRect:[],line:["orientation","curve","handles","handleSize","handleColor","connect"],link:["curve","curvature","spread","arrow","arrowSize","inset","sourceInset","targetInset","loopRadius","format","labelBackground","labelPadding","labelRadius","labelOpacity","cornerRadius","sourceSide","targetSide","sourceOffset","targetOffset","handles","handleSize","handleColor"],needle:["length","handles","handleSize","handleColor","baseWidth"],node:["dy","shape","format"],point:["shape"],rect:["orientation","width","height","rx"],rule:["orientation","strokeDasharray","discreteScale"],sticker:["padding","radius","maxWidth","minWidth","minHeight","lineHeight","fontFamily","format"],text:["orientation","format","wrap","lineHeight"],tick:["orientation","inset","length"],trend:["anchor","probe","grip","handles","handleSize","handleColor"],trendBand:["render","levels","samples","seed","sigma","distribution","anchor","probe","grip","handles","handleSize","handleColor"],waffle:["orientation","unit","multiple","gap","shape","showEmpty","emptyFill"]},$s={axis:["channel","anchor","transform","ticks","tickValues","tickFormat","tickSize","title","stroke","fill","fontSize","grid","handleColor","handleSize"],grid:["channel","ticks","tickValues","stroke","strokeWidth"],legend:["channel","anchor","orient","swatchSize","gap","labelWidth","rampLength","rampThickness","ticks","tickFormat","title","row","stroke","fill","fontSize","handleColor","handleSize"],axisRadial:["channel","channels","radius","innerRadius","bandWidth","ticks","tickValues","tickFormat","tickSize","labelOffset","bands","title","arc","orient","start","end","labelFill","stroke","strokeWidth","fontSize"]},_s={rule:["x","y","stroke","strokeDasharray","strokeWidth","opacity","label"],region:["x","y","fill","opacity","stroke","label"],remaining:["field","total","unit","format","anchor","label","fill","fontSize"],proximity:["target","stroke","strokeDasharray","strokeWidth","opacity"],prompt:["y"],optionRings:["labelOffset","radius"],cellGrid:["pad"],sliderTrack:["format"],crosshair:["x","y"],custom:[]},g0=["type","name","gesture","channel","channels","when","pick","threshold","scope","into","constrain","guide","stage","advance","target","cardinality","inverts","table","inline","multiline","defaults","apply","targets"],m0={move:["mode"],moveSpan:[],brushSpan:["edgeInset"],brushRect:["edgeInset","resize","move"],slide:["axis","increase","extent","mode"],resize:[],rotate:["relativeTo","pivot","fold"],cycle:[],create:[],toggle:[],remove:[],set:[],editText:[],rank:[],select:["exclusive","toggle","multi"],custom:[],"line.anchor":["series"],"line.newSeries":["along","value","samples","series"],"line.draw":["along","value","samples","minDist","series"],"line.sweep":["mode"],"line.removeSeries":["series"],"axis.scale":["field","mode"],"scale.addCategory":["field","mode"],"scale.renameCategory":["field","mode"],"scale.removeCategory":["field","mode"],"legend.category":[],"legend.value":[],"stack.cut":["label","categoryField"],"stack.edge":[],"stack.merge":[],"trend.intercept":["anchor","probe"],"trend.slope":["anchor","probe"],"trend.interceptSpread":["anchor","probe"],"trend.slopeSpread":["anchor","probe"],"waffle.fill":[],"network.connect":[],"network.rewire":[],"network.reverse":[],"geo.move":[],"geo.create":[],"geo.dragVertex":[],"geo.removeVertex":["min"],"geo.draw":["minDist"],"geo.brush":["move","edgeInset"],"geo.createRect":["width","height","edgeInset"]},b0={clamp:["min","max","field"],snap:["step","origin","field"],count:["max","strategy"],unique:["field","max","strategy"],maintainSum:["total","field","strategy"],ordering:["field","strategy"],monotonic:["field","along","dir","series"],spacing:["field","min","series"],custom:[]};function GM(e,t,n){if(!(!e||!t||!n))for(const r of Object.keys(n)){const o=n[r];if(!o||o.field!==e)continue;const s=t[co(r,e)]||t[r];if(s){if(s.domainConfig)return s.domainConfig;if(typeof s.domain=="function")return s.domain()}}}const VM={targetSum:"the total is `total` — maintainSum({ total: 100 }) — the same word guides.remaining uses.",fields:'the columns a rule is about are `field`, singular, which takes one name or an ordered list: ordering({ field: ["lo", "mean", "hi"] }).',lower:'ordering takes its columns as one ordered list: ordering({ field: ["lo", "hi"] }).',upper:'ordering takes its columns as one ordered list: ordering({ field: ["lo", "hi"] }).',mode:"what a constraint does when its rule is broken is `strategy` (cap | normalize | redistribute | push | block | reject | replace)."};function Fr(e,t){if(!t||!ni())return t;const n=b0[e]||[];for(const r of Object.keys(t)){if(n.includes(r))continue;const o=VM[r];ge(`constraintopt:${e}:${r}`,o?`${e}({ ${r}: … }): ${o}`:`${e}({ ${r}: … }) is not an option this constraint reads, so it is ignored. ${e} options are: ${n.slice().sort().join(", ")}.`)}return t}function XM(e){return{type:e.type,field:e.field,options:e.options||{},...e.table!=null?{table:e.table}:{},...typeof e.guide=="function"?{guide:e.guide}:{},apply:e.apply}}function Vt(e,t={}){return XM({...t,type:t.type||"custom",apply:e})}function JM(e,t,n,r){if(typeof e=="function")return e(t,n,r||{});const o=e;r=r||{};const s=Array.isArray(o.field)?o.field[0]:o.field,i=s??r.field,a=r.activeIndex!=null?r.activeIndex:null,l=a!=null&&a>=0&&a<t.length,u=l?t[a]:void 0,c={data:t,oldData:n,activeIndex:a,active:u,field:i,fields:Array.isArray(o.field)?o.field:i!=null?[i]:[],value:u&&i!=null?u[i]:void 0,domain:GM(i,r.scales,r.markChannels),table:r.table,tables:r.tables},d=o.apply(c);return d===!1||d===!0||d===void 0||Array.isArray(d)?d:typeof d=="number"?!l||i==null?t:t.map((f,p)=>p===a?{...f,[i]:d}:f):d&&typeof d=="object"&&l?t.map((f,p)=>p===a?{...f,...d}:f):t}function ol(e){return e==null||typeof e!="object"?JSON.stringify(e)||"null":JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]]))}const ZM=(e,t)=>e===t||e!=null&&t!=null&&ol(e)===ol(t);function QM(e,t,n){return e==null||e===!1?null:typeof e=="function"?(r,o)=>!!e(r,o,n):e===!0||e==="seed"?(r,o)=>o<t():(console.warn(`[elicit] spec.lock: expected "seed", true, or a (datum, index) => boolean predicate; got ${JSON.stringify(e)}. Nothing is locked.`),null)}function e5(e){return Vt(({data:t,oldData:n})=>{if(!n||!n.length)return;if(t.length<n.length){const o=new Map;if(n.forEach((s,i)=>{if(!e(s,i))return;const a=ol(s);o.set(a,(o.get(a)||0)+1)}),!o.size)return;for(const s of t){const i=ol(s),a=o.get(i);a&&(a===1?o.delete(i):o.set(i,a-1))}return o.size===0?void 0:!1}let r=null;for(let o=0;o<n.length;o++){const s=n[o];e(s,o)&&(ZM(t[o],s)||(r=r||t.slice(),r[o]=s))}return r||void 0},{type:"lock"})}function t5(e,t,n,r){if(e.index!=null){const i=n[e.index];return i!=null&&r(i,e.index)}if(e.series===void 0)return!1;const o=t.seriesKey||null;let s=!1;for(let i=0;i<n.length;i++){const a=n[i];if(!(o&&a[o]!==e.series)&&(s=!0,!r(a,i)))return!1}return s}function n5(e){return!!(e&&typeof e=="object"&&typeof e.apply=="function"&&e.gesture)}function ma(e){const t=[],n=e.channels||{};for(const[r,o]of Object.entries(n))if(o&&o.edit){if(typeof o.fn=="function"&&o.field==null)continue;const s=o.edit;t.push(s.channels?s:{...s,channels:[r]})}for(const r of e.edits||[])t.push(r);return t}function r5(e,t){const n=e.channels||{},r=t?t(e):`"${e.id||"?"}"`,o=e.id||e.type||"?";for(const[s,i]of Object.entries(n)){const a=`${o}:${s}`;s==="edit"||n5(i)?ge(a,`mark ${r} has a misplaced edit under channels.${s}. Attach edits on a channel (y: { field, edit: move() }) or at mark level (edits: [move({ channels: ['x','y'] })]). A bare channels.edit key is ignored.`):i&&i.edit&&typeof i.fn=="function"&&i.field==null?ge(a,`mark ${r} puts an edit on the derived channel "${s}" ({ fn }). A derived channel is read-only — it recomputes from the committed rows on every render, so the edit is ignored. Attach the edit to the source field's channel (e.g. x: { field: "x", edit: move() }); the fn re-derives automatically after each commit.`):i&&i.edit&&i.field==null&&typeof i.fn!="function"&&ge(`${a}:nofield`,`mark ${r} puts an edit on channel "${s}", which has no field (it is a constant: ${i.value!==void 0?"{ value }":"{ datum }"}). An edit writes back to a COLUMN, so give the channel a field (${s}: { field: "…", edit: … }) — otherwise there is nothing to elicit.`)}}function Ei(e,t,n,r=void 0){const o=!!(r&&r.views==="scale"),s=r&&r.field!=null?r.field:void 0,i=o||!t||Object.keys(t).length===0,a=[];for(const l of e||[]){const u=t&&t[l];let c=u&&u.field;if(c==null&&i)if(s!=null)c=s;else{const f=n[l],p=f&&f.fields;c=p&&p[0]}if(c==null)continue;const d=n[co(l,c)]||n[l]||void 0;a.push({name:l,field:c,scale:d})}return a}const w0=Symbol("elicit.unverifiedOptions"),o5=e=>e==null?[]:Array.isArray(e)?e:[e],Gr=(e,t)=>n=>e(n)&&(typeof t=="function"?!!t(n):!0);function jl(e,t,n){const{pick:r,...o}=e||{};return r!=null&&r!==n&&ge(`fixedpick:${t}`,`${t} is bound to the "${n}" driver — it reads a zone lock only that driver writes — so { pick: "${r}" } is ignored. Drop it, or use an edit that supports the strategy you want (move/moveSpan take any pick).`),o}function je(e){const{channel:t,channels:n,...r}=e,o=m0[e.type],s=o?Object.keys(r).filter(i=>!g0.includes(i)&&!o.includes(i)):[];return{...r,...s.length?{[w0]:s}:{},type:e.type,name:e.name||null,gesture:e.gesture||"drag",channels:t?[t]:n||null,when:e.when||null,pick:e.pick||"direct",threshold:e.threshold!=null?e.threshold:0,scope:e.scope||null,into:e.into||null,constrain:o5(e.constrain),guide:e.guide||null,stage:e.stage!=null?e.stage:null,advance:e.advance!==!1,target:e.target||void 0,cardinality:e.cardinality||null,inverts:!!e.inverts,apply:e.apply}}function il(e,t){const n=e.when;return{...e,when:r=>{const o=r.node&&r.node.channel;return o!=null&&o!==t?!1:n?n(r):!0}}}function Wl(e,t){if(!t)return 0;const n=new Set((e||[]).map(o=>o[t]));let r=0;for(;n.has(r);)r++;return r}function Wf(e,t,n,{open:r=!1,label:o="Category"}={}){if(!t)return;const s=new Set((e||[]).map(a=>a[t]));for(const a of n||[])if(!s.has(a))return a;if(!r)return;let i=(n||[]).length+1;for(;s.has(`${o} ${i}`)||(n||[]).includes(`${o} ${i}`);)i++;return`${o} ${i}`}function Fn(e,{defaults:t={},seed:n={},label:r}={}){const o={...Ss(e.schema),...t,...n};let s=Object.keys(n).length>0;for(const a of e.channels){const l=fo(a,e.pointer);l!==void 0&&(o[a.field]=l,s=!0)}if(!s)return;const i=i5(e.schema);if(i&&o[i]==null){const a=e.schema&&e.schema[i]||{},l=Wf(e.data,i,a.domain||[],{open:a.open!==!1,label:r||"Item"});if(l===void 0)return;o[i]=l}return o}function i5(e){if(!e)return null;for(const[t,n]of Object.entries(e))if(n&&n.key===!0)return t;return null}function Rr(e){return e.node?e.node:e.index==null||!e.marks?null:e.marks.find(t=>t&&t.index===e.index)||null}function Rn(e){return e?e.cx!=null&&e.cy!=null?{cx:e.cx,cy:e.cy}:e.x!=null&&e.width!=null?{cx:e.x+e.width/2,cy:e.y+(e.height||0)/2}:e.x1!=null&&e.y1!=null&&e.x2!=null&&e.y2!=null?{cx:(e.x1+e.x2)/2,cy:(e.y1+e.y2)/2}:e.x!=null&&e.y!=null?{cx:e.x,cy:e.y}:null:null}const s5=.01,a5=.1;function zu(e,t,n,r=!1){if(!e||!n||!e.invertible)return t;if(e.kind==="band"||e.kind==="point"){const a=e.domain();if(a.length<2)return t;const l=e.invertValue(t),u=a.indexOf(l);if(u<0)return t;const c=e.encode(a[a.length-1])>e.encode(a[0]),d=u+(c?n:-n);return d<0||d>=a.length?t:e.encode(a[d])}const[o,s]=ro(e),i=(s-o)*(r?a5:s5);return Math.max(o,Math.min(s,t+n*i))}const xn=e=>e instanceof Date?e.getTime():e;function x0(e,t,n,r,o){if(n===t)return;let s=(e-t)/(n-t);return s=s<0?0:s>1?1:s,r+s*(o-r)}function v0(e){const t=e&&e.scale&&e.scale.domainConfig;return Array.isArray(t)&&t.length?[t[0],t[t.length-1]]:[0,1]}function k0(e,t){const n=e&&e.scale&&typeof e.scale.domain=="function"?e.scale.domain():null;if(Array.isArray(n)&&n.length)return n;const r=e&&e.field!=null&&t?t[e.field]:null,o=r&&r.domain;return Array.isArray(o)&&o.length?o:null}function fo(e,t,n=null){if(!e||!e.scale||!e.scale.invertible)return;const r=EM(e.name,t,n);if(r!==void 0)return e.scale.invertValue(r)}function ql(e,t,n,r){if(!e||!t||!n||!t.scale||!n.scale||!t.scale.invertible||!n.scale.invertible)return;const o=$t(t.name);if(!o||o!==$t(n.name))return;const s=o==="x"?r.x:r.y,i=o==="x"?e.width:e.height;if(s===void 0||i==null)return;let a=s-i/2,l=s+i/2;const[u,c]=ro(t.scale),d=Math.min(u,c),f=Math.max(u,c),p=f-d;return i>=p?(a=d,l=f):(a<d&&(l+=d-a,a=d),l>f&&(a-=l-f,l=f)),{a:t.scale.invertValue(a),b:n.scale.invertValue(l)}}const S0=["filter","opacity","fill","stroke","strokeWidth","cursor"],l5=["hovered","selected","grabbed"],sl={hovered:{outline:{color:"#ff9800",width:2,pad:5,dash:null,opacity:.65}},selected:{outline:{color:"#ff9800",width:2.5,pad:5,dash:null,opacity:.95}},grabbed:{filter:"brightness(0.82)"}},c5={color:"#ff9800",dash:"2 4",width:1,opacity:.45};function u5(e,t){const n=t||{};if(e===!1)return{enabled:!1};if(typeof e=="string")return{...n,enabled:!0,filter:e};const r=e||{},o=r.outline===!1?null:n.outline||r.outline?{...n.outline,...r.outline||{}}:null;return{...n,...r,outline:o,enabled:!0}}function f5(e={},t=sl){const n=e||{},r=t||sl,o={};for(const s of l5)o[s]=u5(n[s],r[s]);return o}function Pu(e){if(!e||e.enabled===!1)return null;const t={};let n=!1;for(const r of S0)e[r]!=null&&(t[r]=e[r],n=!0);return n?t:null}function d5(e){const t={};let n=!1;for(const r of e||[]){const o=Pu(r);o&&(Object.assign(t,o),n=!0)}return n?t:null}function qf(e,t){if(!e||!t||t.enabled===!1||!t.outline)return[];if(e.effectShape)return qf({...e.effectShape,...e.angle?{angle:e.angle}:{}},t);const{color:n,width:r,pad:o,dash:s,opacity:i}=t.outline,a={fill:"none",stroke:n,strokeWidth:r,opacity:i,...s?{strokeDasharray:s}:{},...e.angle?{angle:e.angle}:{},guide:!0,effect:!0,pointerEvents:"none"};if(e.type==="circle")return[{type:"circle",cx:e.cx,cy:e.cy,r:(e.r||5)+o,...a}];if(e.type==="ellipse")return[{type:"ellipse",cx:e.cx,cy:e.cy,rx:(e.rx!=null?e.rx:5)+o,ry:(e.ry!=null?e.ry:5)+o,...a}];if(e.type==="rect")return[{type:"rect",x:e.x-o,y:e.y-o,width:e.width+o*2,height:e.height+o*2,...a}];if(e.type==="line"){const l=Math.min(e.x1,e.x2),u=Math.min(e.y1,e.y2);return[{type:"rect",x:l-o,y:u-o,width:Math.abs(e.x2-e.x1)+o*2,height:Math.abs(e.y2-e.y1)+o*2,...a}]}if(e.type==="path")return e.d?[{type:"path",d:e.d,...a}]:[];if(e.type==="text"){const l=(e.fontSize||12)*.9+o;return[{type:"circle",cx:e.x,cy:e.y,r:l,...a}]}return[]}function Sp(e,t,n){if(!n||n.enabled===!1||!n.outline)return[];const r=[];for(const o of t){if(o==null)continue;const s=(e||[]).find(i=>i&&i.index===o)||(e||[])[o];!s||s.ghost||r.push(...qf(s,n))}return r}const Hf={ink:"steelblue",accent:"#2563eb",muted:"#9ca3af",handle:"#2563eb",handleStroke:"#fff",background:null,palette:is,ramp:_i,diverging:Lu,font:{family:null,size:10,labelSize:12,titleSize:13},axis:{stroke:"#6b7280",labelFill:"#374151",fontSize:10,handle:"#2563eb"},grid:{stroke:"#e5e7eb",strokeWidth:1},guide:{rule:{stroke:"#64748b",strokeDasharray:"5 4",strokeWidth:1,opacity:.9},region:{fill:"#64748b",opacity:.1},legend:{stroke:"#374151",labelFill:"#374151",fontSize:11,currentStroke:"#111827",currentWidth:2},bounds:{dash:"4 4",width:1,opacity:.9},catchment:{dash:"2 4",width:1,opacity:.45},track:{dash:"3 3",width:2,opacity:.35}},constraint:{color:"#e4572e"},effects:sl,ghost:{opacity:.45,fill:null,stroke:null,strokeDasharray:null},widget:{accent:"#2563eb",ring:"#cbd5e1",track:"#e2e8f0",cellFill:"#f8fafc",cellStroke:"#e2e8f0",label:"#334155",question:"#0f172a",labelSize:12,questionSize:13,radius:11},marks:{}};function Rc(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Date)}function Du(e,t){if(!Rc(t))return t===void 0?e:t;const n={...e};for(const r of Object.keys(t)){const o=e?e[r]:void 0,s=t[r];n[r]=Rc(o)&&Rc(s)?Du(o,s):s===void 0?o:s}return n}let $0={};function h5(e){$0=e||{}}function Bf(e){const t=Du(Hf,$0);return e==null||typeof e=="string"?t:Du(t,e)}function it(e){return e&&e.theme||Hf}function Nt(e,t,n){const r=it(e),o=r.marks&&r.marks[t]||{};return{...n,...o}}const _0={fill:void 0,stroke:void 0,strokeWidth:void 0,opacity:void 0,fillOpacity:void 0,strokeOpacity:void 0},M0=Object.keys(_0),E0=h0;function Hl(e,t,n,r,o,s){if(n==null)return s;try{const i=e.fn(n,r,o);return i??s}catch(i){return ge(`fn:${t}`,`fn on channel "${t}" threw: ${i instanceof Error?i.message:i}; using the fallback.`),s}}function se(e,t,n,r,o,s,i){const a=t[n];if(!a)return o;if(a.expr!==void 0&&ge(`expr:${n}`,`channel "${n}" uses { expr: … }, which is RESERVED for the planned JSON spec layer and is not implemented in 0.1. In JavaScript, write the derived form instead: { fn: (d, i, data) => … }.`),a.field===void 0){if(typeof a.fn=="function")return Hl(a,n,r,s,i,o);if(a.value!==void 0)return a.value;if(a.datum!==void 0){if(a.scale===null)return a.datum;const c=e[n];return c?c.encode(a.datum,o):o}return o}const l=r?r[a.field]:void 0;if(l==null)return o;if(a.scale===null)return l;const u=e[co(n,a.field)]||e[n];return u?u.encode(l,o):o}const Uf={size:5};function dn(e,t,n={}){const{handles:r=!0,handleSize:o,handleColor:s}=t||{},i=it(e),a=r!==!1&&r!=="hit",l=r!==!1;return{visible:a,grabbable:l,size:o??Uf.size,fill:a?s||n.fill||i.handle||i.accent:l?"transparent":s||n.fill||i.handle||i.accent,stroke:a?n.stroke||i.handleStroke:"none",strokeWidth:a?1.25:0}}function Xt(e){const t=e||{};return{xKey:t.x&&t.x.field||"x",yKey:t.y&&t.y.field||"y"}}function xr(e,t,{orientation:n,extent:r="value",single:o="value"}={}){if(n==="horizontal")return"x";if(n==="vertical")return"y";const s=e||{},i=d=>d==="x"?"y":"x",a=!!(s.x1||s.x2),l=!!(s.y1||s.y2);if(a!==l){const d=a?"x":"y";return r==="span"?i(d):d}if(t){const d=$p(t.x),f=$p(t.y);if(d&&!f)return"y";if(f&&!d)return"x"}const u=!!s.x,c=!!s.y;if(u!==c){const d=u?"x":"y";return o==="value"?d:i(d)}return"y"}const $p=e=>!!(e&&e.kind==="band"),Kf=e=>e==="x"?"horizontal":"vertical";function Nn(e,t,n,r,o,s){const i=e?e[t]:void 0,a=r??t;r==null&&n&&n[t]!==void 0&&ge(`implicitcol:${t}`,`a mark places rows on the "${t}" category axis but declares no "${t}" channel, so it is reading the column named "${t}" implicitly. Declare it — channels: { ${t}: { field: "${t}" } } — so the spec says which column the mark draws (and which one an edit would write).`);const l=n?n[a]:void 0;if(!i)return l;if(i.field===void 0)return typeof i.fn=="function"?Hl(i,t,n,o,s,l):i.datum!==void 0?i.datum:(i.value!==void 0&&ge(`catvalue:${t}`,`channel "${t}" is a CATEGORY axis on this mark, and { value: … } is a visual-space constant — there is no visual constant for "which band". Use { datum: … } to pin every row to one category, or { field: "…" } to read it from the data.`),l);const u=n?n[i.field]:void 0;return u??l}function Lt(e,t,n,r,o){if(r==null)return o;const s=t[n];if(s&&s.scale===null)return r;const i=e[n];return i?i.encode(r,o):o}function zr(e,t,n,r,o=0,s,i){if(!t||!t[n])return o;if(e[n])return se(e,t,n,r,o,s,i);const l=t[n];if(typeof l.fn=="function")return+Hl(l,n,r,s,i,o);if(l.field!=null){const u=r?r[l.field]:void 0;return u==null?o:+u}return l.value!==void 0?+l.value:o}function ss(e,t,n,r,o){if(!t||!t.symbol)return;const s=se(e,t,"symbol",n,void 0,r,o);return s==null||s===""?void 0:String(s)}function Bl(e,t,n,r,o={}){return{type:"text",x:t,y:n,text:e,fontSize:Math.max(1,r*2),textAnchor:"middle",dominantBaseline:"central",...o}}function yt(e,t,n,r={},o,s){const i={};for(const a of M0){const l=a in r?r[a]:_0[a],u=se(e,t,a,n,l,o,s);u!==void 0&&(i[a]=u)}return i}function Ms(e={}){return e.series&&e.series.field||e.fill&&e.fill.field||e.stroke&&e.stroke.field||null}function pt(e,t,n,r,o,s){const i=e[t];if(!i)return r;if(i.field!=null){const a=n[i.field];return a??r}return typeof i.fn=="function"?Hl(i,t,n,o,s,r):i.value!==void 0?i.value:(i.datum!==void 0&&ge(`rawdatum:${t}`,`channel "${t}" on a text mark has no scale — its value IS the output — so { datum: … } has nothing to go through. Use { value: … } for a constant.`),r)}function Yf(e={}){return e.order&&e.order.field||null}const p5=d0;function lt(e){return{id:e.id,edits:e.edits,table:e.table}}const A0={color:"there is no `color` channel — use `fill` (or `stroke` for a line).",data:"a mark never owns data. Put `data` on the Elicit spec; the engine hands the rows to every mark.",onChange:"put `onChange` on the Elicit spec, not on a mark.",domain:"a domain describes the DATA, so it lives on the spec's schema: schema: { field: { domain: [...] } }.",range:"a range belongs to the scale: channels.<name>.scale = { range: [...] }.",scale:"a scale is per channel: channels.<name>.scale, or spec.scales for the whole chart.",channel:"did you mean `channels`? (Axis/grid/legend marks take a singular `channel`; data marks take a `channels` map.)",edit:'attach an edit to a channel — y: { field: "…", edit: move() } — or pass several with `edits: [...]`.',r:"the radius channel is `size` (px), on every mark.",handleRadius:"a sub-element's radius is `handleSize`.",order:'order is a CHANNEL — it names the column to sort by: channels: { order: { field: "…" } }. The MODE (sort by the domain axis, or connect in array order) is the `connect` option: connect: "domain" | "sequence".',series:'series is a CHANNEL — it names a column, and `channels` is the only place a mark names one: channels: { series: { field: "…" } }.',z:'the grouping channel is `series`: channels: { series: { field: "…" } }.',constraints:"a constraint is a DATASET invariant — it gates every edit from every mark, whichever one declared it — so writing it inside a mark says something the engine does not mean. Put it on the Elicit spec: constraints: [...].",value:"a constant belongs on a channel: channels.<name> = { value: … } for visual space, { datum: … } for data space.",field:'a field belongs on a channel: channels.<name> = { field: "…" }.',...y5()};function y5(){const e={};for(const t of["x","y","x1","x2","y1","y2","lon","lat"])e[t]=`positional channels are not top-level shorthands (only style names like fill/stroke/size are). For a constant in the field's own units, write channels: { ${t}: { datum: … } } — it goes THROUGH the scale, so it lands where that value is. For a column, channels: { ${t}: { field: "…" } }. And for a plain reference line, a guide is the mark-free way to say it: guides.rule({ ${t}: … }).`;return e}function g5(e,t,n){if(!t||!ni())return;const r=e||"this mark";e&&!n&&ge(`noallow:${e}`,`${r}() calls normalizeMarkOptions without an \`allow\` list, which turns off its unknown-option diagnostics. Declare the mark's own option vocabulary — see the "Adding a new mark" contract in CLAUDE.md.`);const o=n?new Set([...p5,...E0,...n]):null;for(const s of Object.keys(t)){const i=A0[s];if(i){if(o&&o.has(s))continue;ge(`opt:${r}:${s}`,`${r}({ ${s}: … }): ${i}`);continue}!o||o.has(s)||ge(`opt:${r}:${s}`,`${r}({ ${s}: … }) is not an option this mark reads, so it is ignored. Mark options are: ${[...o].sort().join(", ")}.`)}}function at(e={},{except:t=[],mark:n,allow:r}={}){g5(n,e,r);const{channels:o={},...s}=e,i={...o};for(const a of E0)s[a]===void 0||t.includes(a)||(i[a]===void 0&&(i[a]=typeof s[a]=="function"?{fn:s[a]}:{value:s[a]}),delete s[a]);return{...s,channels:i}}const m5=["stroke","strokeWidth","fill","fontSize"],b5=p0;function Es(e,t,n){if(!t||!ni())return;const r=new Set([...b5,...n]);for(const o of Object.keys(t)){if(r.has(o))continue;const s=A0[o];if(s){ge(`opt:${e}:${o}`,`${e}({ ${o}: … }): ${s}`);continue}ge(`opt:${e}:${o}`,`${e}({ ${o}: … }) is not an option this chart element reads, so it is ignored. ${e} options are: ${[...r].sort().join(", ")}.`)}}function Di(e,t){return[e&&e.edit,e&&e.edits].flat(1/0).filter(r=>r&&typeof r.apply=="function").map(r=>r.channels?r:{...r,channels:[t]})}const ju=16,Ai=.4,T0=8,w5=30,x5=.25,v5=25e4,Et=["top","right","bottom","left"];function _p(e,t,n){let r=t[0],o=1/0;for(const s of t){const i=tn[s],a=Math.hypot(e.cx+i.x*e.hw-n.x,e.cy+i.y*e.hh-n.y);a<o&&(o=a,r=s)}return r}function k5(e,t,n,r,o){const s=e||Et,i=t||Et,a=(c,d)=>{if(d.includes(c))return c;const f=Et.indexOf(c),p=h=>{const y=Math.abs(Et.indexOf(h)-f);return Math.min(y,4-y)};return d.slice().sort((h,y)=>p(h)-p(y))[0]};if(n||r){const c=n||a(r,s);return{out:c,in:r||a(c,i),nest:o}}const l=Et.filter(c=>s.includes(c)&&i.includes(c));if(l.length){const c=l[o%l.length];return{out:c,in:c,nest:Math.floor(o/l.length)}}const u=s[0];return{out:u,in:a(u,i),nest:o}}const tn={top:{x:0,y:-1},right:{x:1,y:0},bottom:{x:0,y:1},left:{x:-1,y:0}},S5={top:"bottom",bottom:"top",left:"right",right:"left"};function $5(e,t,n){return Math.max(t,Math.min(n,e))}function O0(e){const t=[];for(const n of e){const r=t[t.length-1];r&&Math.abs(r[0]-n[0])<.01&&Math.abs(r[1]-n[1])<.01||t.push(n)}for(let n=t.length-2;n>=1;n--){const r=t[n-1],o=t[n],s=t[n+1],i=(o[0]-r[0])*(s[1]-r[1])-(o[1]-r[1])*(s[0]-r[0]),a=(o[0]-r[0])*(s[0]-o[0])+(o[1]-r[1])*(s[1]-o[1]);Math.abs(i)<.01&&a>0&&t.splice(n,1)}return t}function Ko(e,t,n,r,o=Ai){const s=tn[t],i=s.x?e.hh:e.hw,a=$5(r,-o,o),l=a*i*2;return{side:t,offset:a,x:e.cx+s.x*(e.hw+n)+-s.y*l,y:e.cy+s.y*(e.hh+n)+s.x*l}}function Mp(e,t,n,r=0){const o=t.x-e.cx,s=t.y-e.cy,i=e.hw||1e-6,a=e.hh||1e-6;let l,u;if(Math.abs(o)*a>=Math.abs(s)*i){l=o>=0?"right":"left";const f=o===0?0:s*(i/Math.abs(o));u=l==="right"?f:-f}else{l=s>=0?"bottom":"top";const f=s===0?0:o*(a/Math.abs(s));u=l==="top"?f:-f}const d=(tn[l].x?a:i)*2;return Ko(e,l,n,u/d+r,.5)}function _5(e,t,n,r,o,s){const i=tn[e.side],a=tn[t.side];if(i.x!==-a.x||i.y!==-a.y)return{a:e,b:t};if(!ba(e,t,i))return{a:e,b:t};const l=!!i.x,u=l?t.y-e.y:t.x-e.x;if(Math.abs(u)<.01)return{a:e,b:t};const c=Math.sign(u),d=(m,b,w)=>{const x=l?b.hh:b.hw,S=l?m.y-b.cy:m.x-b.cx;return Math.max(0,x-w*S)},f=o?Math.min(ju,d(e,n,c)):0,p=s?Math.min(ju,d(t,r,-c)):0,h=Math.min(Math.abs(u),f+p);if(!h)return{a:e,b:t};const y=h*f/(f+p)*c,g=h*c-y;return{a:l?{...e,y:e.y+y}:{...e,x:e.x+y},b:l?{...t,y:t.y-g}:{...t,x:t.x-g}}}function M5(e,t,n,r){const o=n.cx-n.hw-r,s=n.cx+n.hw+r,i=n.cy-n.hh-r,a=n.cy+n.hh+r,l=Math.min(e[0],t[0]),u=Math.max(e[0],t[0]),c=Math.min(e[1],t[1]),d=Math.max(e[1],t[1]);return l<s&&u>o&&c<a&&d>i}function Wu(e,t){return e===t||e.cx===t.cx&&e.cy===t.cy&&e.hw===t.hw&&e.hh===t.hh}function E5(e,t,n,r){let o=0;const s=e.length-2;for(let i=0;i<=s;i++)for(const a of r)i===0&&Wu(a,t)||i===s&&Wu(a,n)||M5(e[i],e[i+1],a,T0)&&o++;return o}function ba(e,t,n){return(t.x-e.x)*n.x+(t.y-e.y)*n.y>=0}function A5(e,t,n,r,o,s,i,a,l){const u=[e.x,e.y],c=[t.x,t.y],d=[n.x,n.y],f=[r.x,r.y];if(o.x===-s.x&&o.y===-s.y){if(ba(e,r,o)){if(o.x){const S=(e.x+r.x)/2;return[u,[S,e.y],[S,r.y],f]}const x=(e.y+r.y)/2;return[u,[e.x,x],[r.x,x],f]}if(o.x){const x=Math.min(i.cy-i.hh,a.cy-a.hh)-l,S=Math.max(i.cy+i.hh,a.cy+a.hh)+l,v=_=>Math.abs(_-t.y)+Math.abs(_-n.y),k=v(x)<=v(S)?x:S;return[u,c,[t.x,k],[n.x,k],d,f]}const g=Math.min(i.cx-i.hw,a.cx-a.hw)-l,m=Math.max(i.cx+i.hw,a.cx+a.hw)+l,b=x=>Math.abs(x-t.x)+Math.abs(x-n.x),w=b(g)<=b(m)?g:m;return[u,c,[w,t.y],[w,n.y],d,f]}if(o.x===s.x&&o.y===s.y){if(o.x){const m=o.x>0?Math.max(t.x,n.x):Math.min(t.x,n.x);return[u,c,[m,t.y],[m,n.y],d,f]}const g=o.y>0?Math.max(t.y,n.y):Math.min(t.y,n.y);return[u,c,[t.x,g],[n.x,g],d,f]}const p=o.x?{x:n.x,y:t.y}:{x:t.x,y:n.y},h={x:-s.x,y:-s.y};if(ba(t,p,o)&&ba(p,n,h))return[u,c,[p.x,p.y],d,f];const y=o.x?{x:t.x,y:n.y}:{x:n.x,y:t.y};return[u,c,[y.x,y.y],d,f]}function C0(e,t,n,r,o,s){const i=+t.offset||0,a=+o.offset||0,l=t.side?Ko(e,t.side,n,i):null,u=o.side?Ko(r,o.side,s,a):null,c=l||Mp(e,u||{x:r.cx,y:r.cy},n,i),d=u||Mp(r,l||{x:e.cx,y:e.cy},s,a);return{a:c,b:d}}function T5(e){const t=e.source.box,n=e.target.box;if(t.cx===n.cx&&t.cy===n.cy)return null;const r=e.sourceGap||0,o=e.targetGap||0,s=Math.max(ju,r,o),i=e.obstacles||[],a=C0(t,e.source.port,r,n,e.target.port,o),{a:l,b:u}=_5(a.a,a.b,t,n,!e.source.port.side,!e.target.port.side),c=tn[l.side],d=tn[u.side],f={x:l.x+c.x*s,y:l.y+c.y*s},p={x:u.x+d.x*s,y:u.y+d.y*s},h=O0(A5(l,f,p,u,c,d,t,n,s)),y=E5(h,t,n,i),g={points:h,sourceSide:l.side,targetSide:u.side,crossings:y};if(y&&e.grid){const m=N5(e.grid,t,n,l,u,s);if(m)return m}return g}function Ep(e){const t=[...e].sort((o,s)=>o-s),n=[];for(const o of t)(!n.length||o-n[n.length-1]>.5)&&n.push(o);const r=[];for(let o=0;o<n.length;o++)o&&r.push((n[o-1]+n[o])/2),r.push(n[o]);return r}function O5(e,t=T0){const n=[],r=[];for(const o of e)n.push(o.cx-o.hw-t,o.cx+o.hw+t),r.push(o.cy-o.hh-t,o.cy+o.hh+t);return{xs:Ep(n),ys:Ep(r),boxes:e,margin:t}}function Ap(e,t){const n=[...e];for(const r of t){let o=0,s=n.length;for(;o<s;){const i=o+s>>1;n[i]<r?o=i+1:s=i}Math.abs((n[o]??1/0)-r)<.01||o>0&&Math.abs(n[o-1]-r)<.01||n.splice(o,0,r)}return n}function Qs(e,t){let n=0,r=e.length-1;for(;n<=r;){const o=n+r>>1,s=e[o]-t;if(Math.abs(s)<.01)return o;s<0?n=o+1:r=o-1}return-1}class C5{constructor(){this.a=[]}get size(){return this.a.length}push(t,n){const r=this.a;r.push([t,n]);let o=r.length-1;for(;o>0;){const s=o-1>>1;if(r[s][0]<=r[o][0])break;[r[o],r[s]]=[r[s],r[o]],o=s}}pop(){const t=this.a,n=t[0],r=t.pop();if(t.length){t[0]=r;let o=0;for(;;){const s=2*o+1,i=s+1;let a=o;if(s<t.length&&t[s][0]<t[a][0]&&(a=s),i<t.length&&t[i][0]<t[a][0]&&(a=i),a===o)break;[t[o],t[a]]=[t[a],t[o]],o=a}}return n}}const Tp=[[0,-1],[1,0],[0,1],[-1,0]];function N5(e,t,n,r,o,s){const i=tn[r.side],a=tn[o.side],l={x:r.x,y:r.y},u={x:o.x,y:o.y},c=Ap(e.xs,[l.x,u.x,r.x+i.x*s,o.x+a.x*s]),d=Ap(e.ys,[l.y,u.y,r.y+i.y*s,o.y+a.y*s]),f=c.length,p=d.length;if(f*p>v5)return null;const h=e.margin-.5,y=e.boxes,g=new Int8Array(f*p).fill(-1),m=(P,j)=>{const G=j*f+P;if(g[G]>=0)return g[G];const J=c[P],re=d[j];let Q=0;for(const ve of y){const Ce=Math.abs(J-ve.cx)-ve.hw,le=Math.abs(re-ve.cy)-ve.hh;if(Ce<h&&le<h){Q=1;break}Ce<=e.margin+.5&&le<=e.margin+.5&&(Q=2)}return g[G]=Q,Q},b=Qs(c,l.x),w=Qs(d,l.y),x=Qs(c,u.x),S=Qs(d,u.y);if(b<0||w<0||x<0||S<0)return null;const v=(P,j)=>y.some(G=>!Wu(G,j)&&Math.abs(P.x-G.cx)-G.hw<h&&Math.abs(P.y-G.cy)-G.hh<h);if(v(l,t)||v(u,n))return null;const k=Et.indexOf(S5[o.side]),_=f*p*4,A=new Float64Array(_).fill(1/0),L=new Int32Array(_).fill(-1),N=new C5,I=(P,j)=>Math.abs(c[P]-c[x])+Math.abs(d[j]-d[S]),T=(w*f+b)*4+Et.indexOf(r.side);A[T]=0,N.push(I(b,w),T);let M=1/0,$=-1;for(;N.size;){const[P,j]=N.pop();if(P>=M)break;const G=j&3,J=j>>2,re=J%f,Q=(J-re)/f,ve=A[j];if(!(P>ve+I(re,Q)+1e-9)){re===x&&Q===S&&G===k&&ve<M&&(M=ve,$=j);for(let Ce=0;Ce<4;Ce++){if(j===T&&Ce!==G)continue;const le=re+Tp[Ce][0],be=Q+Tp[Ce][1];if(le<0||be<0||le>=f||be>=p)continue;const ce=le===x&&be===S?0:m(le,be);if(ce===1)continue;const Y=Math.abs(c[le]-c[re])+Math.abs(d[be]-d[Q]),ue=ve+Y*(ce===2?1+x5:1)+(Ce===G?0:w5),ie=(be*f+le)*4+Ce;ue<A[ie]&&(A[ie]=ue,L[ie]=j,N.push(ue+I(le,be),ie))}}}if($<0)return null;const F=[];for(let P=$;P>=0;P=L[P]){const j=P>>2,G=j%f;F.push([c[G],d[(j-G)/f]])}return F.reverse(),{points:O0(F),sourceSide:r.side,targetSide:o.side,crossings:0}}function N0(e,t){if(e==null||e===!1)return null;const n={},r=(o,s)=>(o===!0?Et:Array.isArray(o)?o:o==null?[]:[o]).filter(a=>Et.includes(a)?!0:(ge(`ports:side:${a}`,`ports got ${JSON.stringify(a)}${s}, which is not an edge. Use any of ${Et.map(l=>`"${l}"`).join(", ")}. Skipping it.`),!1));if(e===!0||typeof e=="string"||Array.isArray(e))for(const o of r(e,""))n[o]="both";else if(typeof e=="object"){const o=r(e.out," in `out`"),s=r(e.in," in `in`");if(t===!1&&(e.out||e.in)){ge("ports:undirected","ports splits its sides into `out` and `in`, but the links table is declared directed: false, so a link has no direction to leave or enter by. Using every side listed, both ways. List them as one array instead.");for(const i of[...o,...s])n[i]="both"}else{for(const i of o)n[i]="out";for(const i of s)n[i]=n[i]==="out"?"both":"in"}}else return ge("ports:value",`ports got ${JSON.stringify(e)}. Use true, a side, a list of sides, or { out: [...], in: [...] }.`),null;return Object.keys(n).length?n:null}function Gf(e,t,n){return`${e}\0${t}\0${n}`}function I0(e,t){return e?e==="both"||e===(t==="source"?"out":"in"):!1}function I5(e,t){const{edit:n,...r}=t||{},o={ports:r};return{id:`${e.id}/ports`,type:"port",table:e.table,...e.glyph?{glyph:e.glyph}:{},channels:o,edits:n?[n]:[],rawChannels:["ports"],discreteScale:"point",portHost:e,build:(s,i,a,l,u)=>{if(typeof e.nodeBox!="function")return[];const c=dn(i,{}),d=u&&u.schema?ks(u.schema):void 0,f=[];return s.forEach((p,h)=>{if(!p)return;const y=N0(pt(o,"ports",p,!1,h,s),d);if(!y)return;const g=e.nodeBox(p,h,s,i,a,l);if(g)for(const m of Et){const b=y[m];if(!b)continue;const w=Ko(g,m,0,0);f.push({type:"circle",cx:w.x,cy:w.y,r:c.size,fill:c.fill,stroke:c.stroke,strokeWidth:c.strokeWidth,channel:"port",side:m,portRole:b,onHover:!0,data:p,index:h})}}),f}}}const L5={name:"plane",sessionKeys:[],onEvent({event:e,edits:t,runEdit:n}){let r=!1;return t.filter(o=>o.gesture===e.type).forEach(o=>{n(o,null)&&(r=!0)}),r}};function as(e,t,n){const r=qu(e,t,n);if(e.type==="circle"||e.type==="ellipse")return Math.hypot(r.x-e.cx,r.y-e.cy);if(e.type==="rect"){if(e.bandAxis==="y"){const i=e.y,a=e.y+e.height;return r.y<i?i-r.y:r.y>a?r.y-a:0}const o=e.x,s=e.x+e.width;return r.x<o?o-r.x:r.x>s?r.x-s:0}if(e.type==="line")return Op(r.x,r.y,e.x1,e.y1,e.x2,e.y2);if(e.type==="path"){const o=e.points||[];let s=1/0;for(let i=1;i<o.length;i++){const a=Op(r.x,r.y,o[i-1][0],o[i-1][1],o[i][0],o[i][1]);a<s&&(s=a)}return s}return 1/0}function qu(e,t,n){if(!e.angle)return{x:t,y:n};const r=Rn(e);if(!r)return{x:t,y:n};const o=-e.angle*Math.PI/180,s=t-r.cx,i=n-r.cy,a=Math.cos(o),l=Math.sin(o);return{x:r.cx+s*a+i*l,y:r.cy-s*l+i*a}}function Op(e,t,n,r,o,s){const i=o-n,a=s-r,l=i*i+a*a,u=l?Math.max(0,Math.min(1,((e-n)*i+(t-r)*a)/l)):0;return Math.hypot(e-(n+u*i),t-(r+u*a))}function In(e,t,n,r,o){let s=null,i=1/0;return(e||[]).forEach(a=>{if(a.index==null||a.locked||o!==void 0&&a.series!==o)return;const l=as(a,t,n);l<i&&(i=l,s=a.index)}),s!=null&&i<=r?s:null}function Mr(e,t,n,r){let o=null,s=1/0;return(e||[]).forEach(i=>{if(i.series===void 0||i.locked)return;let a;if(i.type==="path")a=as(i,t,n);else if(i.cx!=null)a=Math.hypot(t-i.cx,n-i.cy);else return;a<s&&(s=a,o=i.series)}),o!=null&&s<=r?o:null}function Vf(e,t,n,r,o,s){let i=null,a=1/0;return(e||[]).forEach((l,u)=>{if(l.locked||s!==void 0&&l.series!==s)return;const c=o==="x"?l.cx:l.cy;if(c==null)return;const d=Math.abs((o==="x"?t:n)-c);d<a&&(a=d,i=l.index!=null?l.index:u)}),i!=null&&a<=r?i:null}const wn=4,al=12;function Ti(e){const t=e.width||0,n=e.height||0,r=Math.max(t,al),o=Math.max(n,al);return{x:e.x-(r-t)/2,y:e.y-(o-n)/2,w:r,h:o}}function wa(e,t,n){const r=e||[];for(let o=r.length-1;o>=0;o--){const s=r[o];if(!(!s||!s.editable)&&!(s.locked||s.guide||s.background)&&s.pointerEvents!=="none"&&F5(s,t,n))return s}return null}function F5(e,t,n){if(e.type==="circle"){const r=e.r!=null?e.r:5;return as(e,t,n)<=r+wn}if(e.type==="ellipse"){const r=qu(e,t,n),o=Math.max(1e-6,(e.rx!=null?e.rx:5)+wn),s=Math.max(1e-6,(e.ry!=null?e.ry:5)+wn);return Math.hypot((r.x-e.cx)/o,(r.y-e.cy)/s)<=1}if(e.type==="rect"){const r=Ti(e),o=qu(e,t,n);return o.x>=r.x-wn&&o.x<=r.x+r.w+wn&&o.y>=r.y-wn&&o.y<=r.y+r.h+wn}if(e.sector){const{cx:r,cy:o,r0:s,r1:i,a0:a,a1:l}=e.sector,u=Math.hypot(t-r,n-o);if(u<Math.max(0,s)-wn||u>i+wn)return!1;const c=l-a,d=Math.sign(c)||1;return((Math.atan2(-(n-o),t-r)*180/Math.PI-a)*d%360+360)%360<=Math.abs(c)}if(e.type==="line"||e.type==="path"){const r=(e.strokeWidth||1)/2;return as(e,t,n)<=r+wn}return e.type==="text"?Math.hypot(t-e.x,n-e.y)<=(e.fontSize||10)+wn:!1}const Ul=40;function L0(e,t=Ul){return e&&e>0?e:t}function Jn(e,t=Ul){return L0(e?e.threshold:void 0,t)}const R5=8;function Kl(e){const t=e.edgeInset;return t&&t>0?t:R5}const z5={name:"nearest",sessionKeys:["px","py","threshold","hoverIndex","activeIndex"],selects:!0,onEvent({event:e,edits:t,marks:n,session:r,runEdit:o}){const s=Jn(t[0]);let i=!1;if(e.type==="hover"){const a=In(n,e.x,e.y,s);r.set({px:e.x,py:e.y,threshold:s,hoverIndex:a}),i=!0}else if(e.type==="hoverout")r.clear(),i=!0;else if(e.type==="dragstart"){const a=In(n,e.x,e.y,s);r.set({px:e.x,py:e.y,threshold:s,hoverIndex:a,activeIndex:a}),i=!0}else if(e.type==="dragend"){const a=r.get();a&&(a.activeIndex=null),i=!0}else{const a=r.get();a&&(a.px=e.x,a.py=e.y);const l=t.filter(u=>u.gesture===e.type);if(l.length>0){let u=a?a.activeIndex:null;u==null&&(u=In(n,e.x,e.y,s)),u!=null&&l.forEach(c=>{o(c,u)&&(i=!0)})}else a&&(i=!0)}return i}},P5={name:"sweep",sessionKeys:["px","py","threshold","hoverIndex","activeIndex","series"],selects:!0,onEvent({event:e,edits:t,marks:n,session:r,runEdit:o}){const s=Jn(t[0]),i=t[0].channels||["y"],a=i.includes("x")&&i.includes("y"),u=(i[0]||"y")==="x"?"y":"x",c=f=>a?In(n,e.x,e.y,s,f):Vf(n,e.x,e.y,s,u,f);let d=!1;if(e.type==="hover"){const f=Mr(n,e.x,e.y,s),p=c(f??void 0);r.set({px:e.x,py:e.y,threshold:s,hoverIndex:p,series:f}),d=!0}else if(e.type==="hoverout")r.clear(),d=!0;else if(e.type==="dragstart"){const f=Mr(n,e.x,e.y,s),p=c(f??void 0);r.set({px:e.x,py:e.y,threshold:s,hoverIndex:p,activeIndex:p,series:f}),p!=null&&t.forEach(h=>{o(h,p)&&(d=!0)}),d=!0}else if(e.type==="dragend"){const f=r.get();f&&(f.activeIndex=null,f.series=null),d=!0}else if(e.type==="drag"){const f=r.get(),p=f&&f.series!=null?f.series:void 0,h=c(p);r.set({px:e.x,py:e.y,threshold:s,hoverIndex:h,activeIndex:h}),h!=null&&t.forEach(y=>{o(y,h)&&(d=!0)}),d=!0}return d}},D5={name:"draw",sessionKeys:["mode","drawSeries","lastDomain","lastX","lastY","px","py"],onEvent({feature:e,event:t,edits:n,marks:r,data:o,session:s,runEdit:i}){const a=Jn(n[0]);let l=!1;if(t.type==="dragstart"){const u=n[0].into==="new"?null:Mr(r,t.x,t.y,a);if(u!=null)s.set({mode:"edit",drawSeries:u,px:t.x,py:t.y});else{const c=e.seriesKey||null,f=e.connect==="sequence"&&o.length>0&&n[0].into!=="new"?c?o[o.length-1][c]:0:Wl(o,c);s.set({mode:"draw",drawSeries:f,lastDomain:null,lastX:null,lastY:null,px:t.x,py:t.y})}n.forEach(c=>{i(c,null)&&(l=!0)}),l=!0}else if(t.type==="drag"){const u=s.get();u&&(u.px=t.x,u.py=t.y),n.forEach(c=>{i(c,null)&&(l=!0)}),l=!0}else t.type==="dragend"&&(s.clear(),l=!0);return l}};function j5(e,t,n,r,o,s,i){const a=e.channels||{},[l,u]=r,c=a[l],d=a[u];if(!c||!d||!n)return null;const f=$t(l);if(!f)return null;const p=se(t,a,l,n),h=se(t,a,u,n);if(p==null||h==null)return null;const y=Math.min(p,h),g=Math.max(p,h),m=p<=h?c.field:d.field,b=p<=h?d.field:c.field,w=f==="x"?o:s,x=Math.abs(w-y),S=Math.abs(w-g);return Math.min(x,S)<=i?x<=S?{zone:"edgeA",field:m}:{zone:"edgeB",field:b}:{zone:"body"}}const W5={name:"brush",options:["edgeInset"],sessionKeys:["px","py","threshold","hoverIndex","activeIndex","zone","field"],selects:!0,onEvent({feature:e,event:t,edits:n,marks:r,data:o,scales:s,session:i,runEdit:a}){const l=n[0],u=Jn(l),c=Kl(l),d=l.channels||[];let f=!1;if(t.type==="hover"){const p=In(r,t.x,t.y,u);i.set({px:t.x,py:t.y,threshold:u,hoverIndex:p}),f=!0}else if(t.type==="hoverout")i.clear(),f=!0;else if(t.type==="dragstart"){const p=In(r,t.x,t.y,u),h=p!=null?j5(e,s,o[p],d,t.x,t.y,c):null;i.set({px:t.x,py:t.y,threshold:u,hoverIndex:p,activeIndex:p,zone:h?h.zone:null,field:h?h.field:null}),f=!0}else if(t.type==="drag"){const p=i.get();p&&(p.px=t.x,p.py=t.y);const h=p?p.activeIndex:null;h!=null&&p&&p.zone&&a(l,h)&&(f=!0),f=!0}else if(t.type==="dragend"){const p=i.get(),h=p?p.activeIndex:null;h!=null&&p&&p.zone&&(p.zone="canonicalize",a(l,h)),p&&(p.activeIndex=null),f=!0}return f}};function Cp(e,t,n,r){const o=e.channels||{},s=o[r+"1"],i=o[r+"2"];if(!s||!i||!s.field||!i.field||!n)return null;const a=se(t,o,r+"1",n),l=se(t,o,r+"2",n);if(a==null||l==null)return null;const u=a<=l?s.field:i.field,c=a<=l?i.field:s.field;return{loField:u,hiField:c}}function Np(e,t,n,r,o,s,i,a,l){const u=r.x,c=r.x+r.width,d=r.y,f=r.y+r.height,p=a==="both"||a==="x",h=a==="both"||a==="y",y=p?Cp(e,t,n,"x"):null,g=h?Cp(e,t,n,"y"):null;let m=null;if(y){const w=Math.abs(o-u),x=Math.abs(o-c);Math.min(w,x)<=i&&(m=w<=x?y.loField:y.hiField)}let b=null;if(g){const w=Math.abs(s-d),x=Math.abs(s-f);Math.min(w,x)<=i&&(b=w<=x?g.loField:g.hiField)}return m&&b?{zone:"corner",fields:[m,b]}:m?{zone:"edgeX",fields:[m]}:b?{zone:"edgeY",fields:[b]}:l?{zone:"body",fields:[]}:null}function Ip(e,t,n,r){let o=null;return(e||[]).forEach(s=>{s.type!=="rect"||s.index==null||s.width==null||t>=s.x-r&&t<=s.x+s.width+r&&n>=s.y-r&&n<=s.y+s.height+r&&(o=s.index)}),o}function Lp(e){return e==="corner"?"nwse-resize":e==="edgeX"?"ew-resize":e==="edgeY"?"ns-resize":e==="body"?"move":"default"}const q5={name:"brushRect",options:["edgeInset","resize","move"],sessionKeys:["px","py","hoverIndex","activeIndex","zone","fields","cursor"],selects:!0,onEvent({feature:e,event:t,edits:n,marks:r,data:o,scales:s,session:i,runEdit:a}){const l=n[0],u=Kl(l),c=l.resize||"both",d=l.move!==!1;let f=!1;if(t.type==="hover"){const p=Ip(r,t.x,t.y,u),h=p!=null?r.find(g=>g.index===p):null,y=p!=null&&h?Np(e,s,o[p],h,t.x,t.y,u,c,d):null;i.set({px:t.x,py:t.y,hoverIndex:p,cursor:Lp(y?y.zone:null)}),f=!0}else if(t.type==="hoverout")i.clear(),f=!0;else if(t.type==="dragstart"){const p=Ip(r,t.x,t.y,u),h=p!=null?r.find(g=>g.index===p):null,y=p!=null&&h?Np(e,s,o[p],h,t.x,t.y,u,c,d):null;i.set({px:t.x,py:t.y,hoverIndex:p,activeIndex:p,zone:y?y.zone:null,fields:y?y.fields:null,cursor:Lp(y?y.zone:null)}),f=!0}else if(t.type==="drag"){const p=i.get();p&&(p.px=t.x,p.py=t.y);const h=p?p.activeIndex:null;h!=null&&p&&p.zone&&a(l,h)&&(f=!0),f=!0}else if(t.type==="dragend"){const p=i.get(),h=p?p.activeIndex:null;h!=null&&p&&p.zone&&(p.zone="canonicalize",a(l,h)),p&&(p.activeIndex=null,p.cursor="default"),f=!0}return f}};function H5(e,t,n,r){let o=null;return(e||[]).forEach(s=>{s.type!=="rect"||s.index==null||s.width==null||t>=s.x-r&&t<=s.x+s.width+r&&n>=s.y-r&&n<=s.y+s.height+r&&(o=s.index)}),o}function B5(e,t,n,r,o){const s=e.x,i=e.x+e.width,a=e.y,l=e.y+e.height,u=[],c=Math.abs(t-s),d=Math.abs(t-i);Math.min(c,d)<=r&&u.push(c<=d?"west":"east");const f=Math.abs(n-a),p=Math.abs(n-l);return Math.min(f,p)<=r&&u.push(f<=p?"north":"south"),u.length===2?{zone:"corner",edges:u}:u.length===1?{zone:"edge",edges:u}:o?{zone:"body",edges:[]}:null}function Fp(e,t){return e==="corner"?t.includes("west")&&t.includes("north")||t.includes("east")&&t.includes("south")?"nwse-resize":"nesw-resize":e==="edge"?t[0]==="west"||t[0]==="east"?"ew-resize":"ns-resize":e==="body"?"move":"default"}function U5(e){const t=e&&e.channels||{};return{west:t.west&&t.west.field||"west",south:t.south&&t.south.field||"south",east:t.east&&t.east.field||"east",north:t.north&&t.north.field||"north"}}const K5={name:"geoBrush",options:["edgeInset","move"],sessionKeys:["px","py","hoverIndex","activeIndex","zone","edges","grab","box0","cursor"],selects:!0,onEvent({feature:e,event:t,edits:n,marks:r,data:o,scales:s,session:i,runEdit:a}){const l=n[0],u=Kl(l),c=l.move!==!1,d=s.projection||null;let f=!1;const p=(h,y)=>{const g=H5(r,h,y,u);if(g==null)return{hit:null,zone:null};const m=r.find(b=>b.index===g&&b.type==="rect");return m?{hit:g,zone:B5(m,h,y,u,c)}:{hit:null,zone:null}};if(t.type==="hover"){const{hit:h,zone:y}=p(t.x,t.y);i.set({px:t.x,py:t.y,hoverIndex:h,cursor:Fp(y?y.zone:null,y?y.edges:[])}),f=!0}else if(t.type==="hoverout")i.clear(),f=!0;else if(t.type==="dragstart"){const{hit:h,zone:y}=p(t.x,t.y),g=h!=null?o[h]:null,m=Lr(d,{x:t.x,y:t.y}),b=U5(e);i.set({px:t.x,py:t.y,hoverIndex:h,activeIndex:y?h:null,zone:y?y.zone:null,edges:y?y.edges:null,grab:m,box0:g?{west:g[b.west],south:g[b.south],east:g[b.east],north:g[b.north]}:null,cursor:Fp(y?y.zone:null,y?y.edges:[])}),f=!0}else if(t.type==="drag"){const h=i.get();h&&(h.px=t.x,h.py=t.y);const y=h?h.activeIndex:null;y!=null&&h&&h.zone&&a(l,y)&&(f=!0),f=!0}else if(t.type==="dragend"){const h=i.get(),y=h?h.activeIndex:null;y!=null&&h&&h.zone&&(h.zone="canonicalize",a(l,y)),h&&(h.activeIndex=null,h.zone=null,h.edges=null,h.grab=null,h.box0=null,h.cursor="default"),f=!0}return f}};function Rp(e,t){const{marks:n,data:r,event:o}=e;if(o.x!=null&&o.y!=null){const s=In(n,o.x,o.y,Jn(t));if(s!=null)return s}return r.length===1?0:null}const Y5={name:"probe",sessionKeys:[],onEvent:e=>{const{event:t,edits:n,preview:r,stage:o,runEdit:s,previewEdit:i}=e;if(!n.length)return!1;const a=t.type;if(a==="hover"||a==="dragstart"||a==="drag"){let l=!1;for(const u of n)i(u,Rp(e,u))&&(l=!0);return l||r.clear()}if(a==="hoverout")return r.clear();if(a==="click"||a==="dragend"){let l=!1,u=!1;for(const c of n)s(c,Rp(e,c))&&(l=!0,c.stage!=null&&c.advance!==!1&&(u=!0));return u&&o.next(),l}return!1}},G5=14;function zp(e,t,n,r){let o=null,s=r;for(const i of e||[]){if(!i||!i.axisHandle)continue;const a=i.cx!=null?i.cx:i.x,l=i.cy!=null?i.cy:i.y,u=Math.hypot(t-a,n-l);u<=s&&(s=u,o=i)}return o}function V5(e){return{axis:e.axis,grabEnd:e.handle,anchorPixel:e.anchorPixel,anchorValue:e.anchorValue,grabPixel:e.grabPixel,grabValue:e.grabValue,pxPerUnit:e.pxPerUnit,cursor:e.axis==="x"?"ew-resize":"ns-resize"}}const X5={name:"axisDrag",sessionKeys:["axis","grabEnd","anchorPixel","anchorValue","grabPixel","grabValue","pxPerUnit","cursor"],onEvent({event:e,edits:t,marks:n,session:r,runEdit:o}){const s=t[0],i=Jn(s,G5);let a=!1;if(e.type==="hover"){const l=zp(n,e.x,e.y,i),u=l?l.axis==="x"?"ew-resize":"ns-resize":null,c=r.get();(c&&c.cursor)!==u&&(r.set({cursor:u}),a=!0)}else if(e.type==="hoverout")r.clear(),a=!0;else if(e.type==="dragstart"){const l=zp(n,e.x,e.y,i);l&&(r.set(V5(l)),a=!0)}else if(e.type==="drag"){const l=r.get();l&&l.grabEnd&&o(s,null)&&(a=!0)}else e.type==="dragend"&&(r.clear(),a=!0);return a}};function Vn(e={}){const{mode:t="absolute",...n}=e,r=t==="relative";return r&&n.pick!=null&&n.pick!=="direct"&&ge("move:relative:pick",`move({ mode: "relative" }) is direct-pick: it measures from where you GRABBED the mark, so there has to be a mark under the press. { pick: "${n.pick}" } is ignored. Use the default mode: "absolute" with that pick.`),je({type:"move",inverts:!0,gesture:"drag",mode:t,...n,...r?{pick:"direct"}:{},apply:o=>{const s={...o.datum},i=Rn(Rr(o)),a=r?(o.session||{}).move:null,l=a&&a.anchors;for(const u of o.channels){if(r){const d=l&&l[u.field],f=$t(u.name);if(!d||!f||!u.scale||!u.scale.invertible)continue;const p=u.scale.encode(d.startValue);if(typeof p!="number"||Number.isNaN(p))continue;const h=(f==="x"?o.pointer.x:o.pointer.y)-d.startPx;s[u.field]=u.scale.invertValue(p+h);continue}const c=fo(u,o.pointer,i);c!==void 0&&(s[u.field]=c)}return s}})}function J5(e={}){return je({type:"moveSpan",inverts:!0,gesture:"drag",...e,apply:t=>{const[n,r]=t.channels,o=Rr(t),s=ql(o,n,r,t.pointer);if(s)return{...t.datum,[n.field]:s.a,[r.field]:s.b}}})}function Z5(e={}){const t=jl(e,"brushSpan","brush");return je({type:"brushSpan",inverts:!0,gesture:"drag",...t,pick:"brush",apply:n=>{const[r,o]=n.channels,s=n.datum;if(!r||!o||!s)return;const i=n.session&&n.session.zone;if(!i)return;if(i==="canonicalize"){const c=s[r.field],d=s[o.field];return c==null||d==null||c<=d?void 0:{...s,[r.field]:d,[o.field]:c}}if(i==="body"){const c=Rr(n),d=ql(c,r,o,n.pointer);return d?{...s,[r.field]:d.a,[o.field]:d.b}:void 0}const a=n.session&&n.session.field,l=a===r.field?r:a===o.field?o:null;if(!l)return;const u=fo(l,n.pointer);if(u!==void 0)return{...s,[l.field]:u}}})}function F0(e={}){const{resize:t="both",move:n=!0,...r}=jl(e,"brushRect","brushRect");return je({type:"brushRect",inverts:!0,gesture:"drag",channels:["x1","x2","y1","y2"],...r,resize:t,move:n,pick:"brushRect",apply:o=>{const s=o.session&&o.session.zone,i=o.datum;if(!s||!i)return;const a=o.channels.filter(p=>$t(p.name)==="x"),l=o.channels.filter(p=>$t(p.name)==="y"),u=Rr(o);if(s==="canonicalize"){const p={...i};let h=!1;for(const[y,g]of[a,l]){if(!y||!g)continue;const m=i[y.field],b=i[g.field];m==null||b==null||m<=b||(p[y.field]=b,p[g.field]=m,h=!0)}return h?p:void 0}if(s==="body"){const p={...i};let h=!1;for(const[y,g]of[a,l]){if(!y||!g)continue;const m=ql(u,y,g,o.pointer);m&&(p[y.field]=m.a,p[g.field]=m.b,h=!0)}return h?p:void 0}const c=o.session&&o.session.fields||[],d={...i};let f=!1;for(const p of o.channels){if(!p.field||!c.includes(p.field))continue;const h=fo(p,o.pointer);h!==void 0&&(d[p.field]=h,f=!0)}return f?d:void 0}})}function Q5(e,t){const n=t||(e==="x"?"left":"up");return{axis:e,towardSmaller:n==="left"||n==="up"}}function eE(e,t){if(typeof e=="number"&&e>0)return e;const n=t&&t.scale&&t.scale.frameExtent;return typeof n=="number"&&n>0?n:120}const R0=(e,t)=>`${e}:${t}`;function tE(e={}){const{axis:t="x",increase:n,extent:r,mode:o="relative",...s}=e,{towardSmaller:i}=Q5(t,n);return o==="relative"&&s.pick!=null&&s.pick!=="direct"&&s.pick!=="slide"&&(ge("slide:relative:pick",`slide({ mode: "relative" }) needs the slide driver's dragstart anchor, so it is served by that driver alone. { pick: "${s.pick}" } is ignored (direct pick); use mode: "absolute" with that pick, or pick: "slide" for the plane form.`),delete s.pick),je({type:"slide",inverts:!0,gesture:"drag",pick:"direct",axis:t,increase:n,extent:r,mode:o,...s,apply:a=>{const l=a.channels[0];if(!l||!l.field)return;const[u,c]=v0(l),d=t==="x"?a.pointer.x:a.pointer.y,f=eE(r,l);if(o==="relative"){const b=(a.session||{}).slide,w=b&&b[R0(t,l.field)];if(!w||typeof w.startValue!="number")return;const x=(d-w.startPx)*(i?-1:1),S=c-u,v=Math.min(u,c),k=Math.max(u,c),_=Math.max(v,Math.min(k,w.startValue+x/f*S));return{...a.datum,[l.field]:_}}const p=Rn(Rr(a));if(!p)return;const h=t==="x"?p.cx:p.cy,y=i?h+f:h-f,g=i?h-f:h+f,m=x0(d,y,g,u,c);if(m!==void 0)return{...a.datum,[l.field]:m}}})}function nE(e={}){return je({type:"resize",inverts:!0,gesture:"drag",...e,apply:t=>{const n=t.channels[0],r=Rn(Rr(t));if(!n||!n.scale||!n.scale.invertible||!r)return;const o=Math.hypot(t.pointer.x-r.cx,t.pointer.y-r.cy);return{...t.datum,[n.field]:n.scale.invertValue(o)}}})}function rE(e={}){const{relativeTo:t,pivot:n="plot",fold:r=!0,...o}=e,s=o.pick||"plane",i=a=>{let l=(a.width||0)/2,u=(a.height||0)/2;if(n==="mark"){const d=Rn(Rr(a));d&&(l=d.cx,u=d.cy)}let c=zf(a.pointer,{cx:l,cy:u});if(r)c>90?c-=180:c<=-90&&(c+=180);else{const d=a.channels[0]&&a.channels[0].scale,f=d&&typeof d.range=="function"?d.range():null;f&&f.length>=2&&typeof f[0]=="number"&&typeof f[f.length-1]=="number"&&(c=MM(c,f[0],f[f.length-1]))}return c};return je({type:"rotate",inverts:!0,gesture:"drag",pick:"plane",...o,apply:a=>{const l=a.channels[0],u=l&&l.scale;if(!u||!u.invertible)return;const c=i(a),d=f=>{if(!t)return{...f,[l.field]:u.invertValue(c)};const p=a.markChannels[t],h=p?p.field:null,y=a.scales[t],g=h!=null&&y?.encode?y.encode(f[h]):0,m=Math.abs(c-g);return{...f,[l.field]:u.invertValue(m)}};if(s==="direct")return a.datum?d(a.datum):void 0;if(a.data.length)return a.data.map(d)}})}function oE(e={}){return je({type:"cycle",gesture:"click",...e,apply:t=>{const n=t.channels[0];if(!n||!t.datum)return;const r=k0(n,t.schema);if(!r||!r.length)return;const o=r.indexOf(t.datum[n.field]);return{...t.datum,[n.field]:r[(o+1)%r.length]}}})}function Xf(e={}){const{defaults:t={},...n}=e;return je({type:"create",gesture:"click",channels:["x","y"],pick:"plane",cardinality:"append",defaults:t,...n,apply:r=>{const o=Fn(r,{defaults:t});return o?[...r.data,o]:void 0}})}function Jf(e={}){const{defaults:t={},...n}=e;return je({type:"toggle",gesture:"click",channels:["x"],pick:"plane",cardinality:"toggle",defaults:t,...n,apply:r=>{const o=Fn(r,{defaults:t});if(!o)return;const s=r.channels.map(a=>a.field),i=r.data.findIndex(a=>s.every(l=>a[l]===o[l]));return i>=0?r.data.filter((a,l)=>l!==i):[...r.data,o]}})}function z0(e={}){return je({type:"remove",gesture:"click",cardinality:"delete",...e,apply:t=>{if(t.index!=null)return t.data.filter((n,r)=>r!==t.index)}})}function P0(e){const t=e.channels[0];if(!(!t||!t.field||e.value===void 0||!e.datum))return{...e.datum,[t.field]:e.value}}function iE(e={}){return je({type:"set",gesture:"commit",pick:"direct",...e,apply:P0})}function D0(e={}){return je({type:"editText",gesture:"commit",pick:"direct",channels:["text"],inline:!0,...e,apply:P0})}function j0(e={}){return je({type:"rank",inverts:!0,gesture:"drag",...e,apply:t=>{const n=t.channels[0];if(!n||!t.datum||t.index==null)return;const r=n.field;if(!r)return;const o=fo(n,t.pointer);if(o===void 0)return;const s=t.datum[r];if(s!==o)return t.data.map((i,a)=>a===t.index?{...i,[r]:o}:i[r]===o?{...i,[r]:s}:i)}})}function sE(e={}){const{exclusive:t=!0,toggle:n=!0,multi:r=!1,...o}=e;return je({type:"select",gesture:"click",pick:"direct",target:"selection",...o,apply:s=>{if(s.index==null)return;const i=s.event||{},a=r&&!!(i.shiftKey||i.metaKey);return{index:s.index,exclusive:a?!1:t,toggle:n}}})}function W0(e,t={}){return je({type:"custom",gesture:"drag",...t,apply:e})}const aE=40,lE={name:"slide",sessionKeys:["index","slide"],wants:e=>e.type==="slide"&&e.mode==="relative",onEvent({feature:e,event:t,edits:n,marks:r,data:o,index:s,session:i,runEdit:a}){if(!n.length)return!1;let l=!1;if(t.type==="dragstart"){const u=s??In(r,t.x,t.y,Jn(n[0],aE));if(u==null)return!1;const c=o[u],d={};for(const f of n){const p=f.axis==="y"?"y":"x",h=f.channels&&f.channels[0]||null,y=h&&e.channels&&e.channels[h],g=y&&y.field;if(!g)continue;const m=c&&c[g];typeof m=="number"&&(d[R0(p,g)]={startPx:p==="x"?t.x:t.y,startValue:m})}if(!Object.keys(d).length)return!1;i.set({index:u,slide:d}),l=!0}else if(t.type==="drag"){const u=i.get();if(!u||u.index==null||!u.slide)return!1;for(const c of n)a(c,u.index)&&(l=!0)}else if(t.type==="dragend"||t.type==="hoverout"){if(!i.get())return!1;i.set({index:null,slide:null}),l=!0}return l}},cE=40,uE={name:"move",sessionKeys:["move"],wants:e=>e.type==="move"&&e.mode==="relative",onEvent({feature:e,event:t,edits:n,marks:r,data:o,index:s,session:i,runEdit:a}){if(!n.length)return!1;let l=!1;if(t.type==="dragstart"){const u=s??In(r,t.x,t.y,Jn(n[0],cE));if(u==null)return!1;const c=o[u],d={};for(const f of n)for(const p of f.channels||[]){const h=e.channels&&e.channels[p],y=h&&h.field;!y||!c||c[y]===void 0||(d[y]={startPx:$t(p)==="y"?t.y:t.x,startValue:c[y]})}if(!Object.keys(d).length)return!1;i.set({move:{index:u,anchors:d}}),l=!0}else if(t.type==="drag"){const u=(i.get()||{}).move;if(!u||u.index==null)return!1;for(const c of n)a(c,u.index)&&(l=!0)}else if(t.type==="dragend"||t.type==="hoverout"){if(!(i.get()||{}).move)return!1;i.set({move:null}),l=!0}return l}},fE={name:"connect",sessionKeys:["fromIndex","fromSide","fromPoint","targets"],wants:e=>e.type==="network.connect"||e.type==="network.rewire",onEvent({event:e,edits:t,index:n,session:r,runEdit:o,previewEdit:s,preview:i,reachable:a}){if(!t.length)return!1;let l=!1;if(e.type==="dragstart"){if(n==null)return!1;const c=e.node;r.set({fromIndex:n,fromSide:c&&c.side?c.side:null,fromPoint:{x:e.x,y:e.y}});let d=null;for(const p of t){const h=a?a(p,n):null;h&&(d=[...d||[],...h])}const f=t.some(p=>p.cardinality==="append");if(d&&!d.length&&f)return r.clear(),!0;d&&r.set({targets:d});for(const p of t)s(p,n)&&(l=!0);return!0}const u=r.get();if(!u||u.fromIndex==null)return!1;if(e.type==="drag"){let c=!1;for(const d of t)s(d,u.fromIndex)&&(c=!0);(!c&&i.clear()||c)&&(l=!0)}else if(e.type==="dragend"){for(const c of t)o(c,u.fromIndex)&&(l=!0);i.clear()&&(l=!0),r.clear(),l=!0}return l}},Ro=[L5,z5,P5,D5,W5,q5,K5,Y5,X5,lE,uE,fE];function dE(e){if(!e||!e.name||typeof e.onEvent!="function"||e.wants!=null&&typeof e.wants!="function")throw new Error("[elicit] registerDriver expects { name, onEvent(ctx), wants?(edit), sessionKeys? }");const t=Ro.findIndex(n=>n.name===e.name);t>=0?Ro[t]=e:Ro.push(e)}function gr(e){return Ro.find(t=>t.name===e.pick)||Ro.find(t=>t.wants?t.wants(e):!1)}function hE(e){return e.some(t=>t.pick==="direct"||t.pick==="plane"?!1:!!gr(t))}const pE="#e4572e",yE={bounds:{dash:"4 4",width:1,opacity:.9,bandOpacity:.07,fontSize:10,labelOpacity:.95,tickLength:6,tickOpacity:.5},catchment:{dash:"2 4",width:1,opacity:.45},track:{dash:"3 3",width:2,opacity:.35}},gE=["bounds","catchment"];function q0(e,t){let n=e&&e.guide;if(n==null){const a=gr(e);n=a&&a.selects?{catchment:!0}:!1}if(n===!1)return{bounds:null,catchment:null,track:null};const r=t&&t.theme&&t.theme.guide,o=t&&t.theme&&t.theme.constraint&&t.theme.constraint.color,s=n&&typeof n=="object"&&n.color||o||pE,i=a=>{const l=n===!0?gE.includes(a):n&&typeof n=="object"?n[a]:!1;if(!l)return null;const u=r&&r[a];return{color:s,...yE[a],...u&&typeof u=="object"?u:{},...typeof l=="object"?l:{}}};return{bounds:i("bounds"),catchment:i("catchment"),track:i("track")}}function mE(e){const t=[],n=new Set;for(const r of e)ma(r).forEach((o,s)=>{if(o.guide===!1)return;if(!o.guide){const l=gr(o);if(!(l&&l.selects))return}const i=`${r.id}:edit-${o.type}-${s}`;if(n.has(i))return;n.add(i);const a={views:"state",build:(l,u,c,d,f)=>bE(r,o,f)};t.push(a)});return t}function bE(e,t,n){const{scales:r,width:o,height:s}=n,i=n.tableOf?n.tableOf(e):n.data,a=n.constraintsIn?n.constraintsIn(e.table):n.constraints,l=e.channels||{},u=Ei(t.channels,l,r,e),c=u[0],d=q0(t,n),f=[];if(d.bounds&&c&&c.scale){const h=d.bounds,y=[...a||[],...t.constrain].filter(g=>typeof g!="function");for(const g of y){const m=g.field==null?null:[].concat(g.field);m&&c.field&&!m.includes(c.field)||f.push(...xE(g,{feature:e,data:i,scales:r,width:o,height:s,primary:c,color:h.color,style:h}))}u.length>=2&&f.push(...$E(y,u,{color:h.color,style:h}))}const p=gr(t);return p&&p.selects&&f.push(...ME(e,t,n)),d.track&&f.push(...wE(e,t,n,d.track)),f}function wE(e,t,n,r){const o=n.featureNodes&&n.featureNodes[e.id]||[],s=t.channels&&t.channels.length?t.channels:null,i=[],a={stroke:r.color,strokeWidth:r.width,strokeDasharray:r.dash,opacity:r.opacity,fill:"none",guide:!0,pointerEvents:"none"};for(const l of o){const u=l&&l.dm;if(!u)continue;const c=Rn(l);if(c)for(const d of["x","y"]){const f=u[d];!f||f.pxAt0==null||f.pxAt1==null||s&&!s.includes(f.channel)||i.push(d==="x"?{type:"line",x1:f.pxAt0,x2:f.pxAt1,y1:c.cy,y2:c.cy,...a}:{type:"line",x1:c.cx,x2:c.cx,y1:f.pxAt0,y2:f.pxAt1,...a})}}return i}function xE(e,t){if(typeof e.guide=="function")return e.guide(t)||[];switch(e.type){case"clamp":return SE(e.options||{},t);case"maintainSum":return _E(e.options||{},t);case"snap":return kE(e.options||{},t);default:return[]}}const vE=200;function kE({step:e=1,origin:t=0},n){const{primary:r,width:o,height:s,color:i,style:a}=n,l=r.scale;if(!l||!(e>0)||uo(l))return[];const u=l.domain().map(Number),c=Math.min(...u),d=Math.max(...u);if(!Number.isFinite(c)||!Number.isFinite(d))return[];if((d-c)/e>vE)return[];const f=$t(r.name)==="x",[p,h]=ro(l),y=a&&a.tickLength||6,g=(a&&a.tickOpacity)!=null?a.tickOpacity:.5,m=[],b=Math.ceil((c-t)/e),w=Math.floor((d-t)/e);for(let x=b;x<=w;x++){const S=l(t+x*e);!Number.isFinite(S)||S<p-.5||S>h+.5||m.push(f?{type:"line",x1:S,x2:S,y1:s,y2:s-y,stroke:i,strokeWidth:1,opacity:g,pointerEvents:"none",guide:!0}:{type:"line",x1:0,x2:y,y1:S,y2:S,stroke:i,strokeWidth:1,opacity:g,pointerEvents:"none",guide:!0})}return m}function Pp(e,t,n){const{primary:r,width:o,height:s,color:i,style:a}=n;if(e===void 0)return[];const l=r.scale(e),u=a||{},c={stroke:i,strokeDasharray:u.dash,strokeWidth:u.width,opacity:u.opacity,pointerEvents:"none",guide:!0},d={fill:i,fontSize:u.fontSize,opacity:u.labelOpacity,pointerEvents:"none",guide:!0},f=[];return $t(r.name)==="x"?(f.push({type:"line",x1:l,x2:l,y1:0,y2:s,...c}),f.push({type:"text",x:l+4,y:12,text:t,textAnchor:"start",...d})):(f.push({type:"line",x1:0,x2:o,y1:l,y2:l,...c}),f.push({type:"text",x:o-4,y:l-4,text:t,textAnchor:"end",...d})),f}function SE({min:e,max:t},n){const{primary:r,width:o,height:s,color:i}=n,a=[],l=$t(r.name)==="x";if(e!==void 0&&t!==void 0){const u=r.scale(e),c=r.scale(t),d=Math.min(u,c),f=Math.max(u,c),p=(n.style&&n.style.bandOpacity)!=null?n.style.bandOpacity:.07;a.push(l?{type:"rect",x:d,y:0,width:f-d,height:s,fill:i,opacity:p,pointerEvents:"none",guide:!0}:{type:"rect",x:0,y:d,width:o,height:f-d,fill:i,opacity:p,pointerEvents:"none",guide:!0})}return a.push(...Pp(e,`min ${e}`,n)),a.push(...Pp(t,`max ${t}`,n)),a}function $E(e,t,n){const r=t.find(y=>$t(y.name)==="x"),o=t.find(y=>$t(y.name)==="y");if(!r||!o||!r.scale||!o.scale)return[];const s=e.filter(y=>typeof y!="function"),i=s.find(y=>y.type==="clamp"&&y.field===r.field),a=s.find(y=>y.type==="clamp"&&y.field===o.field);if(!i||!a)return[];const l=i.options||{},u=a.options||{};if(l.min==null||l.max==null||u.min==null||u.max==null)return[];const c=r.scale(l.min),d=r.scale(l.max),f=o.scale(u.min),p=o.scale(u.max),{color:h}=n;return[{type:"rect",x:Math.min(c,d),y:Math.min(f,p),width:Math.abs(d-c),height:Math.abs(p-f),fill:h,opacity:(n.style&&n.style.bandOpacity)!=null?n.style.bandOpacity:.08,stroke:h,strokeWidth:n.style&&n.style.width||1,strokeDasharray:n.style&&n.style.dash||"4 4",pointerEvents:"none",guide:!0}]}function _E({total:e},t){if(typeof e!="number")return[];const{feature:n,data:r,scales:o,primary:s,color:i}=t,a=s.name,l=$t(a)||(a==="x"?"x":"y"),u=l==="y"?"x":"y",c=l==="y"?n.yKey||"y":n.xKey||"x",d=u==="y"?n.yKey||"y":n.xKey||"x",f=s.scale,p=o[u];if(!p||!Gn(p))return[];const[h,y]=[Math.min(...f.domain()),Math.max(...f.domain())],g=p.bandwidth(),m=[];return r.forEach(b=>{const w=r.reduce((_,A)=>A[d]===b[d]?_:_+A[c],0),x=e-w;if(x<h||x>y)return;const S=p(b[d]),v=f(x),k={stroke:i,strokeDasharray:t.style&&t.style.dash||"3 3",strokeWidth:(t.style&&t.style.width||1)*1.5,opacity:(t.style&&t.style.opacity)!=null?t.style.opacity:.9,pointerEvents:"none",guide:!0};m.push(l==="y"?{type:"line",x1:S-2,x2:S+g+2,y1:v,y2:v,...k}:{type:"line",x1:v,x2:v,y1:S-2,y2:S+g+2,...k})}),m}function ME(e,t,n){const r=n.ui&&n.ui.session&&n.ui.session[e.id];if(!r||r.px==null||r.py==null||r.threshold==null)return[];const o=q0(t,n).catchment;return o?[{type:"circle",cx:r.px,cy:r.py,r:r.threshold,fill:"none",stroke:o.color,strokeDasharray:o.dash,strokeWidth:o.width,opacity:o.opacity,guide:!0,effect:!0,pointerEvents:"none"}]:[]}const EE={linear:If,catmullRom:rM,natural:sM,step:aM,stepAfter:cM,stepBefore:lM,basis:eM,cardinal:tM,monotoneX:oM,monotoneY:iM};function Oi(e){return e&&EE[e]||If}const H0=[{field:"fill",svgAttr:"fill",base:null},{field:"stroke",svgAttr:"stroke",base:null},{field:"strokeWidth",svgAttr:"stroke-width",base:null},{field:"strokeDasharray",svgAttr:"stroke-dasharray",base:null},{field:"strokeLinecap",svgAttr:"stroke-linecap",base:null},{field:"opacity",svgAttr:"opacity",base:null},{field:"fillOpacity",svgAttr:"fill-opacity",base:null},{field:"strokeOpacity",svgAttr:"stroke-opacity",base:null}];function B0(e){const t=[],n=[],r=[],o=[],s=[];for(const i of e||[])if(i){if(i.effect){s.push(i);continue}if(i.background){t.push(i);continue}if(i.guide){i.type==="rect"?n.push(i):o.push(i);continue}r.push(i)}return{background:t,guideRegions:n,marks:r,guideFront:o,effects:s}}const AE=e=>e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase());class U0{constructor(){this.STYLE_ATTRS=H0.map(({field:t,svgAttr:n,base:r})=>[t,n,r]),this._planeGesture=null,this._planeTracking=null,this._planePointer=null,this._planeNode=null,this._markDragLive=!1}_themeFontSize(){return this._theme&&this._theme.font&&this._theme.font.size||10}render(t){const{container:n,scene:r,width:o,height:s,margins:i,onEvent:a,planeOnTop:l=!1,planeCursor:u="pointer",responsive:c="fixed",overflow:d="hidden",focusOutline:f=!1}=t,p=t.effects||sl,h=o-i.left-i.right,y=s-i.top-i.bottom,{g,plane:m}=this._ensureScene(n,{width:o,height:s,margins:i,innerWidth:h,innerHeight:y,responsive:c,overflow:d});this._sceneG=g,this._onEvent=a,this._theme=t.theme||null;const b=this._theme&&this._theme.font;ir(n).select("svg").style("font-family",b&&b.family||null).style("background",this._theme&&this._theme.background||null);const w=F=>iu(F,g.node());this._bindPlaneGestures(m,w,a,l);const x=this._makeDrag(a),S=this._makeHover(a,p.hovered),v=this._makeKeyboard(a,f),k=(F,D)=>{const[P,j]=w(F);a({type:"click",x:P,y:j,node:D,rawEvent:F})},_=(F,D)=>{F.preventDefault(),F.stopPropagation();const[P,j]=w(F);a({type:"dblclick",x:P,y:j,node:D,rawEvent:F})},{background:A,guideRegions:L,marks:N,guideFront:I,effects:T}=B0(r.children),M=(F,D)=>F.filter(P=>P.type===D),$=this._sceneLayers(g);if(this._drawBackground($.bg,M(A,"image"),M(A,"path"),M(A,"line"),M(A,"text"),M(A,"rect"),M(A,"circle")),this._drawGuideRegions($.guideBack,L),this._drawPaths($.marks,M(N,"path"),{drag:x,markClick:k,markDblClick:_,keys:v,hover:S}),this._drawMarks($.marks,M(N,"rect"),M(N,"circle"),{drag:x,markClick:k,markDblClick:_,keys:v,hover:S}),this._drawEllipses($.marks,M(N,"ellipse"),{drag:x,markClick:k,markDblClick:_,keys:v,hover:S}),this._drawLines($.marks,M(N,"line"),{drag:x,markClick:k,markDblClick:_,keys:v,hover:S}),this._drawTextMarks($.marks,M(N,"text"),{drag:x,markClick:k,markDblClick:_,keys:v,hover:S}),this._orderMarkLayer($.marks,N),this._drawGuideFront($.guideFront,I),this._drawEffects($.effects,T),l){g.selectAll(".mark, .mark-hit").style("pointer-events","none");const F=m.node(),D=$.effects.node(),P=F&&F.parentNode;P&&P.lastElementChild===D&&D.previousElementSibling===F||(m.raise(),$.effects.raise()),m.style("cursor",u||"pointer")}}_ensureScene(t,{width:n,height:r,margins:o,innerWidth:s,innerHeight:i,responsive:a="fixed",overflow:l="hidden"}){let u=ir(t).select("svg");if(u.empty()){u=ir(t).append("svg").style("user-select","none").style("display","block");const d=u.append("g").attr("class","scene-container");d.append("rect").attr("class","plane").attr("x",0).attr("y",0).style("fill","transparent").style("pointer-events","all"),d.append("g").attr("class","bg-layer"),d.append("g").attr("class","guide-back-layer"),d.append("g").attr("class","mark-layer"),d.append("g").attr("class","guide-front-layer"),d.append("g").attr("class","effects-layer")}a==="scale"?u.attr("viewBox",`0 0 ${n} ${r}`).attr("preserveAspectRatio","xMidYMid meet").attr("width",null).attr("height",null).style("width","100%").style("height","auto"):u.attr("viewBox",null).attr("width",n).attr("height",r).style("width",null).style("height",null),u.style("overflow",l==="visible"?"visible":null);const c=u.select(".scene-container").attr("transform",`translate(${o.left},${o.top})`);return c.select("rect.plane").attr("width",s).attr("height",i),this._sceneLayers(c),{svg:u,g:c,plane:c.select("rect.plane")}}_sceneLayers(t){const n=!t.select("g.mark-layer").empty(),r=[],o=c=>{let d=t.select(`g.${c}`);return d.empty()&&(d=t.append("g").attr("class",c),r.push(c)),d},s=o("bg-layer"),i=o("guide-back-layer"),a=o("mark-layer"),l=o("guide-front-layer"),u=o("effects-layer");if(n||t.selectAll(":scope > .mark, :scope > path.mark-line, :scope > .guide-region, :scope > .guide-circle, :scope > .guide-label").remove(),r.length){const c=t.node(),d=t.select("rect.plane").node();for(const f of[d,s.node(),i.node(),a.node(),l.node(),u.node()])f&&c.appendChild(f)}return{bg:s,guideBack:i,marks:a,guideFront:l,effects:u}}_orderMarkLayer(t,n){const r=new Map(n.map((c,d)=>[c,d])),o=t.selectAll(".mark, path.mark-line").filter(c=>r.has(c)),s=o.nodes();let i=-1,a=!1;for(const c of s){const d=r.get(ir(c).datum());if(d<i){a=!0;break}i=d}if(!a)return;const l=typeof document<"u"?document.activeElement:null,u=t.node();o.sort((c,d)=>r.get(c)-r.get(d)),l&&u&&u.contains(l)&&typeof l.focus=="function"&&l.focus()}_bindPlaneGestures(t,n,r,o){if(t.on("click",s=>{if(this._suppressClick){this._suppressClick=!1;return}const[i,a]=n(s);r({type:"click",x:i,y:a,rawEvent:s})}).on("dblclick",s=>{const[i,a]=n(s);r({type:"dblclick",x:i,y:a,rawEvent:s})}),!o){this._abortPlaneGesture(),t.on("pointerdown",null).on("pointermove",null).on("pointerleave",null);return}this._planePointer=n,this._planeNode=t.node(),t.on("pointerdown",s=>{const[i,a]=n(s);this._planeGesture={startX:i,startY:a,down:!0,dragging:!1,pointerId:s.pointerId},this._trackPlaneGesture()}).on("pointermove",s=>{if(this._planeGesture)return;const[i,a]=n(s);r({type:"hover",x:i,y:a,rawEvent:s})}).on("pointerleave",s=>{this._planeGesture||r({type:"hoverout",rawEvent:s})})}_trackPlaneGesture(){if(this._planeTracking||typeof window>"u")return;const t=r=>this._planeMoved(r),n=r=>this._planeReleased(r);this._planeTracking={move:t,end:n},window.addEventListener("pointermove",t,!0),window.addEventListener("pointerup",n,!0),window.addEventListener("pointercancel",n,!0)}_releasePlaneTracking(){const t=this._planeTracking;!t||typeof window>"u"||(window.removeEventListener("pointermove",t.move,!0),window.removeEventListener("pointerup",t.end,!0),window.removeEventListener("pointercancel",t.end,!0),this._planeTracking=null)}_abortPlaneGesture(){this._releasePlaneTracking(),this._planeGesture=null}_planeMoved(t){const n=this._planeGesture;if(!n||!this._planePointer||!this._onEvent||n.pointerId!=null&&t.pointerId!==n.pointerId)return;if(t.pointerType==="mouse"&&t.buttons===0)return this._planeReleased(t);const[r,o]=this._planePointer(t);!n.dragging&&Math.hypot(r-n.startX,o-n.startY)>3&&(n.dragging=!0,this._onEvent({type:"dragstart",x:n.startX,y:n.startY,rawEvent:t})),n.dragging&&this._onEvent({type:"drag",x:r,y:o,rawEvent:t})}_planeReleased(t){const n=this._planeGesture;if(!n)return this._releasePlaneTracking();if(n.pointerId!=null&&t.pointerId!==n.pointerId||(this._releasePlaneTracking(),this._planeGesture=null,!this._planePointer||!this._onEvent))return;const[r,o]=this._planePointer(t);n.dragging&&(this._onEvent({type:"dragend",x:r,y:o,rawEvent:t}),this._suppressClick=!0),this._pointerOverPlane(t)||this._onEvent({type:"hoverout",rawEvent:t})}_pointerOverPlane(t){const n=this._planeNode;if(!n||typeof n.getBoundingClientRect!="function")return!1;const r=n.getBoundingClientRect();return t.clientX>=r.left&&t.clientX<=r.right&&t.clientY>=r.top&&t.clientY<=r.bottom}_makeKeyboard(t,n=!1){const r={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]};return o=>{o.attr("tabindex",s=>s.editable?0:null).attr("role",s=>s.editable?"button":null).style("outline",n?null:"none").on("keydown",(s,i)=>{if(!i||!i.editable)return;const a=r[s.key];if(!a)return;s.preventDefault();const[l,u]=a;t({type:"nudge",node:i,dx:l,dy:u,coarse:!!s.shiftKey,rawEvent:s})})}}_makeHover(t,n){const r=!n||n.enabled!==!1;return o=>{o.on("pointerenter",(s,i)=>{!r||!i||!i.editable||t({type:"pointerover",node:i})}).on("pointerleave",(s,i)=>{!r||!i||!i.editable||t({type:"pointerout",node:i})})}}_makeDrag(t){return Lv().clickDistance(4).subject(n=>({x:n.x,y:n.y})).on("start",(n,r)=>{this._markDragLive=!0,t({type:"dragstart",x:n.x,y:n.y,node:r,rawEvent:n.sourceEvent})}).on("drag",(n,r)=>{const o=n.sourceEvent;if(o&&o.type==="mousemove"&&o.buttons===0){this._endMarkDrag(t,n,r);return}this._markDragLive&&t({type:"drag",x:n.x,y:n.y,node:r,rawEvent:n.sourceEvent})}).on("end",(n,r)=>{this._endMarkDrag(t,n,r)})}_endMarkDrag(t,n,r){this._markDragLive&&(this._markDragLive=!1,t({type:"dragend",x:n.x,y:n.y,node:r,rawEvent:n.sourceEvent}))}_applyStyle(t,n={}){for(const[r,o,s]of this.STYLE_ATTRS){const i=r in n?n[r]:s;t.attr(o,a=>a[r]!=null?a[r]:i)}return t.attr("data-ghost",r=>r.ghost?"":null),t.attr("data-hit",r=>r.hit?"":null),t.attr("data-channel",r=>r.channel!=null?r.channel:null),t}_applyEffectStyle(t,n="move"){for(const r of S0)r!=="cursor"&&t.style(AE(r),o=>o.effectStyle&&o.effectStyle[r]!=null?o.effectStyle[r]:null);return t.style("cursor",r=>r.effectStyle&&r.effectStyle.cursor!=null?r.effectStyle.cursor:r.editable?r.cursor||n:"default"),t}_angleTransform(t){if(t==null||t.angle==null||t.angle===0)return null;const n=Rn(t);return n?`rotate(${-t.angle} ${n.cx} ${n.cy})`:null}_geomRect(t){t.attr("x",n=>n.x).attr("y",n=>n.y).attr("width",n=>n.width).attr("height",n=>Math.max(0,n.height)).attr("rx",n=>n.rx!=null?n.rx:null).attr("ry",n=>n.ry!=null?n.ry:n.rx!=null?n.rx:null).attr("transform",n=>this._angleTransform(n))}_geomCircle(t){t.attr("cx",n=>n.cx).attr("cy",n=>n.cy).attr("r",n=>Math.max(0,n.r!=null?n.r:5)).attr("transform",n=>this._angleTransform(n))}_geomEllipse(t){t.attr("cx",n=>n.cx).attr("cy",n=>n.cy).attr("rx",n=>Math.max(0,n.rx!=null?n.rx:5)).attr("ry",n=>Math.max(0,n.ry!=null?n.ry:5)).attr("transform",n=>this._angleTransform(n))}_geomLine(t){t.attr("x1",n=>n.x1).attr("x2",n=>n.x2).attr("y1",n=>n.y1).attr("y2",n=>n.y2).attr("transform",n=>this._angleTransform(n))}_geomText(t,n="start"){t.attr("x",r=>r.x).attr("y",r=>r.y).attr("text-anchor",r=>r.textAnchor||n).attr("dominant-baseline",r=>r.dominantBaseline||null).attr("font-size",r=>r.fontSize!=null?r.fontSize:this._themeFontSize()).attr("transform",r=>this._angleTransform(r)),t.each(function(r){const o=ir(this),s=Array.isArray(r.lines)?r.lines:null;if(!s||s.length<=1){o.selectAll("tspan").remove(),o.text(s?s[0]||"":r.text);return}const i=r.fontSize!=null?r.fontSize:12,a=r.lineHeight!=null?r.lineHeight:Math.round(i*1.35),l=-(s.length-1)*a/2;o.text(null),o.selectAll("tspan").data(s).join("tspan").attr("x",r.x).attr("dy",(u,c)=>c===0?l:a).text(u=>u)})}_drawBackground(t,n,r,o,s,i=[],a=[]){t.selectAll("image").data(n,h=>h.key).join("image").style("pointer-events","none").attr("x",h=>h.x).attr("y",h=>h.y).attr("width",h=>h.width).attr("height",h=>h.height).attr("transform",h=>this._angleTransform(h)).attr("preserveAspectRatio","none").attr("href",h=>h.href).attr("opacity",h=>h.opacity!=null?h.opacity:null).lower();const u=t.selectAll("rect.bg-rect").data(i).join("rect").attr("class","bg-rect").style("pointer-events","none");this._geomRect(u),this._applyStyle(u,{fill:"none",stroke:"none",strokeWidth:1,opacity:1});const c=t.selectAll("circle.bg-circle").data(a).join("circle").attr("class","bg-circle").style("pointer-events","none");this._geomCircle(c),this._applyStyle(c,{fill:"none",stroke:"none",strokeWidth:1,opacity:1});const d=t.selectAll("line").data(o).join("line").style("pointer-events","none");this._geomLine(d),this._applyStyle(d,{stroke:"#6b7280",strokeWidth:1,opacity:1});const f=t.selectAll("text").data(s).join("text").style("pointer-events","none");this._geomText(f,"middle"),this._applyStyle(f,{fill:"#374151",opacity:1});const p=t.selectAll("path.bg-path").data(r).join("path").attr("class","bg-path").style("pointer-events","none").attr("d",h=>h.d?h.d:Si().curve(Oi(h.curve))(h.points||[]));this._applyStyle(p,{fill:"none",stroke:"black",strokeWidth:1,opacity:1})}_drawGuideRegions(t,n){const r=t.selectAll("rect.guide-region").data(n).join("rect").attr("class","guide-region").style("pointer-events","none");this._geomRect(r),this._applyStyle(r,{fill:"none",stroke:"none",strokeWidth:1,opacity:1})}_drawGuideFront(t,n){const r=u=>n.filter(c=>c.type===u),o=t.selectAll("line.guide-line").data(r("line")).join("line").attr("class","guide-line").style("pointer-events","none");this._geomLine(o),this._applyStyle(o,{stroke:"black",strokeWidth:1,opacity:1});const s=t.selectAll("circle.guide-circle").data(r("circle")).join("circle").attr("class","guide-circle").style("pointer-events","none");this._geomCircle(s),this._applyStyle(s,{fill:"none",stroke:"none",strokeWidth:1,opacity:1});const i=t.selectAll("path.guide-path").data(r("path")).join("path").attr("class","guide-path").style("pointer-events","none").attr("d",u=>u.d?u.d:Si().curve(Oi(u.curve))(u.points||[]));this._applyStyle(i,{fill:"none",stroke:"black",strokeWidth:1,opacity:1});const a=t.selectAll("text.guide-label").data(r("text")).join("text").attr("class","guide-label").style("pointer-events","none");this._geomText(a,"start"),this._applyStyle(a,{fill:"black",opacity:1});const l=new Map(n.map((u,c)=>[u,c]));t.selectAll("line.guide-line, circle.guide-circle, path.guide-path, text.guide-label").filter(u=>l.has(u)).sort((u,c)=>l.get(u)-l.get(c))}_drawEffects(t,n){const r=d=>n.filter(f=>f.type===d),o={fill:"none",stroke:"none",strokeWidth:1,opacity:1},s=t.selectAll("circle.effect").data(r("circle")).join("circle").attr("class","effect").style("pointer-events","none");this._geomCircle(s),this._applyStyle(s,o);const i=t.selectAll("rect.effect").data(r("rect")).join("rect").attr("class","effect").style("pointer-events","none");this._geomRect(i),this._applyStyle(i,o);const a=t.selectAll("ellipse.effect").data(r("ellipse")).join("ellipse").attr("class","effect").style("pointer-events","none");this._geomEllipse(a),this._applyStyle(a,o);const l=t.selectAll("line.effect").data(r("line")).join("line").attr("class","effect").style("pointer-events","none");this._geomLine(l),this._applyStyle(l,o);const u=t.selectAll("path.effect").data(r("path")).join("path").attr("class","effect").style("pointer-events","none").attr("d",d=>d.d?d.d:Si().curve(Oi(d.curve))(d.points||[]));this._applyStyle(u,o);const c=new Map(n.map((d,f)=>[d,f]));t.selectAll("circle.effect, rect.effect, ellipse.effect, line.effect, path.effect").filter(d=>c.has(d)).sort((d,f)=>c.get(d)-c.get(f))}_dblClick(t){return(n,r)=>{if(r&&r.editText){n.preventDefault(),n.stopPropagation(),this._editText(n,r);return}t&&t(n,r)}}_drawMarks(t,n,r,{drag:o,markClick:s,markDblClick:i,keys:a,hover:l}){const u=t.selectAll("rect.mark").data(n).join("rect").attr("class","mark").style("pointer-events",p=>p.pointerEvents||"auto").style("cursor",p=>p.editable?p.cursor||"ns-resize":"default").on("click",s).on("dblclick",this._dblClick(i)).call(o).call(l).call(a);this._geomRect(u),this._applyStyle(u,{fill:"black"}),this._applyEffectStyle(u,"ns-resize");const c=n.filter(p=>p.editable&&p.pointerEvents!=="none"&&((p.width||0)<al||(p.height||0)<al));t.selectAll("rect.mark-hit").data(c).join("rect").attr("class","mark-hit").style("pointer-events","all").style("fill","transparent").style("cursor",p=>p.cursor||"ns-resize").attr("x",p=>Ti(p).x).attr("y",p=>Ti(p).y).attr("width",p=>Ti(p).w).attr("height",p=>Ti(p).h).attr("transform",p=>this._angleTransform(p)).on("click",s).on("dblclick",this._dblClick(i)).call(o).call(l).lower();const f=t.selectAll("circle.mark").data(r).join("circle").attr("class","mark").style("pointer-events",p=>p.pointerEvents||"auto").style("cursor",p=>p.editable?p.cursor||"move":"default").on("click",s).on("dblclick",this._dblClick(i)).call(o).call(l).call(a);this._geomCircle(f),this._applyStyle(f,{fill:"black"}),this._applyEffectStyle(f,"move")}_drawEllipses(t,n,{drag:r,markClick:o,markDblClick:s,keys:i,hover:a}){const l=t.selectAll("ellipse.mark").data(n).join("ellipse").attr("class","mark").style("pointer-events",u=>u.pointerEvents||"auto").style("cursor",u=>u.editable?u.cursor||"move":"default").on("click",o).on("dblclick",this._dblClick(s)).call(r).call(a).call(i);this._geomEllipse(l),this._applyStyle(l,{fill:"black"}),this._applyEffectStyle(l,"move")}_drawLines(t,n,{drag:r,markClick:o,markDblClick:s,keys:i,hover:a}){const l=t.selectAll("line.mark").data(n).join("line").attr("class","mark").style("pointer-events",u=>u.pointerEvents||"auto").style("cursor",u=>u.editable?u.cursor||"move":"default").on("click",o).on("dblclick",this._dblClick(s)).call(r).call(a).call(i);this._geomLine(l),this._applyStyle(l,{stroke:"black",strokeWidth:1,opacity:1}),this._applyEffectStyle(l,"move")}_drawPaths(t,n,r){const o=t.selectAll("path.mark-line").data(n).join("path").attr("class","mark-line").style("pointer-events",s=>s.pointerEvents||(s.editable?"auto":"none")).style("cursor",s=>s.editable?s.cursor||"pointer":"default").attr("d",s=>s.d?s.d:Si().curve(Oi(s.curve))(s.points||[]));this._applyStyle(o,{fill:"none",stroke:"black",strokeWidth:1,opacity:1}),this._applyEffectStyle(o,"pointer"),r&&o.on("click",r.markClick).on("dblclick",this._dblClick(r.markDblClick)).call(r.drag).call(r.hover).call(r.keys)}_drawTextMarks(t,n,{drag:r,markClick:o,markDblClick:s,keys:i,hover:a}){const l=t.selectAll("text.mark").data(n).join("text").attr("class","mark").style("pointer-events",u=>u.pointerEvents||"auto").style("cursor",u=>u.editable?u.cursor||"move":"default").on("click",o).on("dblclick",this._dblClick(s)).call(r).call(a).call(i);this._geomText(l,"middle"),this._applyStyle(l,{fill:"black",opacity:1}),this._applyEffectStyle(l,"move")}_editText(t,n){if(!n||!n.editText)return;const r=this._sceneG,o=this._onEvent;if(!r||!o)return;r.selectAll("foreignObject.text-editor").remove();const s=n.fontSize!=null?n.fontSize:12,i=n.editBox||(n.type==="rect"&&n.width!=null?{x:n.x,y:n.y,width:n.width,height:Math.max(0,n.height)}:null),a=i?i.width:140,l=i?i.height:s+10,u=i?i.x:n.x-a/2,c=i?i.y:n.y-l+4,d=r.append("foreignObject").attr("class","text-editor").attr("x",u).attr("y",c).attr("width",a).attr("height",l),f=!!n.multiline,p=d.append(f?"xhtml:textarea":"xhtml:input").attr("type",f?null:"text").style("width","100%").style("height",f?"100%":null).style("box-sizing","border-box").style("font-size",s+"px").style("font-family","inherit").style("text-align","center").style("resize",f?"none":null).node();p.value=n.text!=null?String(n.text):n.editValue!=null?String(n.editValue):"",p.focus(),f?p.setSelectionRange(p.value.length,p.value.length):p.select();let h=!1;const y=()=>{if(h)return;h=!0;const m=p.value;d.remove(),o({type:"commit",node:n,value:m,x:n.x,y:n.y,rawEvent:t})},g=()=>{h||(h=!0,d.remove())};p.addEventListener("keydown",m=>{m.key==="Enter"?(!f||m.metaKey||m.ctrlKey)&&(m.preventDefault(),y()):m.key==="Escape"&&(m.preventDefault(),g()),m.stopPropagation()}),p.addEventListener("blur",y)}}const K0=$s.axis,Zf=$s.grid,Dp=e=>e instanceof Date?e.getTime():e;function jp({x:e,y:t,textAnchor:n,v:r,format:o,fill:s,fontSize:i}){return{type:"text",x:e,y:t,text:o(r),textAnchor:n,fill:s,fontSize:i,category:r,editText:!0,index:0,cursor:"text"}}function Wp({x:e,y:t,v:n,fontSize:r}){return{type:"text",x:e,y:t,text:"×",textAnchor:"middle",fill:"#dc2626",fontSize:r+1,cursor:"pointer",removeCategory:n,index:0}}function TE(e,t,n){switch(e){case"top":return{x:0,y:0};case"bottom":return{x:0,y:n};case"left":return{x:0,y:0};case"right":return{x:t,y:0};default:return{x:0,y:0}}}function Yl(e,t={}){const{ticks:n=5,tickValues:r,tickFormat:o}=t,s=e.kind!=="continuous";let i;r?i=r:s?i=e.domain():typeof e.ticks=="function"?i=e.ticks(n):i=e.domain();let a;return typeof o=="function"?a=o:typeof o=="string"?a=Qo(o):!s&&typeof e.tickFormat=="function"?a=e.tickFormat(n):a=l=>`${l}`,{values:i,format:a}}function Gl(e={}){Es("axis",e,K0);const{channel:t="x",anchor:n=t==="x"?"bottom":"left",transform:r,ticks:o=5,tickValues:s,tickFormat:i,tickSize:a=6,title:l,stroke:u,fill:c,fontSize:d,grid:f=!1,field:p,table:h,handleColor:y,handleSize:g,id:m}=e,b=t==="x"||t!=="y"&&(n==="bottom"||n==="top"),w=Di(e,t),x=w.length>0;return{id:m,type:"axis",isAxis:!0,views:"scale",channel:t,layer:"background",edits:w,field:p,table:h,grid:f,build:(S,v,k,_)=>{const A=v[t];if(!A)return[];const L=it(v),N=u??L.axis.stroke,I=c??L.axis.labelFill,T=d??L.axis.fontSize,M=dn(v,{handles:!0,handleSize:g,handleColor:y??L.axis.handle}),$=M.fill,F=M.size,D=M.stroke,P=TE(n,k,_),j=r?{...P,...r({width:k,height:_,scales:v,anchor:n,base:P})||{}}:P,{values:G,format:J}=Yl(A,{ticks:o,tickValues:s,tickFormat:i}),re=n==="bottom"||n==="right"?1:-1,Q=[],ve=x&&uo(A),Ce=x&&A.kind==="continuous";b?Q.push({type:"line",x1:j.x,x2:j.x+k,y1:j.y,y2:j.y,stroke:N,strokeWidth:1,background:!0,pointerEvents:"none"}):Q.push({type:"line",x1:j.x,x2:j.x,y1:j.y,y2:j.y+_,stroke:N,strokeWidth:1,background:!0,pointerEvents:"none"});for(const le of G){const be=$r(A,le);if(!(be==null||Number.isNaN(be)))if(b){const ce=j.x+be;Q.push({type:"line",x1:ce,x2:ce,y1:j.y,y2:j.y+re*a,stroke:N,strokeWidth:1,background:!0,pointerEvents:"none"});const Y=j.y+re*(a+T);Q.push(ve?jp({x:ce,y:Y,textAnchor:"middle",v:le,format:J,fill:I,fontSize:T}):{type:"text",x:ce,y:Y,text:J(le),textAnchor:"middle",fill:I,fontSize:T,background:!0,pointerEvents:"none"}),ve&&Q.push(Wp({x:ce,y:Y+T,v:le,fontSize:T}))}else{const ce=j.y+be;Q.push({type:"line",x1:j.x,x2:j.x+re*a,y1:ce,y2:ce,stroke:N,strokeWidth:1,background:!0,pointerEvents:"none"});const Y=j.x+re*(a+3);Q.push(ve?jp({x:Y,y:ce+T/3,textAnchor:re<0?"end":"start",v:le,format:J,fill:I,fontSize:T}):{type:"text",x:Y,y:ce+T/3,text:J(le),textAnchor:re<0?"end":"start",fill:I,fontSize:T,background:!0,pointerEvents:"none"}),ve&&Q.push(Wp({x:Y+re*(T+4),y:ce+T/3,v:le,fontSize:T}))}}if(ve){const le=b?j.x+k+T:j.x,be=b?j.y+re*(a+T):j.y+_+re*(a+T);Q.push({type:"text",x:le,y:be,text:"+",textAnchor:"middle",fill:$,fontSize:T+4,cursor:"pointer",addCategory:!0,editText:!0,index:0})}else if(Ce){const le=typeof A.domain=="function"?A.domain():[],be=le[0],ce=le[le.length-1],Y=ue=>(b?j.x:j.y)+$r(A,ue);for(const ue of["min","max"]){const ie=ue==="max"?ce:be,U=ue==="max"?be:ce,we=Y(ie),xe=Y(U),z=Dp(ie)-Dp(U)||1;Q.push({type:"circle",cx:b?j.x+$r(A,ie):j.x,cy:b?j.y:j.y+$r(A,ie),r:F,fill:$,stroke:D,strokeWidth:M.strokeWidth,axisHandle:!0,handle:ue,axis:t,anchorPixel:xe,anchorValue:U,grabPixel:we,grabValue:ie,pxPerUnit:(we-xe)/z,cursor:b?"ew-resize":"ns-resize"})}}return l&&(b?Q.push({type:"text",x:j.x+k/2,y:j.y+re*(a+T*2.4),text:l,textAnchor:"middle",fill:I,fontSize:T+1,background:!0,pointerEvents:"none"}):Q.push({type:"text",x:j.x+re*(a+T*2.4),y:j.y+_/2,text:l,textAnchor:"middle",fill:I,fontSize:T+1,background:!0,pointerEvents:"none"})),Q}}}function Qf(e={}){Es("grid",e,Zf);const{channel:t="x",ticks:n=5,tickValues:r,stroke:o,strokeWidth:s,id:i}=e,a=t==="x";return{id:i,type:"grid",isGrid:!0,views:"scale",channel:t,layer:"background",build:(l,u,c,d)=>{const f=u[t];if(!f)return[];const p=it(u),h=o??p.grid.stroke,y=s??p.grid.strokeWidth,{values:g}=Yl(f,{ticks:n,tickValues:r}),m=[];for(const b of g){const w=$r(f,b);w==null||Number.isNaN(w)||(a?m.push({type:"line",x1:w,x2:w,y1:0,y2:d,stroke:h,strokeWidth:y,background:!0,pointerEvents:"none"}):m.push({type:"line",x1:0,x2:c,y1:w,y2:w,stroke:h,strokeWidth:y,background:!0,pointerEvents:"none"}))}return m}}}const Y0=(e={})=>Gl({...e,channel:"x"}),G0=(e={})=>Gl({...e,channel:"y"}),V0=(e={})=>Qf({...e,channel:"x"}),X0=(e={})=>Qf({...e,channel:"y"});function OE(e){const t={};for(const n of Zf)e[n]!==void 0&&(t[n]=e[n]);return t}function CE(e){return(e||[]).flat(1/0).filter(t=>t&&typeof t=="object")}function NE(e){return({scales:t})=>{if(e==="x"){const o=t.y;if(!o)return{};const s=typeof o.encode=="function"?o.encode(0):o(0);return s!=null&&!Number.isNaN(Number(s))?{y:Number(s)}:{}}const n=t.x;if(!n)return{};const r=typeof n.encode=="function"?n.encode(0):n(0);return r!=null&&!Number.isNaN(Number(r))?{x:Number(r)}:{}}}function IE(e,t){if(t===!1)return[];const n=CE(e),r=t&&typeof t=="object"?t.origin:void 0,o=r===!0||r===void 0&&t==null&&n.some(l=>l.isTrend),s=[],i=l=>n.some(u=>(u.isAxis||u.isGrid)&&u.channel===l),a={x:{axis:Y0,grid:V0},y:{axis:G0,grid:X0}};if(t&&t.count&&!i("count")){const l=n.find(u=>u.countAxis);if(l){const u=t.count===!0?{}:{...t.count};s.push(Gl({anchor:l.countAxis==="x"?"bottom":"left",...u,channel:"count"}))}}for(const l of["x","y"]){const u=t?t[l]:void 0;if(u===!1||i(l))continue;const c=u?{...u}:{};o&&c.transform==null&&(c.transform=NE(l)),s.push(a[l].axis(c)),c.grid&&s.push(a[l].grid(OE(c)))}return s}const J0=$s.legend,Oo=e=>e instanceof Date?e.getTime():e,LE=e=>e==="fill"||e==="stroke";function FE(e){return e.kind==="continuous"||!!e.ramp}function RE(e,t){return FE(t)?e==="size"?"graduated":e==="theta"?"fan":e==="strokeWidth"?"weights":"ramp":"swatches"}function qp(e,t,n,r){if(e!=="size")return r;let o=0;for(const s of n){const i=Number(typeof t.encode=="function"?t.encode(s):t(s));Number.isFinite(i)&&(o=Math.max(o,i))}return Math.max(r,2*o)}function Hp(e,t,n){if(e===!1||e===null)return null;if(e!=null)return String(e);const r=t??(n&&n.fields&&n.fields[0]||null);return r==null?null:String(r)}function zE(e,t,n){let r=0;for(const o of e)r=Math.max(r,String(t(o)).length);return Math.ceil(r*n*.6)}function As(e={}){Es("legend",e,J0);const{channel:t="fill",anchor:n="right",orient:r,swatchSize:o=14,gap:s=6,labelWidth:i,rampLength:a=140,rampThickness:l=12,ticks:u=4,tickFormat:c,title:d,row:f,stroke:p,fill:h,fontSize:y,handleColor:g,handleSize:m,field:b,table:w,id:x}=e,S=r||(n==="left"||n==="right"?"vertical":"horizontal"),v=S==="vertical",k=Di(e,t),_=k.length>0,A=k.some(T=>T.target==="domain"),L=T=>T[co(t,b)]||T[t],N={offset:0,size:0},I=(T,M)=>{const $=y??(M.guide.legend.fontSize||11),F=RE(t,T),D=F!=="swatches";let P,j;if(D){const J=T.domain(),re=Pi().domain([Math.min(...J.map(Oo)),Math.max(...J.map(Oo))]);P=re.ticks(u),j=typeof c=="string"?Qo(c):typeof c=="function"?c:re.tickFormat(u)}else P=T.domain(),j=c?Yl(T,{tickFormat:c}).format:J=>`${J}`;const G=i??zE(P,j,$);return{ramp:D,form:F,values:P,format:j,labelW:G,fontSize:$}};return{id:x,type:"legend",isLegend:!0,views:"scale",channel:t,anchor:n,orient:S,layer:"background",edits:k,field:b,table:w,_place:N,measure(T){const M=L(T);if(!M||typeof M.domain!="function")return null;const $=it(T),{form:F,values:D,labelW:P,fontSize:j}=I(M,$),J=Hp(d,b,M)?j+4:0;if(F==="graduated"){const le=Z0(M,D);if(!le.length)return{width:P,height:j+J};const be=le[le.length-1].r,ce=le.reduce((Y,ue)=>Y+2*ue.r+s,0);return v?{width:2*be+6+P,height:ce+J}:{width:le.reduce((Y,ue)=>Y+2*ue.r+6+P+s,0),height:2*be+j+J}}if(F==="fan"){const le=Q0(M,D,P,j);return{width:le.width,height:le.height+J}}if(F==="weights"){const le=D.reduce((be,ce)=>{const Y=Number(typeof M.encode=="function"?M.encode(ce):M(ce));return be+Math.max(Number.isFinite(Y)?Y:0,j)+s},0);return{width:2*ls+6+P,height:le+J}}if(F==="ramp")return v?{width:l+6+P,height:a+J}:{width:a,height:l+6+j+J};const re=(D.length||1)+(A?1:0),Q=A?j+6:0,ve=qp(t,M,D,o);if(v)return{width:ve+4+P+Q,height:re*(ve+s)+J};const Ce=ve+4+P+Q+s;return{width:re*Ce,height:ve+s+J}},build(T,M,$,F){const D=L(M);if(!D||typeof D.domain!="function")return[];const P=D.domain();if(!P.length)return[];_&&b==null&&!(D.fields||[]).length&&ge(`legend:field:${t}`,`legend({ channel: "${t}", edit: … }) can't tell which column to write: no mark binds a field to "${t}", so the scale carries none and the edit is a no-op. Pin it with legend({ field: "…" }), or bind the channel on a mark.`);const j=it(M),G=p??(j.guide.legend.stroke||"#374151"),J=h??(j.guide.legend.labelFill||"#374151"),re=dn(M,{handles:!0,handleSize:m,handleColor:g??j.axis.handle}),Q=re.fill,ve=re.size,Ce=re.stroke,{form:le,values:be,format:ce,labelW:Y,fontSize:ue}=I(D,j),ie=N.size||(this.measure(M)||{width:0,height:0})[v?"width":"height"];let U=0,we=0;n==="right"?U=$+N.offset:n==="left"?U=-(N.offset+ie):n==="bottom"?we=F+N.offset:n==="top"&&(we=-(N.offset+ie));const xe=[];let z=we;const H=Hp(d,b,D);H&&(xe.push({type:"text",x:U,y:we+ue,text:H,textAnchor:"start",fill:J,fontSize:ue+1,background:!0,pointerEvents:"none"}),z=we+ue+4);const oe=M.selection,de=M.selectionAll,ke=typeof de=="function"?de(this.table):oe!=null?[oe]:[];let he;if(f!=null&&f!=="selection"){const ae=typeof f=="function"?f(T,{selection:oe}):f;he=ae==null?[]:Array.isArray(ae)?ae:[ae]}else ke.length?he=ke:he=T.length===1?[0]:[];const $e=he.filter(ae=>Number.isInteger(ae)&&ae>=0&&ae<T.length),Te=$e.length?$e[0]:null,Se={scale:D,values:be,format:ce,cx0:U,cy0:z,vertical:v,anchor:n,fontSize:ue,swatchStroke:G,labelFill:J,editable:_,domainEditable:A,handleColor:Q,data:T,channel:t,field:b,targetRow:Te,targetRows:$e,currentStroke:j.guide.legend.currentStroke||"#111827",currentWidth:j.guide.legend.currentWidth??2};return le==="graduated"?PE(xe,{...Se,gap:s}):le==="fan"?DE(xe,{...Se,labelW:Y}):le==="weights"?jE(xe,{...Se,gap:s}):le==="ramp"?HE(xe,{...Se,rampLength:a,rampThickness:l,handleColor:Q,handleSize:ve,handleStroke:Ce}):qE(xe,{...Se,domain:P,swatchSize:qp(t,D,P,o),gap:s,labelW:Y}),xe}}}function Z0(e,t){const n=[];for(const r of t){const o=Number(typeof e.encode=="function"?e.encode(r):e(r));!Number.isFinite(o)||o<1||n.push({v:r,r:o})}return n.sort((r,o)=>r.r-o.r),n}function PE(e,t){const{scale:n,values:r,format:o,cx0:s,cy0:i,vertical:a,gap:l,labelFill:u,fontSize:c,swatchStroke:d}=t,f=Z0(n,r);if(!f.length)return;const p=f[f.length-1].r;let h=0;for(const{v:y,r:g}of f){const m=a?s+p:s+h+g,b=a?i+h+g:i+p;e.push({type:"circle",cx:m,cy:b,r:g,fill:"none",stroke:d,strokeWidth:1,background:!0,pointerEvents:"none"}),e.push({type:"text",x:a?s+2*p+6:m,y:a?b+c*.35:i+2*p+c,text:String(o(y)),fill:u,fontSize:c,textAnchor:a?"start":"middle",background:!0,pointerEvents:"none"}),h+=2*g+l}}const ls=22;function Q0(e,t,n,r){const o=[];let s=0,i=0,a=0,l=0;for(const u of t){const c=Number(typeof e.encode=="function"?e.encode(u):e(u));if(!Number.isFinite(c))continue;const d=c*Math.PI/180,f=Math.cos(d)*ls,p=-Math.sin(d)*ls,h=f+Math.cos(d)*6,y=p-Math.sin(d)*6,g=Math.cos(d)<-.1?"end":Math.cos(d)>.1?"start":"middle";o.push({v:u,tx:f,ty:p,lx:h,ly:y,anchor:g});const m=g==="end"?h-n:g==="middle"?h-n/2:h,b=g==="end"?h:g==="middle"?h+n/2:h+n;s=Math.min(s,f,m),i=Math.max(i,f,b),a=Math.min(a,p,y-r),l=Math.max(l,p,y+r*.5)}return{spokes:o,width:i-s,height:l-a,ox:-s,oy:-a}}function DE(e,t){const{scale:n,values:r,format:o,cx0:s,cy0:i,labelFill:a,fontSize:l,swatchStroke:u,labelW:c}=t,{spokes:d,ox:f,oy:p}=Q0(n,r,c,l),h=s+f,y=i+p;for(const g of d)e.push({type:"line",x1:h,y1:y,x2:h+g.tx,y2:y+g.ty,stroke:u,strokeWidth:1.5,background:!0,pointerEvents:"none"}),e.push({type:"text",x:h+g.lx,y:y+g.ly+l*.35,text:String(o(g.v)),fill:a,fontSize:l,textAnchor:g.anchor,background:!0,pointerEvents:"none"})}function jE(e,t){const{scale:n,values:r,format:o,cx0:s,cy0:i,gap:a,labelFill:l,fontSize:u,swatchStroke:c}=t,d=[];for(const p of r){const h=Number(typeof n.encode=="function"?n.encode(p):n(p));Number.isFinite(h)&&h>0&&d.push({v:p,w:h})}d.sort((p,h)=>p.w-h.w);let f=0;for(const{v:p,w:h}of d){const y=i+f+h/2;e.push({type:"line",x1:s,y1:y,x2:s+ls*2,y2:y,stroke:c,strokeWidth:h,background:!0,pointerEvents:"none"}),e.push({type:"text",x:s+ls*2+6,y:y+u*.35,text:String(o(p)),fill:l,fontSize:u,textAnchor:"start",background:!0,pointerEvents:"none"}),f+=Math.max(h,u)+a}}function WE({channel:e,x:t,y:n,size:r,encoded:o,stroke:s,ink:i,interactive:a}){const l=a?{}:{background:!0,pointerEvents:"none"};if(e==="symbol")return{type:"text",x:t+r/2,y:n+r/2,text:String(o),fontSize:r,textAnchor:"middle",dominantBaseline:"central",...l};if(e==="size"){const u=Math.max(1,Number(o)||r/2);return{type:"circle",cx:t+r/2,cy:n+r/2,r:u,fill:i,stroke:s,strokeWidth:1,...l}}return e==="opacity"?{type:"rect",x:t,y:n,width:r,height:r,fill:i,fillOpacity:Number(o),stroke:s,strokeWidth:1,...l}:{type:"rect",x:t,y:n,width:r,height:r,fill:o,stroke:s,strokeWidth:1,...l}}function qE(e,t){const{domain:n,cx0:r,cy0:o,vertical:s,swatchSize:i,gap:a,fontSize:l,swatchStroke:u,labelFill:c,editable:d,domainEditable:f,handleColor:p,targetRow:h,targetRows:y,scale:g,channel:m,data:b,field:w,currentStroke:x,currentWidth:S}=t,v=d&&h!=null,k=v||f,_=h??0,A=w??(g.fields&&g.fields[0]||null),L=new Set;if(v&&A!=null)for(const $ of y){const F=b&&b[$];F&&F[A]!==void 0&&L.add(F[A])}const N=f?l+6:0,I=i+4+t.labelW+N+a,T=i+a,M=$=>({sx:s?r:r+$*I,sy:s?o+$*T:o});if(n.forEach(($,F)=>{const D=typeof g.encode=="function"?g.encode($):typeof g=="function"?g($):$,{sx:P,sy:j}=M(F),G=WE({channel:m,x:P,y:j,size:i,encoded:D,stroke:u,ink:c,interactive:k});k&&(G.category=$,G.index=_,G.indices=y,G.cursor=f&&!v?"text":"pointer",f&&(G.editText=!0,G.editValue=String($))),e.push(G),L.has($)&&e.push({type:"rect",x:P-2.5,y:j-2.5,width:i+5,height:i+5,fill:"none",stroke:x,strokeWidth:S,rx:2,effect:!0,background:!0,pointerEvents:"none"}),e.push({type:"text",x:P+i+4,y:j+i*.75,text:String(t.format($)),fill:c,fontSize:l,textAnchor:"start",background:!0,pointerEvents:"none"}),f&&e.push({type:"text",x:P+i+4+t.labelW+l*.5,y:j+i*.75,text:"×",textAnchor:"middle",fill:"#dc2626",fontSize:l+1,cursor:"pointer",removeCategory:$,index:0})}),f){const{sx:$,sy:F}=M(n.length);e.push({type:"text",x:$+i/2,y:F+i*.75,text:"+",textAnchor:"middle",fill:p,fontSize:l+4,cursor:"pointer",addCategory:!0,editText:!0,index:0})}}function HE(e,t){const{scale:n,values:r,format:o,cx0:s,cy0:i,vertical:a,rampLength:l,rampThickness:u,fontSize:c,swatchStroke:d,labelFill:f,handleColor:p,handleSize:h,handleStroke:y,editable:g,data:m,targetRow:b,targetRows:w,channel:x,field:S}=t,v=n.domain(),k=Math.min(...v.map(Oo)),_=Math.max(...v.map(Oo)),A=_-k||1,L=40,N=a?"y":"x",I=a?i+l:s,T=a?i:s+l,M=LE(x),$=x==="opacity"||x==="fillOpacity"||x==="strokeOpacity",F=D=>M?{fill:D}:$?{fill:f,fillOpacity:Number(D)}:{fill:"#94a3b8"};for(let D=0;D<L;D++){const P=D/L,j=(D+1)/L,G=k+(P+j)/2*A,J=typeof n.encode=="function"?n.encode(G):n(G);if(a){const re=i+(1-j)*l;e.push({type:"rect",x:s,y:re,width:u,height:l/L+.5,...F(J),stroke:"none",background:!0,pointerEvents:"none"})}else{const re=s+P*l;e.push({type:"rect",x:re,y:i,width:l/L+.5,height:u,...F(J),stroke:"none",background:!0,pointerEvents:"none"})}}e.push({type:"rect",x:s,y:i,width:a?u:l,height:a?l:u,fill:"none",stroke:d,strokeWidth:1,background:!0,pointerEvents:"none"});for(const D of r){const P=(Oo(D)-k)/A;if(!(P<-.001||P>1.001))if(a){const j=i+(1-P)*l;e.push({type:"text",x:s+u+4,y:j+c*.35,text:String(o(D)),fill:f,fontSize:c,textAnchor:"start",background:!0,pointerEvents:"none"})}else{const j=s+P*l;e.push({type:"text",x:j,y:i+u+c+2,text:String(o(D)),fill:f,fontSize:c,textAnchor:"middle",background:!0,pointerEvents:"none"})}}if(g&&b!=null){const D=S??(n.fields&&n.fields[0]||null),P=D!=null?m[b]&&m[b][D]:null,j=P==null?.5:Math.max(0,Math.min(1,(Oo(P)-k)/A)),G=a?s+u/2:s+j*l,J=a?i+(1-j)*l:i+u/2;e.push({type:"circle",cx:G,cy:J,r:h,fill:p,stroke:y,strokeWidth:1.5,index:b,indices:w,along:N,rampStart:I,rampEnd:T,loValue:k,hiValue:_,cursor:a?"ns-resize":"ew-resize"})}}const BE=(e={})=>As({...e,channel:e.channel||"fill"}),UE=(e={})=>As({...e,channel:"size"}),KE=(e={})=>As({...e,channel:"symbol"}),zc=["fill","stroke","size","symbol","opacity","theta","strokeWidth"];function YE(e){const t=(e||[]).flat(1/0).filter(r=>r&&typeof r=="object"),n=[];for(const r of t){if(r.views==="scale"||!r.channels)continue;const o=new Set(r.rawChannels||[]);for(const[s,i]of Object.entries(r.channels)){const a=i;!a||a.field==null||a.scale===null||o.has(s)||Yr(a)||n.some(l=>l.channel===s&&l.field===a.field)||n.push({channel:s,field:a.field,table:r.table,tableRole:r.tableRole,spec:a,feature:r})}}return n}function GE(e,t){const n=(e||[]).flat(1/0).filter(l=>l&&typeof l=="object"),r=YE(e),o=l=>r.filter(u=>u.channel===l),s=n.filter(l=>l.isLegend);for(const l of s){if(l.field!=null)continue;const u=o(l.channel);u.length&&(u.length>1&&ge(`legend:ambiguous:${l.channel}`,`legend({ channel: "${l.channel}" }) — "${l.channel}" carries ${u.length} encodings (${u.map(c=>`"${c.field}"`).join(", ")}), and a legend is a key for one. Name which: legend({ channel: "${l.channel}", field: "${u[0].field}" }). Using "${u[0].field}".`),l.field=u[0].field,l.table==null&&(l.table=u[0].table),l.tableRole==null&&(l.tableRole=u[0].tableRole))}const i=(l,u)=>s.find(c=>c.channel===l&&c.field===u),a=[];for(const l of r){const{channel:u,field:c,spec:d}=l,f=d.legend;if(f===!1||f===null)continue;const p=[d.edit].flat(1/0).filter(S=>S&&typeof S.apply=="function"),h=p.filter(S=>S.scope==="legend");let y;if(f!==void 0)y=f===!0?{}:f;else if(h.length)y={};else{if(!t)continue;const S=t===!0?void 0:t[u];if(S===!1||t!==!0&&S===void 0||!zc.includes(u))continue;y=S||{}}if(!zc.includes(u)){ge(`legend:channel:${u}`,`a legend was asked for on channel "${u}", which has no legend form. Legendable channels are ${zc.join(", ")}.`+(u==="x"||u==="y"?" An axis is the key for x/y.":""));continue}if(h.length){const S=p.filter(k=>k.scope!=="legend"),v={...d};S.length?v.edit=S.length===1?S[0]:S:delete v.edit,l.feature.channels[u]=v}const g=i(u,c);if(g){const S=[...h,...Di(y,u)];S.length&&(g.edits=[...g.edits||[],...Di({edits:S},u)]);for(const[v,k]of Object.entries(y))v==="edit"||v==="edits"||g[v]===void 0&&(g[v]=k);continue}const{edit:m,edits:b,...w}=y,x=As({...w,channel:u,field:c,table:l.table,edits:[...Di(y,u),...h]});x.tableRole=l.tableRole,a.push(x)}return a}function VE(e,t,n,r=8){const o={top:0,right:0,bottom:0,left:0},s=(e||[]).filter(a=>a&&a.isLegend&&typeof a.measure=="function");if(!s.length)return o;const i={top:n.top+r,right:n.right+r,bottom:n.bottom+r,left:n.left+r};for(const a of s){const l=a.anchor||"right",c=t[co(a.channel,a.field)]||t[a.channel]?a.measure(t):null;if(!c){a._place.offset=0,a._place.size=0;continue}const d=a.orient==="vertical"?c.width:c.height;a._place.offset=i[l],a._place.size=d,i[l]+=d+r,o[l]+=d+r}return o}function nt(e){return e?e.id&&!e.autoId?`"${e.id}"`:e.type?`${e.type}()`:e.id?`"${e.id}"`:"(an unnamed mark)":"(unknown mark)"}const XE={line:{flag:"supportsSeries",expects:"a line mark (line/area)"},geo:{flag:"supportsGeo",expects:"a geo* mark (geoPoint, geoLine, …)"},stack:{flag:"supportsStack",expects:"a stacked mark (bar with `stack`, or arc/donut)"},waffle:{flag:"supportsWaffle",expects:"a waffle mark"},axis:{flag:"isAxis",expects:"an axis element (axisX/axisY/axisRadial)"},trend:{flag:"supportsTrend",expects:"a trend mark (trend/trendBand)"},network:{flag:"supportsNetwork",expects:"a link mark"},legend:{flag:"isLegend",expects:"a legend element"},scale:{test:e=>e.views==="scale",expects:"an axis or legend element"}},JE={discrete:e=>e==="band"||e==="point",band:e=>e==="band",point:e=>e==="point",continuous:e=>e==="continuous"};function ZE(e,t){const n=e&&e.requires;if(Array.isArray(n))for(const r of n){const o=JE[r.kind];if(!o)continue;const s=r.channels||[],i=c=>{const d=t[c];return!!(d&&o(d.kind))};if(r.match==="any"?s.some(i):s.every(i))continue;const l=r.match==="any"?`one of ${s.map(c=>`"${c}"`).join(" / ")}`:s.map(c=>`"${c}"`).join(" and "),u=s.map(c=>{const d=t[c];return`${c}: ${d?d.kind:"no scale"}`}).join(", ");ge(`requires:${nt(e)}:${r.kind}:${s.join(",")}`,`mark ${nt(e)} needs a ${r.kind} scale on ${l}, but got ${u}. ${r.why||""} It will still draw, using fallback geometry that is not meaningful — declare the field's type on the spec's schema so the right scale resolves.`)}}function QE(e,t){for(const n of t){if(!n.scope)continue;const r=XE[n.scope];r&&((r.test?r.test(e):e[r.flag])||ge(`${nt(e)}:${n.type}`,`edit.${n.type}() is attached to a mark without ${n.scope} support (mark ${nt(e)}). ${n.scope}-scoped edits expect ${r.expects}; it may not behave.`))}}function e6(e,t){if(!t.projection)return;const n=e.filter(r=>{if(r.supportsGeo||r.views==="scale")return!1;const o=r.channels||{};return Object.keys(o).some(s=>$t(s)&&o[s]&&o[s].scale!==null)});n.length&&ge(`projcartesian:${n.map(nt).join(",")}`,`spec.projection is set together with cartesian x/y channels on ${n.map(nt).join(", ")}. Projection charts use geo* marks (geoPoint, geoLine, …); mixing ordinary positional marks is unsupported.`)}function t6(e,t,n){const r={};for(const o of e)for(const s of t(o)){if(s.pick==="direct")continue;const i=n(o,s),a=r[i]||(r[i]=[]);a.includes(o)||a.push(o)}for(const[o,s]of Object.entries(r))s.length<2||ge(`planedup:${o}:${s.map(nt).join(",")}`,`${s.length} marks carry a plane-pick edit over the same rows (marks ${s.map(nt).join(", ")}). A plane gesture fans to all of them, so a whole-dataset edit (create/remove/rotate/toggle) will apply once per mark. Declare it on exactly one.`)}function n6(e,t,n){const r=i=>t(i).filter(a=>!a.target),o=e.filter(i=>i&&i.isLegend&&r(i).length&&i.row==null);if(!o.length)return;const s=new Set(e.filter(i=>i&&i.views!=="scale"&&t(i).some(a=>a.target==="selection")).map(i=>i.table));for(const i of o)s.has(i.table)||n(i).length<=1||ge(`legend:norow:${i.channel}:${i.id}`,`${nt(i)} is a picker with no way to choose a row. Its target row defaults to the chart's SELECTION, "${i.table}" has more than one row, and no mark over that table carries edit.select(). Add one, pin a row (legend({ row: 0 })), or drive el.select(i) — otherwise clicking a swatch writes nothing.`)}function r6(e,t){if(!t.filter(o=>o.type==="network.connect"&&!o.when).length)return;const r=t.filter(o=>o.type!=="network.connect"&&o.pick==="direct"&&o.gesture==="drag"&&!o.when);r.length&&ge(`connectconflict:${nt(e)}`,`mark ${nt(e)} carries edit.network.connect() beside ${r.map(o=>`${o.type}()`).join(", ")}, and neither arbitrates with \`when\`. A plain drag fans to both: the other edit moves the source node along under the pointer, so connect finds that same node at release and creates nothing. Split them — connect({ when: when.shift }) and ${r[0].type}({ when: when.noShift }).`)}const o6=new Set(["append","appendMany","toggle"]);function ed(e){return e.target!=="domain"&&o6.has(e.cardinality)}function i6(e,t,n){for(const r of t){if(!ed(r)||e.supportsGeo)continue;const o=`${nt(e)}:nomark:${r.type}`;if(e.views==="scale"){ge(o,`a create/${r.type} edit is on ${nt(e)}, which is a chart element (axis/grid/legend), not a data mark. Creation mints dataset rows; a guide edits the DOMAIN instead (edit.axis.*). Move the create to a data mark.`);continue}const s=r.channels&&r.channels.length?r.channels:["x","y"];s.some(a=>{const l=n[a];return l&&l.invertible})||ge(o,`a create/${r.type} edit is on ${nt(e)}, but none of its positional channels (${s.join(", ")}) has an invertible scale — the pointer can't be inverted to a datum, so the create is a no-op. Creation needs a data mark on an axis.`)}}function s6(e,t,n){const r=e.channels||{},o=[];r.x1&&r.x2&&o.push(r.x1.field,r.x2.field),r.y1&&r.y2&&o.push(r.y1.field,r.y2.field);const s=o.filter(Boolean);if(s.length)for(const i of t){if(!ed(i))continue;const a=new Set(Object.keys(i.defaults||{})),l=s.filter(u=>!a.has(u)&&!(n&&n[u]&&n[u].default!==void 0));l.length&&ge(`${nt(e)}:extent:${i.type}`,`create/${i.type} on the extent mark ${nt(e)} doesn't seed ${l.join(", ")}, so a new row is minted with no extent (zero-size, invisible). Seed it via create({ defaults: { … } }) or a field default in the schema.`)}}function a6(e,t){for(const n of t)!n.pick||n.pick==="direct"||gr(n)||ge(`${nt(e)}:nopick:${n.pick}`,`${n.type}() on ${nt(e)} has pick: "${n.pick}", which names no registered driver, so no gesture will ever reach it. Built-in picks are direct, plane, nearest, probe, sweep, draw, brush, brushRect, geoBrush, axisDrag, slide; a custom one needs registerDriver().`)}function l6(e,t){for(const n of t){const r=n[w0];if(!r||!r.length)continue;const o=gr(n),s=new Set(o&&o.options?o.options:[]),i=r.filter(a=>!s.has(a));i.length&&ge(`${nt(e)}:editopt:${n.type}:${i.join(",")}`,`${n.type}() on ${nt(e)} was given ${i.map(a=>`\`${a}\``).join(", ")}, which ${i.length>1?"are":"is"} not ${i.length>1?"options":"an option"} this edit${o?` or its "${o.name}" driver`:""} reads, so ${i.length>1?"they are":"it is"} ignored.`)}}function Bp(e){return e?typeof e!="function"&&e.type?`${e.type}()`:e.name?`${e.name}()`:"(an anonymous constraint)":"(unknown)"}function c6(e){if(e===null)return"null";if(Array.isArray(e))return"an array";const t=typeof e;return t==="object"?"an object":t==="string"?`the string ${JSON.stringify(e.slice(0,20))}`:`the ${t} ${String(e)}`}function u6(e,t,n){const r=e.channels||{};for(const o of t){if(!o.inverts||ed(o)||e.supportsGeo)continue;const s=o.channels||[];if(!s.length)continue;const i=s.filter(a=>{const l=r[a];if(!l||l.field==null)return!1;const u=n[a];return u&&!u.invertible});i.length&&ge(`${nt(e)}:dead:${o.type}:${i.join(",")}`,`${o.type}() on ${nt(e)} edits channel${i.length>1?"s":""} ${i.map(a=>`"${a}"`).join(", ")}, whose scale cannot be inverted (${i.map(a=>n[a].type||"ordinal").join(", ")}). An edit runs a gesture BACKWARD through the scale, so a non-invertible channel silently does nothing. Edit a positional channel (x/y), or give the channel a continuous, band or point scale.`)}}const Up=["width","height","margins","responsive","overflow","focusOutline","marks","elements","guides","axes","legends","schema","data","constraints","lock","scales","projection","theme","effects","stage","stageLabels","onChange","renderer"],f6={mark:"did you mean `marks`? (an array of marks — plot.*)",element:"did you mean `elements`? (an array of chart elements — elements.*)",guide:"did you mean `guides`? (an array of guides — guides.*)",constraint:"did you mean `constraints`? (an array of dataset invariants)",scale:"did you mean `scales`? (per-channel scale config, keyed by channel name)",edit:"an edit goes on a mark — either on a channel (`y: { field, edit: move() }`) or in the mark's `edits: [...]`. There is no chart-level `edit`.",edits:"edits go on a MARK, not on the spec: `barY({ edits: [move()] })`.",onchange:"did you mean `onChange`? (capital C)",domain:"a domain describes the DATA, so it lives on the schema: schema: { field: { domain: [...] } }.",x:"there is no chart-level `x`. Scale config is `scales: { x: {...} }`; a field's domain is the schema's.",y:"there is no chart-level `y`. Scale config is `scales: { y: {...} }`; a field's domain is the schema's.",type:"a chart has no `type` — what it draws is its `marks`. A FIELD's type belongs on the schema; the DATASET's shape is the schema's `structure`.",title:"there is no chart-level `title`. Draw one with a `text` mark, or a widget's `question`.",container:"Elicit returns the chart element — append it yourself: `container.appendChild(Elicit(spec))`.",el:"Elicit returns the chart element; it does not take one."};function d6(e){if(!e||!ni())return;const t=new Set(Up);for(const n of Object.keys(e)){if(t.has(n))continue;const r=f6[n];ge(`spec:${n}`,r?`Elicit({ ${n}: … }): ${r}`:`Elicit({ ${n}: … }) is not a key the chart reads, so it is ignored. Spec keys are: ${Up.slice().sort().join(", ")}.`)}}function h6(e,t){const n=t||{},r=e.opacity!=null?e.opacity:1;e.opacity=r*(n.opacity!=null?n.opacity:.45),n.fill!=null&&(e.fill=n.fill),n.stroke!=null&&(e.stroke=n.stroke),n.strokeDasharray!=null&&(e.strokeDasharray=n.strokeDasharray)}function eb(e){d6(e);const{width:t=600,height:n=400,margins:r={top:20,right:20,bottom:30,left:40},marks:o=[],elements:s=[],axes:i,legends:a,guides:l=[],effects:u,responsive:c,overflow:d="hidden",focusOutline:f=!1,renderer:p=new U0}=e,h=c===!0?"reflow":c==="scale"||c==="reflow"?c:"fixed",y=Bf(e.theme),g=f5(u,y.effects),m=[...s,...o],b=e.projection!=null&&i===void 0?!1:i,w=[...IE(m,b),...m,...GE(m,a)].flat(1/0),x=w.some(E=>E&&E.isLegend),S=typeof t=="number"?t:600,v=typeof n=="number"?n:400;let k=S,_=v;const A=r;let L={...A},N=k-L.left-L.right,I=_-L.top-L.bottom;w.forEach((E,R)=>{E.id||(E.id=`feature-${R}`,E.autoId=!0)});const T=RM(structuredClone(e.schema||{})),M=T.tables[T.primary].fields;let $=xp(structuredClone(e.data??null),T);const F=E=>$[E.table]||[],D=(E,R)=>R&&R.table&&T.byRole[R.table]||E.table,P=()=>$[T.primary],j=()=>ga(T)?P():$;w.forEach(E=>{const R=E.table;R!=null&&!T.tables[R]&&ge(`${nt(E)}:table:${R}`,`mark ${nt(E)} draws table "${R}", which the schema does not declare. Declared tables: ${Object.keys(T.tables).map(K=>`"${K}"`).join(", ")}. Falling back to "${T.primary}".`),E.table=R!=null&&T.tables[R]?R:T.byRole[E.tableRole]||T.primary});const G=T.byRole.nodes||null;for(let E=0;E<w.length;E++){const R=w[E],K=R&&!R.portHost&&R.views!=="scale"&&R.channels&&R.channels.ports;if(!K)continue;if(delete R.channels.ports,typeof R.nodeBox!="function"){ge(`${nt(R)}:ports:box`,`mark ${nt(R)} has a \`ports\` channel, but it does not declare the box it draws, so there is no edge to put a port on. Put \`ports\` on a mark that draws a node shape: point, rect, ellipse, text, sticker, node, face, or a composite.`);continue}if(!G||R.table!==G){ge(`${nt(R)}:ports:table`,`mark ${nt(R)} has a \`ports\` channel, but it draws table "${R.table}", which is not a network's nodes table. Ports are where links meet NODES: declare schema: { structure: "network", … } and put \`ports\` on the mark drawing the nodes.`);continue}let X=E+1;for(;R.glyph&&X<w.length&&w[X]&&w[X].glyph===R.glyph;)X++;w.splice(X,0,I5(R,K))}const J=w.filter(E=>E&&E.portHost&&E.table===G);J.length>1&&ge("ports:hosts",`${J.length} marks draw ports over the "${G}" table; only the first (${nt(J[0].portHost)}) decides where links may meet a node. Put \`ports\` on one mark.`);const re=J[0]||null,Q=G?w.filter(E=>E&&E.views!=="scale"&&E.table===G&&typeof E.nodeBox=="function"):[],ve=re?re.portHost:Q.find(E=>!E.labelBox)||Q[0]||null;let Ce=null,le=[];const be=()=>{if(!ve)return null;const E=[tt,N,I];if(!Ce||E.some((R,K)=>R!==le[K])){const R=tt,K=N,X=I;Ce=(ne,fe,ye)=>ve.nodeBox(ne,fe,ye,R,K,X),le=E}return Ce},ce=re?(E,R,K)=>N0(pt(re.channels,"ports",E,!1,R,K),ks(T)):null,Y={},ue=E=>{if(E in Y)return Y[E];const R=w.filter(X=>X&&X.views!=="scale"&&!X.portHost&&X.table===E&&X.channels),K=(X,ne)=>X.channels[ne]&&X.channels[ne].field||null;for(const X of["source","target","sourceSide","targetSide"]){const ne=new Set(R.map(fe=>K(fe,X)).filter(Boolean));ne.size>1&&ge(`viewers:${E}:${X}`,`marks drawing table "${E}" name different columns for \`${X}\` (${[...ne].map(fe=>`"${fe}"`).join(", ")}). An edit writing that table uses the first. Name the column on one mark, or the same column on each.`)}return Y[E]=R.length?R[0].channels:null,Y[E]};let ie={};for(const E of Object.keys($))ie[E]=$[E].length;const U={},we={},xe=E=>(E in U||(U[E]=QM(e.lock,()=>ie[E]||0,E)),U[E]),z=E=>{if(!(E in we)){const R=xe(E);we[E]=R?e5(R):null}return we[E]};Lc(T,$);const H={...e,schema:M,schemaSpec:T,theme:y},oe={},de=(E,R)=>{const K=oe[R]||(oe[R]=[]);K.includes(E)||K.push(E)};for(const E of e.constraints||[]){const R=E.table;de(E,R&&(T.byRole[R]||T.tables[R]&&R)||T.primary)}const ke=E=>oe[E]||[],he=ke(T.primary),$e=[...mE(w),...l];let Te=e.stage!=null?e.stage:0;const Se=Array.isArray(e.stageLabels)?e.stageLabels:[],ae=E=>Se[E]!=null?Se[E]:null,_e=E=>ma(E).filter(R=>R.stage==null||R.stage===Te),ze=E=>{Te=E,Z.session={},Z.preview=null,Z.hover=null,Z.grab=null,Z.selection.clear();for(const R of qt.stage)R(Te,ae(Te))},Z={session:{},preview:null,selection:new Set,hover:null,grab:null};let vt=!1;const rt=E=>E?`${E.index}\0${E.channel??""}\0${E.side??""}\0${E.vertexIndex??""}`:"",dt=(E,R)=>`${E}\0${R}`,gt=E=>{const R=E.indexOf("\0");return{table:E.slice(0,R),index:Number(E.slice(R+1))}},Wt=E=>{const R=new Set;for(const K of Z.selection){const X=gt(K);X.table===E&&R.add(X.index)}return R},At=()=>{for(const E of Wt(T.primary))if(E>=0&&E<P().length)return E;return null},Jt=(E=T.primary)=>{const R=($[E]||[]).length;return[...Wt(E)].filter(K=>K>=0&&K<R).sort((K,X)=>K-X)},qt={change:new Set,stage:new Set,select:new Set,gesture:new Set},Zn=100;let C=[],W=[],q=null,V=[];const ee=()=>({tables:structuredClone($),schema:structuredClone(M),width:k,height:_}),pe=E=>{$=structuredClone(E.tables);for(const R of Object.keys(M))delete M[R];Object.assign(M,structuredClone(E.schema)),(E.width!==k||E.height!==_)&&Rt({width:E.width,height:E.height}),Z.preview=null},me=()=>{q||(q={recorded:!1,before:null,edits:[]})},Oe=(E=!1)=>{const R=q;q=null,E&&R&&R.recorded&&Ht(R),V.length&&y1()},Je=()=>{if(q||me(),!q||q.recorded)return;const E=ee();C.push(E),C.length>Zn&&C.shift(),W=[],q.before=E.tables,q.recorded=!0},Ht=E=>{if(!qt.gesture.size)return;const R=new Set,K=E.edits.filter(fe=>{const ye=`${fe.type}\0${fe.name??""}\0${fe.table}`;return R.has(ye)?!1:(R.add(ye),!0)}),X=fe=>ga(T)?fe[T.primary]:fe,ne={edits:K,before:structuredClone(X(E.before)),after:structuredClone(j())};for(const fe of qt.gesture)fe(ne)},wt=()=>{e.onChange&&e.onChange(j());for(const E of qt.change)E(structuredClone(j()))},ct=()=>{const E=At(),R=ga(T)?[...Wt(T.primary)]:[...Z.selection].map(gt);for(const K of qt.select)K(E,R)},Pn=(E,R=T.primary)=>{const K=[...Z.selection].join(",");An(E,R);const X=[...Z.selection].join(",");return K===X?!1:(ct(),!0)},An=(E,R=T.primary)=>{if(E.clear||E.index==null){Z.selection.clear();return}const K=dt(R,E.index),X=Z.selection.has(K);if(E.exclusive!==!1){const ne=X&&Z.selection.size===1;if(Z.selection.clear(),E.toggle&&ne)return}else if(E.toggle&&X){Z.selection.delete(K);return}Z.selection.add(K)},Bt={},Ut=(E,R,K)=>{let X=R&&R.frame?R:null;return!X&&K!=null&&E&&(X=(Bt[E.id]||[]).find(ne=>ne&&ne.index===K&&ne.frame)||null),X?{...tt,...X.frame}:null},It={width:N,height:I};let tt=Fc(w,$,H,It);const Ge=document.createElement("div");Ge.style.position="relative",h==="scale"?(Ge.style.width="100%",Ge.style.height="auto"):h==="reflow"?(Ge.style.width="100%",Ge.style.height=`${_}px`):(Ge.style.width=`${k}px`,Ge.style.height=`${_}px`);const Pr=()=>{N=k-L.left-L.right,I=_-L.top-L.bottom,It.width=N,It.height=I},Dr=()=>{if(h!=="reflow")return!1;const E=Ge.clientWidth||S;return E>0&&E!==k?(k=E,Pr(),!0):!1},Qn=new Cw,on=()=>{if(Dr(),Qn.clear(),x){L={...A},Pr();const te=Fc(w,$,H,It);te.theme=y;const Ae=VE(w,te,A);L={top:A.top+Ae.top,right:A.right+Ae.right,bottom:A.bottom+Ae.bottom,left:A.left+Ae.left},Pr()}tt=Fc(w,$,H,It);const E=u0(H.projection,It);E&&(tt.projection=E),tt.theme=y,tt.selection=At(),tt.selectionAll=Jt,tt.schema=M,e6(w,tt);const R=w.some(te=>hE(_e(te)));let K="pointer";if(R&&Z.session)for(const te of Object.keys(Z.session)){const Ae=Z.session[te]&&Z.session[te].cursor;if(Ae){K=Ae;break}}t6(w,_e,D),n6(w,_e,F);const X=[];if(w.forEach(te=>{const Ae=F(te),Ie=xe(te.table),Le=te.build(Ae,tt,N,I,{tables:$,schema:T,table:te.table,nodeBox:be(),nodePorts:ce});Bt[te.id]=Le;const Ne=ma(te);ZE(te,tt),QE(te,Ne),r5(te,nt),i6(te,Ne,tt),s6(te,Ne,H.schema),u6(te,Ne,tt),r6(te,Ne),a6(te,Ne),l6(te,Ne);const _t=_e(te).some(We=>We.pick==="direct"),Mt=_e(te).find(We=>We.inline),Ot=Mt?(Ei(Mt.channels,te.channels||{},tt,te)[0]||{}).field:null;Le.forEach(We=>{We.featureId=te.id;const mt=Ie&&t5(We,te,Ae,Ie);if(mt&&(We.locked=!0),_t&&!mt?We.editable=!0:We.pointerEvents==null&&(We.pointerEvents="none"),Mt&&!mt&&(We.editText=!0,Mt.multiline&&(We.multiline=!0),Ot!=null&&We.data)){const bt=We.data[Ot];bt!=null&&(We.editValue=String(bt))}}),X.push({glyph:te.glyph,nodes:Le})}),Qd(X).forEach(te=>Qn.add(te)),Z.preview){const te=Object.values(Z.preview),Ae=te.length===1?te[0]:null,Ie=[];for(const Le of w){if(Le.views==="scale")continue;const Ne=Z.preview[Le.id]||Ae;if(!Ne||Ne.table!==Le.table)continue;const _t=Ne.rows,Mt=F(Le),Ot=new Set;let We=_t.length!==Mt.length;const mt=Math.max(_t.length,Mt.length);for(let Ke=0;Ke<mt;Ke++)_t[Ke]!==Mt[Ke]&&(Ot.add(Ke),We=!0);if(!We)continue;const Pe=Le.build(_t,tt,N,I,{tables:{...$,[Ne.table]:_t},schema:T,table:Le.table,ghost:{pointer:Ne.pointer},nodeBox:be(),nodePorts:ce}).filter(Ke=>(Ke.index!=null?Ot.has(Ke.index):We)?(Ke.ghost=!0,Ke.featureId=Le.id,Ke.editable=!1,Ke.pointerEvents="none",h6(Ke,y.ghost),!0):!1);Ie.push({glyph:Le.glyph,nodes:Pe})}Qd(Ie).forEach(Le=>Qn.add(Le))}const ne={scales:tt,data:P(),tableOf:F,constraintsIn:ke,constraints:he,features:w,featureNodes:Bt,ui:Z,effects:g,theme:y,width:N,height:I,stage:Te};$e.forEach(te=>{(te.build(ne.data,tt,N,I,ne)||[]).forEach(Ie=>{Ie.guide=!0,Qn.add(Ie)})});const fe={},ye={},Me=te=>{if(!te||te.index==null)return;const Ae=w.find(Ie=>Ie.id===te.featureId);!Ae||Ae.table==null||(ye[Ae.table]||(ye[Ae.table]=new Set)).add(te.index)};Me(Z.hover),Me(Z.grab),vt=!1;let Ee=null;for(const te of Object.values(Z.session||{}))if(te&&Array.isArray(te.targets)){Ee=Ee||new Set;for(const Ae of te.targets)Ee.add(Ae)}for(const te of w){if(te.views==="scale")continue;const Ae=fe[te.table]||(fe[te.table]=Wt(te.table)),Ie=Bt[te.id]||[],Le=new Set,Ne=Z.session&&Z.session[te.id],_t=Ne?Ne.activeIndex!=null?Ne.activeIndex:Ne.hoverIndex:null;_t!=null&&Le.add(_t),Z.hover&&Z.hover.featureId===te.id&&Z.hover.index!=null&&Le.add(Z.hover.index);for(const Pe of Ae)Le.delete(Pe);const Mt=new Set;Z.grab&&Z.grab.featureId===te.id&&Z.grab.index!=null&&Mt.add(Z.grab.index);const Ot=[[Le,g.hovered],[Ae,g.selected],[Mt,g.grabbed]],We=new Map;for(const[Pe,Ke]of Ot)for(const zt of Pe){const Pt=We.get(zt)||[];Pt.push(Ke),We.set(zt,Pt)}for(const Pe of Ie){if(!Pe||Pe.ghost||Pe.index==null)continue;const Ke=d5(We.get(Pe.index)||[]);Ke&&(Pe.effectStyle=Ke)}const mt=ye[te.table];for(const Pe of Ie){if(!Pe||Pe.ghost||!Pe.onHover||Pe.index==null)continue;vt=!0;const Ke=Pe.index,zt=mt&&mt.has(Ke)||Le.has(Ke)||Ae.has(Ke)||Mt.has(Ke)||_t===Ke;let Pt=zt;Pe.portRole&&(Ee?Pt=!!Ne&&Ne.fromIndex===Ke&&Ne.fromSide===Pe.side||Ee.has(Gf(te.table,Ke,Pe.side)):Pt=zt&&Pe.portRole!=="in"&&Ls(te,Pe)),Pt||(Pe.effectStyle={...Pe.effectStyle||{},opacity:0},Pe.pointerEvents="none")}const bt=Z.hover&&Z.hover.featureId===te.id&&Z.hover.node&&Z.hover.node.channel!=null?Ie.find(Pe=>Pe&&rt(Pe)===rt(Z.hover&&Z.hover.node)):null;for(const[Pe,Ke]of Ot){if(!Pe.size)continue;let zt;if(Ke===g.hovered&&bt&&Pe.has(bt.index)){const Pt=new Set(Pe);Pt.delete(bt.index),zt=[...qf(bt,Ke),...Sp(Ie,Pt,Ke)]}else zt=Sp(Ie,Pe,Ke);zt.forEach(Pt=>{Pt.guide=!0,Qn.add(Pt)})}}p.render({container:Ge,scene:Qn,width:k,height:_,margins:L,scales:tt,spec:e,planeOnTop:R,planeCursor:K,responsive:h,overflow:d,focusOutline:f,effects:g,theme:y,onEvent:Id})},Ue=(E,R,K,X,ne=!1,fe=void 0)=>{const ye=F(E),Me=D(E,R),Ee=$[Me]||[],te=E.channels||{},Ae=Ut(E,K.node,X)||tt,Ie=Ei(R.channels,te,Ae,E),Le={data:Ee,datum:X!=null?ye[X]:void 0,index:X,tables:$,table:Me,pointer:{x:K.x,y:K.y},node:K.node||null,event:K.rawEvent,value:K.value,channels:Ie,scales:Ae,markChannels:te,projection:tt.projection||null,width:N,height:I,margins:L,schema:(T.tables[Me]||T.tables[T.primary]).fields,schemaSpec:T,xKey:E.xKey||"x",yKey:E.yKey||"y",seriesKey:E.seriesKey||null,marks:Bt[E.id]||[],connect:E.connect||null,session:fe!==void 0?fe:Z.session&&Z.session[E.id]||null,nodeBox:be(),nodePorts:ce,targetChannels:Me!==E.table?ue(Me):null,selection:At(),edit:R,preview:ne};if(R.when&&!R.when(Le))return null;const Ne=R.apply(Le);if(Ne===void 0)return null;const _t=mt=>R.cardinality==="append"?mt.length-1:R.cardinality==="delete"?null:X,Mt=(mt,bt=Me)=>{const Pe=bt===Me,Ke=z(bt),zt=[...ke(bt),...Pe?R.constrain:[],...Ke?[Ke]:[]],Pt={activeIndex:Pe?_t(mt):null,scales:tt,markChannels:te,field:Pe&&Ie[0]?Ie[0].field:void 0,tables:$,table:bt};let Ps=mt;const g1=Pe?Ee:$[bt]||[];for(const uc of zt){const bo=JM(uc,Ps,g1,Pt);if(bo===!1)return null;if(!(bo===!0||bo===void 0)){if(!Array.isArray(bo)){ge(`constraint:return:${Bp(uc)}`,`constraint ${Bp(uc)} returned ${c6(bo)}; a constraint must return the repaired rows (an array), false to reject the edit, or true/undefined to accept it unchanged. Ignoring the return value.`);continue}Ps=bo}}return Ps};if(R.target==="domain"){if(!(Ne&&typeof Ne=="object"&&Ne.domains))return null;const mt={...Ne};if(Array.isArray(Ne.data)){const bt=Mt(Ne.data);if(!bt)return null;mt.data=bt}if(Ne.tables){const bt={};for(const[Pe,Ke]of Object.entries(Ne.tables)){const zt=Ke;if(!Array.isArray(zt.data)){bt[Pe]=zt;continue}const Pt=Mt(zt.data,Pe);if(!Pt)return null;bt[Pe]={...zt,data:Pt}}mt.tables=bt}return{kind:"domain",result:mt}}if(R.target==="selection")return Ne&&typeof Ne=="object"&&"index"in Ne?{kind:"selection",selection:Ne}:null;const Ot=Array.isArray(Ne)?Ne:Ee.map((mt,bt)=>bt===X?Ne:mt),We=Mt(Ot);return We?{kind:"rows",rows:We}:null},Tt=(E,R,K,X)=>{const ne=Ue(E,R,K,X);return ne?(q&&ne.kind!=="selection"&&q.edits.push({type:R.type,name:R.name,table:D(E,R)}),ne.kind==="domain"?Zt(ne.result,D(E,R)):ne.kind==="selection"?Pn(ne.selection,D(E,R)):(Je(),$[D(E,R)]=ne.rows,Ic(T,$),Z.preview=null,wt(),!0)):!1},Zt=(E,R=T.primary)=>{Je();const K={[R]:{domains:E.domains,data:E.data}};for(const[ne,fe]of Object.entries(E.tables||{})){if(!T.tables[ne]){ge(`domain:table:${ne}`,`a domain edit names table "${ne}", which the schema does not declare. Declared tables: ${Object.keys(T.tables).map(Me=>`"${Me}"`).join(", ")}.`);continue}const ye=K[ne];K[ne]=ye?{domains:{...ye.domains,...fe.domains},data:fe.data??ye.data}:fe}let X=!1;for(const[ne,fe]of Object.entries(K)){const ye=(T.tables[ne]||T.tables[T.primary]).fields;for(const[Me,Ee]of Object.entries(fe.domains||{})){const te=ye[Me];ye[Me]={...te||{type:l0(Ee)},domain:Ee}}Array.isArray(fe.data)&&($[ne]=fe.data,X=!0)}return X&&Ic(T,$),E.resize&&Rt(E.resize),Z.preview=null,wt(),!0},Rt=E=>{typeof E.width=="number"&&E.width>0&&(k=E.width),typeof E.height=="number"&&E.height>0&&(_=E.height),h==="fixed"?(Ge.style.width=`${k}px`,Ge.style.height=`${_}px`):h==="reflow"&&(Ge.style.height=`${_}px`),Pr()},sn=(E,R,K,X)=>{const ne=Ue(E,R,K,X,!0);if(!ne||ne.kind!=="rows")return!1;const fe=ne.rows;return Z.preview||(Z.preview={}),Z.preview[E.id]={table:D(E,R),rows:fe,pointer:typeof K.x=="number"&&typeof K.y=="number"?{x:K.x,y:K.y}:void 0},!0},er=(E,R,K,X,ne)=>{if(typeof R.targets!="function")return null;const fe=D(E,R),ye={scales:tt,schemaSpec:T,tables:$,table:fe,data:$[fe]||[],nodeBox:be(),nodePorts:ce,width:N,height:I,node:X||null,edit:R,pointer:{x:0,y:0},index:K,datum:K!=null?F(E)[K]:void 0,markChannels:E.channels||{}},Me=[],Ee=R.targets(ye);if(!Ee)return null;for(const te of Ee)Ue(E,R,{x:te.x,y:te.y,node:X},K,!1,ne)!==null&&Me.push(te.key);return Me},po=new Map;let yo=[];const Ls=(E,R)=>{const K=Object.keys($).map(Me=>$[Me]);(K.length!==yo.length||K.some((Me,Ee)=>Me!==yo[Ee]))&&(po.clear(),yo=K);const X=`${E.id}\0${R.index}\0${R.side}`,ne=po.get(X);if(ne!==void 0)return ne;let fe=!1;const ye={...Z.session&&Z.session[E.id]||{},fromIndex:R.index,fromSide:R.side,fromPoint:null};for(const Me of _e(E)){const Ee=er(E,Me,R.index,R,ye);if(Ee&&Ee.length){fe=!0;break}}return po.set(X,fe),fe},cc=(E,R)=>{const K=R.node?R.node.index:void 0;if(K==null)return!1;let X=!1;const ne=_e(E).filter(ye=>ye.pick==="direct"&&(!R.editName||ye.name===R.editName)),fe=ne.filter(ye=>gr(ye));return fe.length&&Fs(E,R,fe,K)&&(X=!0),ne.filter(ye=>ye.gesture===R.type&&!gr(ye)).forEach(ye=>{Tt(E,ye,R,K)&&(X=!0)}),X},Fs=(E,R,K,X)=>{if(K.length===0)return!1;const ne=E.id,fe=(Ie,Le)=>Tt(E,Ie,R,Le),ye=(Ie,Le)=>sn(E,Ie,R,Le),Me={get:()=>Z.preview&&Z.preview[ne]||null,clear:()=>!Z.preview||!Z.preview[ne]?!1:(delete Z.preview[ne],Object.keys(Z.preview).length===0&&(Z.preview=null),!0)},Ee={get:()=>Te,set:Ie=>ze(Ie),next:()=>ze(Te+1)},te=new Map;for(const Ie of K){const Le=gr(Ie);if(!Le)continue;const Ne=te.get(Le)||[];Ne.push(Ie),te.set(Le,Ne)}let Ae=!1;for(const Ie of Ro){const Le=te.get(Ie);if(!Le)continue;const Ne=Ie.sessionKeys||[],_t={get:()=>Z.session&&Z.session[ne]||null,set:Ot=>{Z.session=Z.session||{},Z.session[ne]={...Z.session[ne]||{},...Ot}},clear:()=>{if(!Z.session||!Z.session[ne])return;const Ot={};for(const We of Ne)Ot[We]=null;Z.session[ne]={...Z.session[ne],...Ot}}},Mt={feature:E,event:R,edits:Le,marks:Bt[ne]||[],data:F(E),scales:tt,index:X??null,session:_t,preview:Me,stage:Ee,runEdit:fe,previewEdit:ye,reachable:(Ot,We,mt)=>er(E,Ot,We,mt!==void 0?mt:R.node)};Ie.onEvent(Mt)&&(Ae=!0)}return Ae},Rs=(E,R)=>Fs(E,R,_e(E).filter(K=>K.pick!=="direct"),null),Id=E=>{let R=!1;if(E.type==="pointerover"||E.type==="pointerout"){const K=E.node,X=E.type==="pointerover"&&K&&K.index!=null?{featureId:K.featureId,index:K.index,node:K}:null,ne=(ye,Me)=>!ye&&!Me||!!(ye&&Me&&ye.featureId===Me.featureId&&ye.index===Me.index&&rt(ye.node)===rt(Me.node));if(!(E.type==="pointerout"&&Z.hover&&K&&!ne(Z.hover,{featureId:K.featureId,index:K.index,node:K}))&&!ne(Z.hover,X)){Z.hover=X;const ye=g.hovered;ye&&ye.enabled!==!1&&(ye.outline||Pu(ye))&&(R=!0),vt&&(R=!0)}R&&on();return}if(E.type==="nudge"){const K=E.node,X=Rn(K);if(!X)return;const ne=w.find(Ae=>Ae.id===K.featureId),fe=ne&&ne.channels||{},ye=K.index!=null?(ne?F(ne):[])[K.index]:K.data,Me=Ut(ne,K,K.index)||tt,Ee=ye?se(Me,fe,"x",ye,X.cx):X.cx,te=ye?se(Me,fe,"y",ye,X.cy):X.cy;E={type:"drag",node:K,x:zu(Me.x,Ee,E.dx,E.coarse),y:zu(Me.y,te,E.dy,E.coarse),nudge:!0,rawEvent:E.rawEvent}}if(E.type==="dragstart"?(Oe(!0),me()):q||me(),E.type==="dragstart"||E.type==="dragend"){const K=E.type==="dragstart"&&E.node&&E.node.index!=null?{featureId:E.node.featureId,index:E.node.index}:null,X=!!Z.grab!=!!K||!!(Z.grab&&K&&(Z.grab.featureId!==K.featureId||Z.grab.index!==K.index));Z.grab=K;const ne=g.grabbed;X&&ne&&ne.enabled!==!1&&(ne.outline||Pu(ne))&&(R=!0)}if(E.node){const K=w.find(X=>X.id===E.node.featureId);K&&cc(K,E)&&(R=!0)}else w.forEach(K=>{Rs(K,E)&&(R=!0)});(E.type==="dragend"||E.nudge||E.type!=="dragstart"&&E.type!=="drag")&&Oe(!0),R&&on()},Ze=Ge;Ze.getData=()=>structuredClone(j()),Ze.getSchema=()=>structuredClone(zM(T)),Ze.setData=E=>{$=xp(structuredClone(E??null),T),Lc(T,$,"setData()"),ie={};for(const R of Object.keys($))ie[R]=$[R].length;Z.preview=null,Z.hover=null,Z.grab=null,Z.selection.clear(),C=[],W=[],V=[],Oe(),on()};const Ld=E=>{const R=T.tables[E];if(!R)throw new Error(`patch(): there is no table named "${E}".`);const K=Object.entries(R.fields),X=K.filter(([,fe])=>fe&&fe.key).map(([fe])=>fe);if(X.length)return X;const ne=K.filter(([,fe])=>fe&&fe.type==="ref").map(([fe])=>fe);if(ne.length)return ne;throw new Error(`patch(): table "${E}" has no key field (\`key: true\`) and no \`ref\` fields, so its rows cannot be addressed.`)},tr=(E,R)=>JSON.stringify(E.map(K=>R?R[K]:void 0)),d1=(E,R)=>Array.isArray(R)?JSON.stringify(R):R!=null&&typeof R=="object"?tr(E,R):JSON.stringify([R]),h1=E=>Object.entries(E||{}).map(([R,K])=>{const X=Ld(R);return{name:R,fields:X,insert:K.insert||[],update:K.update||[],remove:new Set((K.remove||[]).map(ne=>d1(X,ne)))}}),Fd=(E,R,K)=>{for(const X of R){let ne=E[X.name]||[];X.remove.size&&(ne=ne.filter(ye=>!X.remove.has(tr(X.fields,ye))));const fe=new Map(ne.map((ye,Me)=>[tr(X.fields,ye),Me]));for(const ye of X.update){const Me=tr(X.fields,ye),Ee=fe.get(Me);if(Ee===void 0){K&&K.missing.push({table:X.name,key:JSON.parse(Me)});continue}ne[Ee]={...ne[Ee],...structuredClone(ye)},K&&K.updated++}for(const ye of X.insert){const Me=tr(X.fields,ye);if(fe.has(Me)){K&&K.conflicts.push({table:X.name,key:JSON.parse(Me)});continue}fe.set(Me,ne.length),ne.push(structuredClone(ye)),K&&K.inserted++}E[X.name]=ne}Ic(T,E)},Rd=(E,R)=>{const K=[...Z.selection].map(gt).map(({table:Ee,index:te})=>{const Ae=T.tables[Ee]?p1(Ee):null;return{table:Ee,key:Ae?tr(Ae,($[Ee]||[])[te]):null,fields:Ae}}),X={};for(const Ee of E)X[Ee.name]=new Set(($[Ee.name]||[]).slice(0,ie[Ee.name]||0).map(te=>tr(Ee.fields,te)));const ne=Object.fromEntries(Object.entries($).map(([Ee,te])=>[Ee,te.length]));R==="record"&&(C.push(ee()),C.length>Zn&&C.shift(),W=[]);const fe={inserted:0,updated:0,removed:0,missing:[],conflicts:[]};if(Fd($,E,fe),Lc(T,$,"patch()"),R==="keep")for(const Ee of[...C,...W])Fd(Ee.tables,E);let ye=0;for(const Ee of new Set([...Object.keys(ne),...Object.keys($)]))ye+=(ne[Ee]||0)-($[Ee]||[]).length;fe.removed=ye+fe.inserted;for(const Ee of E)ie[Ee.name]&&(ie[Ee.name]=($[Ee.name]||[]).filter(te=>X[Ee.name].has(tr(Ee.fields,te))).length);const Me=[...Z.selection].join("|");Z.selection.clear();for(const{table:Ee,key:te,fields:Ae}of K){if(te==null||!Ae)continue;const Ie=($[Ee]||[]).findIndex(Le=>tr(Ae,Le)===te);Ie>=0&&Z.selection.add(dt(Ee,Ie))}return Z.preview=null,Z.hover=null,wt(),[...Z.selection].join("|")!==Me&&ct(),on(),fe},p1=E=>{try{return Ld(E)}catch{return null}},y1=()=>{const E=V;V=[];for(const R of E)Rd(R.plan,R.history)};Ze.patch=(E,R={})=>{const K=R.history??"keep";if(K!=="keep"&&K!=="record")throw new Error(`patch(): history is "keep" or "record", not "${K}".`);const X=h1(E);return q&&(V.length||X.some(ne=>ne.remove.size))?(V.push({plan:X,history:K}),{deferred:!0}):Rd(X,K)},Ze.getSelection=()=>At(),Ze.getSelectionAll=()=>Jt();const zs=E=>{const R=Pn(E);return R&&on(),R};Ze.select=E=>{const R=P(),K=ne=>typeof ne=="number"&&ne>=0&&ne<R.length;if(Array.isArray(E)){const ne=E.filter(K);if(!ne.length)return zs({index:null,clear:!0});const fe=[...Z.selection].join(",");An({index:ne[0],exclusive:!0,toggle:!1});for(const ye of ne.slice(1))An({index:ye,exclusive:!1,toggle:!1});return[...Z.selection].join(",")===fe?!1:(ct(),on(),!0)}const X=K(E)?E:null;return zs({index:X,exclusive:!0,toggle:!1,clear:X==null})},Ze.toggleSelection=E=>zs({index:E,exclusive:!1,toggle:!0}),Ze.selectAll=()=>Ze.select(P().map((E,R)=>R)),Ze.selectWhere=(E,R,K)=>{const X=typeof E=="function"?E:ye=>ye&&ye[E]===R,ne=P();if(K&&K.all){const ye=ne.map((Me,Ee)=>X(Me,Ee)?Ee:-1).filter(Me=>Me>=0);return Ze.select(ye.length?ye:null)}const fe=ne.findIndex(X);return Ze.select(fe<0?null:fe)},Ze.clearSelection=()=>zs({index:null,clear:!0}),Ze.emit=E=>Id(E);const go=E=>{let R=null;const K=new Set;for(const X of w)for(const ne of ma(X))ne.name===E&&(K.add(ne.apply),R||(R={feature:X,edit:ne}));return K.size===0&&ge(`control:none:${E}`,`el.control("${E}"): no edit is named "${E}".`),K.size>1&&ge(`control:many:${E}`,`el.control("${E}"): ${K.size} different edits share the name "${E}"; driving the first.`),R},mo=(E,R)=>(Bt[E.id]||[]).find(K=>K&&K.index===R)||null;Ze.control=(E,R=0)=>{const K=(fe,ye,Me)=>{const Ee=mo(fe,R),te=Rn(Ee),Ae=P()[R],Ie=fe.channels||{},Le=Ut(fe,Ee,R)||tt;let Ne=Ae?se(Le,Ie,"x",Ae,te?te.cx:0):te?te.cx:0,_t=Ae?se(Le,Ie,"y",Ae,te?te.cy:0):te?te.cy:0;const Mt=Ei(ye.channels,Ie,Le,fe),Ot=We=>Me!=null&&typeof Me=="object"&&!(Me instanceof Date)?We.name in Me?Me[We.name]:We.field!=null&&We.field in Me?Me[We.field]:void 0:Me;for(const We of Mt){if(!We.scale||!We.scale.invertible)continue;const mt=Ot(We);if(mt===void 0)continue;const bt=We.scale.encode(mt),Pe=AM(We.name,bt,te);if(!Pe)continue;const Ke=$t(We.name);Ke!=="y"&&(Ne=Pe.x),Ke!=="x"&&(_t=Pe.y)}return{node:Ee,x:Ne,y:_t}};let X=!1;return{set(fe){const ye=go(E);if(!ye)return;const{feature:Me,edit:Ee}=ye,te=mo(Me,R);if(Ee.gesture==="commit"){Ze.emit({type:"commit",node:te,value:fe,editName:E,x:te?te.cx:0,y:te?te.cy:0});return}const{node:Ae,x:Ie,y:Le}=K(Me,Ee,fe);Ze.emit(X?{type:"drag",node:Ae,x:Ie,y:Le,editName:E}:{type:"drag",node:Ae,x:Ie,y:Le,nudge:!0,editName:E})},begin(){const fe=go(E);fe&&(X=!0,Ze.emit({type:"dragstart",node:mo(fe.feature,R),editName:E}))},end(){const fe=go(E);X=!1,fe&&Ze.emit({type:"dragend",node:mo(fe.feature,R),editName:E})},fire(fe){const ye=go(E);if(!ye)return;const Me=fe||ye.edit.gesture||"click";Ze.emit({type:Me,node:mo(ye.feature,R),editName:E})},emit(fe){const ye=go(E);Ze.emit({node:ye?mo(ye.feature,R):void 0,...fe})},accepts(){const fe=go(E);if(!fe)return null;const{feature:ye,edit:Me}=fe,Ee=Ut(ye,null,R)||tt,te=Ei(Me.channels,ye.channels||{},Ee,ye)[0],Ae=te&&te.scale,Ie=M&&te&&te.field&&M[te.field]||null,Le=Ie&&Ie.type||null,Ne=(Ae&&typeof Ae.domain=="function"?Ae.domain():null)||Ie&&Ie.domain||null,_t=Ae&&typeof Ae.range=="function"?Ae.range():null;return{field:te?te.field:null,type:Le,kind:Ae?Ae.kind:null,temporal:!!(Ae&&Ae.temporal),invertible:!!(Ae&&Ae.invertible),domain:Ne,values:Ae&&(Ae.kind==="band"||Ae.kind==="discrete"||Ae.kind==="point")||Le==="categorical"||Le==="ordinal"?Ne:null,range:_t}}}},Ze.canUndo=()=>C.length>0,Ze.canRedo=()=>W.length>0,Ze.undo=()=>C.length?(W.push(ee()),pe(C.pop()),Oe(),wt(),on(),!0):!1,Ze.redo=()=>W.length?(C.push(ee()),pe(W.pop()),Oe(),wt(),on(),!0):!1,Ze.on=(E,R)=>(qt[E].add(R),()=>qt[E].delete(R)),Ze.getStage=()=>Te,Ze.getStageLabel=()=>ae(Te),Ze.setStage=E=>{ze(E),on()},Ze.nextStage=()=>Ze.setStage(Te+1);let li=null;if(h==="reflow"&&typeof ResizeObserver<"u"){let E=!1;li=new ResizeObserver(()=>{E||(E=!0,requestAnimationFrame(()=>{E=!1,Dr()&&on()}))}),li.observe(Ge)}return Ze.destroy=()=>{li&&(li.disconnect(),li=null)},setTimeout(on,0),Ze}function td(e,t,n,r={}){const o=n.filter(i=>t&&t[i]&&t[i].field!=null),s=new Map;return e.forEach((i,a)=>{const l=o.length?o.map(c=>String(Nn(t,c,i,r[c],a,e))).join("\0"):"__all__";let u=s.get(l);u||(u={key:l,rep:i,members:[]},s.set(l,u)),u.members.push(a)}),[...s.values()]}function Vl(e,t,n){const r=e.map(i=>{const a=t[i],l=n!=null&&a?Number(a[n]):NaN;return Number.isFinite(l)&&l>0?l:0}),o=[];let s=0;for(const i of r)o.push([s,s+i]),s+=i;return{mags:r,total:s,bounds:o}}function cs({members:e,local:t,field:n,geometry:r}){return{members:e,local:t,field:n,geometry:r}}function p6(e,t,n){if(!n)return e;const r=[];for(const s of t){const i=s[n];r.includes(i)||r.push(i)}const o=s=>{const i=r.indexOf(t[s][n]);return i<0?r.length:i};return[...e].sort((s,i)=>o(s)-o(i))}function y6(e,t,n,r,o,s){const i=new Map;for(const a of td(e,t,[n],{[n]:r})){const l=p6(a.members,e,s),{bounds:u}=Vl(l,e,o);l.forEach((c,d)=>{i.set(c,{y0:u[d][0],y1:u[d][1],members:l,local:d})})}return i}function g6(e){const t=at(e,{mark:"bar",allow:st.bar}),{channels:n={},id:r,edits:o,orientation:s,stack:i,handles:a=!0,handleSize:l,handleColor:u}=t,{xKey:c,yKey:d}=Xt(n),f=!!(n.x1&&n.x2),p=!!(n.y1&&n.y2),h=i?Ms(n):null,y=!!i&&!f&&!p,g=o||[],m=g.some(b=>b&&b.scope==="stack");return{...lt(t),type:"bar",channels:n,rawChannels:["series"],edits:g,supportsStack:y,discreteScale:"band",xKey:c,yKey:d,build:(b,w)=>{const{x,y:S}=w,v=Kf(xr(n,w,{orientation:s})),k=v==="horizontal"?"y":"x",_=v==="horizontal"?"x":"y",A=v==="horizontal"?d:c,L=v==="horizontal"?c:d,N=y?y6(b,n,k,A,L,h):null,I=Nt(w,"bar",y?{fill:it(w).ink,stroke:it(w).handleStroke,strokeWidth:1}:{fill:it(w).ink}),T=dn(w,{handles:a,handleSize:l,handleColor:u}),M={kind:"linear",axis:_},$=D=>{const P=N&&N.get(D);return P?cs({members:P.members,local:P.local,field:L,geometry:M}):void 0},F=b.map((D,P)=>{const j=yt(w,n,D,I,P,b),G=$(P);if(v==="horizontal"){const le=Kr(S,Nn(n,"y",D,d,P,b),0),be=yn(S,20),ce=yr(x);let Y,ue;if(f){const ie=se(w,n,"x1",D,ce,P,b),U=se(w,n,"x2",D,ce,P,b);Y=Math.min(ie,U),ue=Math.max(ie,U)}else if(N){const{y0:ie,y1:U}=N.get(P)||{y0:0,y1:D[c]},we=Lt(w,n,"x",ie,ce),xe=Lt(w,n,"x",U,ce);Y=Math.min(we,xe),ue=Math.max(we,xe)}else{const ie=se(w,n,"x",D,ce,P,b);Y=Math.min(ie,ce),ue=Math.max(ie,ce)}return{type:"rect",x:Y,y:le,width:ue-Y,height:be,...j,data:D,index:P,orientation:v,bandAxis:"y",...G?{stack:G}:{}}}const J=Kr(x,Nn(n,"x",D,c,P,b),0),re=yn(x,20),Q=yr(S);let ve,Ce;if(p){const le=se(w,n,"y1",D,Q,P,b),be=se(w,n,"y2",D,Q,P,b);ve=Math.min(le,be),Ce=Math.max(le,be)}else if(N){const{y0:le,y1:be}=N.get(P)||{y0:0,y1:D[d]},ce=Lt(w,n,"y",le,Q),Y=Lt(w,n,"y",be,Q);ve=Math.min(ce,Y),Ce=Math.max(ce,Y)}else{const le=se(w,n,"y",D,Q,P,b);ve=Math.min(le,Q),Ce=Math.max(le,Q)}return{type:"rect",x:J,y:ve,width:re,height:Ce-ve,...j,data:D,index:P,orientation:v,bandAxis:"x",...G?{stack:G}:{}}});if(N&&m&&T.grabbable){const D=k==="x"?x:S,j=yr(_==="x"?x:S),G=yn(D,20),J=new Set;for(const re of N.values()){const Q=re.members;if(J.has(Q))continue;J.add(Q);const ve=b[Q[0]],le=Kr(D,Nn(n,k,ve,A,Q[0],b),0)+G/2;for(let be=0;be<Q.length-1;be++){const ce=Q[be],Y=N.get(ce);if(!Y)continue;const ue=Lt(w,n,_,Y.y1,j);F.push({type:"circle",cx:_==="x"?ue:le,cy:_==="x"?le:ue,r:T.size,fill:T.visible?T.fill:"transparent",stroke:T.visible?T.stroke:"none",strokeWidth:T.visible?T.strokeWidth:0,cursor:"grab",data:b[ce],index:ce,edge:!0,loIndex:ce,hiIndex:Q[be+1],stack:cs({members:Q,local:be,field:L,geometry:M})})}}}return F}}}function nd(e={}){return g6(e)}function Xl(e={}){return nd({...e,orientation:"vertical"})}function m6(e={}){return nd({...e,orientation:"horizontal"})}function ea(e,t,n,r,o,s,i,a,l,u){const c=e+"1",d=e+"2";if(t[c]&&t[d]){const y=se(n,t,c,o,0,l,u),g=se(n,t,d,o,0,l,u);return{lo:Math.min(y,g),hi:Math.max(y,g),band:!1}}const f=e==="x"?"width":"height";if(t[f]){const y=se(n,t,f,o,0,l,u),[g,m]=r?ro(r):[0,a],b=se(n,t,e,o,(g+m)/2,l,u);return{lo:b-y/2,hi:b+y/2,band:!1}}if(!i&&Gn(r)){const y=Kr(r,Nn(t,e,o,s,l,u),0),g=yn(r,20);return{lo:y,hi:y+g,band:!0}}if(t[e]){const y=yr(r),g=se(n,t,e,o,y,l,u);return{lo:Math.min(g,y),hi:Math.max(g,y),band:!1}}const[p,h]=r?ro(r):[0,a];return{lo:Math.min(p,h),hi:Math.max(p,h),band:!1}}function b6(e){const t=at(e,{mark:"rect",allow:st.rect}),n=t.orientation==="vertical"?"y":t.orientation==="horizontal"?"x":null,{channels:r={},id:o,edits:s,width:i,height:a,rx:l}=t;i!==void 0&&!r.width&&(r.width={value:i}),a!==void 0&&!r.height&&(r.height={value:a}),l!==void 0&&!r.rx&&(r.rx={value:l});const{xKey:u,yKey:c}=Xt(r);return{...lt(t),type:"rect",channels:r,discreteScale:"band",xKey:u,yKey:c,nodeBox:(d,f,p,h,y,g)=>{const m=ea("x",r,h,h.x,d,u,n==="x",y,f,p),b=ea("y",r,h,h.y,d,c,n==="y",g,f,p);return{cx:(m.lo+m.hi)/2,cy:(b.lo+b.hi)/2,hw:(m.hi-m.lo)/2,hh:(b.hi-b.lo)/2}},build:(d,f,p,h)=>{const{x:y,y:g}=f,m=Nt(f,"rect",{fill:it(f).ink});return d.map((b,w)=>{const x=yt(f,r,b,m,w,d),S=ea("x",r,f,y,b,u,n==="x",p,w,d),v=ea("y",r,f,g,b,c,n==="y",h,w,d);let k;S.band&&!v.band?k="x":v.band&&!S.band&&(k="y");const _=zr(f,r,"angle",b,0,w,d),A=r.rx?se(f,r,"rx",b,0,w,d):void 0;return{type:"rect",x:S.lo,y:v.lo,width:S.hi-S.lo,height:v.hi-v.lo,...x,data:b,index:w,..._?{angle:_}:{},...A?{rx:A}:{},...k?{bandAxis:k}:{}}})}}}function Ts(e={}){return b6(e)}function w6(e={}){return Ts({...e,orientation:"horizontal"})}function x6(e={}){return Ts({...e,orientation:"vertical"})}function Kp(e,t,n,r,o,s,i,a,l,u,c){const d=n[`${e}1`],f=n[`${e}2`];if(d&&f)return[se(r,n,`${e}1`,o,0,u,c),se(r,n,`${e}2`,o,i,u,c)];if(l!=null&&n[e]){const p=se(r,n,e,o,i/2,u,c);return[p-l/2,p+l/2]}return Zm(t,Nn(n,e,o,s,u,c),i,{inset:a,length:l})}function v6(e){const t=at(e,{mark:"tick",allow:st.tick}),{channels:n={},id:r,edits:o,inset:s=0,length:i}=t,{xKey:a,yKey:l}=Xt(n);return{...lt(t),type:"tick",channels:n,discreteScale:"band",xKey:a,yKey:l,build:(u,c,d,f)=>{const{x:p,y:h}=c,y=xr(n,c,{orientation:t.orientation,extent:"span"}),g=Nt(c,"tick",{stroke:it(c).ink,strokeWidth:2});return u.map((m,b)=>{const w=yt(c,n,m,g,b,u),x=zr(c,n,"angle",m,0,b,u);if(y==="x"){const _=se(c,n,"x",m,d/2,b,u),[A,L]=Kp("y",h,n,c,m,l,f,s,i,b,u);return{type:"line",x1:_,x2:_,y1:A,y2:L,...w,data:m,index:b,bandAxis:"y",cursor:"ew-resize",...x?{angle:x}:{}}}const S=se(c,n,"y",m,f/2,b,u),[v,k]=Kp("x",p,n,c,m,a,d,s,i,b,u);return{type:"line",x1:v,x2:k,y1:S,y2:S,...w,data:m,index:b,bandAxis:"x",cursor:"ns-resize",...x?{angle:x}:{}}})}}}function us(e={}){return v6(e)}function tb(e={}){return us({...e,orientation:"vertical"})}function k6(e={}){return us({...e,orientation:"horizontal"})}function S6(e){const t=at(e,{mark:"rule",allow:st.rule}),{channels:n={},id:r,edits:o,strokeDasharray:s,discreteScale:i}=t,a=!!(n.y1||n.y2),l=!!(n.x1||n.x2),u=a?"y":l?"x":null,c=xr(n,null,{orientation:t.orientation,extent:"span",single:"value"}),d=!Object.values(n).some(h=>h&&h.field!=null),{xKey:f,yKey:p}=Xt(n);return{...lt(t),type:"rule",channels:n,discreteScale:i,xKey:f,yKey:p,build:(h,y,g,m)=>{const b=[],w=(x,S)=>{const v=yt(y,n,x||{},Nt(y,"rule",{stroke:it(y).ink,strokeWidth:1}),S,h);if(u){const A=u==="y"?"x":"y",L=A==="x"?g:m,N=yr(y[u]),[I,T]=u==="y"?["y1","y2"]:["x1","x2"],M=n[I]?se(y,n,I,x,N,S,h):N,$=n[T]?se(y,n,T,x,N,S,h):N;if(M===void 0||$===void 0)return;const F=y[A];let D=L/2;if(n[A])if(Gn(F)){const G=Nn(n,A,x,A==="x"?f:p,S,h);D=Kr(F,G,0)+yn(F,0)/2}else D=se(y,n,A,x,L/2,S,h);const P={type:"line",...u==="y"?{x1:D,x2:D,y1:M,y2:$}:{x1:M,x2:$,y1:D,y2:D},...v,data:x,index:S};s!=null&&(P.strokeDasharray=s),b.push(P);return}const k=se(y,n,c,x,void 0,S,h);if(k===void 0)return;const _={type:"line",...c==="y"?{x1:0,x2:g,y1:k,y2:k}:{x1:k,x2:k,y1:0,y2:m},...v,data:x,index:S};s!=null&&(_.strokeDasharray=s),b.push(_)};return d?w(null,-1):h.forEach(w),b}}}function rd(e={}){return S6(e)}function nb(e={}){return rd({...e,orientation:"vertical"})}function $6(e={}){return rd({...e,orientation:"horizontal"})}function _6(e){const t=e&&e.domainConfig;if(Array.isArray(t)&&t.length>=2){const n=Math.min(t[0],t[t.length-1]),r=Math.max(t[0],t[t.length-1]);return[n,r]}return ge("waffle:domain",'a waffle needs a declared DOMAIN on its value axis — one cell is a fixed quantity, so the number of cells is (domain span / unit). Without it the domain falls back to [0, 1] and the grid stops being countable. Declare it: schema: { <field>: { type: "quantitative", domain: [0, max] } }, and bind it to the `count` channel.'),[0,1]}function M6(e){const t=at(e,{mark:"waffle",allow:st.waffle}),{channels:n={},id:r,edits:o,orientation:s,unit:i=1,multiple:a,gap:l=1,shape:u="rect",showEmpty:c=!0,emptyFill:d="#eee"}=t,{xKey:f,yKey:p}=Xt(n),y=Kf(xr(n,null,{orientation:s,single:"other"}))!=="horizontal";return{...lt(t),type:"waffle",channels:n,countAxis:y?"y":"x",discreteScale:"band",xKey:f,yKey:p,requires:[{channels:["x","y"],kind:"discrete",match:"any",why:"a waffle tiles ONE category's block into countable cells, so its category axis has to be a band (an interval to tile)."}],supportsWaffle:!0,build:(g,m)=>{const{x:b,y:w}=m,x=[],S=Nt(m,"waffle",{fill:it(m).ink});return g.forEach((v,k)=>{const _=yt(m,n,v,S,k,g),A=u==="symbol"?ss(m,n,v,k,g)||"·":ss(m,n,v,k,g),L=y?b:w,N="count",I=m.count,M=Kr(L,Nn(n,y?"x":"y",v,y?f:p,k,g),0),$=yn(L,20),F=yr(I),[D,P]=_6(I),j=Math.abs(P-D)||1,G=I?I.encode(P,F):F,J=Math.abs(F-G)||1,re=j/i;Math.abs(re-Math.round(re))>1e-9&&ge("waffle:unit",`a waffle's domain span (${j}) is not a whole number of \`unit\`s (${i}) — it needs ${re.toFixed(2)} cells, so the grid is rounded to ${Math.round(re)} and one cell no longer means exactly ${i}. Pick a unit that divides the domain.`);const Q=Math.max(1,Math.round(re));let ve=a;if(!(ve>=1)){const ke=Math.sqrt(Q*$/J);ve=Number.isFinite(ke)&&ke>=1?Math.floor(ke):1}ve=Math.max(1,Math.min(Q,Math.round(ve)));const Ce=Math.ceil(Q/ve),le=Math.min($/ve,J/Ce),be=($-ve*le)/2,ce=Math.max(.5,le-l),Y={axis:y?"y":"x",sign:y?-1:1,baseline:F,cellSize:le,rows:Ce,multiple:ve,bandStart:M,bandInset:be,unit:i,dlo:D,dhi:P,totalCells:Q},ue=y?-1:1,ie=M+be+l/2,U=Math.min(F,F+ue*Ce*le)+l/2,we=Math.max(0,ve*le-l),xe=Math.max(0,Ce*le-l),z={type:"rect",x:y?ie:U,y:y?U:ie,width:y?we:xe,height:y?xe:we},H=se(m,n,N,v,F,k,g),oe=Math.abs(F-H)/J,de=Math.max(0,Math.min(Q,Math.round(oe*Q)));for(let ke=0;ke<Q;ke++){const he=Math.floor(ke/ve),$e=ke%ve,Te=ke<de,Se=Te?_:{..._,fill:c?d:"transparent"},ae=M+be+$e*le,_e=F+ue*he*le,ze=F+ue*(he+1)*le,Z=Math.min(_e,ze);if(A!==void 0){const vt=ae+le/2,rt=(_e+ze)/2,dt={..._,data:v,index:k,grid:Y,effectShape:z};Te||(dt.opacity=c?.2:0),x.push(Bl(A,y?vt:rt,y?rt:vt,ce/2,dt));continue}if(u==="circle"){const vt=ce/2,rt=ae+le/2,dt=(_e+ze)/2;x.push({type:"circle",cx:y?rt:dt,cy:y?dt:rt,r:vt,...Se,data:v,index:k,grid:Y,effectShape:z});continue}x.push({type:"rect",x:(y?ae:Z)+l/2,y:(y?Z:ae)+l/2,width:ce,height:ce,...Se,data:v,index:k,grid:Y,effectShape:z})}}),x}}}function od(e={}){return M6(e)}function E6(e={}){return od({...e,orientation:"vertical"})}function A6(e={}){return od({...e,orientation:"horizontal"})}function vr(e={}){const t=at(e,{mark:"point",allow:st.point}),{channels:n={},id:r,edits:o,shape:s="circle"}=t;return{...lt(t),type:"point",channels:n,discreteScale:"point",...Xt(n),nodeBox:(i,a,l,u,c,d)=>{const f=Math.max(0,+se(u,n,"size",i,5,a,l)||0);return{cx:se(u,n,"x",i,c/2,a,l),cy:se(u,n,"y",i,d/2,a,l),hw:f,hh:f,round:s!=="square"}},build:(i,a,l,u)=>{const c=Nt(a,"point",{fill:it(a).ink});return i.map((d,f)=>{const p=yt(a,n,d,c,f,i),h=se(a,n,"x",d,l/2,f,i),y=se(a,n,"y",d,u/2,f,i),g=se(a,n,"size",d,5,f,i),m=zr(a,n,"angle",d,0,f,i),b=ss(a,n,d,f,i);if(b!==void 0)return Bl(b,h,y,g,{...p,data:d,index:f,...m?{angle:m}:{}});if(s==="square"){const w=Math.max(0,g*2);return{type:"rect",x:h-w/2,y:y-w/2,width:w,height:w,...p,data:d,index:f,...m?{angle:m}:{}}}return{type:"circle",cx:h,cy:y,r:g,...p,data:d,index:f,...m?{angle:m}:{}}})}}}function rb(e={}){const t=at(e,{mark:"ellipse",allow:st.ellipse}),{channels:n={},id:r,edits:o}=t;return{...lt(t),type:"ellipse",channels:n,discreteScale:"point",...Xt(n),nodeBox:(s,i,a,l,u,c)=>{const d=se(l,n,"size",s,5,i,a);return{cx:se(l,n,"x",s,u/2,i,a),cy:se(l,n,"y",s,c/2,i,a),hw:Math.max(0,+se(l,n,"rx",s,d,i,a)||0),hh:Math.max(0,+se(l,n,"ry",s,d,i,a)||0),round:!0}},build:(s,i,a,l)=>{const u=Nt(i,"ellipse",{fill:it(i).ink});return s.map((c,d)=>{const f=yt(i,n,c,u,d,s),p=se(i,n,"x",c,a/2,d,s),h=se(i,n,"y",c,l/2,d,s),y=se(i,n,"size",c,5,d,s),g=se(i,n,"rx",c,y,d,s),m=se(i,n,"ry",c,y,d,s),b=zr(i,n,"angle",c,0,d,s);return{type:"ellipse",cx:p,cy:h,rx:g,ry:m,...f,data:c,index:d,...b?{angle:b}:{}}})}}}function Yp(e,t,n){if(e&&Array.isArray(e.domainConfig))return e.domainConfig;const r=[];for(const o of n)r.includes(o[t])||r.push(o[t]);return r}function T6(e){const t=at(e,{mark:"dotStack",allow:st.dotStack}),{channels:n={},id:r,edits:o,orientation:s,gap:i=2,ghost:a=!0,label:l=!1}=t,{xKey:u,yKey:c}=Xt(n),d=xr(n,null,{orientation:s,single:"other"}),f=n.size&&n.size.value!=null?+n.size.value:7;return{...lt(t),type:"dotStack",channels:n,countAxis:d,countPitch:2*f+i,discreteScale:"point",xKey:u,yKey:c,build:(p,h,y,g)=>{const m=se(h,n,"size",null,7),b=2*m+i,w=d==="y"?u:c,x=d==="y"?"x":"y",S=d==="y"?g:0,v=new Map;p.forEach((L,N)=>{const I=Nn(n,x,L,w,N,p);v.set(I,(v.get(I)||0)+1)});const k=(L,N)=>{const I=se(h,n,x,L,(d==="y"?y:g)/2),T=(N+.5)*b;return{cx:d==="y"?I:S+T,cy:d==="y"?S-T:I}},_=[];if(a)for(const L of Yp(h[x],w,p))_.push({type:"circle",...k({[w]:L},v.get(L)||0),r:m,fill:"none",stroke:"#bbb",strokeWidth:1,pointerEvents:"none"});const A=new Map;if(p.forEach((L,N)=>{const I=Nn(n,x,L,w,N,p),T=A.get(I)||0;A.set(I,T+1);const M=yt(h,n,L,Nt(h,"dotStack",{fill:it(h).ink}),N,p),$=k(L,T),F=ss(h,n,L,N,p);F!==void 0?_.push(Bl(F,$.cx,$.cy,m,{...M,data:L,index:N})):_.push({type:"circle",...$,r:m,...M,data:L,index:N})}),l)for(const L of Yp(h[x],w,p)){const N=v.get(L)||0;if(N===0)continue;const I={[w]:L},T=se(h,n,x,I,(d==="y"?y:g)/2),M=(N+1)*b;_.push({type:"text",text:String(N),x:d==="y"?T:S+M,y:d==="y"?S-M:T,textAnchor:"middle",fontSize:11,fill:"#555",pointerEvents:"none"})}return _}}}function id(e={}){return T6(e)}function ob(e={}){return id({...e,orientation:"vertical"})}function O6(e={}){return id({...e,orientation:"horizontal"})}const C6="__single__";function ib(e,t="domain"){const n=at(e,{mark:"line",allow:st.line}),{channels:r={},id:o,edits:s,curve:i="linear",handles:a=!0,handleSize:l,handleColor:u,connect:c=t}=n,{xKey:d,yKey:f}=Xt(r),p=Ms(r);return{...lt(n),type:"line",channels:r,rawChannels:["curve","series","order"],discreteScale:"point",xKey:d,yKey:f,seriesKey:p,connect:c,supportsSeries:!0,build:(h,y,g,m)=>{const{x:b,y:w}=y,S=xr(r,y,{orientation:n.orientation})==="y"?"x":"y",v=[],k=h.map((N,I)=>({d:N,i:I,cx:se(y,r,"x",N,g/2,I,h),cy:se(y,r,"y",N,m/2,I,h),series:p?N[p]:C6})),_=new Map;for(const N of k){const I=_.get(N.series);I?I.push(N):_.set(N.series,[N])}const A=Nt(y,"line",{stroke:it(y).ink,strokeWidth:2});for(const N of _.values()){if(N.length<2)continue;const I=N6(N,c,S,r),T=yt(y,r,N[0].d,A,N[0].i,h),M=String(pt(r,"curve",N[0].d,i,N[0].i,h));v.push({type:"path",points:I.map($=>[$.cx,$.cy]),curve:M,...T,fill:"none",pointerEvents:"none",series:N[0].series})}const L=dn(y,{handles:a,handleSize:l,handleColor:u},{fill:A.stroke});return k.forEach(({d:N,i:I,cx:T,cy:M,series:$})=>{if(!L.grabbable)return;const F=yt(y,r,N,{fill:L.fill,stroke:L.stroke,strokeWidth:L.strokeWidth},I,h);v.push({type:"circle",cx:T,cy:M,r:L.size,...F,...L.visible?{}:{fill:"transparent",stroke:"none",strokeWidth:0},data:N,index:I,series:$,sweepAxis:S})}),v}}}function N6(e,t,n,r){const o=Yf(r);if(o)return[...e].sort((s,i)=>{const a=s.d[o],l=i.d[o];return a<l?-1:a>l?1:0});if(t==="domain"){const s=n==="x"?"cx":"cy";return[...e].sort((i,a)=>i[s]-a[s])}return e}function sd(e={}){return ib(e)}function I6(e={}){return sd({...e,orientation:"vertical"})}function L6(e={}){return sd({...e,orientation:"horizontal"})}function F6(e={}){return ib(e,"sequence")}const Pc="__single__";function R6(e,t,n){if(!e)return{channels:t,edits:n};const r={...t};for(const s of e){const i=r[s];i&&i.edit&&(r[s]={...i,edit:il(i.edit,s)})}const o=n&&n.map(s=>{const i=(s.channels||[]).filter(a=>e.includes(a));return i.length===1?il(s,i[0]):s});return{channels:r,edits:o}}function z6(e){const t=at(e,{mark:"area",allow:st.area}),{channels:n={},id:r,edits:o,curve:s="linear",handles:i=!0,handleSize:a,handleColor:l,connect:u="domain"}=t,{xKey:c,yKey:d}=Xt(n),f=Ms(n),p=!!(n.x1&&n.x2),h=!!(n.y1&&n.y2),y=h?["y1","y2"]:p?["x1","x2"]:null,{channels:g,edits:m}=R6(y,n,o);return{...lt(t),type:"area",channels:g,rawChannels:["curve","series","order"],discreteScale:"point",xKey:c,yKey:d,seriesKey:f,connect:u,supportsSeries:!0,build:(b,w,x,S)=>{const{x:v,y:k}=w,_=xr(g,w,{orientation:t.orientation,extent:"value"}),A=_==="y"?h:p,L=new Map;b.forEach(($,F)=>{const D=f!=null?$[f]:Pc;let P=L.get(D);P||(P=[],L.set(D,P)),P.push({d:$,i:F})});const N=[],I=dn(w,{handles:i,handleSize:a,handleColor:l}),T=yr(k),M=yr(v);for(const[$,F]of L){const P=[...F||[]],j=Yf(g);if(j)P.sort((be,ce)=>be.d[j]<ce.d[j]?-1:be.d[j]>ce.d[j]?1:0);else if(u==="domain"){const be=_==="y"?c:d;P.sort((ce,Y)=>{const ue=ce.d[be],ie=Y.d[be];return ue instanceof Date&&ie instanceof Date?ue-ie:ue<ie?-1:ue>ie?1:0})}const G=it(w).ink,J=yt(w,g,P[0]?P[0].d:{},Nt(w,"area",{fill:G,stroke:G,fillOpacity:.35}),P[0]?P[0].i:void 0,b),re=String(pt(g,"curve",P[0]?P[0].d:{},s,P[0]?P[0].i:void 0,b));let Q,ve;if(_==="y"){const be=(ce,Y)=>se(w,g,"x",ce,x/2,Y,b);Q=P.map(({d:ce,i:Y})=>[be(ce,Y),A?se(w,g,"y2",ce,T,Y,b):se(w,g,"y",ce,S/2,Y,b)]),ve=[...P].reverse().map(({d:ce,i:Y})=>[be(ce,Y),A?se(w,g,"y1",ce,T,Y,b):T])}else{const be=(ce,Y)=>se(w,g,"y",ce,S/2,Y,b);Q=P.map(({d:ce,i:Y})=>[A?se(w,g,"x2",ce,M,Y,b):se(w,g,"x",ce,x/2,Y,b),be(ce,Y)]),ve=[...P].reverse().map(({d:ce,i:Y})=>[A?se(w,g,"x1",ce,M,Y,b):M,be(ce,Y)])}const Ce=[...Q,...ve];Ce.length>=2&&N.push({type:"path",points:Ce,curve:re,...J,strokeWidth:J.strokeWidth!=null?J.strokeWidth:1,series:$===Pc?void 0:$,pointerEvents:"none"});const le=A?_==="y"?["y1","y2"]:["x1","x2"]:[_];I.grabbable&&P.forEach(({d:be,i:ce})=>{const Y=yt(w,g,be,{fill:I.fill,stroke:I.stroke,strokeWidth:I.strokeWidth},ce,b);for(const ue of le){const ie=ue[0]==="y",U=ie?se(w,g,"x",be,x/2,ce,b):se(w,g,"y",be,S/2,ce,b),we=se(w,g,ue,be,ie?S/2:x/2,ce,b);N.push({type:"circle",cx:ie?U:we,cy:ie?we:U,r:I.size,...Y,...I.visible?{}:{fill:"transparent",stroke:"none",strokeWidth:0},data:be,index:ce,channel:ue,series:$===Pc?void 0:$})}})}return N}}}function ad(e={}){return z6(e)}function P6(e={}){return ad({...e,orientation:"vertical"})}function D6(e={}){return ad({...e,orientation:"horizontal"})}const Hu=16,sb=16;function Jl(e,t,n,r=Hu){const o=[];for(let s=0;s<=r;s++){const i=s/r,a=1-i;o.push([a*a*e[0]+2*a*i*t[0]+i*i*n[0],a*a*e[1]+2*a*i*t[1]+i*i*n[1]])}return o}function ll(e,t,n,r){const o=[];for(let s=0;s<=Hu;s++){const i=s/Hu,a=1-i,l=a*a*a,u=3*a*a*i,c=3*a*i*i,d=i*i*i;o.push([l*e[0]+u*t[0]+c*n[0]+d*r[0],l*e[1]+u*t[1]+c*n[1]+d*r[1]])}return o}function Dc(e,t,n){if(!n)return e;const r=-n*Math.PI/180,o=Math.cos(r),s=Math.sin(r),i=e[0]-t.cx,a=e[1]-t.cy;return[t.cx+i*o-a*s,t.cy+i*s+a*o]}function j6(e){const t=at(e,{mark:"curve",allow:st.curve}),{channels:n={},id:r,edits:o,length:s}=t,{xKey:i,yKey:a}=Xt(n);return{...lt(t),type:"curve",channels:n,discreteScale:"point",xKey:i,yKey:a,build:(l,u,c,d)=>{const f=xr(n,u,{orientation:t.orientation,extent:"span",single:"other"}),p=f==="x"?"y":"x",h=p==="x"?c:d,y=f==="x"?c:d,g=Nt(u,"curve",{fill:"none",stroke:it(u).ink,strokeWidth:2}),m=[];return l.forEach((b,w)=>{const x=yt(u,n,b,g,w,l),S=se(u,n,f,b,y/2,w,l);let v,k;if(n[`${p}1`]&&n[`${p}2`])v=se(u,n,`${p}1`,b,h*.25,w,l),k=se(u,n,`${p}2`,b,h*.75,w,l);else{const re=se(u,n,p,b,h/2,w,l),Q=(s??Math.min(c,d)*.25)/2;v=re-Q,k=re+Q}let _=p==="x"?[v,S]:[S,v],A=p==="x"?[k,S]:[S,k];const L={cx:(_[0]+A[0])/2,cy:(_[1]+A[1])/2},N=A[0]-_[0],I=A[1]-_[1],T=Math.hypot(N,I)||1,M=I/T,$=-N/T,D=(se(u,n,"curvature",b,0,w,l)||0)*(T/2);let P=[L.cx+M*D*2,L.cy+$*D*2];const j=zr(u,n,"angle",b,0,w,l);j&&(_=Dc(_,L,j),A=Dc(A,L,j),P=Dc(P,L,j));const G=`M ${_[0]} ${_[1]} Q ${P[0]} ${P[1]} ${A[0]} ${A[1]}`,J=Jl(_,P,A);m.push({type:"path",d:G,cx:L.cx,cy:L.cy,...x,data:b,index:w,pointerEvents:"none"}),m.push({type:"path",d:G,points:J,cx:L.cx,cy:L.cy,fill:"none",stroke:"transparent",strokeWidth:Math.max(sb,(x.strokeWidth||2)*6),data:b,index:w,cursor:"grab"})}),m}}}function ld(e={}){return j6(e)}function ab(e={}){return ld({...e,orientation:"vertical"})}function W6(e={}){return ld({...e,orientation:"horizontal"})}function lb(e){return e*Math.PI/180}function un(e,t,n,r){const o=lb(r);return{x:e+n*Math.cos(o),y:t-n*Math.sin(o)}}const xa={top:[180,0],right:[-90,90],bottom:[0,-180],left:[90,270]};function cd(e={}){return e.start!=null&&e.end!=null?[e.start,e.end]:e.arc==="full"?[-180,180]:e.orient&&xa[e.orient]?xa[e.orient]:xa.top}function cb(e,t){let n=t-e;for(;n>360;)n-=360;for(;n<-360;)n+=360;return n}function fs(e,t,n,r,o,s={}){const i=s.innerRadius||0,a=cb(r,o);if(Math.abs(a)<1e-6||n<=0)return"";if(Math.abs(Math.abs(a)-360)<1e-6){const y=r+a/2,g=fs(e,t,n,r,y,s),m=fs(e,t,n,y,o,s);return`${g} ${m}`.trim()}const l=a>=0?0:1,u=Math.abs(a)>180?1:0,c=un(e,t,n,r),d=un(e,t,n,o);if(i<=0)return[`M ${e} ${t}`,`L ${c.x} ${c.y}`,`A ${n} ${n} 0 ${u} ${l} ${d.x} ${d.y}`,"Z"].join(" ");const f=un(e,t,i,r),p=un(e,t,i,o),h=l===0?1:0;return[`M ${c.x} ${c.y}`,`A ${n} ${n} 0 ${u} ${l} ${d.x} ${d.y}`,`L ${p.x} ${p.y}`,`A ${i} ${i} 0 ${u} ${h} ${f.x} ${f.y}`,"Z"].join(" ")}function cl(e,t,n,r,o){const s=cb(r,o);if(Math.abs(s)<1e-6||n<=0)return"";if(Math.abs(Math.abs(s)-360)<1e-6){const c=r+s/2;return`${cl(e,t,n,r,c)} ${cl(e,t,n,c,o)}`.trim()}const i=un(e,t,n,r),a=un(e,t,n,o),l=Math.abs(s)>180?1:0,u=s>=0?0:1;return`M ${i.x} ${i.y} A ${n} ${n} 0 ${l} ${u} ${a.x} ${a.y}`}function ub(e,t){if(!e||!uo(e))return null;const n=e.domain();if(!n.length)return null;if(Gn(e)){const c=e(t);return c==null?null:[c,c+e.bandwidth()]}const r=e.range(),o=r[0],s=r[r.length-1],i=n.indexOf(t);if(i<0)return null;const a=n.map(c=>e(c)),l=i===0?o:(a[i-1]+a[i])/2,u=i===n.length-1?s:(a[i]+a[i+1])/2;return[l,u]}function fb(e,t,n,r,o=10){const s=un(e,t,n,r),i=o/2,a=un(e,t,i,r+90),l=un(e,t,i,r-90);return[[s.x,s.y],[a.x,a.y],[l.x,l.y]]}function db(e={}){const t=at(e,{mark:"arc",allow:st.arc}),{channels:n={},id:r,edits:o,outerRadius:s,innerRadius:i=0,padAngle:a=0,arc:l,start:u,end:c,handles:d=!0,handleSize:f,handleColor:p}=t,h=o||[],y=h.some(w=>w&&w.scope==="stack"),[g,m]=cd({arc:l||"full",start:u??(l?void 0:-180),end:c??(l?void 0:180)}),b=n.theta&&n.theta.field;return{...lt(t),type:"arc",channels:n,rawChannels:["theta"],edits:h,discreteScale:"band",yKey:b,supportsStack:!0,build:(w,x,S,v)=>{const k=td(w,n,["x","y"]),_=Gn(x.x),A=Gn(x.y),L=_?yn(x.x,S):S,N=A?yn(x.y,v):v,I=_||A?.42*Math.min(L,N):(k.length>1?.14:.4)*Math.min(S,v),T=m-g,M=a,$=[],F=dn(x,{handles:d,handleSize:f,handleColor:p});return k.forEach(D=>{const P=D.rep,j=D.members,G=j[0],J=se(x,n,"x",P,S/2,G,w),re=se(x,n,"y",P,v/2,G,w),Q=s??(n.size?se(x,n,"size",P,I,G,w):I),ve=i>0&&i<=1?i*Q:Math.min(i,Q*.95),Ce=b!=null?Vl(j,w,b).mags:j.map(U=>{const we=se(x,n,"theta",w[U],0,U,w);return Number.isFinite(we)&&we>0?Number(we):0}),le=Ce.reduce((U,we)=>U+we,0),be=j.length,ce=le>0?T-M*be:0,Y={kind:"angular",cx:J,cy:re,spanStart:g,spanEnd:m,pad:M},ue={};let ie=g+M/2;if(j.forEach((U,we)=>{const xe=w[U],z=le>0?Ce[we]/le:0,H=ce*z,oe=ie,de=ie+H;if(ie=de+M,ue[we]=de,H<=0)return;const ke=yt(x,n,xe,Nt(x,"arc",{fill:"#4f46e5",stroke:"#fff",strokeWidth:1}),U,w),he=fs(J,re,Q,oe,de,{innerRadius:ve});he&&$.push({type:"path",d:he,...ke,cx:J,cy:re,index:U,midAngle:(oe+de)/2,a0:oe,a1:de,stack:cs({members:j,local:we,field:b,geometry:Y}),sector:{cx:J,cy:re,r0:ve,r1:Q,a0:oe,a1:de}})}),y&&F.grabbable&&le>0&&be>1)for(let U=0;U<be-1;U++){const we=ue[U]+M/2,xe=un(J,re,Q,we);$.push({type:"circle",cx:xe.x,cy:xe.y,r:F.size,fill:F.visible?F.fill:"transparent",stroke:F.visible?F.stroke:"none",strokeWidth:F.visible?F.strokeWidth:0,cursor:"grab",index:j[U],edge:!0,loIndex:j[U],hiIndex:j[U+1],stack:cs({members:j,local:U,field:b,geometry:Y})})}}),$}}}function q6(e={}){const t=e.innerRadius!=null?e.innerRadius:e.outerRadius!=null?e.outerRadius*.55:.55;return db({...e,arc:e.arc||"full",innerRadius:t})}function H6(e={}){const t=at(e,{mark:"needle",allow:st.needle});for(const p of["arc","orient","start","end"])e&&e[p]!==void 0&&ge(`needle:span:${p}`,`needle({ ${p}: … }) does nothing: a needle's sweep is the theta scale's range. Set it on the channel — channels: { theta: { field, scale: { range: [180, 0] } } } — or chart-wide with scales: { theta: { range } }; axisRadial takes arc/orient/start/end for the chrome.`);t.channels&&t.channels.angle&&!t.channels.theta&&ge("needle:angle","needle({ channels: { angle: … } }) — a needle's direction is `theta`, the polar angular POSITION (what axisRadial draws). `angle` is a mark's rotation in place and this mark does not read it, so the needle would point at 0°. Rename the channel to `theta`.");const{channels:n={},id:r,edits:o,length:s,handles:i=!0,handleSize:a,handleColor:l,baseWidth:u=10}=t,c=n.theta&&n.theta.field,d=n.x&&n.x.field,f=n.y&&n.y.field;return{...lt(t),type:"needle",channels:n,discreteScale:"point",xKey:d||c,yKey:f||c,build:(p,h,y,g)=>{const m=[],b=dn(h,{handles:i,handleSize:a,handleColor:l});return p.forEach((w,x)=>{const S=se(h,n,"x",w,y/2,x,p),v=se(h,n,"y",w,g/2,x,p),k=zr(h,n,"theta",w,0,x,p),_=s??se(h,n,"size",w,Math.min(y,g)*.4,x,p),A=yt(h,n,w,Nt(h,"needle",{fill:"#1e293b",stroke:"#1e293b",strokeWidth:1}),x,p),L=fb(S,v,_,k,u),N=`M ${L[0][0]} ${L[0][1]} L ${L[1][0]} ${L[1][1]} L ${L[2][0]} ${L[2][1]} Z`;m.push({type:"path",d:N,...A,cx:S,cy:v,data:w,index:x,cursor:b.grabbable?"grab":void 0}),b.grabbable&&m.push({type:"circle",cx:S,cy:v,r:b.size,fill:b.fill,stroke:b.stroke,strokeWidth:b.strokeWidth,data:w,index:x,cursor:"grab"})}),m}}}const B6=.52,U6=4096,hi=new Map;let $o;function K6(){if($o!==void 0)return $o;if($o=null,typeof document<"u")try{$o=document.createElement("canvas").getContext("2d")}catch{$o=null}return $o}function Y6({fontSize:e=12,fontFamily:t="sans-serif",fontWeight:n="normal"}){return`${n} ${e}px ${t}`}function ji(e,t={}){const n=e==null?"":String(e);if(!n)return 0;const r=Y6(t),o=`${r}\0${n}`,s=hi.get(o);if(s!==void 0)return s;const i=K6();let a;if(i?(i.font=r,a=i.measureText(n).width):a=n.length*(t.fontSize||12)*B6,hi.size>=U6){const l=hi.keys().next().value;l!==void 0&&hi.delete(l)}return hi.set(o,a),a}function hb(e,t={}){const{maxWidth:n,...r}=t,s=(e==null?"":String(e)).split(`
13
+ `);if(!n||n<=0)return s;const i=[];for(const a of s){const l=a.split(/\s+/).filter(c=>c.length);if(!l.length){i.push("");continue}let u="";for(const c of l){const d=u?`${u} ${c}`:c;if(ji(d,r)<=n){u=d;continue}if(u&&i.push(u),ji(c,r)>n){let f="";for(const p of c)f&&ji(f+p,r)>n?(i.push(f),f=p):f+=p;u=f}else u=c}i.push(u)}return i}function Zl(e,t={}){const{lineHeight:n,...r}=t,o=r.fontSize||12,s=n||Math.round(o*1.35),i=hb(e,r);let a=0;for(const l of i)a=Math.max(a,ji(l,r));return{lines:i,width:a,height:i.length*s,lineHeight:s}}function $n(e,t={}){const{padding:n=10,maxWidth:r=160,minWidth:o=60,minHeight:s=0,fontSize:i=13,fontFamily:a,lineHeight:l}=t,u=Zl(e==null?"":String(e),{maxWidth:r-n*2,fontSize:+i||13,fontFamily:a,lineHeight:l});return{block:u,width:Math.max(o,Math.min(r,u.width+n*2)),height:Math.max(s,u.height+n*2)}}function kr(e){if(typeof e=="function")return e;if(typeof e=="string"){const t=Qo(e);return n=>n==null||n===""?"":t(n)}return t=>t==null?"":String(t)}function G6(e=""){return kr(e)}function V6(e=".0%"){return kr(e)}function X6(e=".2s"){return kr(e)}function J6(e="%Y-%m-%d"){const t=Nf(e);return n=>{if(n==null||n==="")return"";const r=n instanceof Date?n:new Date(n);return Number.isNaN(+r)?String(n):t(r)}}function Z6(e,t=""){const n=kr(t);return r=>r==null||r===""?"":`${e}${n(r)}`}function Q6(e,t=""){const n=kr(t);return r=>r==null||r===""?"":`${n(r)}${e}`}const eA=Object.freeze(Object.defineProperty({__proto__:null,number:G6,percent:V6,prefix:Z6,resolveFormat:kr,si:X6,suffix:Q6,time:J6},Symbol.toStringTag,{value:"Module"}));function tA(e){switch(e){case"top":return"text-before-edge";case"bottom":return"text-after-edge";default:return"central"}}function ud(e,t,n,r,o,s,i={}){const{format:a=x=>x,data:l,wrap:u,lineHeight:c}=i,d=typeof u=="function"?u(n,r,l||[n]):u,f=yt(e,t,n,Nt(e,"text",{fill:"#111"}),r,l),p=+pt(t,"dx",n,0,r,l)||0,h=+pt(t,"dy",n,0,r,l)||0,y=zr(e,t,"angle",n,0,r,l),g=pt(t,"lineAnchor",n,"middle",r,l),m=pt(t,"fontSize",n,12,r,l),b=a(pt(t,"text",n,"",r,l)),w=d||c?Zl(b,{maxWidth:d,fontSize:+m||12,fontFamily:it(e).font&&it(e).font.family||void 0,lineHeight:c}):null;return{type:"text",x:o+p,y:s+h,text:b,fontSize:m,textAnchor:pt(t,"textAnchor",n,"middle",r,l),lineAnchor:g,dominantBaseline:tA(g),...y?{angle:y}:{},...w&&w.lines.length>1?{lines:w.lines,lineHeight:w.lineHeight}:{},...f,data:n,index:r}}function nA(e){const t=at(e,{mark:"text",allow:st.text}),{channels:n={},id:r,edits:o,format:s,wrap:i,lineHeight:a}=t,l=kr(s);return{...lt(t),type:"text",channels:n,rawChannels:["text","fontSize","textAnchor","lineAnchor","dx","dy"],discreteScale:"point",...Xt(n),build:(c,d,f,p)=>c.map((h,y)=>{const{x:g,y:m}=u(h,y,c,d,f,p);return ud(d,n,h,y,g,m,{format:l,data:c,wrap:i,lineHeight:a})}),labelBox:!0,nodeBox:(c,d,f,p,h,y)=>{const g=u(c,d,f,p,h,y),m=+pt(n,"dx",c,0,d,f)||0,b=+pt(n,"dy",c,0,d,f)||0,w=+pt(n,"fontSize",c,12,d,f)||12,x=Zl(l(pt(n,"text",c,"",d,f)),{maxWidth:typeof i=="function"?i(c,d,f):i,fontSize:w,fontFamily:it(p).font&&it(p).font.family||void 0,lineHeight:a}),S=x.width/2,v=x.height/2,k=pt(n,"textAnchor",c,"middle",d,f),_=pt(n,"lineAnchor",c,"middle",d,f),A=g.x+m,L=g.y+b;return{cx:k==="start"?A+S:k==="end"?A-S:A,cy:_==="top"?L+v:_==="bottom"?L-v:L,hw:S,hh:v}}};function u(c,d,f,p,h,y){const g=t.orientation==="vertical"?"y":t.orientation==="horizontal"?"x":null;return{x:g==="y"?h/2:se(p,n,"x",c,h/2,d,f),y:g==="x"?y/2:se(p,n,"y",c,y/2,d,f)}}}function Tr(e={}){return nA(e)}function rA(e={}){return Tr({...e,orientation:"horizontal"})}function oA(e={}){return Tr({...e,orientation:"vertical"})}const iA=["intercept","slope","interceptSpread","slopeSpread","intercept1","intercept2","slope1","slope2"];function fd(e,t={}){const n={x:{field:"x"},y:{field:"y"},...t,...e};for(const r of iA){const o=n[r];o&&(n[r]={...o,scale:null})}return n}function dd(e,t,n,r,o){const s=(p,h)=>{const y=se(n,t,p,e,h,r,o),g=Number(y);return Number.isFinite(g)?g:h},i=s("intercept",0),a=s("slope",0),l=(p,h)=>{if(t[`${p}1`]||t[`${p}2`]){const g=s(`${p}1`,h),m=s(`${p}2`,h);return g<=m?[g,m]:[m,g]}const y=Math.abs(s(`${p}Spread`,0));return[h-y,h+y]},[u,c]=l("intercept",i),[d,f]=l("slope",a);return{a:i,b:a,aLo:u,aHi:c,bLo:d,bHi:f}}function hd(e){const t=e.x&&e.x.domainConfig;return{x0:Array.isArray(t)?Number(t[0]):0,x1:Array.isArray(t)?Number(t[t.length-1]):1}}function Ql(e,t={}){const{x0:n,x1:r}=hd(e),o=Math.min(n,r),s=Math.max(n,r),i=o<=0&&0<=s?0:n;return{anchor:t.anchor!=null?Number(t.anchor):i,probe:t.probe!=null?Number(t.probe):r}}const Or=(e,t)=>e.a+e.b*t;function sA(e,t,n,r,o,s){const i=n-e,a=r-t;if(i===0&&a===0)return e<0||e>o||t<0||t>s?null:{x1:e,y1:t,x2:n,y2:r};let l=-1/0,u=1/0;const c=(d,f)=>{if(d===0)return f>=0;const p=f/d;if(d<0){if(p>u)return!1;p>l&&(l=p)}else{if(p<l)return!1;p<u&&(u=p)}return!0};return!c(-i,e-0)||!c(i,o-e)||!c(-a,t-0)||!c(a,s-t)||l>u?null:{x1:e+l*i,y1:t+l*a,x2:e+u*i,y2:t+u*a}}function aA(e,t,n){const r=[{inside:i=>i[0]>=0,at:(i,a)=>o(i,a,0,0)},{inside:i=>i[0]<=t,at:(i,a)=>o(i,a,0,t)},{inside:i=>i[1]>=0,at:(i,a)=>o(i,a,1,0)},{inside:i=>i[1]<=n,at:(i,a)=>o(i,a,1,n)}];function o(i,a,l,u){const c=a[l]-i[l],d=c===0?0:(u-i[l])/c;return[i[0]+d*(a[0]-i[0]),i[1]+d*(a[1]-i[1])]}let s=e;for(const i of r){const a=[];for(let l=0;l<s.length;l++){const u=s[l],c=s[(l+s.length-1)%s.length],d=i.inside(u),f=i.inside(c);d?(f||a.push(i.at(c,u)),a.push(u)):f&&a.push(i.at(c,u))}if(s=a,!s.length)return[]}return s}function ul(e,t,n,r,o){const{x0:s,x1:i}=hd(t),a=u=>Lt(t,n,"x",u,0),l=u=>Lt(t,n,"y",u,0);return sA(a(s),l(Or(e,s)),a(i),l(Or(e,i)),r,o)}function pb(e,t=0){if(!e)return null;const n=e.x2-e.x1,r=e.y2-e.y1,o=Math.hypot(n,r);if(!Number.isFinite(o))return null;const s=t>0&&o>4*t?t/o:0;return[{x:e.x1+s*n,y:e.y1+s*r},{x:e.x2-s*n,y:e.y2-s*r}]}function pd(e,t,n,r,o){const{aLo:s,aHi:i,bLo:a,bHi:l}=e,{x0:u,x1:c}=hd(t),d=Math.min(u,c),f=Math.max(u,c),p=[d];d<0&&0<f&&p.push(0),p.push(f);const h=w=>Lt(t,n,"x",w,0),y=w=>Lt(t,n,"y",w,0),g=w=>i+Math.max(a*w,l*w),m=w=>s+Math.min(a*w,l*w),b=[];for(const w of p)b.push([h(w),y(g(w))]);for(let w=p.length-1;w>=0;w--)b.push([h(p[w]),y(m(p[w]))]);return aA(b,r,o)}function yb(e,t,n,r,o,s){const{a:i,b:a,aLo:l,aHi:u,bLo:c,bHi:d}=e,f=[];for(let p=1;p<=t;p++){const h=p/t,y={aLo:i-(i-l)*h,aHi:i+(u-i)*h,bLo:a-(a-c)*h,bHi:a+(d-a)*h},g=pd(y,n,r,o,s);g.length>=3&&f.push(g)}return f}function lA(e){let t=e>>>0;return function(){t|=0,t=t+1831565813|0;let n=Math.imul(t^t>>>15,1|t);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function cA(e){let t=0,n=0;for(;t===0;)t=e();for(;n===0;)n=e();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*n)}function gb(e,t={}){const{samples:n=60,seed:r=7,distribution:o="normal",sigma:s=1.96}=t,{a:i,b:a,aLo:l,aHi:u,bLo:c,bHi:d}=e,f=lA(r),p=s>0?s:1.96,h=(g,m,b)=>{if(o==="uniform")return m+f()*(b-m);const w=cA(f)/p;return w>=0?g+w*(b-g):g+w*(g-m)},y=[];for(let g=0;g<n;g++)y.push({a:h(i,l,u),b:h(a,c,d)});return y}function mb(e={}){const t=at(e,{mark:"trend",allow:st.trend}),{edits:n,anchor:r,probe:o,grip:s="end",handles:i=!0,handleSize:a,handleColor:l}=t;o!=null&&s!=="probe"&&ge("trend:probe-ignored","trend(): `probe` places the slope handle only under `grip: 'probe'`. The default grip mounts the handles on the line's own ends; add `grip: 'probe'` to pin one at that column instead.");const u=fd(t.channels||{},{intercept:{field:"intercept"},slope:{field:"slope"}}),c={anchor:r,probe:o};return{...lt(t),type:"trend",channels:u,isTrend:!0,supportsTrend:!0,...Xt(u),requires:[{channels:["x","y"],kind:"continuous",match:"all",why:"an intercept and a slope are only defined over two continuous axes."}],build:(d,f,p,h)=>{if(!f.x||!f.y)return[];const{anchor:y,probe:g}=Ql(f,c),m=[],b=Nt(f,"trend",{stroke:"#333",fill:"#333"}),w=dn(f,{handles:i,handleSize:a,handleColor:l},{fill:b.fill});return d.forEach((x,S)=>{const v=dd(x,u,f,S,d),k=yt(f,u,x,b,S,d),_=ul(v,f,u,p,h);if(_&&m.push({type:"line",..._,stroke:k.stroke||b.stroke,strokeWidth:k.strokeWidth||2,pointerEvents:"none"}),!w.grabbable)return;const A=(L,N,I)=>{m.push({type:"circle",cx:N,cy:I,r:w.size,fill:w.visible?k.fill||w.fill:"transparent",data:x,index:S,channel:L,anchor:y,probe:g,grip:s})};if(A("intercept",Lt(f,u,"x",y,0),Lt(f,u,"y",Or(v,y),0)),s==="probe"){A("slope",Lt(f,u,"x",g,0),Lt(f,u,"y",Or(v,g),0));return}for(const L of pb(_,w.size+1)||[])A("slope",L.x,L.y)}),m}}}function bb(e={}){const t=at(e,{mark:"trendBand",allow:st.trendBand}),{edits:n,render:r="region",levels:o=5,samples:s=60,seed:i=7,sigma:a=1.96,distribution:l="normal",anchor:u,probe:c,grip:d="end",handles:f=!1,handleSize:p,handleColor:h}=t;c!=null&&d!=="probe"&&ge("trendBand:probe-ignored","trendBand(): `probe` places the slopeSpread handle only under `grip: 'probe'`. The default grip mounts the handles on the band's own edge ends; add `grip: 'probe'` to pin one at that column instead.");const y=fd(t.channels||{},{intercept:{field:"intercept"},slope:{field:"slope"}}),g={anchor:u,probe:c};return{...lt(t),type:"trendBand",channels:y,supportsTrend:!0,isTrend:!0,...Xt(y),requires:[{channels:["x","y"],kind:"continuous",match:"all",why:"an intercept and a slope are only defined over two continuous axes."}],build:(m,b,w,x)=>{if(!b.x||!b.y)return[];const{anchor:S,probe:v}=Ql(b,g),k=[],_=dn(b,{handles:f,handleSize:p,handleColor:h}),A=it(b).ink,L=Nt(b,"trendBand",{fill:A,stroke:A,fillOpacity:.18,strokeOpacity:.15}),N=(I,T)=>{const M=pb(ul(I,b,y,w,x),_.size+1);if(!M)return null;const $=b.x,F=$&&$.invertible?j=>Number($.invertValue(j.x)):j=>j.x,[D,P]=M;return T>0==F(D)>=F(P)?D:P};return m.forEach((I,T)=>{const M=dd(I,y,b,T,m),$=yt(b,y,I,L,T,m),F=$.fill||L.fill,D=$.fillOpacity,P=M.aLo===M.aHi&&M.bLo===M.bHi;if(!P&&r==="samples")for(const J of gb(M,{samples:s,seed:i,distribution:l,sigma:a})){const re=ul(J,b,y,w,x);re&&k.push({type:"line",...re,stroke:$.stroke||L.stroke,strokeWidth:$.strokeWidth!=null?$.strokeWidth:1,strokeOpacity:$.strokeOpacity,pointerEvents:"none",background:!0})}else if(!P&&r==="gradient"){const J=Math.max(1,Math.round(o)),re=1-Math.pow(1-Math.min(.99,D),1/J);for(const Q of yb(M,J,b,y,w,x))k.push({type:"path",points:Q,curve:"linear",fill:F,fillOpacity:re,stroke:"none",pointerEvents:"none",background:!0})}else if(!P){const J=pd(M,b,y,w,x);J.length>=3&&k.push({type:"path",points:J,curve:"linear",fill:F,fillOpacity:D,stroke:"none",pointerEvents:"none",background:!0})}if(!_.grabbable)return;const j=J=>M.aHi+Math.max(M.bLo*J,M.bHi*J),G=(J,re,Q)=>{k.push({type:"circle",cx:re,cy:Q,r:_.size,fill:_.visible?h||F:"transparent",data:I,index:T,channel:J,anchor:S,probe:v,grip:d})};if(y.interceptSpread&&G("interceptSpread",Lt(b,y,"x",S,0),Lt(b,y,"y",P?Or(M,S):j(S),0)),!!y.slopeSpread){if(d==="probe"){G("slopeSpread",Lt(b,y,"x",v,0),Lt(b,y,"y",P?Or(M,v):j(v),0));return}for(const[J,re]of[[1,M.bHi],[-1,M.bLo]]){const Q=N({a:M.aHi,b:re},J);Q&&G("slopeSpread",Q.x,Q.y)}}}),k}}}const ta=["x","y","size"],uA=["ports"];let fA=0;function dA(e,t,n){const r={};for(const[o,s]of Object.entries(e||{}))if(s)if(!n&&s.edit){const{edit:i,...a}=s;r[o]=a}else r[o]=s;for(const[o,s]of Object.entries(t||{}))s!==void 0&&(r[o]=s);return r}function Gp(e){for(const[t,n]of Object.entries(e||{})){const r=bM(n);r!==n&&(e[t]=r)}return e}function hA(e){return Object.values(e||{}).some(t=>!!Yr(t))}function pA(e,t,n){const r=[];Gn(e.x)&&r.push(yn(e.x,0)),Gn(e.y)&&r.push(yn(e.y,0));const o=r.filter(s=>s>0);return o.length?Math.min(...o)/2:Math.min(t,n)*.35}function jc(e,t,n,r,o,s,i){const a=pA(e,s,i);return{cx:se(e,t,"x",n,s/2,r,o),cy:se(e,t,"y",n,i/2,r,o),r:se(e,t,"size",n,a,r,o)}}function yA(e,t,n){if(e.field==null)return t;const r=n&&n[e.field],o=r&&r.domain;return Array.isArray(o)&&o.length?[o[0],o[o.length-1]]:(ge(`frame:domain:${e.field}`,`field "${e.field}" is encoded in a composite's local frame, but the schema declares no domain for it — a frame maps the field's DOMAIN onto the glyph's local box, so without one it falls back to [0, 1]. Declare it: schema: { ${e.field}: { type: "quantitative", domain: [lo, hi] } }.`),[0,1])}function gA(e,t,n,r,o,s){const i={};for(const a of t){const l=e[a],u=Yr(l)||{},c=Ff(a),d=u.range||xM(a)||r0(a,"linear",o,s),f=dM({domain:yA(l,d,r),localRange:d,origin:c==="x"?n.cx:c==="y"?n.cy:0,halfSize:n.r,family:c});f&&(i[a]=f,l&&l.field!=null&&(i[co(a,l.field)]=f))}return i}function mA(e,t,n){const r={};for(const o of t){const s=e[o],i=n[o];if(!s||!s.edit||s.field==null||!i)continue;const a=Ff(o);if(a!=="x"&&a!=="y")continue;const l=i.domainConfig||[];if(l.length<2||r[a])continue;const u=l[0],c=l[l.length-1];r[a]={channel:o,field:s.field,pxAt0:i.encode(u),pxAt1:i.encode(c),loVal:u,hiVal:c}}return Object.keys(r).length?r:null}function ri(e={}){const t=`glyph#${++fA}`,n=at(e,{mark:"composite",allow:st.composite}),{id:r,parts:o=[],edits:s,table:i,channels:a={},discreteScale:l="band"}=n,u=r||"composite",c=o.length-1;Gp(a);for(const m of o)Gp(m.channels||(m.channels={}));const d=o.some(m=>hA(m.channels))||Object.entries(a).some(([m,b])=>!ta.includes(m)&&Yr(b)),f={};for(const[m,b]of Object.entries(a))d&&ta.includes(m)||uA.includes(m)||(f[m]=b);if(!d&&a.ports){const m=o.filter(w=>typeof w.nodeBox=="function"),b=m.find(w=>!w.labelBox)||m[0]||o[0];b&&((b.channels||(b.channels={})).ports=a.ports)}const p=o.map((m,b)=>{const w=m.channels,x=dA(f,{...w},b===c);for(const _ of Object.keys(w))delete w[_];Object.assign(w,x);let S=Object.keys(w).filter(_=>Yr(w[_]));if(S.length)for(const _ of["x","y"])w[_]===void 0&&(w[_]={datum:0,scale:"frame"},S.push(_));S.length&&m.supportsSeries&&ge(`composite:series:${u}:${b}`,`composite "${u}" contains a series mark (${m.type||"a line-family mark"}) with local (frame) channels. A frame is per ROW, so the mark is built one row at a time and cannot group rows into a series. Position it on the global scales, or move it out of the composite.`);const v=m.build,k=S.length?((_,A,L,N)=>{const I=A.schema||{},T=it(A),M={width:L,height:N},$=[];for(let F=0;F<_.length;F++){const D=_[F],P=jc(A,a,D,F,_,L,N),j=gA(w,S,P,I,M,T),G=mA(w,S,j),J=v([D],{...A,...j},L,N)||[];for(const re of J)re.index=F,re.data=D,re.frame=j,G&&re.dm==null&&(re.dm=G),$.push(re)}return $}):v;return{...m,channels:w,build:k,nodeBox:S.length?void 0:m.nodeBox,labelBox:m.labelBox,glyph:t,xKey:w.x&&w.x.field||m.xKey,yKey:w.y&&w.y.field||m.yKey,id:m.id||`${u}/${b}`,table:m.table||i,discreteScale:m.discreteScale||l,edits:!d&&b===c&&s?[...s,...m.edits||[]]:m.edits}});if(!d)return p;const h={};for(const m of ta){const b=a[m];!b||Yr(b)||(h[m]=b)}a.ports&&(h.ports=a.ports);const y=!!(s&&s.length)||ta.some(m=>h[m]&&h[m].edit);return[{id:`${u}/frame`,type:"composite",glyph:t,channels:h,edits:s,table:i,discreteScale:l,...Xt(h),nodeBox:(m,b,w,x,S,v)=>{const k=jc(x,a,m,b,w,S,v);return{cx:k.cx,cy:k.cy,hw:k.r,hh:k.r,round:!0}},build:(m,b,w,x)=>m.map((S,v)=>{const k=jc(b,a,S,v,m,w,x);return{type:"circle",cx:k.cx,cy:k.cy,r:k.r,fill:"none",stroke:"none",hit:!0,...y?{pointerEvents:"all"}:{},data:S,index:v}})},...p]}const bA=e=>e<0?0:e>1?1:e,wA=["mouthCurve","mouthAsym","eyeScale","eyeSquint","browHeight","browTilt"],kt={ink:"#1f2937",headFill:"#FFD666",headStroke:"#B7791F",headStrokeWidth:.03,lineWidth:.055,eyeX:.4,eyeY:.16,eyeRx:[.055,.185],eyeRy:[.12,.03],eyeNeutral:.12,browInner:.14,browOuter:.5,browY:[.23,.57],browTiltRight:[-45,45],browTiltLeft:[45,-45],mouthY:-.34,mouthX:.36,mouthCurve:[.67,-.67],mouthAsym:[-20,20]};function xA(e={}){const t=at(e,{mark:"face",allow:st.face}),{id:n,edits:r,table:o,ink:s=kt.ink}=t,i={...t.channels};wA.some(x=>i[x])||(i.mouthCurve={field:"valence"},i.eyeScale={field:"arousal"});const a=(x,S,v=.5)=>{const k=i[x];if(k&&k.field!=null)return k.scale!==void 0||k.frame!==void 0?k:{...k,frame:S};const _=k&&k.value!==void 0?bA(+k.value):v;return{frame:S[0]+_*(S[1]-S[0])}},l=x=>({frame:x}),u=x=>({frame:x}),c=a("eyeScale",kt.eyeRx,(kt.eyeNeutral-kt.eyeRx[0])/(kt.eyeRx[1]-kt.eyeRx[0])),d=x=>{if(!x)return x;const{edit:S,...v}=x;return v},f=i.eyeSquint?a("eyeSquint",kt.eyeRy):d(c),p=a("browHeight",kt.browY),h=u(kt.lineWidth),y=n||"face",g=x=>`${y}/${x}`,m=x=>x<0?"left":"right",b=(x,S)=>tb({id:g(`brow-${m(x)}`),channels:{x1:l(x*kt.browInner),x2:l(x*kt.browOuter),y:p,angle:a("browTilt",S),stroke:{value:s},strokeWidth:h}}),w=x=>rb({id:g(`eye-${m(x)}`),channels:{x:l(x*kt.eyeX),y:l(kt.eyeY),rx:c,ry:f,fill:{value:s},stroke:{value:"none"}}});return ri({id:y,edits:r,table:o,channels:{x:i.x,y:i.y,size:i.size,...i.ports?{ports:i.ports}:{}},parts:[vr({id:g("head"),channels:{size:u(1),fill:i.fill||{value:kt.headFill},stroke:i.stroke||{value:kt.headStroke},strokeWidth:i.strokeWidth||u(kt.headStrokeWidth)}}),w(-1),w(1),b(-1,kt.browTiltLeft),b(1,kt.browTiltRight),ab({id:g("mouth"),channels:{x1:l(-.36),x2:l(kt.mouthX),y:l(kt.mouthY),curvature:a("mouthCurve",kt.mouthCurve),angle:a("mouthAsym",kt.mouthAsym),stroke:{value:s},strokeWidth:h}})]})}const vA=["text","fontSize","textAnchor","lineAnchor","dx"],kA=["x","y"];function SA(e={}){const t=at(e,{mark:"node",except:["dy"],allow:st.node}),{channels:n={},dy:r=-16,shape:o,format:s}=t,i=lt(t),a=i.id||"node",l={},u={},c={};for(const[f,p]of Object.entries(n))kA.includes(f)?l[f]=p:vA.includes(f)?c[f]=p:u[f]=p;const d=[];return n.text&&d.push(Tr({id:`${a}/label`,dy:r,...s!==void 0?{format:s}:{},channels:{textAnchor:{value:"middle"},...c}})),d.push(vr({id:`${a}/dot`,...o!==void 0?{shape:o}:{},channels:u})),ri({...i,channels:l,parts:d})}const $A=["text","fontSize","textAnchor","lineAnchor","dx","dy"],_A=["x","y"],MA=["width","height"],Wc=e=>{if(!e)return e;const{edit:t,...n}=e;return n};function EA(e={}){const t=at(e,{mark:"sticker",except:["padding","radius","maxWidth","minWidth","lineHeight"],allow:st.sticker}),{channels:n={},padding:r=10,radius:o=6,maxWidth:s=160,minWidth:i=60,minHeight:a=0,lineHeight:l,fontFamily:u,format:c}=t,d=lt(t),f=d.id||"sticker",p={},h={},y={};for(const[_,A]of Object.entries(n))_A.includes(_)?p[_]=A:$A.includes(_)?y[_]=A:h[_]=A;const g=y.fontSize&&(y.fontSize.value??y.fontSize)||13,m=n.text&&n.text.field,b=n.text&&n.text.fn,w=n.text&&n.text.value,x=(_,A,L)=>{const N=n.width?+pt(n,"width",_,NaN,A,L):NaN;return Number.isFinite(N)?N:s},S=(_,A,L)=>{const N=m!=null?_[m]:typeof b=="function"?b(_,A,L):w;return $n(N,{padding:r,maxWidth:x(_,A,L),minWidth:i,minHeight:a,fontSize:+g||13,fontFamily:u,lineHeight:l})},v={...h,...p,rx:{value:o}};n.text&&(v.text=Wc(n.text));for(const _ of MA){if(v[_])continue;const A=_==="width"?L=>L.width:L=>L.height;v[_]={fn:(L,N,I)=>A(S(L,N,I))}}const k=[Ts({id:`${f}/body`,...d.edits?{edits:d.edits}:{},...d.table?{table:d.table}:{},channels:v}),Tr({id:`${f}/label`,wrap:(_,A,L)=>x(_,A,L)-r*2,...l!==void 0?{lineHeight:l}:{},...c!==void 0?{format:c}:{},channels:{textAnchor:{value:"middle"},lineAnchor:{value:"middle"},fontSize:{value:g},...y,...p.x?{x:Wc(p.x)}:{},...p.y?{y:Wc(p.y)}:{}}})];return ri({id:d.id,table:d.table,channels:{},parts:k})}const AA=6;function ur(e,t){const n=Math.hypot(e,t)||1;return{x:e/n,y:t/n}}function TA(e){return ur(e.x2-e.x1,e.y2-e.y1)}function OA(e){const t=TA(e);return{points:[[e.x1,e.y1],[e.x2,e.y2]],curve:"linear",start:{x:e.x1,y:e.y1},end:{x:e.x2,y:e.y2},mid:{x:(e.x1+e.x2)/2,y:(e.y1+e.y2)/2},tangentIn:t,tangentOut:t}}function qc(e){return(t,n)=>{const r=t.x2-t.x1,o=t.y2-t.y1,s=Math.sign(r)||1,i=Math.sign(o)||1,a={x:s,y:0},l={x:0,y:i};let u,c,d;if(e==="stepAfter")u=[[t.x1,t.y1],[t.x2,t.y1],[t.x2,t.y2]],c=a,d=l;else if(e==="stepBefore")u=[[t.x1,t.y1],[t.x1,t.y2],[t.x2,t.y2]],c=l,d=a;else{const f=Math.min(.85,Math.max(.15,.5+n)),p=t.x1+r*f;u=[[t.x1,t.y1],[p,t.y1],[p,t.y2],[t.x2,t.y2]],c=a,d=a}return{points:u,curve:"linear",start:{x:t.x1,y:t.y1},end:{x:t.x2,y:t.y2},mid:{x:(t.x1+t.x2)/2,y:(t.y1+t.y2)/2},tangentIn:c,tangentOut:d}}}function CA(e,t){const n=(e.x1+e.x2)/2,r=(e.y1+e.y2)/2,o=e.x2-e.x1,s=e.y2-e.y1,i=n-s*t,a=r+o*t;return{d:`M${e.x1},${e.y1}Q${i},${a} ${e.x2},${e.y2}`,hit:Jl([e.x1,e.y1],[i,a],[e.x2,e.y2]),start:{x:e.x1,y:e.y1},end:{x:e.x2,y:e.y2},mid:{x:.25*e.x1+.5*i+.25*e.x2,y:.25*e.y1+.5*a+.25*e.y2},tangentIn:ur(i-e.x1,a-e.y1),tangentOut:ur(e.x2-i,e.y2-a)}}function Vp(e,t,n={}){const r=e.x2-e.x1,o=e.y2-e.y1,s=Math.abs(r)>=Math.abs(o),i=Math.abs(s?r:o)*(.5+Math.abs(t)),a=n.sourceNormal,l=n.targetNormal,u=Math.hypot(r,o),c=(w,x)=>x<0?Math.min(i,Math.max(20,u*.2)):i,d=a?c(a,a.x*r+a.y*o):i,f=l?c(l,-(l.x*r+l.y*o)):i,p=a?[e.x1+a.x*d,e.y1+a.y*d]:s?[e.x1+Math.sign(r||1)*i,e.y1]:[e.x1,e.y1+Math.sign(o||1)*i],h=l?[e.x2+l.x*f,e.y2+l.y*f]:s?[e.x2-Math.sign(r||1)*i,e.y2]:[e.x2,e.y2-Math.sign(o||1)*i],y=[e.x1,e.y1],g=[e.x2,e.y2],m=p,b=h;return{d:`M${e.x1},${e.y1}C${p[0]},${p[1]} ${h[0]},${h[1]} ${e.x2},${e.y2}`,hit:ll(y,m,b,g),start:{x:e.x1,y:e.y1},end:{x:e.x2,y:e.y2},mid:{x:.125*e.x1+.375*p[0]+.375*h[0]+.125*e.x2,y:.125*e.y1+.375*p[1]+.375*h[1]+.125*e.y2},tangentIn:ur(p[0]-e.x1,p[1]-e.y1),tangentOut:ur(e.x2-h[0],e.y2-h[1])}}const Xp=12;function NA(e,t,n,r={}){const o=r.source,s=n*(1+.6*(r.nest||0));if(!o||!r.loopOut){const M=e.x1,$=e.y1,F=t<0?-1:1,D=s*.9,P=s*1.8*F,j=[M-D,$-P],G=[M+D,$-P],J=[M,$];return{d:`M${M},${$}C${j[0]},${j[1]} ${G[0]},${G[1]} ${M},${$}`,hit:ll(J,j,G,J),start:{x:M,y:$},end:{x:M,y:$},mid:{x:M,y:$-P*.75},tangentIn:ur(j[0]-M,j[1]-$),tangentOut:ur(M-G[0],$-G[1])}}const i=r.loopOut,a=r.loopIn||i,l=r.sourceGap||0,u=r.targetGap||0,c=tn[i],d=tn[a];if(i===a){const M=c,$={x:-M.y,y:M.x},F=M.x?o.hh:o.hw,D=Math.min(s*.35,F*.8),P=o.cx+M.x*o.hw,j=o.cy+M.y*o.hh,G=[P-$.x*D+M.x*l,j-$.y*D+M.y*l],J=[P+$.x*D+M.x*u,j+$.y*D+M.y*u],re=[P+M.x*s*1.8-$.x*s*.9,j+M.y*s*1.8-$.y*s*.9],Q=[P+M.x*s*1.8+$.x*s*.9,j+M.y*s*1.8+$.y*s*.9];return{d:`M${G[0]},${G[1]}C${re[0]},${re[1]} ${Q[0]},${Q[1]} ${J[0]},${J[1]}`,hit:ll(G,re,Q,J),start:{x:G[0],y:G[1]},end:{x:J[0],y:J[1]},mid:{x:P+M.x*(s*1.35+Xp),y:j+M.y*(s*1.35+Xp)},tangentIn:ur(re[0]-G[0],re[1]-G[1]),tangentOut:ur(J[0]-Q[0],J[1]-Q[1])}}const f=Et.indexOf(i),p=Et.indexOf(a),h=(p-f+4)%4,y=M=>{const $=[];for(let F=f;F!==p;F=(F+M+4)%4)$.push(Et[(F+M+4)%4]);return $};let g=h<2?1:h>2?-1:0;if(!g){const M=y(1);g=M.includes("top")||!y(-1).includes("top")&&M.includes("right")?1:-1}const m=o.cx-o.hw-s,b=o.cx+o.hw+s,w=o.cy-o.hh-s,x=o.cy+o.hh+s,S={top:[b,w],right:[b,x],bottom:[m,x],left:[m,w]},v=o.cx+c.x*o.hw,k=o.cy+c.y*o.hh,_=o.cx+d.x*o.hw,A=o.cy+d.y*o.hh,L=[[v+c.x*l,k+c.y*l],[v+c.x*s,k+c.y*s]];for(let M=f;M!==p;M=(M+g+4)%4){const $=g>0?Et[M]:Et[(M+3)%4];L.push(S[$])}L.push([_+d.x*s,A+d.y*s],[_+d.x*u,A+d.y*u]);const N=wb(L,Number(r.cornerRadius)||s*.4),I=L[0],T=L[L.length-1];return{points:N,curve:"linear",start:{x:I[0],y:I[1]},end:{x:T[0],y:T[1]},mid:xb(N),tangentIn:c,tangentOut:{x:-d.x||0,y:-d.y||0}}}function wb(e,t){if(!(t>0)||e.length<3)return e;const n=[e[0]];for(let r=1;r<e.length-1;r++){const o=e[r-1],s=e[r],i=e[r+1],a=Math.hypot(s[0]-o[0],s[1]-o[1]),l=Math.hypot(i[0]-s[0],i[1]-s[1]),u=Math.min(t,a/2),c=Math.min(t,l/2);if(!a||!l){n.push(s);continue}const d=[s[0]+(o[0]-s[0])/a*u,s[1]+(o[1]-s[1])/a*u],f=[s[0]+(i[0]-s[0])/l*c,s[1]+(i[1]-s[1])/l*c];for(const p of Jl(d,s,f,AA))n.push(p)}return n.push(e[e.length-1]),n}function xb(e){const t=[];let n=0;for(let o=1;o<e.length;o++){const s=Math.hypot(e[o][0]-e[o-1][0],e[o][1]-e[o-1][1]);t.push(s),n+=s}let r=n/2;for(let o=0;o<t.length;o++){if(r<=t[o]||o===t.length-1){const s=t[o]?r/t[o]:0;return{x:e[o][0]+(e[o+1][0]-e[o][0])*s,y:e[o][1]+(e[o+1][1]-e[o][1])*s}}r-=t[o]}return{x:e[0][0],y:e[0][1]}}function Jp(e,t){const n=r=>r&&r!=="auto"?String(r):null;return e?{side:n(e.side),offset:+e.offset||0}:{side:n(t),offset:0}}function IA(e,t,n){const r=n.source||{cx:e.x1,cy:e.y1,hw:0,hh:0},o=n.target||{cx:e.x2,cy:e.y2,hw:0,hh:0},s=Jp(n.sourcePort,n.sourceSide),i=Jp(n.targetPort,n.targetSide),a=T5({source:{box:r,port:{side:s.side,offset:s.offset+t}},target:{box:o,port:{side:i.side,offset:i.offset-t}},sourceGap:n.sourceGap||0,targetGap:n.targetGap||0,obstacles:n.obstacles,grid:n.grid});if(!a)return null;const l=wb(a.points,Number(n.cornerRadius)||0),u=a.points[0],c=a.points[a.points.length-1],d=tn[a.sourceSide],f=tn[a.targetSide];return{points:l,curve:"linear",start:{x:u[0],y:u[1]},end:{x:c[0],y:c[1]},mid:xb(l),tangentIn:d,tangentOut:{x:-f.x||0,y:-f.y||0}}}const fl={line:{anchors:"chord",build:e=>OA(e)},step:{anchors:"chord",build:qc("step")},stepBefore:{anchors:"chord",build:qc("stepBefore")},stepAfter:{anchors:"chord",build:qc("stepAfter")},orthogonal:{anchors:"box",build:IA},arc:{anchors:"chord",build:(e,t)=>CA(e,t)},bezier:{anchors:"chord",build:(e,t,n)=>Vp(e,t,n)},smooth:{anchors:"chord",build:(e,t,n)=>Vp(e,t,n)},loop:{anchors:"chord",build:(e,t,n)=>NA(e,t,n.loopRadius||0,n)}},LA=Object.keys(fl).filter(e=>e!=="loop");function vb(e,t){const n=r=>!!(t&&t.fields[r]);return{x:e.x||(n("x")?{field:"x"}:void 0),y:e.y||(n("y")?{field:"y"}:void 0)}}function kb(e,t,n,r,o,s,i,a,l){const u=vb(t,n);return r.map((c,d)=>{if(!c)return null;if(o){const f=o(c,d,r);if(f&&[f.cx,f.cy,f.hw,f.hh].every(Number.isFinite))return f}return{cx:se(e,u,"x",c,a/2,d,r),cy:se(e,u,"y",c,l/2,d,r),hw:s/2,hh:i/2}})}const FA=.16,RA=.9,zA=22,Zp=12,PA=8,Qp=140,ey=10,DA=["stroke","strokeWidth","strokeOpacity"],jA="#ffffff",WA=3,qA=3,HA=.9;function BA(e){return e?Object.keys(e.fields).filter(t=>e.fields[t]&&e.fields[t].type==="ref"):[]}function UA(e,t,n,r){if(!n||!n.schema)return null;const o=n.schema,s=o.tables[r],i=o.byRole.nodes||o.primary,a=o.tables[i];if(!s||!a)return null;const l=BA(s),u=e.source&&e.source.field||l[0],c=e.target&&e.target.field||l[1],d=a.key;return{rows:n.tables&&n.tables[i]||[],nodesName:i,sourceField:u,targetField:c,keyField:d}}function KA(e,t,n,r,o,s){const i=n-e,a=r-t,l=Math.hypot(i,a);if(!l||o+s>=l)return null;const u=i/l,c=a/l;return{x1:e+u*o,y1:t+c*o,x2:n-u*s,y2:r-c*s}}function ty(e,t){if(e==null||e==="auto")return null;const n=String(e);return Et.includes(n)?n:(ge(`link:side:${n}`,`link() got ${t}: ${JSON.stringify(e)}, which is not an edge. Use ${Et.map(r=>`"${r}"`).join(", ")}, or null to let the end slide along the box toward the other node. Sliding.`),null)}function ny(e,t){if(e==null)return 0;const n=+e;return Number.isFinite(n)?Math.max(-Ai,Math.min(Ai,n)):(ge(`link:offset:${t}`,`link() got ${t}: ${JSON.stringify(e)}, which is not a number. It is a fraction of the edge from its midpoint, between ${-Ai} and ${Ai}. Using the midpoint.`),0)}function YA(e,t){let n=e;switch(n==null||n==="auto"?n=t===!0?"target":"none":n===!0?n="target":n===!1&&(n="none"),n){case"none":return{source:!1,target:!1};case"target":return{source:!1,target:!0};case"source":return{source:!0,target:!1};case"both":return{source:!0,target:!0};default:return ge(`link:arrow:${n}`,`link() got arrow: ${JSON.stringify(n)}, which it doesn't know. Use "none", "target", "source", "both", or "auto" (the target end when the links table declares directed: true). Drawing no arrowhead.`),{source:!1,target:!1}}}function ry(e,t,n,r){const o=r*.5;return`M${e+n.x*r},${t+n.y*r}L${e-n.y*o},${t+n.x*o}L${e+n.y*o},${t-n.x*o}Z`}function GA(e,t,n,r,o){const s=new Map,i=new Map,a=u=>{const c=String(u[t]),d=String(u[n]);return c<d?`${c}\0${d}`:`${d}\0${c}`};e.forEach((u,c)=>{if(!u)return;const d=a(u),f=s.get(d);f?f.push(c):s.set(d,[c])});const l=new Array(e.length).fill(0);for(const u of s.values())u.length<2||u.forEach((c,d)=>{const f=e[c];if(r){const p=`${f[t]}\0${f[n]}`,h=i.get(p)||0;i.set(p,h+1),l[c]=o*(h+1)}else l[c]=o*((2*d-(u.length-1))/2)});return l}function VA(e,t,n){const r=new Map;return e.map(o=>{if(!o||o[t]==null||o[t]!==o[n])return-1;const s=String(o[t]),i=r.get(s)||0;return r.set(s,i+1),i})}function XA(e={}){const t=at(e,{mark:"link",allow:st.link}),{channels:n={},id:r,edits:o,table:s,curve:i="line",curvature:a="auto",spread:l=FA,arrow:u="auto",arrowSize:c=6,loopRadius:d=zA,inset:f=0,sourceInset:p,targetInset:h,format:y,cornerRadius:g=PA,sourceSide:m="auto",targetSide:b="auto",sourceOffset:w=0,targetOffset:x=0,labelBackground:S,labelPadding:v=WA,labelRadius:k=qA,labelOpacity:_=HA}=t,A=kr(y),L=I=>!!(n[I]&&n[I].edit)||Array.isArray(o)&&o.some(T=>T&&Array.isArray(T.channels)&&T.channels.includes(I)),N={source:L("source"),target:L("target")};return{...lt(t),type:"link",channels:n,table:s,tableRole:"links",supportsNetwork:!0,rawChannels:["sourceSide","targetSide","sourceOffset","targetOffset","curve","arrow","fontSize"],discreteScale:void 0,build:(I,T,M,$,F)=>{const D=UA(n,t,F,F?F.table:"");if(!D)return ge("link:structure",'link() needs a network dataset: declare schema: { structure: "network", tables: { nodes: {…}, links: {…} } }. Without a links table there is nothing for it to draw.'),[];if(!D.keyField)return ge("link:key",'link() cannot find the column that identifies a node. Mark one in the node table with `key: true` (e.g. id: { type: "categorical", key: true }), or pass link({ key: "id" }). No links are drawn until it can.'),[];if(!D.sourceField||!D.targetField)return ge("link:refs",`link() cannot find the link table's endpoint columns. Declare them as references — source: { type: "ref" }, target: { type: "ref" } — or name them with channels: { source: { field: … }, target: { field: … } }.`),[];const P=F.schema,j=P.tables[D.nodesName],G=vb(n,j),J=it(T),re=Nt(T,"link",{stroke:J.ink,fill:"none"}),Q=dn(T,t),ve=p??f,Ce=h??f,le=F&&F.nodeBox||null,be=F&&F.nodePorts||null,ce=(f||Zp)*2,Y=(f||Zp)*2,ue=!!le,ie=ks(P),U=a==="auto"?GA(I,D.sourceField,D.targetField,ie,l):null,we=VA(I,D.sourceField,D.targetField),xe=n.text?{...n}:null;if(xe)for(const Se of DA)delete xe[Se];const z=xe&&S?S===!0?J.background||jA:String(S):null,H=J.font&&J.font.family||void 0,oe=new Map;D.rows.forEach((Se,ae)=>{const _e=Se?Se[D.keyField]:void 0;_e!=null&&!oe.has(_e)&&oe.set(_e,{row:Se,index:ae})});let de=null,ke=[],he;const $e=()=>{if(de)return de;const Se=kb(T,n,j,D.rows,le,ce,Y,M,$);return ke=Se.filter(Boolean),he=O5(ke),de=Se,Se},Te=[];return I.forEach((Se,ae)=>{const _e=oe.get(Se?Se[D.sourceField]:void 0),ze=oe.get(Se?Se[D.targetField]:void 0),Z=F&&F.ghost&&F.ghost.pointer?F.ghost.pointer:null,vt=!_e&&ze&&Z?Z:null,rt=!ze&&_e&&Z?Z:null,dt=vt||rt;if(!_e&&!vt||!ze&&!rt)return;const gt=le&&_e?$e()[_e.index]:null,Wt=le&&ze?$e()[ze.index]:null,At=gt?gt.cx:_e?se(T,G,"x",_e.row,M/2,_e.index,D.rows):vt.x,Jt=gt?gt.cy:_e?se(T,G,"y",_e.row,$/2,_e.index,D.rows):vt.y,qt=Wt?Wt.cx:ze?se(T,G,"x",ze.row,M/2,ze.index,D.rows):rt.x,Zn=Wt?Wt.cy:ze?se(T,G,"y",ze.row,$/2,ze.index,D.rows):rt.y,C=!!ze&&!!_e&&_e.index===ze.index,W=YA(pt(n,"arrow",Se,u,ae,I),ie);let q=U?U[ae]:+a||0,V=C?"loop":String(pt(n,"curve",Se,i,ae,I));fl[V]||(ge(`link:curve:${V}`,`link() got curve: "${V}", which it doesn't know. Use one of ${LA.map(Ue=>`"${Ue}"`).join(", ")}. Drawing a straight line.`),V="line"),V==="line"&&q&&(V="arc");const ee=fl[V];let pe;const me={loopRadius:d,cornerRadius:+g||0},Oe={side:ty(pt(n,"sourceSide",Se,m,ae,I),"sourceSide"),offset:ny(pt(n,"sourceOffset",Se,w,ae,I),"sourceOffset")},Je={side:ty(pt(n,"targetSide",Se,b,ae,I),"targetSide"),offset:ny(pt(n,"targetOffset",Se,x,ae,I),"targetOffset")},Ht=(Ue,Tt,Zt)=>$e()[Ue]||{cx:Tt,cy:Zt,hw:ce/2,hh:Y/2},wt=_e?Ht(_e.index,At,Jt):{cx:At,cy:Jt,hw:0,hh:0},ct=ze?Ht(ze.index,qt,Zn):{cx:qt,cy:Zn,hw:0,hh:0},Pn=(Ue,Tt)=>{if(!be||!Ue)return null;const Zt=be(Ue.row,Ue.index,D.rows)||{},Rt=Et.filter(sn=>I0(Zt[sn],Tt));return Rt.length?Rt:null},An=Pn(_e,"source"),Bt=Pn(ze,"target");if(C){const Ue=k5(An,Bt,Oe.side,Je.side,Math.max(0,we[ae]));me.loopOut=Ue.out,me.loopIn=Ue.in,me.nest=Ue.nest}else An&&!Oe.side&&(Oe.side=_p(wt,An,{x:ct.cx,y:ct.cy}));!C&&Bt&&!Je.side&&(Je.side=_p(ct,Bt,{x:wt.cx,y:wt.cy}));const Ut=(An?0:ve)+(W.source?c:0),It=(Bt?0:Ce)+(W.target?c:0);if(ee.anchors==="box")pe={x1:At,y1:Jt,x2:qt,y2:Zn},me.source=wt,me.target=ct,me.sourceGap=Ut,me.targetGap=It,me.obstacles=ke,me.grid=he,me.sourcePort=Oe,me.targetPort=Je;else if(C)pe={x1:At,y1:Jt,x2:At,y2:Jt},ue?(me.source=wt,me.sourceGap=Ut,me.targetGap=It):(delete me.loopOut,me.nest=Math.floor(Math.max(0,we[ae])/2));else if(ue||Oe.side||Je.side){const Ue=C0(wt,Oe,Ut,ct,Je,It),Tt=(sn,er,po)=>{const yo=po.x-sn.cx,Ls=po.y-sn.cy,cc=sn.hw+er,Fs=sn.hh+er,Rs=1/(Math.hypot(yo/(cc||1e-6),Ls/(Fs||1e-6))||1);return{x:sn.cx+yo*Rs,y:sn.cy+Ls*Rs}},Zt=!Oe.side&&wt.round?Tt(wt,Ut,Je.side?Ue.b:{x:ct.cx,y:ct.cy}):Ue.a,Rt=!Je.side&&ct.round?Tt(ct,It,Oe.side?Ue.a:{x:wt.cx,y:wt.cy}):Ue.b;pe=Math.hypot(Rt.x-Zt.x,Rt.y-Zt.y)<1?null:{x1:Zt.x,y1:Zt.y,x2:Rt.x,y2:Rt.y},Oe.side&&(me.sourceNormal=tn[Oe.side]),Je.side&&(me.targetNormal=tn[Je.side])}else pe=KA(At,Jt,qt,Zn,Ut,It);if(!pe)return;if(U&&q&&xe&&ee.anchors==="chord"&&!C){const Ue=Math.hypot(pe.x2-pe.x1,pe.y2-pe.y1),Tt=l*Ue/2,Rt=(+pt(n,"fontSize",Se,12,ae,I)||12)+v*2+2;Tt>0&&Tt<Rt&&(q=Math.sign(q)*Math.min(Math.abs(q)*(Rt/Tt),RA))}const tt=yt(T,n,Se,re,ae,I),Ge=ee.build(pe,q,me);if(!Ge)return;const Pr=+pt(n,"fontSize",Se,12,ae,I)||12,Dr={x:Ge.mid.x-Qp/2,y:Ge.mid.y-(Pr+ey)/2,width:Qp,height:Pr+ey},Qn=Ge.hit||Ge.points;Qn&&Te.push({type:"path",points:Qn,curve:Ge.hit?"linear":Ge.curve,stroke:"transparent",strokeWidth:Math.max(sb,+tt.strokeWidth||0),strokeLinecap:"round",fill:"none",hit:!0,editBox:Dr,data:Se,index:ae}),Te.push({type:"path",...Ge.d?{d:Ge.d}:{points:Ge.points,curve:Ge.curve},...tt,fill:"none",...dt?{strokeDasharray:"4 3"}:{},editBox:Dr,data:Se,index:ae});const on=tt.stroke||re.stroke;if(W.target&&Te.push({type:"path",d:ry(Ge.end.x,Ge.end.y,Ge.tangentOut,c),fill:on,stroke:"none",data:Se,index:ae}),W.source&&Te.push({type:"path",d:ry(Ge.start.x,Ge.start.y,{x:-Ge.tangentIn.x,y:-Ge.tangentIn.y},c),fill:on,stroke:"none",data:Se,index:ae}),xe){const Ue=Object.assign(ud(T,xe,Se,ae,Ge.mid.x,Ge.mid.y,{format:A,data:I}),{editBox:Dr});if(z&&Ue.text!==""&&Ue.text!=null){const Tt=Zl(String(Ue.text),{fontSize:+(Ue.fontSize||0)||12,fontFamily:H}),Zt=Tt.width+v*2,Rt=Tt.height+v*2,sn=Ue.x||0,er=Ue.y||0;Te.push({type:"rect",x:Ue.textAnchor==="start"?sn:Ue.textAnchor==="end"?sn-Zt:sn-Zt/2,y:Ue.lineAnchor==="top"?er:Ue.lineAnchor==="bottom"?er-Rt:er-Rt/2,width:Zt,height:Rt,rx:k,fill:z,fillOpacity:_,stroke:"none",...Ue.angle?{angle:Ue.angle}:{},editBox:Dr,data:Se,index:ae})}Te.push(Ue)}for(const[Ue,Tt]of[["source",Ge.start],["target",Ge.end]])!N[Ue]||!Q.grabbable||Te.push({type:"circle",cx:Tt.x,cy:Tt.y,r:Q.size,fill:Q.fill,stroke:Q.stroke,strokeWidth:Q.strokeWidth,channel:Ue,onHover:!0,raise:!0,data:Se,index:ae})}),Te}}}function Sb(e){if(!e||!e.raw||typeof e.raw.scale!="function")return!1;const t=2*Math.PI*e.raw.scale();if(!Number.isFinite(t)||t<=0)return!1;const n=e.apply([0,0]);if(!n)return!1;const r=n[0]-t/2,o=n[1]-t/2,s=l=>{const u=l*Math.PI/180;return o+t*(.5-Math.log(Math.tan(Math.PI/4+u/2))/(2*Math.PI))},i=l=>r+t*(l+180)/360,a=Math.max(.5,t*1e-6);for(const[l,u]of[[90,0],[-60,45],[30,-30],[0,60]]){const c=e.apply([l,u]);if(!c||Math.abs(c[0]-i(l))>a||Math.abs(c[1]-s(u))>a)return!1}return!0}function $b(e,t,n,r={}){const{tileSize:o=256,minZoom:s=0,maxZoom:i=19,zoomOffset:a=0}=r;if(!Sb(e)||!(t>0)||!(n>0))return null;const l=e,u=2*Math.PI*l.raw.scale();if(!Number.isFinite(u)||u<=0)return null;const c=Math.round(Math.log2(u/o))+a,d=Math.max(s,Math.min(i,c)),f=2**d,p=u/f,h=l.apply([0,0]);if(!h)return null;const y=h[0]-u/2,g=h[1]-u/2,m=Math.floor((0-y)/p),b=Math.ceil((t-y)/p),w=Math.floor((0-g)/p),x=Math.ceil((n-g)/p),S=[];for(let v=Math.max(0,w);v<Math.min(f,x);v++)for(let k=m;k<b;k++){const _=(k%f+f)%f;S.push({z:d,x:_,y:v,px:y+k*p,py:g+v*p,size:p,key:`${d}/${_}/${v}`})}return{z:d,size:p,tiles:S}}function _b(e,t,n=["a","b","c"]){if(typeof e=="function")return e(t);const r=n.length?n[Math.abs(t.x+t.y)%n.length]:"";return e.replace("{s}",r).replace("{z}",String(t.z)).replace("{x}",String(t.x)).replace("{y}",String(t.y))}const JA=Symbol("single");function ZA(){ge("geoTile:mercator",'geoTile needs projection: "mercator" (unrotated). Tiles are images baked in Web Mercator — under another projection they cannot align with the data, so none are drawn. Use geoBasemap({ geojson }) for vector chrome under other projections.')}function Cr(e){return e&&e.projection||null}function pn(e,t){const n=e[t];return n&&n.field!=null?n.field:null}function QA(e={}){const t=at(e,{mark:"geoBasemap",allow:st.geoBasemap,except:["stroke","strokeWidth","fill"]}),{channels:n={},id:r,edits:o,geojson:s,stroke:i="#94a3b8",strokeWidth:a=.75,fill:l="#e2e8f0"}=t,u=s||null;return{...lt(t),type:"geoBasemap",channels:n,supportsGeo:!0,build:(c,d,f,p)=>{const h=Cr(d);if(!h||!u)return[];const y=yt(d,n,{},{fill:l,stroke:i,strokeWidth:a}),g=y.fill!=null?y.fill:l,m=y.stroke!=null?y.stroke:i,b=y.strokeWidth!=null?y.strokeWidth:a,w=u.type==="FeatureCollection"&&Array.isArray(u.features)?u.features:[u],x=[];return w.forEach((S,v)=>{const k=S&&S.type==="Feature"?S.geometry:S;if(!k)return;const _=h.path(k);_&&x.push({type:"path",d:_,fill:g,stroke:m,strokeWidth:b,opacity:y.opacity,fillOpacity:y.fillOpacity,strokeOpacity:y.strokeOpacity,background:!0,pointerEvents:"none",index:v})}),x}}}function e4(e={}){const t=at(e,{mark:"geoTile",allow:st.geoTile,except:["opacity"]}),{channels:n={},id:r,edits:o,url:s="https://tile.openstreetmap.org/{z}/{x}/{y}.png",subdomains:i=[],tileSize:a=256,minZoom:l=0,maxZoom:u=19,zoomOffset:c=0,opacity:d,attribution:f="© OpenStreetMap contributors",attributionSize:p=9}=t;return{...lt(t),type:"geoTile",channels:n,supportsGeo:!0,build:(h,y,g,m)=>{const b=Cr(y);if(!b)return[];const w=$b(b,g,m,{tileSize:a,minZoom:l,maxZoom:u,zoomOffset:c});if(!w)return ZA(),[];const x=w.tiles.map(S=>({type:"image",x:S.px,y:S.py,width:S.size+.5,height:S.size+.5,href:_b(s,S,i),opacity:d,background:!0,pointerEvents:"none",key:S.key}));return f&&x.push({type:"text",x:g-4,y:m-4,text:f,fontSize:p,textAnchor:"end",lineAnchor:"bottom",dominantBaseline:"text-after-edge",fill:"#334155",pointerEvents:"none"}),x}}}function t4(e={}){const t=at(e,{mark:"geoPoint",allow:st.geoPoint}),{channels:n={},id:r,edits:o}=t,s=pn(n,"lon")||"lon",i=pn(n,"lat")||"lat";return{...lt(t),type:"geoPoint",channels:n,supportsGeo:!0,lonKey:s,latKey:i,xKey:s,yKey:i,build:(a,l,u,c)=>{const d=Cr(l),f=[],p=Nt(l,"geoPoint",{fill:it(l).ink});return a.forEach((h,y)=>{const g=n.lon?h[s]:h.lon,m=n.lat?h[i]:h.lat,b=cr(d,g,m);if(!b)return;const w=yt(l,n,h,p,y,a);f.push({type:"circle",cx:b.x,cy:b.y,r:se(l,n,"size",h,5,y,a),...w,data:h,index:y})}),f}}}function n4(e={}){const t=at(e,{mark:"geoPolygon",allow:st.geoPolygon}),{channels:n={},id:r,edits:o}=t,s=pn(n,"geometry")||"geometry";return{...lt(t),type:"geoPolygon",channels:n,supportsGeo:!0,geometryKey:s,build:(i,a)=>{const l=Cr(a);if(!l)return[];const u=[];return i.forEach((c,d)=>{const f=c[s];if(!f)return;const p=l.path(f);if(!p)return;const h=yt(a,n,c,{fill:"#93c5fd",stroke:"#1e3a8a",strokeWidth:.75});u.push({type:"path",d:p,...h,data:c,index:d})}),u}}}function r4(e,t){const n=Yf(t);return n?e.slice().sort((r,o)=>{const s=r.d[n],i=o.d[n];return s==null||i==null?0:s<i?-1:s>i?1:0}):e}function o4(e={}){const t=at(e,{mark:"geoLine",allow:st.geoLine}),{channels:n={},id:r,edits:o,curve:s="linear",handles:i=!0,handleSize:a,handleColor:l}=t,u=pn(n,"coordinates")||"coordinates",c=pn(n,"geometry")||null,d=!!(n.lon&&n.lat),f=pn(n,"lon")||"lon",p=pn(n,"lat")||"lat",h=Ms(n),y=t.connect||"sequence",g=t.showVertices!=null?t.showVertices:!d;return d?{...lt(t),type:"geoLine",channels:n,rawChannels:["curve","series","order"],supportsGeo:!0,lonKey:f,latKey:p,xKey:f,yKey:p,seriesKey:h,connect:y,supportsSeries:!0,build:(m,b)=>{const w=Cr(b);if(!w)return[];const x=[];m.forEach((_,A)=>{const L=cr(w,_[f],_[p]);L&&x.push({d:_,i:A,x:L.x,y:L.y,series:h?_[h]:JA})});const S=new Map;for(const _ of x){const A=S.get(_.series);A?A.push(_):S.set(_.series,[_])}const v=[],k=dn(b,{handles:i,handleSize:a,handleColor:l});for(const _ of S.values()){if(_.length<2)continue;const A=r4(_,n),L=yt(b,n,_[0].d,{stroke:"#1d4ed8",strokeWidth:2}),N=String(pt(n,"curve",_[0].d,s,_[0].i,m));v.push({type:"path",points:A.map(I=>[I.x,I.y]),curve:N,...L,fill:"none"})}return g&&x.forEach(_=>{v.push({type:"circle",cx:_.x,cy:_.y,r:k.size,fill:k.visible?k.fill:"transparent",stroke:"#fff",strokeWidth:1,data:_.d,index:_.i})}),v}}:{...lt(t),type:"geoLine",channels:n,supportsGeo:!0,coordinatesKey:u,geometryKey:c,supportsSeries:!1,build:(m,b)=>{const w=Cr(b);if(!w)return[];const x=[],S=dn(b,{handles:i,handleSize:a,handleColor:l});return m.forEach((v,k)=>{let _=null;if(c&&v[c]&&v[c].coordinates){const I=v[c];_=I.type==="LineString"?I.coordinates:I.type==="MultiLineString"?I.coordinates.flat():null}if(!_&&Array.isArray(v[u])&&(_=v[u]),!_||!_.length)return;const A={type:"LineString",coordinates:_},L=w.path(A),N=yt(b,n,v,{fill:"none",stroke:"#1d4ed8",strokeWidth:2});L&&x.push({type:"path",d:L,...N,fill:"none",data:v,index:k,pointerEvents:"stroke"}),g&&_.forEach((I,T)=>{const M=cr(w,I[0],I[1]);M&&x.push({type:"circle",cx:M.x,cy:M.y,r:S.size,fill:S.visible?l||N.stroke||S.fill:"transparent",stroke:"#fff",strokeWidth:1,data:v,index:k,channel:"vertex",vertexIndex:T})})}),x}}}function i4(e={}){const t=at(e,{mark:"geoText",allow:st.geoText}),{channels:n={},id:r,edits:o,format:s}=t,i=pn(n,"lon")||"lon",a=pn(n,"lat")||"lat",l=kr(s);return{...lt(t),type:"geoText",channels:n,supportsGeo:!0,lonKey:i,latKey:a,xKey:i,yKey:a,build:(u,c)=>{const d=Cr(c),f=[];return u.forEach((p,h)=>{const y=cr(d,p[i],p[a]);y&&f.push(ud(c,n,p,h,y.x,y.y,{format:l,data:u}))}),f}}}function s4(e={}){const t=at(e,{mark:"geoRect",allow:st.geoRect}),{channels:n={},id:r,edits:o}=t,s=pn(n,"west")||"west",i=pn(n,"south")||"south",a=pn(n,"east")||"east",l=pn(n,"north")||"north";return{...lt(t),type:"geoRect",channels:n,supportsGeo:!0,westKey:s,southKey:i,eastKey:a,northKey:l,xKey:s,yKey:i,build:(u,c)=>{const d=Cr(c),f=[];return u.forEach((p,h)=>{const y=p[s],g=p[i],m=p[a],b=p[l];if(y==null||g==null||m==null||b==null)return;const w=Math.min(y,m),x=Math.max(y,m),S=Math.min(g,b),v=Math.max(g,b),k=f0(d,w,S,x,v);if(!k||k.width<=0||k.height<=0)return;const _=yt(c,n,p,{fill:"rgba(37, 99, 235, 0.2)",stroke:"#1d4ed8",strokeWidth:1.5}),A={type:"Polygon",coordinates:[[[w,S],[w,v],[x,v],[x,S],[w,S]]]},L=d&&d.path(A);L&&f.push({type:"path",d:L,..._,data:p,index:h,pointerEvents:"none"}),f.push({type:"rect",x:k.x,y:k.y,width:k.width,height:k.height,fill:"transparent",stroke:"transparent",data:p,index:h})}),f}}}const yd=Object.freeze(Object.defineProperty({__proto__:null,arc:db,area:ad,areaX:D6,areaY:P6,bar:nd,barX:m6,barY:Xl,composite:ri,curve:ld,curveX:W6,curveY:ab,donut:q6,dotStack:id,dotStackX:O6,dotStackY:ob,ellipse:rb,face:xA,geoBasemap:QA,geoLine:o4,geoPoint:t4,geoPolygon:n4,geoRect:s4,geoText:i4,geoTile:e4,line:sd,lineX:L6,lineY:I6,link:XA,needle:H6,node:SA,path:F6,point:vr,rect:Ts,rectX:w6,rectY:x6,rule:rd,ruleX:$6,ruleY:nb,sticker:EA,text:Tr,textX:rA,textY:oA,tick:us,tickX:k6,tickY:tb,trend:mb,trendBand:bb,waffle:od,waffleX:A6,waffleY:E6},Symbol.toStringTag,{value:"Module"}));function a4(e,t,n=1){return e>t+n?"start":e<t-n?"end":"middle"}const Mb=$s.axisRadial;function l4(e={}){Es("axisRadial",e,Mb);const{channels:t={},id:n,edits:r,channel:o="theta",radius:s,innerRadius:i=0,bandWidth:a=18,ticks:l=5,tickValues:u,tickFormat:c,tickSize:d=6,labelOffset:f=14,bands:p=!1,title:h,arc:y,orient:g,start:m,end:b,labelFill:w,stroke:x,strokeWidth:S=1.25,fontSize:v}=e,[k,_]=cd({arc:y,orient:g,start:m,end:b}),A=t.x&&t.x.field,L=t.y&&t.y.field;return{id:n,type:"axisRadial",channel:o,channels:t,edits:r,isAxis:!0,views:"scale",layer:"background",build:(N,I,T,M)=>{const $=I[o];if(!$)return[];const F=it(I),D=w??F.axis.labelFill,P=x??F.axis.stroke,j=v??F.axis.fontSize,G=typeof $.range=="function"?$.range():null;let J=k,re=_;G&&G.length>=2&&typeof G[0]=="number"&&(J=G[0],re=G[G.length-1]);const Q={background:!0,pointerEvents:"none"},{values:ve,format:Ce}=Yl($,{ticks:l,tickValues:u,tickFormat:c}),le=t.fill&&t.fill.field,be=(ie,U,we)=>{const xe=[];p&&uo($)&&$.domain().forEach((oe,de)=>{const ke=ub($,oe);if(!ke)return;const[he,$e]=ke,Te=le?{[le]:oe}:{};let Se=se(I,t,"fill",Te,null);Se==null&&(Se=is[de%is.length]);const ae=i>0?i:Math.max(0,we-a),_e=fs(ie,U,we,he,$e,{innerRadius:ae});_e&&xe.push({type:"path",d:_e,fill:Se,stroke:"none",fillOpacity:.9,...Q})});const z=cl(ie,U,we,J,re);return z&&xe.push({type:"path",d:z,fill:"none",stroke:P,strokeWidth:S,...Q}),ve.forEach(H=>{const oe=$r($,H);if(oe==null||Number.isNaN(oe))return;const de=un(ie,U,we,oe),ke=un(ie,U,we-d,oe);d>0&&xe.push({type:"line",x1:de.x,y1:de.y,x2:ke.x,y2:ke.y,stroke:P,strokeWidth:1,...Q});const he=un(ie,U,we+f,oe);xe.push({type:"text",x:he.x,y:he.y,text:Ce(H),textAnchor:a4(he.x,ie),dominantBaseline:"middle",fontSize:j,fill:D,...Q})}),h&&xe.push({type:"text",x:ie,y:U+we+f+j+8,text:h,textAnchor:"middle",fontSize:j+1,fill:"#0f172a",...Q}),xe};if(A||L){const ie=[],U=s??Math.min(T,M)*.42;return N.forEach((we,xe)=>{const z=se(I,t,"x",we,T/2,xe,N),H=se(I,t,"y",we,M/2,xe,N);ie.push(...be(z,H,U))}),ie}const ce=se(I,t,"x",N[0],T/2,0,N),Y=se(I,t,"y",N[0],M/2,0,N),ue=s??Math.min(T,M)*.42;return be(ce,Y,ue)}}}const c4=Object.freeze(Object.defineProperty({__proto__:null,axis:Gl,axisRadial:l4,axisX:Y0,axisY:G0,grid:Qf,gridX:V0,gridY:X0,legend:As,legendColor:BE,legendSize:UE,legendSymbol:KE},Symbol.toStringTag,{value:"Module"})),oy=e=>e.edit&&e.edit.threshold>0?e.edit.threshold:Ul,u4={shift:e=>!!(e.event&&e.event.shiftKey),noShift:e=>!(e.event&&e.event.shiftKey),alt:e=>!!(e.event&&e.event.altKey),noAlt:e=>!(e.event&&e.event.altKey),modifier:e=>t=>!!(t.event&&t.event[e]),noModifier:e=>t=>!(t.event&&t.event[e]),near:e=>Mr(e.marks||[],e.pointer.x,e.pointer.y,oy(e))!=null,far:e=>Mr(e.marks||[],e.pointer.x,e.pointer.y,oy(e))==null,nearWithin:e=>t=>Mr(t.marks||[],t.pointer.x,t.pointer.y,e)!=null},iy={year:Yn,month:zl,week:vs,day:ti,hour:Rl,minute:Fl};function Eb(e,t){if(!e)return[];if(uo(e)||e.kind==="discrete")return[...e.domain()];if(Array.isArray(t))return t;if(typeof t=="number")return sy(e,t);if(t&&typeof t=="object"){if(typeof t.count=="number")return sy(e,t.count);if(t.every&&e.temporal&&iy[t.every]&&typeof e.ticks=="function")return e.ticks(iy[t.every])}if(typeof e.ticks=="function"){const n=e.ticks();if(n&&n.length)return n}return[...e.domain()]}function sy(e,t){const n=e.domain(),r=Number(n[0]),o=Number(n[n.length-1]),s=!!e.temporal;if(t<=1)return[n[0]];const i=[];for(let a=0;a<t;a++){const l=r+(o-r)*a/(t-1);i.push(s?new Date(l):l)}return i}function f4(e={}){const{into:t="nearest",series:n,...r}=e,o=L0(e.threshold);return je({type:"line.anchor",gesture:"click",channels:["x","y"],pick:"plane",scope:"line",into:t,cardinality:"append",...r,apply:s=>{const i=n||s.seriesKey||null;let a=null;t==="nearest"&&(a=Mr(s.marks||[],s.pointer.x,s.pointer.y,o),a==null&&s.connect==="sequence"&&i&&(s.data||[]).length&&(a=s.data[s.data.length-1][i])),a==null&&(a=Wl(s.data,i));const l=Fn(s,{defaults:i?{[i]:a}:{}});if(l)return[...s.data,l]}})}function d4(e={}){const{along:t="x",value:n="y",samples:r,series:o,...s}=e;return je({type:"line.newSeries",gesture:"dblclick",cardinality:"appendMany",channels:[t,n],pick:"plane",scope:"line",...s,apply:i=>{const a=o||i.seriesKey||null,l=i.markChannels[t]&&i.markChannels[t].field||(t==="x"?i.xKey:i.yKey),u=i.markChannels[n]&&i.markChannels[n].field||(n==="x"?i.xKey:i.yKey),c=i.scales[t],d=i.scales[n];if(!c||!l)return;const f=Eb(c,r);if(!f.length)return;const p=n==="x"?i.pointer.x:i.pointer.y,h=d&&d.invertible?d.invertValue(p):d&&d.domain?d.domain()[0]:null,y=Wl(i.data,a),g=f.map(m=>{const b={...Ss(i.schema)};return a&&(b[a]=y),b[l]=m,u&&(b[u]=h),b});return[...i.data,...g]}})}function h4(e={}){const{along:t="x",value:n="y",samples:r,minDist:o=8,into:s="nearest",series:i,...a}=e;return je({type:"line.draw",gesture:"drag",cardinality:"appendMany",inverts:!0,channels:[t,n],pick:"draw",scope:"line",into:s,...a,apply:l=>{const u=l.session;if(!u)return;const c=i||l.seriesKey||null,d=u.drawSeries,f=l.connect==="sequence",p={};for(const v of l.channels)p[v.name]=v;if(u.mode==="edit"){const v=f?In(l.marks||[],l.pointer.x,l.pointer.y,1/0,d):Vf(l.marks||[],l.pointer.x,l.pointer.y,1/0,t,d);if(v==null||l.data[v]==null)return;const k={...l.data[v]};for(const _ of l.channels){if(!f&&_.name!==n)continue;const A=fo(_,l.pointer);A!==void 0&&(k[_.field]=A)}return l.data.map((_,A)=>A===v?k:_)}if(f){const v=l.pointer.x,k=l.pointer.y;if(u.lastX!=null&&u.lastY!=null&&Math.hypot(v-u.lastX,k-u.lastY)<o)return;const _=Fn(l,{defaults:c?{[c]:d}:{}});return _?(u.lastX=v,u.lastY=k,[...l.data,_]):void 0}const h=p[t],y=p[n];if(!h||!y||!h.scale||!y.scale||!h.scale.invertible||!y.scale.invertible)return;const g=Eb(l.scales[t],r);if(!g.length)return;const m=h.scale.invertValue(t==="x"?l.pointer.x:l.pointer.y),b=y.scale.invertValue(n==="x"?l.pointer.x:l.pointer.y),w=()=>{let v=null,k=1/0;for(const _ of g){const A=Math.abs(xn(_)-xn(m));A<k&&(k=A,v=_)}return v==null?[]:[v]};let x;if(u.lastDomain==null)x=w();else{const v=Math.min(xn(u.lastDomain),xn(m)),k=Math.max(xn(u.lastDomain),xn(m));x=g.filter(_=>xn(_)>=v&&xn(_)<=k),x.length||(x=w())}u.lastDomain=m;const S=l.data.slice();for(const v of x){const k=S.findIndex(A=>(!c||A[c]===d)&&xn(A[h.field])===xn(v)),_={...Ss(l.schema),...k>=0?S[k]:{}};c&&(_[c]=d),_[h.field]=v,_[y.field]=b,k>=0?S[k]=_:S.push(_)}return S}})}function p4(e={}){return e.mode==="relative"&&(ge("sweep:relative",`edit.line.sweep({ mode: "relative" }) is not a mode a sweep has — the pointer's POSITION is the value it paints. Ignoring mode.`),e={...e,mode:"absolute"}),Vn({pick:"sweep",guide:!0,scope:"line",...e,type:"line.sweep"})}function y4(e={}){const{series:t,...n}=e;return je({type:"line.removeSeries",gesture:"click",scope:"line",cardinality:"delete",...n,apply:r=>{if(r.datum==null)return;const o=t||r.seriesKey||null;if(!o)return r.data.filter((i,a)=>a!==r.index);const s=r.datum[o];return r.data.filter(i=>i[o]!==s)}})}function g4(e,t){return t?[t]:e&&e.fields||[]}function m4(e,t){const n={};for(const r of e)n[r]=t;return n}function b4(e={}){const{field:t,mode:n="rescale",...r}=e,o=6;return je({type:"axis.scale",gesture:"drag",pick:"axisDrag",scope:"axis",target:"domain",...r,apply:s=>{const i=s.session,a=s.channels[0];if(!i||!i.grabEnd||!a||!a.scale)return;const l=g4(a.scale,t);if(!l.length)return;const u=i.anchorPixel,c=xn(i.anchorValue),d=xn(i.grabValue),f=i.anchorValue instanceof Date||i.grabValue instanceof Date;let h=(i.axis==="x"?s.pointer.x:s.pointer.y)-u;const y=i.grabPixel-u;Math.abs(h)<o&&(h=h<0?-o:o);let g;if(n==="grow"){const S=i.pxPerUnit||y/(d-c||1);g=c+h/(S||1)}else g=c+(d-c)*(y/h);const m=Math.min(c,g),b=Math.max(c,g);if(!Number.isFinite(m)||!Number.isFinite(b)||b<=m)return;const w=f?[new Date(m),new Date(b)]:[m,b],x={domains:m4(l,w)};if(n==="grow"){const S=Math.abs(i.pxPerUnit||1),v=(b-m)*S,k=s.margins||{top:20,right:20,bottom:30,left:40};x.resize=i.axis==="x"?{width:v+k.left+k.right}:{height:v+k.top+k.bottom}}return x}})}function w4(e,t,n){const r=e&&e.fieldRefs||[];if(t){const o=r.filter(s=>s.field===t);return o.length?o:[{table:n,field:t}]}return r.length?r:(e&&e.fields||[]).map(o=>({table:n,field:o}))}function Hc(e,t,n,r,o){const s={domains:{}},i={},a={};for(const l of e)(a[l.table]||(a[l.table]=[])).push(l.field);for(const[l,u]of Object.entries(a)){const c={};let d=o[l]||[],f=!1;for(const p of u){c[p]=t({table:l,field:p});const h=n({table:l,field:p},d);h&&(d=h,f=!0)}l===r?(s.domains=c,f&&(s.data=d)):i[l]=f?{domains:c,data:d}:{domains:c}}return Object.keys(i).length&&(s.tables=i),s}function ay(e,t){const n=e.channels[0],r=n&&$t(n.name);if(!r)return;const o=n&&n.scale,s=o&&typeof o.step=="function"?o.step():null;if(!s)return;const i=e.margins||{top:20,right:20,bottom:30,left:40};if(r==="y"){const l=(e.height||0)+t*s;return l>s?{height:l+i.top+i.bottom}:void 0}const a=(e.width||0)+t*s;return a>s?{width:a+i.left+i.right}:void 0}function x4(e={}){const{field:t,mode:n="rescale",when:r,...o}=e,s=n==="grow",i=f=>w4(f.channels[0]&&f.channels[0].scale,t,f.table||"data"),a=f=>{const p=f.channels[0];return p&&p.scale&&typeof p.scale.domain=="function"?[...p.scale.domain()]:[]},l=f=>f.tables||{[f.table]:f.data},u=je({type:"scale.addCategory",gesture:"commit",pick:"direct",scope:"scale",target:"domain",...o,when:Gr(f=>!!(f.node&&f.node.addCategory),r),apply:f=>{const p=f.value!=null?String(f.value).trim():"";if(!p)return;const h=a(f);if(h.includes(p))return;const y=i(f);if(!y.length)return;const g=Hc(y,()=>[...h,p],()=>null,f.table,l(f));if(s){const m=ay(f,1);m&&(g.resize=m)}return g}}),c=je({type:"scale.renameCategory",gesture:"commit",pick:"direct",scope:"scale",target:"domain",...o,when:Gr(f=>!!(f.node&&f.node.category!=null),r),apply:f=>{const p=f.node&&f.node.category,h=f.value!=null?String(f.value).trim():"";if(p==null||!h||h===p)return;const y=a(f);if(y.includes(h))return;const g=i(f);if(!g.length)return;const m=y.map(b=>b===p?h:b);return Hc(g,()=>m,({field:b},w)=>w.map(x=>x[b]===p?{...x,[b]:h}:x),f.table,l(f))}}),d=je({type:"scale.removeCategory",gesture:"click",pick:"direct",scope:"scale",target:"domain",...o,when:Gr(f=>!!(f.node&&f.node.removeCategory!=null),r),apply:f=>{const p=f.node&&f.node.removeCategory;if(p==null)return;const h=a(f);if(!h.includes(p))return;const y=i(f);if(!y.length)return;const g=h.filter(b=>b!==p),m=Hc(y,()=>g,({field:b},w)=>w.filter(x=>x[b]!==p),f.table,l(f));if(s){const b=ay(f,-1);b&&(m.resize=b)}return m}});return[u,c,d]}function Ab(e){return e?e.field:void 0}function Tb(e,t,n){const r=e.node&&e.node.indices||[];if(r.length>1){const o=new Set(r);return e.data.map((s,i)=>o.has(i)?{...s,[t]:n}:s)}return{...e.datum,[t]:n}}function v4(e={}){return je({type:"legend.category",gesture:"click",pick:"direct",scope:"legend",...e,apply:t=>{const n=Ab(t.channels[0]);if(!n||!t.node||t.datum==null)return;const r=t.node.category;if(r!==void 0)return Tb(t,n,r)}})}function k4(e={}){return je({type:"legend.value",gesture:"drag",pick:"direct",scope:"legend",...e,apply:t=>{const n=t.node;if(!n||n.rampStart==null||n.rampEnd==null)return;const r=Ab(t.channels[0]);if(!r||t.datum==null)return;const o=n.rampEnd-n.rampStart;if(!o)return;const s=n.along==="y"?t.pointer.y:t.pointer.x,i=Math.max(0,Math.min(1,(s-n.rampStart)/o)),a=n.loValue+i*(n.hiValue-n.loValue);return Tb(t,r,a)}})}const S4={linear:(e,t,n)=>{const r=t.scales&&t.scales[e.axis];if(!r||!r.invertible)return;const o=e.axis==="x"?t.pointer.x:t.pointer.y,s=Number(r.invertValue(o));if(Number.isFinite(s))return Math.max(n.lo,Math.min(n.hi,s))},angular:(e,t,n)=>{const{cx:r,cy:o,spanStart:s,spanEnd:i,pad:a}=e,l=i-s-a*n.n;if(!Number.isFinite(l)||l===0||!(n.total>0))return;const u=Math.sign(l)||1,c=s+a/2+n.local*a+l*(n.lo/n.total),f=((zf(t.pointer,{cx:r,cy:o})-c)*u%360+360)%360,p=Math.abs(l)*((n.hi-n.lo)/n.total);return p<1e-9?n.lo:f<=p?n.lo+f/Math.abs(l)*n.total:f-p<360-f?n.hi:n.lo}};function Ob(e,t,n){const r=e&&S4[e.kind];return r?r(e,t,n):void 0}function gd(e,t){const n=e&&e.stack;if(!n||!Array.isArray(n.members)||n.local==null||!n.field||!Array.isArray(t.data)||!t.data.length)return null;const{mags:r,total:o,bounds:s}=Vl(n.members,t.data,n.field);return{st:n,members:n.members,local:n.local,field:n.field,mags:r,total:o,bounds:s}}function $4(e,t){const n=e.markChannels||{},r=t||n.fill&&n.fill.field||n.stroke&&n.stroke.field||null;if(!r)return{field:null,domain:[],open:!0};const o=e.schema&&e.schema[r],s=o&&Array.isArray(o.domain)?o.domain:null;if(s)return{field:r,domain:s,open:!!o.open};for(const i of["fill","stroke"]){const a=n[i];if(!a||a.field!==r)continue;const l=e.scales[i],u=l&&Array.isArray(l.domainConfig)?l.domainConfig:null;if(u)return{field:r,domain:u,open:!0}}return{field:r,domain:[],open:!0}}function _4(e={}){const{defaults:t={},label:n,categoryField:r,when:o,...s}=e;return je({type:"stack.cut",gesture:"click",pick:"direct",scope:"stack",target:"domain",...s,when:Gr(i=>!!(i.node&&i.node.stack&&!i.node.edge),o),apply:i=>{const a=i.node,l=gd(a,i);if(!l)return;const{members:u,local:c,field:d,mags:f,total:p,bounds:h}=l,[y,g]=h[c];if(!(g>y))return;const m=Ob(l.st.geometry,i,{lo:y,hi:g,local:c,n:u.length,total:p});if(m===void 0)return;const b=u[c],w=i.data[b],x=$4(i,r),S=u.map(N=>i.data[N]),v=Wf(S,x.field,x.domain,{open:x.open,label:n});if(x.field&&v===void 0){ge(`stack:domainfull:${x.field}`,`edit.stack.cut() has no category left to give a new segment: this stack already uses every value in schema.${x.field}'s domain (${JSON.stringify(x.domain)}). A declared domain is the whole vocabulary, so the cut is refused. Declare more categories, or set schema.${x.field}.open = true to let a cut add one.`);return}const k={};for(const N of["x","y"]){const I=i.markChannels[N]&&i.markChannels[N].field;I&&(k[I]=w[I])}const _={...Ss(i.schema),...k,...x.field?{[x.field]:v}:{},[d]:g-m,...t},A=i.data.slice();A[b]={...w,[d]:m-y},A.splice(b+1,0,_);const L={};return x.field&&x.open&&!x.domain.includes(v)&&(L[x.field]=[...x.domain,v]),{domains:L,data:A}}})}function M4(e={}){const{when:t,...n}=e;return je({type:"stack.edge",inverts:!0,gesture:"drag",pick:"direct",scope:"stack",...n,when:Gr(r=>!!(r.node&&r.node.edge&&r.node.stack),t),apply:r=>{const o=gd(r.node,r);if(!o)return;const{members:s,local:i,field:a,mags:l,total:u,bounds:c}=o,d=i+1;if(d>=s.length)return;const f=l[i]+l[d];if(!(f>0))return;const p=c[i][0],h=c[d][1],y=Ob(o.st.geometry,r,{lo:p,hi:h,local:i,n:s.length,total:u});if(y===void 0)return;const g=y-p,m=f-g,b=s[i],w=s[d];return r.data.map((x,S)=>S===b?{...x,[a]:g}:S===w?{...x,[a]:m}:x)}})}function E4(e={}){const{when:t,...n}=e;return je({type:"stack.merge",gesture:"dblclick",pick:"direct",scope:"stack",cardinality:"delete",...n,when:Gr(r=>!!(r.node&&r.node.edge&&r.node.stack),t),apply:r=>{const o=gd(r.node,r);if(!o)return;const{members:s,local:i,field:a,mags:l}=o,u=i+1;if(u>=s.length)return;const c=s[i],d=s[u],f=l[i]+l[u];return r.data.map((p,h)=>h===c?{...p,[a]:f}:p).filter((p,h)=>h!==d)}})}const A4=1;function T4(e,t){const n=e.markChannels&&e.markChannels[t];return n&&n.field!=null?n.field:null}function ly(e,t,n){const r=e.markChannels&&e.markChannels[t];if(!r)return n;if(r.field!=null){const s=e.datum?Number(e.datum[r.field]):NaN;return Number.isFinite(s)?s:n}const o=Number(r.datum!==void 0?r.datum:r.value);return Number.isFinite(o)?o:n}function O4(e,t){const n=e.scales.x,r=e.scales.y;if(!r||!r.invertible)return null;const o=e.node?{anchor:e.node.anchor,probe:e.node.probe}:{},{anchor:s,probe:i}=Ql(e.scales,{anchor:t.anchor!=null?t.anchor:o.anchor,probe:t.probe!=null?t.probe:o.probe}),a=ly(e,"intercept",0),l=ly(e,"slope",0),u=e.node&&e.node.grip==="probe";let c=i;return u||(c=n&&n.invertible?Number(n.invertValue(e.pointer.x)):null),c!=null&&!Number.isFinite(c)&&(c=null),c!=null&&((n&&n.encode?Math.abs(Number(n.encode(c))-Number(n.encode(s))):c===s?0:1/0)>=A4||(c=null)),{a,b:l,anchor:s,probeX:c,yv:Number(r.invertValue(e.pointer.y)),yAnchor:Or({a,b:l},s)}}function C4(e,t){const n={};let r=!1;for(const[o,s]of Object.entries(t)){const i=T4(e,o);i==null||!Number.isFinite(s)||(n[i]=s,r=!0)}if(r){if(e.datum)return{...e.datum,...n};if(e.data.length)return e.data.map(o=>({...o,...n}))}}function ec(e,t,n,r){const{anchor:o,probe:s,...i}=r||{};return il(je({type:e,gesture:"drag",pick:"direct",scope:"trend",channels:[t],...i,apply:a=>{const l=O4(a,{anchor:o,probe:s});if(!l)return;const u=n(l,a);return u?C4(a,u):void 0}}),t)}function N4(e={}){return ec("trend.intercept","intercept",t=>({intercept:t.yv-t.b*t.anchor}),e)}function I4(e={}){return ec("trend.slope","slope",t=>{if(t.probeX==null)return;const n=(t.yv-t.yAnchor)/(t.probeX-t.anchor);return{slope:n,intercept:t.yAnchor-n*t.anchor}},e)}function L4(e={}){return ec("trend.interceptSpread","interceptSpread",t=>({interceptSpread:Math.abs(t.yv-t.yAnchor)}),e)}function F4(e={}){return ec("trend.slopeSpread","slopeSpread",t=>{if(t.probeX==null)return;const n=(t.yv-t.yAnchor)/(t.probeX-t.anchor);return{slopeSpread:Math.abs(n-t.b)}},e)}function R4(e,t){const n=t.axis==="y"?e.y:e.x,r=t.axis==="y"?e.x:e.y,o=t.sign*(n-t.baseline);if(o<=0)return 0;const s=Math.floor(o/t.cellSize);if(s>=t.rows)return t.totalCells;let i=Math.floor((r-(t.bandStart+t.bandInset))/t.cellSize);i=Math.max(0,Math.min(t.multiple-1,i));const a=s*t.multiple+i+1;return Math.max(0,Math.min(t.totalCells,a))}function z4(e={}){return je({type:"waffle.fill",gesture:"drag",scope:"waffle",...e,apply:t=>{const n=t.node&&t.node.grid,r=t.channels&&t.channels[0];if(!n||!r||!r.field)return;const o=R4(t.pointer,n),s=Math.max(n.dlo,Math.min(n.dhi,n.dlo+o*n.unit));return{...t.datum,[r.field]:s}}})}const md=28,cy=12,P4=8;function dl(e){const t=e.schemaSpec;if(!t)return null;const n=t.byRole.nodes||t.primary,r=t.tables[n];return!r||!r.key?null:{name:n,table:r,rows:(e.tables||{})[n]||[],key:r.key}}function hl(e,t){const n=e.schemaSpec,r=n&&(n.byRole.links||e.table),o=n&&n.tables[r];if(!o)return null;const s=Object.keys(o.fields).filter(u=>o.fields[u]&&o.fields[u].type==="ref"),i=u=>t[u]&&t[u].field!=null?t[u].field:null,a=i("source")||s[0],l=i("target")||s[1];return!a||!l?null:{source:a,target:l,sourceSide:i("sourceSide"),targetSide:i("targetSide")}}function bd(e){ge(`${e}:refs`,`edit.network.${e}() cannot find the link table's endpoint columns. Declare them as references (source: { type: "ref" }, target: { type: "ref" }), or name them on the link mark: channels: { source: { field: … }, target: { field: … } }.`)}function Cb(e,t){const n=e.nodeBox||null,r=e.nodePorts||null,o=kb(e.scales,{},t.table,t.rows,n,cy*2,cy*2,e.width||0,e.height||0),s=t.rows.map((i,a)=>!r||!i?null:r(i,a,t.rows)||{});return{boxed:!!n,ported:!!r,boxes:o,roles:s}}function Wi(e,t){return e?Et.filter(n=>I0(e[n],t)):null}function Bu(e,t,n,r,o=null){const s=Cb(e,t),i=e.pointer,a=d=>d===r||!!o&&d===o.index&&!o.body;let l=null,u=1/0;if(s.ported){const d=Uf.size+wn;if(s.boxes.forEach((f,p)=>{if(!(!f||p===r))for(const h of Wi(s.roles[p],n)||[]){if(o&&p===o.index&&h===o.side)continue;const y=Ko(f,h,0,0),g=Math.hypot(y.x-i.x,y.y-i.y);g<=d&&g<u&&(u=g,l={row:t.rows[p],index:p,side:h})}}),l)return l}if(s.boxed&&(s.boxes.forEach((d,f)=>{if(!d||a(f))return;const p=Wi(s.roles[f],n);if(p&&!p.length||Math.abs(i.x-d.cx)>d.hw||Math.abs(i.y-d.cy)>d.hh)return;const h=Math.hypot(d.cx-i.x,d.cy-i.y);h<u&&(u=h,l={row:t.rows[f],index:f,side:null})}),l))return l;const c=Jn(e.edit,md);return s.boxes.forEach((d,f)=>{if(!d||a(f))return;const p=Wi(s.roles[f],n);if(p&&!p.length)return;const h=Math.hypot(d.cx-i.x,d.cy-i.y);h<=c&&h<u&&(u=h,l={row:t.rows[f],index:f,side:null})}),l}function Nb(e,t){const n=dl(e);if(!n)return null;const r=Cb(e,n);if(!r.ported)return null;const o=[];return r.boxes.forEach((s,i)=>{if(s)for(const a of Wi(r.roles[i],t)||[]){const l=Ko(s,a,0,0);o.push({x:l.x,y:l.y,key:Gf(n.name,i,a)})}}),o}function Ib(e,t,n,r,o){const s=e.schemaSpec;if(nl(s).multi)return!1;const i=ks(s)===!1;return e.data.some((a,l)=>!a||l===o?!1:a[t.source]===n&&a[t.target]===r?!0:i&&a[t.source]===r&&a[t.target]===n)}function D4(e={}){const{defaults:t={},threshold:n,...r}=e;return je({type:"network.connect",gesture:"drag",pick:"direct",table:"links",cardinality:"append",threshold:n??md,...r,targets:o=>Nb(o,"target"),apply:o=>{const s=dl(o),i=o.session;if(!s||!i||i.fromIndex==null)return;const a=hl(o,o.targetChannels||{});if(!a){bd("connect");return}const l=s.rows[i.fromIndex];if(!l)return;const u=l[s.key];if(u==null)return;const c=o.nodePorts;if(c){const w=c(l,i.fromIndex,s.rows)||{},x=Wi(w,"source")||[];if(i.fromSide!=null?!x.includes(i.fromSide):!x.length)return}const d=w=>({...a.sourceSide?{[a.sourceSide]:i.fromSide!=null?i.fromSide:null}:{},...a.targetSide?{[a.targetSide]:w}:{}}),f=()=>{if(!o.preview)return;const w=Fn(o,{defaults:t,seed:{[a.source]:u,[a.target]:null,...d(null)}});return w?[...o.data,w]:void 0},p=nl(o.schemaSpec).selfLoops,h=i.fromPoint,y=!h||Math.hypot(o.pointer.x-h.x,o.pointer.y-h.y)>=P4,g=p?Bu(o,s,"target",null,{index:i.fromIndex,side:i.fromSide,body:y}):Bu(o,s,"target",i.fromIndex);if(!g)return f();const m=g.row[s.key];if(m==null||Ib(o,a,u,m,null))return f();const b=Fn(o,{defaults:t,seed:{[a.source]:u,[a.target]:m,...d(g.side)}});return b?[...o.data,b]:void 0}})}function j4(e={}){const{threshold:t,when:n,channel:r,channels:o,...s}=e,i=r?[r]:Array.isArray(o)?o:["source","target"],a=l=>{const u=l.node&&l.node.channel;return u==="source"||u==="target"?u:null};return je({type:"network.rewire",gesture:"drag",pick:"direct",scope:"network",threshold:t??md,...s,channels:i,when:l=>{const u=a(l);return!u||!i.includes(u)?!1:n?!!n(l):!0},targets:l=>{const u=a(l),c=dl(l),d=u?Nb(l,u):null;if(!d||!c||!l.datum||nl(l.schemaSpec).selfLoops)return d;const f=hl(l,l.markChannels||{}),p=f&&l.datum[u==="source"?f.target:f.source],h=c.rows.findIndex(y=>y&&y[c.key]===p);return d.filter(y=>!y.key.startsWith(Gf(c.name,h,"")))},apply:l=>{const u=dl(l),c=a(l);if(!u||!c||l.index==null||!l.datum)return;const d=hl(l,l.markChannels||{});if(!d){bd("rewire");return}const f=c==="source"?d.source:d.target,p=c==="source"?d.sourceSide:d.targetSide,h=l.datum[c==="source"?d.target:d.source],y=u.rows.findIndex(S=>S&&S[u.key]===h),g=nl(l.schemaSpec).selfLoops,m=Bu(l,u,c,!g&&y>=0?y:null);if(!m||m.row[u.key]==null)return l.preview?{...l.datum,[f]:null}:l.data.filter((S,v)=>v!==l.index);const b=m.row[u.key],w=!p||l.datum[p]===m.side;if(l.datum[f]===b&&w)return;const x=c==="source"?[b,h]:[h,b];if(!(l.datum[f]!==b&&Ib(l,d,x[0],x[1],l.index)))return{...l.datum,[f]:b,...p?{[p]:m.side}:{}}}})}function W4(e={}){return je({type:"network.reverse",gesture:"click",pick:"direct",scope:"network",...e,apply:t=>{if(!t.datum)return;const n=hl(t,t.markChannels||{});if(!n){bd("reverse");return}if(ks(t.schemaSpec)===!1){ge("reverse:undirected","edit.network.reverse() is on a links table declared directed: false, where source and target name the same relationship either way round — so swapping them has no visible effect. Declare directed: true, or drop the edit.");return}return{...t.datum,[n.source]:t.datum[n.target],[n.target]:t.datum[n.source]}}})}function oi(e){return e.projection||e.scales&&e.scales.projection||null}function Lb(e){const t=e.lon&&e.lon.field||"lon",n=e.lat&&e.lat.field||"lat";return{lon:t,lat:n}}function q4(e={}){const{...t}=e;return je({type:"geo.move",gesture:"drag",channels:null,pick:"direct",scope:"geo",...t,apply:n=>{if(!n.datum)return;const r=Lr(oi(n),n.pointer);if(!r)return;const o=Lb(n.markChannels||{});return{...n.datum,[o.lon]:r.lon,[o.lat]:r.lat}}})}function H4(e={}){const{defaults:t={},...n}=e;return je({type:"geo.create",gesture:"click",channels:null,pick:"plane",scope:"geo",cardinality:"append",...n,apply:r=>{const o=Lr(oi(r),r.pointer);if(!o)return;const s=Lb(r.markChannels||{}),i=Fn(r,{defaults:t,seed:{[s.lon]:o.lon,[s.lat]:o.lat}});return i?[...r.data,i]:void 0}})}function B4(e={}){const{...t}=e;return je({type:"geo.dragVertex",gesture:"drag",channels:null,pick:"direct",scope:"geo",when:n=>!!(n.node&&n.node.channel==="vertex"),...t,apply:n=>{if(!n.datum||!n.node)return;const r=n.node.vertexIndex;if(r==null)return;const o=Lr(oi(n),n.pointer);if(!o)return;const s=n.markChannels.coordinates&&n.markChannels.coordinates.field||"coordinates",i=n.datum[s];if(!Array.isArray(i)||!i[r])return;const a=i.map((l,u)=>u===r?[o.lon,o.lat]:l.slice());return{...n.datum,[s]:a}}})}function U4(e={}){const{min:t=2,...n}=e;return je({type:"geo.removeVertex",gesture:"click",channels:null,pick:"direct",scope:"geo",when:r=>!!(r.node&&r.node.channel==="vertex"),...n,apply:r=>{if(!r.datum||!r.node)return;const o=r.node.vertexIndex;if(o==null)return;const s=r.markChannels.coordinates&&r.markChannels.coordinates.field||"coordinates",i=r.datum[s];if(!Array.isArray(i)||!i[o]||i.length<=t)return;const a=i.filter((l,u)=>u!==o).map(l=>l.slice());return{...r.datum,[s]:a}}})}function K4(e={}){const{threshold:t=24,minDist:n=8,defaults:r={},into:o="new",...s}=e;return je({type:"geo.draw",gesture:"drag",cardinality:"appendMany",channels:null,pick:"draw",scope:"geo",threshold:t,into:o,...s,apply:i=>{const a=i.session;if(!a)return;const l=Lr(oi(i),i.pointer);if(!l)return;const u=i.markChannels.coordinates&&i.markChannels.coordinates.field||"coordinates",c=i.pointer.x,d=i.pointer.y;if(a.lastX!=null&&a.lastY!=null&&Math.hypot(c-a.lastX,d-a.lastY)<n)return;if(a.drawIndex!=null&&i.data[a.drawIndex]){const h=a.drawIndex,y=i.data[h],g=Array.isArray(y[u])?y[u].slice():[];return g.push([l.lon,l.lat]),a.lastX=c,a.lastY=d,i.data.map((m,b)=>b===h?{...m,[u]:g}:m)}const f=Fn(i,{defaults:r,seed:{[u]:[[l.lon,l.lat]]}});if(!f)return;const p=[...i.data,f];return a.drawIndex=p.length-1,a.lastX=c,a.lastY=d,p}})}function Fb(e){return{west:e.west&&e.west.field||"west",south:e.south&&e.south.field||"south",east:e.east&&e.east.field||"east",north:e.north&&e.north.field||"north"}}function Y4(e={}){const{move:t=!0,...n}=jl(e,"geo.brush","geoBrush");return je({type:"geo.brush",gesture:"drag",channels:null,scope:"geo",...n,move:t,pick:"geoBrush",apply:r=>{const o=r.session,s=o&&o.zone,i=r.datum;if(!s||!i)return;const a=Fb(r.markChannels||{});if(s==="canonicalize"){const p={...i};let h=!1;for(const[y,g]of[[a.west,a.east],[a.south,a.north]])i[y]==null||i[g]==null||i[y]<=i[g]||(p[y]=i[g],p[g]=i[y],h=!0);return h?p:void 0}const l=Lr(oi(r),r.pointer);if(!l)return;let u=i[a.west],c=i[a.south],d=i[a.east],f=i[a.north];if(s==="body"){if(!t||!o.grab||!o.box0)return;const p=l.lon-o.grab.lon,h=l.lat-o.grab.lat;u=o.box0.west+p,d=o.box0.east+p,c=o.box0.south+h,f=o.box0.north+h}else for(const p of o.edges||[])p==="west"?u=l.lon:p==="east"?d=l.lon:p==="south"?c=l.lat:p==="north"&&(f=l.lat);return{...i,[a.west]:u,[a.south]:c,[a.east]:d,[a.north]:f}}})}function G4(e,t){const{x:n,y:r}=e.pointer;return(e.marks||[]).some(o=>o.type!=="rect"||o.index==null||o.x==null||o.y==null||o.width==null||o.height==null?!1:n>=o.x-t&&n<=o.x+o.width+t&&r>=o.y-t&&r<=o.y+o.height+t)}function V4(e={}){const{defaults:t={},width:n=10,height:r=6,edgeInset:o=8,...s}=e;return je({type:"geo.createRect",gesture:"click",channels:null,pick:"plane",scope:"geo",cardinality:"append",when:i=>!G4(i,o),...s,apply:i=>{const a=Lr(oi(i),i.pointer);if(!a)return;const l=Fb(i.markChannels||{}),u=n/2,c=r/2,d=Fn(i,{defaults:t,seed:{[l.west]:a.lon-u,[l.east]:a.lon+u,[l.south]:a.lat-c,[l.north]:a.lat+c}});return d?[...i.data,d]:void 0}})}const X4={anchor:f4,newSeries:d4,draw:h4,sweep:p4,removeSeries:y4},J4={categories:x4},Z4={scale:b4},Q4={category:v4,value:k4},e8={cut:_4,edge:M4,merge:E4},Uu={intercept:N4,slope:I4,interceptSpread:L4,slopeSpread:F4},t8={fill:z4},n8={connect:D4,rewire:j4,reverse:W4},r8={move:q4,create:H4,draw:K4,dragVertex:B4,removeVertex:U4,brush:Y4,createRect:V4},wd=Object.freeze(Object.defineProperty({__proto__:null,axis:Z4,brushRect:F0,brushSpan:Z5,create:Xf,custom:W0,cycle:oE,editText:D0,geo:r8,legend:Q4,line:X4,move:Vn,moveSpan:J5,network:n8,rank:j0,remove:z0,resize:nE,rotate:rE,scale:J4,select:sE,set:iE,slide:tE,stack:e8,toggle:Jf,trend:Uu,waffle:t8,when:u4},Symbol.toStringTag,{value:"Module"}));function Qt(e={}){const{min:t,max:n,field:r}=Fr("clamp",e);return Vt(({value:o,domain:s})=>{let i=t,a=n;i===void 0&&s&&(i=Math.min(...s)),a===void 0&&s&&(a=Math.max(...s));let l=o;return i!==void 0&&l!==void 0&&(l=Math.max(i,l)),a!==void 0&&l!==void 0&&(l=Math.min(a,l)),l},{type:"clamp",options:{min:t,max:n},field:r})}function Rb(e={}){const{total:t,field:n,strategy:r="cap"}=Fr("maintainSum",e);return typeof t!="number"?(ge("maintainSum:target","maintainSum() needs the total the rows must sum to — maintainSum({ total: 100 }). Without one the constraint accepts every edit unchanged."),Vt(()=>{},{type:"maintainSum",options:{total:t,strategy:r},field:n})):r==="normalize"?Vt(({data:o,activeIndex:s,value:i,field:a})=>{if(a==null)return;const l=o.map((d,f)=>f===s&&i!==void 0?{...d,[a]:i}:{...d}),u=l.reduce((d,f)=>d+(Number(f[a])||0),0);if(u===0)return l;const c=t/u;return l.map(d=>({...d,[a]:(Number(d[a])||0)*c}))},{type:"maintainSum",options:{total:t,strategy:r},field:n}):r==="redistribute"?Vt(({data:o,activeIndex:s,value:i,field:a})=>{if(a==null)return;if(s==null||i===void 0)return i;const l=Math.max(0,Math.min(t,Number(i)||0)),u=o.map((f,p)=>p===s?0:Number(f[a])||0).reduce((f,p)=>f+p,0),c=Math.max(0,t-l),d=u>0?c/u:0;return o.map((f,p)=>{if(p===s)return{...f,[a]:l};const h=Number(f[a])||0;return{...f,[a]:u>0?h*d:o.length>1?c/(o.length-1):0}})},{type:"maintainSum",options:{total:t,strategy:r},field:n}):Vt(({data:o,activeIndex:s,value:i,field:a})=>{if(a==null)return;if(s==null||i===void 0)return i;const l=o.reduce((c,d,f)=>f===s?c:c+(d[a]||0),0),u=Math.max(0,t-l);return Math.min(i,u)},{type:"maintainSum",options:{total:t,strategy:"cap"},field:n})}function tc(e={}){const{max:t=1/0,strategy:n="replace"}=Fr("count",e);return Vt(({data:r})=>{if(!(r.length<=t))return n==="reject"?!1:r.slice(r.length-t)},{type:"count",options:{max:t,strategy:n}})}function xd(e={}){const{field:t,max:n=1,strategy:r="reject"}=Fr("unique",e);return Vt(({data:o,activeIndex:s,fields:i})=>{const a=d=>i.map(f=>d[f]).join(""),l=new Map;o.forEach((d,f)=>{const p=a(d);let h=l.get(p);h||(h=[],l.set(p,h)),h.push(f)});let u=!1;for(const d of l.values())if(d.length>n){u=!0;break}if(!u)return;if(r==="reject")return!1;const c=new Set;for(const d of l.values()){if(d.length<=n)continue;let f;if(s!=null&&d.includes(s)){const p=d.filter(h=>h!==s);f=new Set([s,...p.slice(p.length-(n-1))])}else f=new Set(d.slice(d.length-n));d.forEach(p=>{f.has(p)||c.add(p)})}return o.filter((d,f)=>!c.has(f))},{type:"unique",options:{field:t,max:n,strategy:r},field:t})}function vd(e={}){const{step:t=1,origin:n=0,field:r}=Fr("snap",e);return Vt(({value:o})=>o===void 0||t<=0?o:n+Math.round((o-n)/t)*t,{type:"snap",options:{step:t,origin:n},field:r})}function o8(e){for(let t=1;t<e.length;t++)if(e[t]<e[t-1])return!1;return!0}function i8(e,t,n){if(!n)return-1;let r=-1;for(let o=0;o<e.length;o++)if(Number(n[e[o]])!==Number(t[e[o]])){if(r>=0)return-1;r=o}return r}function s8(e={}){const{field:t,strategy:n="push"}=Fr("ordering",e),r=Array.isArray(t)?t:t!=null?[t]:[];return r.length<2?(ge("ordering:fields","ordering() needs at least two columns, in order — ordering({ field: ['lo', 'mean', 'hi'] }). Without them the constraint accepts every edit unchanged."),Vt(()=>{},{type:"ordering",options:{strategy:n},field:r})):Vt(({active:o,oldData:s,activeIndex:i})=>{if(!o)return;const a=r.map(f=>Number(o[f]));if(a.some(f=>!Number.isFinite(f))||o8(a))return;if(n==="block")return!1;const l=s&&i!=null?s[i]:null,u=i8(r,o,l),c=a.slice();if(u>=0){for(let f=u-1;f>=0;f--)c[f]=Math.min(c[f],c[f+1]);for(let f=u+1;f<c.length;f++)c[f]=Math.max(c[f],c[f-1])}else for(let f=1;f<c.length;f++)c[f]=Math.max(c[f],c[f-1]);const d={...o};return r.forEach((f,p)=>{d[f]=c[p]}),d},{type:"ordering",options:{strategy:n},field:r})}function a8(e={}){const{field:t,along:n="x",dir:r="up",series:o=null}=Fr("monotonic",e),s=r!=="down";return Vt(({data:i,activeIndex:a,field:l})=>{if(!i||i.length<2||l==null)return;const u=new Map;i.forEach((f,p)=>{const h=o?f[o]:null;u.has(h)||u.set(h,[]),u.get(h).push(p)});const c=i.map(f=>({...f}));let d=!1;for(const f of u.values()){const p=f.filter(g=>Number.isFinite(Number(c[g][l]))).sort((g,m)=>uy(c[g][n])-uy(c[m][n]));if(p.length<2)continue;const h=p.indexOf(a),y=h>=0?h:0;for(let g=y+1;g<p.length;g++){const m=Number(c[p[g-1]][l]),b=Number(c[p[g]][l]),w=s?Math.max(b,m):Math.min(b,m);w!==b&&(c[p[g]][l]=w,d=!0)}for(let g=y-1;g>=0;g--){const m=Number(c[p[g+1]][l]),b=Number(c[p[g]][l]),w=s?Math.min(b,m):Math.max(b,m);w!==b&&(c[p[g]][l]=w,d=!0)}}return d?c:void 0},{type:"monotonic",options:{dir:r,along:n,series:o},field:t})}function uy(e){return e instanceof Date?e.getTime():Number(e)}function l8(e={}){const{field:t,min:n=1,series:r=null}=Fr("spacing",e);return Vt(({data:o,activeIndex:s,field:i})=>{if(!o||o.length<2||!(n>0)||i==null)return;const a=new Map;o.forEach((c,d)=>{const f=r?c[r]:null;a.has(f)||a.set(f,[]),a.get(f).push(d)});const l=o.map(c=>({...c}));let u=!1;for(const c of a.values()){const d=c.filter(h=>Number.isFinite(Number(l[h][i]))).sort((h,y)=>Number(l[h][i])-Number(l[y][i]));if(d.length<2)continue;const f=d.indexOf(s),p=f>=0?f:0;for(let h=p+1;h<d.length;h++){const y=Number(l[d[h-1]][i])+n;Number(l[d[h]][i])<y&&(l[d[h]][i]=y,u=!0)}for(let h=p-1;h>=0;h--){const y=Number(l[d[h+1]][i])-n;Number(l[d[h]][i])>y&&(l[d[h]][i]=y,u=!0)}}return u?l:void 0},{type:"spacing",options:{min:n,series:r},field:t})}const zb=Object.freeze(Object.defineProperty({__proto__:null,clamp:Qt,count:tc,custom:Vt,maintainSum:Rb,monotonic:a8,ordering:s8,snap:vd,spacing:l8,unique:xd},Symbol.toStringTag,{value:"Module"}));function c8(e,t){return typeof e=="function"?e(t):e}function kd(e,t){const n={};for(const[r,o]of Object.entries(e))n[r]=c8(o,t);return n}const u8=y0,f8={channels:"a guide has no channel map — it views STATE, not columns. Its options take a literal or a function of the chart context: guides.rule({ y: ({ data }) => … }).",field:"a guide names no field: it draws a statement about the chart, not a column. Read the rows in a function option instead: ({ data }) => …",edit:"a guide is read-only by construction — it can never carry an edit. Put the edit on the MARK whose data the gesture should change.",edits:"a guide is read-only by construction. Put edits on a mark.",table:"a guide views chart STATE, so it has no table. It is handed the primary table's rows and may read any of them through the context.",data:"a guide never owns data. It is handed the rows: guides.rule({ y: ({ data }) => … }).",constraints:"invariants belong to the DATASET (spec.constraints), not to a guide. A guide can READ them: ({ constraints }) => …"};function nc(e,t,n){if(!t||!ni())return;const r=new Set([...u8,...n]);for(const o of Object.keys(t)){if(r.has(o))continue;const s=f8[o];if(s){ge(`guideopt:${e}:${o}`,`guides.${e}({ ${o}: … }): ${s}`);continue}ge(`guideopt:${e}:${o}`,`guides.${e}({ ${o}: … }) is not an option this guide reads, so it is ignored. ${e} options are: ${[...r].sort().join(", ")}.`)}}const d8=_s.rule;function h8(e={}){return nc("rule",e,d8),{views:"state",type:"rule",build:(t,n,r,o,s)=>{const{scales:i,width:a,height:l}=s,u=s.theme&&s.theme.guide&&s.theme.guide.rule||{},{x:c,y:d,label:f,stroke:p=u.stroke,strokeDasharray:h=u.strokeDasharray,strokeWidth:y=u.strokeWidth,opacity:g=u.opacity}=kd(e,s),m=s.theme&&s.theme.font&&s.theme.font.labelSize||10,b=[];if(d!==void 0&&i.y){const w=i.y.encode(d);b.push({type:"line",x1:0,x2:a,y1:w,y2:w,stroke:p,strokeDasharray:h,strokeWidth:y,opacity:g,pointerEvents:"none",guide:!0}),f&&b.push({type:"text",x:a-4,y:w-4,text:f,fill:p,fontSize:m,textAnchor:"end",pointerEvents:"none",guide:!0})}if(c!==void 0&&i.x){const w=i.x.encode(c);b.push({type:"line",x1:w,x2:w,y1:0,y2:l,stroke:p,strokeDasharray:h,strokeWidth:y,opacity:g,pointerEvents:"none",guide:!0}),f&&b.push({type:"text",x:w+4,y:10,text:f,fill:p,fontSize:m,textAnchor:"start",pointerEvents:"none",guide:!0})}return b}}}const p8=_s.region;function y8(e={}){return nc("region",e,p8),{views:"state",type:"region",build:(t,n,r,o,s)=>{const{scales:i,width:a,height:l}=s,u=s.theme&&s.theme.guide&&s.theme.guide.region||{},{x:c,y:d,fill:f=u.fill||"#64748b",opacity:p=u.opacity!=null?u.opacity:.1}=kd(e,s),h=[];if(Array.isArray(d)&&i.y){const y=i.y.encode(d[0]),g=i.y.encode(d[1]);h.push({type:"rect",x:0,y:Math.min(y,g),width:a,height:Math.abs(g-y),fill:f,opacity:p,pointerEvents:"none",guide:!0})}if(Array.isArray(c)&&i.x){const y=i.x.encode(c[0]),g=i.x.encode(c[1]);h.push({type:"rect",x:Math.min(y,g),y:0,width:Math.abs(g-y),height:l,fill:f,opacity:p,pointerEvents:"none",guide:!0})}return h}}}const g8=_s.remaining;function m8(e,t){for(const n of e||[]){const r=n;if(!r||r.type!=="maintainSum"||r.field!=null&&t!=null&&r.field!==t)continue;const o=r.options&&r.options.total;if(typeof o=="number")return o}return null}function b8(e={}){return nc("remaining",e,g8),{views:"state",type:"remaining",build:(t,n,r,o,s)=>{const i=s&&s.theme&&s.theme.guide&&s.theme.guide.rule||{},{field:a="y",total:l,unit:u,format:c,anchor:d="top-right",label:f,fill:p=i.stroke||"#64748b",fontSize:h=11}=kd(e,s),y=t||[],g=typeof l=="number"?l:m8(s&&s.constraints||[],a);if(g==null)return[];const m=y.reduce((k,_)=>{const A=_&&_[a];return k+(typeof A=="number"&&Number.isFinite(A)?A:0)},0),b=g-m,w=typeof c=="function"?c:k=>{const _=Math.round(k*100)/100;return String(_)};let x;if(typeof f=="function")x=String(f(b,m,g));else if(u){const k=Math.round(b);x=`${w(b)} ${u}${k===1?"":"s"} left`}else x=`${w(b)} of ${w(g)} left`;const S=d.endsWith("right"),v=d.startsWith("top");return[{type:"text",x:S?r-4:4,y:v?12:o-6,text:x,fill:p,fontSize:h,textAnchor:S?"end":"start",pointerEvents:"none",guide:!0}]}}}const w8=_s.proximity;function x8(e){nc("proximity",e,w8);const{target:t,stroke:n,strokeDasharray:r,strokeWidth:o,opacity:s}=e;return{views:"state",type:"proximity",build:(i,a,l,u,c)=>{const d=c.ui&&c.ui.session&&c.ui.session[t];if(!d||d.px==null||d.py==null||d.threshold==null)return[];const f={...c5,...n!==void 0?{color:n}:{},...r!==void 0?{dash:r}:{},...o!==void 0?{width:o}:{},...s!==void 0?{opacity:s}:{}};return[{type:"circle",cx:d.px,cy:d.py,r:d.threshold,fill:"none",stroke:f.color,strokeDasharray:f.dash,strokeWidth:f.width,opacity:f.opacity,guide:!0,effect:!0,pointerEvents:"none"}]}}}function ii(e){return{views:"state",type:"custom",build:(t,n,r,o,s)=>(e(s)||[]).map(i=>({pointerEvents:"none",...i,guide:!0}))}}const Os=(e,t)=>Object.assign(t,{type:e}),Pb={accent:"#2563eb",ring:"#cbd5e1",track:"#e2e8f0",cellFill:"#f8fafc",cellStroke:"#e2e8f0",label:"#334155",question:"#0f172a",labelSize:12,questionSize:13,radius:11},Cs=e=>e&&e.theme&&e.theme.widget||Pb,Ku=e=>e&&Array.isArray(e.domainConfig)?e.domainConfig:[];function Sd(e={}){const{labelOffset:t=30,radius:n}=e;return Os("optionRings",ii(r=>{const{scales:o,height:s}=r,i=Cs(r),a=n??i.radius,l=Ku(o.x);if(!l.length)return[];const u=s/2,c=f=>o.x.encode(f),d=[];for(let f=0;f<l.length-1;f++)d.push({type:"line",x1:c(l[f])+a,y1:u,x2:c(l[f+1])-a,y2:u,stroke:i.track,strokeWidth:3,background:!0});for(const f of l)d.push({type:"circle",cx:c(f),cy:u,r:a,fill:"none",stroke:i.ring,strokeWidth:1.5}),d.push({type:"text",x:c(f),y:u+t,text:String(f),textAnchor:"middle",fontSize:i.labelSize,fill:i.label});return d}))}function Db(e={}){const{pad:t=3}=e;return Os("cellGrid",ii(n=>{const{scales:r}=n,o=Cs(n),s=Ku(r.x),i=Ku(r.y);if(!s.length||!i.length)return[];const a=yn(r.x,40),l=yn(r.y,30),u=[];for(const c of i)for(const d of s)u.push({type:"rect",x:r.x.encode(d)-a/2+t,y:r.y.encode(c)-l/2+t,width:a-2*t,height:l-2*t,fill:o.cellFill,stroke:o.cellStroke,strokeWidth:1});for(const c of s)u.push({type:"text",x:r.x.encode(c),y:-14,text:String(c),textAnchor:"middle",fontSize:o.labelSize,fill:o.label});for(const c of i)u.push({type:"text",x:-10,y:r.y.encode(c)+4,text:String(c),textAnchor:"end",fontSize:o.labelSize,fill:o.label});return u}))}function jb(e={}){const{format:t=n=>String(n)}=e;return Os("sliderTrack",ii(n=>{const{scales:r,width:o,height:s}=n,i=Cs(n);if(!r.x)return[];const a=s/2,l=r.x.domainConfig||[0,1],u=l[0],c=l[l.length-1];return[{type:"line",x1:0,y1:a,x2:o,y2:a,stroke:i.track,strokeWidth:4,background:!0},{type:"line",x1:0,y1:a-7,x2:0,y2:a+7,stroke:i.ring,strokeWidth:2},{type:"line",x1:o,y1:a-7,x2:o,y2:a+7,stroke:i.ring,strokeWidth:2},{type:"text",x:0,y:a+26,text:t(u),textAnchor:"start",fontSize:i.labelSize,fill:i.label},{type:"text",x:o,y:a+26,text:t(c),textAnchor:"end",fontSize:i.labelSize,fill:i.label}]}))}function nn(e,t={}){const{y:n=-18}=t;return Os("prompt",ii(r=>{const o=Cs(r);return e?[{type:"text",x:0,y:n,text:e,textAnchor:"start",fontSize:o.questionSize,fill:o.question}]:[]}))}function Wb(e={}){const{x:t="x",y:n="y"}=e;return Os("crosshair",ii(r=>{const{width:o,height:s}=r,i=Cs(r),a=o/2,l=s/2,u=(f,p,h,y)=>({type:"text",x:f,y:p,text:h,textAnchor:y,fontSize:i.labelSize,fill:i.label}),c=14,d=(f,p,h)=>{const y=[...String(t).split(/\s+/),`(${p})`],g=l-(y.length-1)*c/2;return y.map((m,b)=>u(f,g+b*c+4,m,h))};return[{type:"line",x1:0,y1:l,x2:o,y2:l,stroke:i.ring,strokeWidth:1,background:!0},{type:"line",x1:a,y1:0,x2:a,y2:s,stroke:i.ring,strokeWidth:1,background:!0},...d(o+10,"high","start"),...d(-10,"low","end"),u(a,-8,`${n} (high)`,"middle"),u(a,s+20,`${n} (low)`,"middle")]}))}const v8=Object.freeze(Object.defineProperty({__proto__:null,cellGrid:Db,crosshair:Wb,custom:ii,optionRings:Sd,prompt:nn,proximity:x8,region:y8,remaining:b8,rule:h8,sliderTrack:jb},Symbol.toStringTag,{value:"Module"}));function mn(e){return Bf(e)}function k8(e={}){const{question:t,options:n=[],value:r,onChange:o,width:s=560,height:i=130,stage:a,theme:l}=e,u=mn(l);return{width:s,height:i,theme:l,margins:{top:34,right:60,bottom:44,left:60},schema:{choice:{type:"ordinal",domain:n}},scales:{x:{type:"band"}},data:r!=null?[{choice:r}]:[],constraints:[tc({max:1,strategy:"replace"})],onChange:o,axes:!1,guides:[nn(t||""),Sd()],marks:[vr({id:"likert",size:u.widget.radius-3,fill:u.widget.accent,channels:{x:{field:"choice"}},edits:[Xf({pick:"probe",channels:["x"],advance:!1,stage:a})]})]}}function S8(e={}){const{question:t,options:n=[],max:r=1/0,value:o=[],onChange:s,width:i=560,height:a=130,stage:l,theme:u}=e,c=mn(u),d=[xd({field:"choice",strategy:"reject"})];return r!==1/0&&d.push(tc({max:r,strategy:"reject"})),{width:i,height:a,theme:u,margins:{top:34,right:60,bottom:44,left:60},schema:{choice:{type:"categorical",domain:n}},scales:{x:{type:"band"}},data:o.map(f=>({choice:f})),constraints:d,onChange:s,axes:!1,guides:[nn(t||""),Sd()],marks:[vr({id:"choice",size:c.widget.radius-3,fill:c.widget.accent,channels:{x:{field:"choice"}},edits:[Jf({pick:"probe",channels:["x"],advance:!1,stage:l})]})]}}function $8(e={}){const{question:t,domain:n=[0,1],step:r,value:o,format:s,onChange:i,width:a=560,height:l=120,stage:u,theme:c}=e,d=mn(c),f=[Qt({min:n[0],max:n[1],field:"value"})];return r&&f.push(vd({field:"value",step:r,origin:n[0]})),{width:a,height:l,theme:c,margins:{top:34,right:40,bottom:40,left:40},schema:{value:{type:"quantitative",domain:n}},data:[{value:o??n[0]}],constraints:f,onChange:i,axes:!1,guides:[nn(t||""),jb(s?{format:s}:{})],marks:[vr({id:"slider",size:d.widget.radius-2,fill:d.widget.accent,channels:{x:{field:"value"}},edits:[Vn({pick:"probe",channels:["x"],advance:!1,stage:u})]})]}}function _8(e={}){const{question:t,questions:n=[],options:r=[],value:o=[],onChange:s,width:i=620,height:a=100+n.length*46,stage:l,theme:u}=e,c=mn(u),d={top:62,right:30,bottom:20,left:130},f=a-d.top-d.bottom;return{width:i,height:a,theme:u,margins:d,schema:{option:{type:"ordinal",domain:r},question:{type:"categorical",domain:n}},scales:{x:{type:"band"},y:{type:"band",range:[0,f]}},data:o,constraints:[xd({field:"question",strategy:"replace"})],onChange:s,axes:!1,guides:[nn(t||"",{y:-38}),Db()],marks:[vr({id:"matrix",size:c.widget.radius-3,fill:c.widget.accent,channels:{x:{field:"option"},y:{field:"question"}},edits:[Jf({pick:"probe",channels:["x","y"],advance:!1,stage:l})]})]}}const M8={top:56,right:92,bottom:52,left:92};function E8(e,t){const n={...M8},r=e-n.left-n.right,o=t-n.top-n.bottom;if(r>o){const s=(r-o)/2;n.left+=s,n.right+=s}else if(o>r){const s=(o-r)/2;n.top+=s,n.bottom+=s}return n}function A8(e={}){const{question:t,x:n="x",y:r="y",r:o=0,spread:s=0,samples:i=60,seed:a=7,render:l="samples",onChange:u,width:c=460,height:d=400,theme:f}=e;return{width:c,height:d,theme:f,margins:E8(c,d),schema:{x:{type:"quantitative",domain:[-1,1]},y:{type:"quantitative",domain:[-1,1]},r:{type:"quantitative",domain:[-1,1],default:0},spread:{type:"quantitative",domain:[0,1],default:0}},data:[{r:o,spread:s}],constraints:[Qt({field:"r",min:-1,max:1}),Qt({field:"spread",min:0,max:1})],onChange:u,axes:!1,guides:[nn(t||"",{y:-32}),Wb({x:n,y:r})],marks:[ri({id:"lineCone",parts:[bb({render:l,samples:i,seed:a,channels:{intercept:{datum:0},slope:{field:"r"},slopeSpread:{field:"spread"}}}),mb({handles:!1,channels:{intercept:{datum:0},slope:{field:"r",edit:Uu.slope({pick:"probe",stage:0})},slopeSpread:{field:"spread",edit:Uu.slopeSpread({pick:"probe",stage:1})}}})]})]}}function T8(e={}){const{question:t="Rank these items",items:n=["A","B","C","D"],onChange:r,width:o=420,height:s=280,stage:i,theme:a}=e,l=mn(a),u=n.map((d,f)=>f+1),c=n.map((d,f)=>({item:d,rank:f+1}));return{width:o,height:s,theme:a,margins:{top:40,right:24,bottom:24,left:100},schema:{item:{type:"categorical",domain:n},rank:{type:"ordinal",domain:u}},data:c,onChange:r,axes:!1,guides:[nn(t)],marks:[vr({id:"rank-dots",size:l.widget.radius-2,fill:l.widget.accent,channels:{x:{value:40},y:{field:"rank",edit:j0({stage:i})}}}),Tr({id:"rank-labels",fontSize:13,fill:l.widget.label,channels:{x:{value:56},y:{field:"rank"},text:{field:"item"},textAnchor:{value:"start"}}})]}}function O8(e={}){const{question:t="Allocate the budget",categories:n=["A","B","C","D"],total:r=100,values:o,onChange:s,width:i=480,height:a=280,stage:l,theme:u}=e,c=mn(u),d=r/n.length,f=n.map((p,h)=>({cat:p,share:o&&o[h]!=null?o[h]:d}));return{width:i,height:a,theme:u,margins:{top:40,right:24,bottom:36,left:48},schema:{cat:{type:"categorical",domain:n},share:{type:"quantitative",domain:[0,r]}},data:f,constraints:[Qt({min:0,max:r,field:"share"}),Rb({total:r,field:"share",strategy:"redistribute"})],onChange:s,guides:[nn(t)],marks:[Xl({id:"alloc",fill:c.widget.accent,fillOpacity:.75,channels:{x:{field:"cat"},y:{field:"share",edit:Vn({guide:!0,stage:l})}}})]}}function C8(e={}){const{question:t="Place tokens to express probability",bins:n=["Low","Med","High"],maxTokens:r=20,onChange:o,width:s=420,height:i=300,stage:a,theme:l}=e,u=mn(l);return{width:s,height:i,theme:l,margins:{top:40,right:24,bottom:36,left:40},schema:{bin:{type:"categorical",domain:n}},data:[],constraints:[tc({max:r,strategy:"reject"})],onChange:o,guides:[nn(t)],marks:[ob({id:"tokens",fill:u.widget.accent,channels:{x:{field:"bin"}},edits:[Xf({pick:"probe",channels:["x"],defaults:{},advance:!1,stage:a}),z0({pick:"direct",stage:a})]})]}}function N8(){return Vt(({active:e})=>{if(e)return{lo:Math.min(e.lo,e.mean),hi:Math.max(e.hi,e.mean)}},{type:"orderInterval"})}function I8(e){return W0(t=>{const n=t.datum,r=t.channels[0];if(!r||!r.scale||!n)return;const o=r.scale.invertValue(t.pointer.y);if(o==null||Number.isNaN(Number(o)))return;const s=r.scale.domainConfig||(typeof r.scale.domain=="function"?r.scale.domain():null);if(!s||s.length<2){const p=o-n.mean;return{...n,mean:o,lo:n.lo+p,hi:n.hi+p}}const i=Math.min(...s.map(Number)),a=Math.max(...s.map(Number)),l=Number(n.hi)-Number(n.lo);let u=Number(o)-Number(n.mean),c=Number(n.lo)+u,d=Number(n.hi)+u;l>=a-i?(c=i,d=a):(c<i&&(d+=i-c,c=i),d>a&&(c-=d-a,d=a));const f=Number(n.mean)+(c-Number(n.lo));return{...n,mean:f,lo:c,hi:d}},{guide:!0,stage:e})}function L8(e={}){const{question:t="Set your interval",category:n="estimate",mean:r=50,lo:o=30,hi:s=70,domain:i=[0,100],onChange:a,width:l=360,height:u=280,stage:c,theme:d}=e,f=mn(d);return{width:l,height:u,theme:d,margins:{top:40,right:24,bottom:36,left:48},schema:{cat:{type:"categorical",domain:[n]},mean:{type:"quantitative",domain:i},lo:{type:"quantitative",domain:i},hi:{type:"quantitative",domain:i}},data:[{cat:n,mean:r,lo:o,hi:s}],constraints:[Qt({min:i[0],max:i[1],field:"mean"}),Qt({min:i[0],max:i[1],field:"lo"}),Qt({min:i[0],max:i[1],field:"hi"}),N8()],onChange:a,guides:[nn(t)],marks:[ri({id:"ci",parts:[nb({stroke:f.widget.accent,strokeWidth:2,channels:{x:{field:"cat"},y1:{field:"lo"},y2:{field:"hi"}}}),vr({size:f.widget.radius-2,fill:f.widget.accent,channels:{x:{field:"cat"},y:{field:"mean",edit:I8(c)}}}),us({stroke:f.widget.accent,strokeWidth:2,channels:{x:{field:"cat"},y:{field:"lo",edit:Vn({stage:c})}}}),us({stroke:f.widget.accent,strokeWidth:2,channels:{x:{field:"cat"},y:{field:"hi",edit:Vn({stage:c})}}})]})]}}function F8(e={}){const{question:t="How often?",bins:n=["0-1","1-2","2-3","3-4","4+"],max:r=40,values:o,onChange:s,width:i=480,height:a=280,stage:l,theme:u}=e,c=mn(u),d=n.map((f,p)=>({bin:f,n:o&&o[p]!=null?o[p]:0}));return{width:i,height:a,theme:u,margins:{top:40,right:24,bottom:40,left:40},schema:{bin:{type:"categorical",domain:n},n:{type:"quantitative",domain:[0,r]}},data:d,constraints:[Qt({min:0,max:r,field:"n"})],onChange:s,guides:[nn(t)],marks:[Xl({id:"hist",fill:c.widget.accent,fillOpacity:.7,channels:{x:{field:"bin"},y:{field:"n",edit:Vn({guide:!0,stage:l})}}})]}}function R8(e={}){const{question:t="Drag the region",xDomain:n=[0,10],yDomain:r=[0,10],x1:o=3,x2:s=7,y1:i=3,y2:a=7,onChange:l,width:u=400,height:c=320,stage:d,theme:f}=e,p=mn(f);return{width:u,height:c,theme:f,margins:{top:40,right:24,bottom:36,left:40},schema:{x1:{type:"quantitative",domain:n},x2:{type:"quantitative",domain:n},y1:{type:"quantitative",domain:r},y2:{type:"quantitative",domain:r}},data:[{x1:o,x2:s,y1:i,y2:a}],constraints:[Qt({min:n[0],max:n[1],field:"x1"}),Qt({min:n[0],max:n[1],field:"x2"}),Qt({min:r[0],max:r[1],field:"y1"}),Qt({min:r[0],max:r[1],field:"y2"})],onChange:l,guides:[nn(t)],marks:[Ts({id:"region",fill:p.widget.accent,fillOpacity:.35,stroke:p.widget.accent,channels:{x1:{field:"x1"},x2:{field:"x2"},y1:{field:"y1"},y2:{field:"y2"}},edits:[F0({edgeInset:12,stage:d})]})]}}function z8(e={}){const{question:t="Set the value",domain:n=[0,100],step:r,value:o,onChange:s,width:i=200,height:a=320,stage:l,theme:u}=e,c=mn(u),d=[Qt({min:n[0],max:n[1],field:"value"})];return r&&d.push(vd({field:"value",step:r,origin:n[0]})),{width:i,height:a,theme:u,margins:{top:40,right:40,bottom:36,left:48},schema:{cat:{type:"categorical",domain:["v"]},value:{type:"quantitative",domain:n}},data:[{cat:"v",value:o??n[0]}],constraints:d,onChange:s,guides:[nn(t)],marks:[Xl({id:"thermo",fill:c.widget.accent,fillOpacity:.8,channels:{x:{field:"cat"},y:{field:"value"}},edits:[Vn({pick:"probe",channels:["y"],advance:!1,guide:!0,stage:l})]})]}}function P8(e={}){const{question:t="Set the value",input:n="number",value:r,domain:o=[0,100],label:s="value",onChange:i,width:a=360,height:l=200,stage:u,theme:c}=e,d=mn(c);return n==="text"?{width:a,height:l,theme:c,margins:{top:40,right:24,bottom:24,left:24},schema:{label:{type:"categorical"},x:{type:"quantitative",domain:[0,10]},y:{type:"quantitative",domain:[0,10]}},data:[{x:5,y:5,label:r!=null?String(r):s}],onChange:i,axes:!1,guides:[nn(t)],marks:[Tr({id:"label",fontSize:18,fill:d.widget.accent,channels:{x:{field:"x"},y:{field:"y"},text:{field:"label",edit:D0()}},edits:[Vn({channels:["x","y"],stage:u})]})]}:{width:a,height:l,theme:c,margins:{top:40,right:40,bottom:36,left:48},schema:{cat:{type:"categorical",domain:["v"]},n:{type:"quantitative",domain:o}},data:[{cat:"v",n:r??o[0]}],constraints:[Qt({min:o[0],max:o[1],field:"n"})],onChange:i,guides:[nn(t)],marks:[Tr({id:"readout",fontSize:22,fill:d.widget.accent,channels:{x:{field:"cat"},y:{field:"n",edit:Vn({guide:!0,stage:u})},text:{field:"n"}}})]}}const D8=Object.freeze(Object.defineProperty({__proto__:null,allocation:O8,histogram:F8,interval:L8,labeledValue:P8,likert:k8,lineCone:A8,matrix:_8,multipleChoice:S8,probabilityTokens:C8,ranking:T8,region:R8,slider:$8,thermometer:z8},Symbol.toStringTag,{value:"Module"})),j8=Object.freeze(Object.defineProperty({__proto__:null,AXIS_CHROME:m5,AXIS_OPTIONS:K0,AXIS_RADIAL_OPTIONS:Mb,CONSTRAINT_OPTIONS:b0,DEFAULT_PICK_THRESHOLD:Ul,EDIT_OPTIONS:m0,EDIT_UNIVERSAL_OPTIONS:g0,ELEMENT_OPTIONS:$s,ELEMENT_UNIVERSAL_OPTIONS:p0,GRID_OPTIONS:Zf,GUIDE_OPTIONS:_s,GUIDE_UNIVERSAL_OPTIONS:y0,HANDLE_DEFAULTS:Uf,LEGEND_OPTIONS:J0,LINK_SHAPES:fl,MARK_OPTIONS:st,MARK_SHORTHANDS:h0,MARK_UNIVERSAL_OPTIONS:d0,ORIENT_SPAN:xa,STANDARD_STYLE_CHANNELS:M0,THEME:Pb,anchorsOf:Ql,andWhen:Gr,angularBand:ub,arcPath:fs,arcSpan:cd,arcSpine:cl,bandSpan:Zm,bandStartOf:Kr,bandwidthOf:yn,baselineOf:yr,categoryOf:Nn,channelDomain:v0,claimEdge:il,claimPick:jl,createProjection:u0,defineConstraint:Vt,degToRad:lb,discreteDomain:k0,distanceToMark:as,edgeInsetOf:Kl,encodeAngle:zr,encodeChannel:se,encodeValue:Lt,envelopePolygon:pd,groupByPosition:td,hitTest:wa,invertChannel:fo,invertPoint:Lr,isBand:Gn,isDiscrete:uo,isWebMercator:Sb,lineSegment:ul,linearInvert:x0,makeEdit:je,markCenter:Rn,markCommon:lt,markDefaults:Nt,measureText:ji,mintDatum:Fn,nearestMark:In,nearestMarkOnAxis:Vf,nearestSeries:Mr,needleTriangle:fb,nestedEnvelopes:yb,nextCategory:Wf,nextSeriesKey:Wl,normalizeMarkOptions:at,noteBox:$n,nudgeTarget:zu,orientationOf:Kf,paramChannels:fd,pickThreshold:Jn,polarToXY:un,positionalKeys:Xt,projectBounds:f0,projectPoint:cr,rangeExtent:ro,readParams:dd,recenterSpan:ql,registerDriver:dE,resolveHandles:dn,resolveMarkNode:Rr,resolveStyle:yt,resolveSymbol:ss,resolveValueAxis:xr,sampleCubic:ll,sampleLines:gb,sampleQuadratic:Jl,schemaDefaults:Ss,seriesFieldOf:Ms,stackDescriptor:cs,stackLayout:Vl,symbolNode:Bl,themeOf:it,tileCover:$b,tileUrl:_b,valueAt:Or,warn:ge,warnUnknownElementOptions:Es,widgetTheme:mn,wrapText:hb},Symbol.toStringTag,{value:"Module"}));let Ci=null;const W8={start:"start",middle:"center",end:"end",left:"left",right:"right",center:"center"},q8={middle:"middle",central:"middle",hanging:"hanging","text-before-edge":"top","text-after-edge":"bottom",alphabetic:"alphabetic",ideographic:"ideographic"};function si(e,t){const n={},r=e.effectStyle;for(const{field:o,base:s}of H0){const i=o in t?t[o]:s;n[o]=r&&r[o]!=null?r[o]:e[o]!=null?e[o]:i}return n}function H8(e,t){if(t==null||t==="none"){e.setLineDash([]);return}if(Array.isArray(t)){e.setLineDash(t);return}e.setLineDash(String(t).split(/[\s,]+/).map(Number).filter(n=>!Number.isNaN(n)))}function Ns(e,t,n){const r=t.opacity!=null?t.opacity:1;t.fill&&t.fill!=="none"&&(e.globalAlpha=r*(t.fillOpacity!=null?t.fillOpacity:1),e.fillStyle=t.fill,n?e.fill(n):e.fill()),t.stroke&&t.stroke!=="none"&&(e.globalAlpha=r*(t.strokeOpacity!=null?t.strokeOpacity:1),e.strokeStyle=t.stroke,e.lineWidth=t.strokeWidth!=null?t.strokeWidth:1,e.lineCap=t.strokeLinecap||"butt",H8(e,t.strokeDasharray),n?e.stroke(n):e.stroke()),e.globalAlpha=1,e.lineCap="butt",e.setLineDash([])}function ai(e,t,n){if(t.angle!=null&&t.angle!==0){const r=Rn(t);if(r){e.save(),e.translate(r.cx,r.cy),e.rotate(-t.angle*Math.PI/180),e.translate(-r.cx,-r.cy),n(),e.restore();return}}n()}function rc(e,t,n){ai(e,t,()=>{const r=Math.max(0,t.r!=null?t.r:5);e.beginPath(),e.arc(t.cx,t.cy,r,0,2*Math.PI),Ns(e,si(t,n))})}function qb(e,t,n){ai(e,t,()=>{const r=Math.max(0,t.rx!=null?t.rx:5),o=Math.max(0,t.ry!=null?t.ry:5);e.beginPath(),e.ellipse(t.cx,t.cy,r,o,0,0,2*Math.PI),Ns(e,si(t,n))})}function pl(e,t,n){ai(e,t,()=>{const r=Math.max(0,t.height);if(e.beginPath(),t.rx!=null&&typeof e.roundRect=="function"){const o=Math.max(0,t.rx),s=t.ry!=null?Math.max(0,t.ry):o;e.roundRect(t.x,t.y,t.width,r,[o,s])}else e.rect(t.x,t.y,t.width,r);Ns(e,si(t,n))})}function oc(e,t,n){ai(e,t,()=>{e.beginPath(),e.moveTo(t.x1,t.y1),e.lineTo(t.x2,t.y2),Ns(e,si(t,n))})}function ic(e,t,n){let r;t.d?r=new Path2D(t.d):(r=new Path2D,Si().curve(Oi(t.curve)).context(r)(t.points||[])),Ns(e,si(t,n),r)}function $d(e,t,n,r){t.text!=null&&ai(e,t,()=>{const o=si(t,n),s=Ci&&Ci.family||"sans-serif",i=t.fontSize!=null?t.fontSize:Ci&&Ci.size||10;e.font=`${i}px ${s}`,e.textAlign=W8[t.textAnchor||r]||"start",e.textBaseline=q8[t.dominantBaseline]||"alphabetic";const a=Array.isArray(t.lines)?t.lines:[String(t.text)],l=t.lineHeight!=null?t.lineHeight:Math.round(i*1.35),u=t.y-(a.length-1)*l/2,c=o.opacity!=null?o.opacity:1;o.fill&&o.fill!=="none"&&(e.globalAlpha=c*(o.fillOpacity!=null?o.fillOpacity:1),e.fillStyle=o.fill,a.forEach((d,f)=>e.fillText(String(d),t.x,u+f*l))),o.stroke&&o.stroke!=="none"&&(e.globalAlpha=c*(o.strokeOpacity!=null?o.strokeOpacity:1),e.strokeStyle=o.stroke,e.lineWidth=o.strokeWidth!=null?o.strokeWidth:1,a.forEach((d,f)=>e.strokeText(String(d),t.x,u+f*l))),e.globalAlpha=1})}function B8(e,t,n,r){if(!t.href)return;let o=n.get(t.href);if(!o){const s=new Image;o={img:s,ready:!1},s.onload=()=>{o.ready=!0,r()},s.src=t.href,n.set(t.href,o)}o.ready&&ai(e,t,()=>{const s=e.globalAlpha;t.opacity!=null&&(e.globalAlpha=t.opacity),e.drawImage(o.img,t.x,t.y,t.width,t.height),e.globalAlpha=s})}function U8(e,t){switch(t.type){case"path":ic(e,t,{fill:"none",stroke:"black",strokeWidth:1,opacity:1});break;case"rect":pl(e,t,{fill:"black"});break;case"circle":rc(e,t,{fill:"black"});break;case"ellipse":qb(e,t,{fill:"black"});break;case"line":oc(e,t,{stroke:"black",strokeWidth:1,opacity:1});break;case"text":$d(e,t,{fill:"black",opacity:1},t.editable?"middle":"start");break}}function K8(e,t){switch(t.type){case"line":oc(e,t,{stroke:"black",strokeWidth:1,opacity:1});break;case"circle":rc(e,t,{fill:"none",stroke:"none",strokeWidth:1,opacity:1});break;case"path":ic(e,t,{fill:"none",stroke:"black",strokeWidth:1,opacity:1});break;case"text":$d(e,t,{fill:"black",opacity:1},"start");break}}function Y8(e,t){const n={fill:"none",stroke:"none",strokeWidth:1,opacity:1};switch(t.type){case"circle":rc(e,t,n);break;case"rect":pl(e,t,n);break;case"ellipse":qb(e,t,n);break;case"line":oc(e,t,n);break;case"path":ic(e,t,n);break}}function fy(e,t,n){Ci=n&&n.theme&&n.theme.font||null;const{background:r,guideRegions:o,marks:s,guideFront:i,effects:a}=B0(t);r.filter(l=>l.type==="image").forEach(l=>B8(e,l,n.images,n.requestRepaint));for(const l of r)l.type==="image"||l.type==="path"||(l.type==="rect"?pl(e,l,{fill:"none",stroke:"none",strokeWidth:1,opacity:1}):l.type==="circle"?rc(e,l,{fill:"none",stroke:"none",strokeWidth:1,opacity:1}):l.type==="line"?oc(e,l,{stroke:"#6b7280",strokeWidth:1,opacity:1}):l.type==="text"&&$d(e,l,{fill:"#374151",opacity:1},"middle"));r.filter(l=>l.type==="path").forEach(l=>ic(e,l,{fill:"none",stroke:"black",strokeWidth:1,opacity:1})),o.forEach(l=>pl(e,l,{fill:"none",stroke:"none",strokeWidth:1,opacity:1})),s.forEach(l=>U8(e,l)),i.forEach(l=>K8(e,l)),a.forEach(l=>Y8(e,l))}const G8=4,V8=3;function X8(e,t){let n=null,r=null,o=!1;e.style.touchAction="none",e.style.userSelect="none";const s=a=>{const l=t(),u=e.getBoundingClientRect(),c=u.width?l.width/u.width:1,d=u.height?l.height/u.height:1;return[(a.clientX-u.left)*c-l.margins.left,(a.clientY-u.top)*d-l.margins.top]},i=(a,l,u,c=!0)=>{const d=t();n&&(n.mode==="direct"?(d.onEvent({type:"dragend",x:l,y:u,node:n.node,rawEvent:a}),c&&!n.moved&&d.onEvent({type:"click",x:l,y:u,node:n.node,rawEvent:a}),c&&(o=!0)):n.dragging&&(d.onEvent({type:"dragend",x:l,y:u,rawEvent:a}),c&&(o=!0))),n=null;const f=e.getBoundingClientRect();(a.clientX<f.left||a.clientX>f.right||a.clientY<f.top||a.clientY>f.bottom)&&(d.planeOnTop?d.onEvent({type:"hoverout",rawEvent:a}):r!==null&&(r=null,d.onEvent({type:"pointerout",rawEvent:a})))};e.addEventListener("pointerdown",a=>{const l=t(),[u,c]=s(a);if(l.planeOnTop)n={mode:"plane",sx:u,sy:c,dragging:!1};else{const d=wa(l.scene.children,u,c);if(d)n={mode:"direct",node:d,sx:u,sy:c,moved:!1},l.onEvent({type:"dragstart",x:u,y:c,node:d,rawEvent:a});else{n=null;return}}a.preventDefault();try{e.setPointerCapture(a.pointerId)}catch{}}),e.addEventListener("pointermove",a=>{const l=t(),[u,c]=s(a);if(n&&a.pointerType==="mouse"&&a.buttons===0){i(a,u,c);return}if(!n){if(l.planeOnTop)l.onEvent({type:"hover",x:u,y:c,rawEvent:a}),e.style.cursor=l.planeCursor||"pointer";else{const d=wa(l.scene.children,u,c),f=d?`${d.featureId}:${d.index}`:null;f!==r&&(r=f,l.onEvent(d?{type:"pointerover",node:d,rawEvent:a}:{type:"pointerout",rawEvent:a})),e.style.cursor=d?d.cursor||"move":"default"}return}n.mode==="direct"?(Math.hypot(u-n.sx,c-n.sy)>G8&&(n.moved=!0),l.onEvent({type:"drag",x:u,y:c,node:n.node,rawEvent:a})):(!n.dragging&&Math.hypot(u-n.sx,c-n.sy)>V8&&(n.dragging=!0,l.onEvent({type:"dragstart",x:n.sx,y:n.sy,rawEvent:a})),n.dragging&&l.onEvent({type:"drag",x:u,y:c,rawEvent:a}))}),e.addEventListener("pointerup",a=>{const[l,u]=s(a);i(a,l,u)}),e.addEventListener("pointercancel",a=>{const[l,u]=s(a);i(a,l,u,!1)}),e.addEventListener("pointerleave",a=>{if(!n){const l=t();l.planeOnTop?l.onEvent({type:"hoverout",rawEvent:a}):r!==null&&(r=null,l.onEvent({type:"pointerout",rawEvent:a}))}}),e.addEventListener("click",a=>{if(o){o=!1;return}const l=t(),[u,c]=s(a);l.onEvent({type:"click",x:u,y:c,rawEvent:a})}),e.addEventListener("dblclick",a=>{const l=t(),[u,c]=s(a),d=l.planeOnTop?null:wa(l.scene.children,u,c);l.onEvent({type:"dblclick",x:u,y:c,...d?{node:d}:{},rawEvent:a})})}class J8{constructor(){this._canvas=null,this._2d=null,this._ctx=null,this._images=new Map}render(t){const{container:n,scene:r,width:o,height:s,margins:i}=t,a=t.responsive||"fixed";this._ensure(n),this._ctx=t;const l=this._canvas;l.style.background=t.theme&&t.theme.background||"";const u=this._canvas,c=this._2d,d=typeof window<"u"&&window.devicePixelRatio||1,f=Math.round(o*d),p=Math.round(s*d);(u.width!==f||u.height!==p)&&(u.width=f,u.height=p),a==="scale"?(u.style.width="100%",u.style.height="auto"):(u.style.width=`${o}px`,u.style.height=`${s}px`),c.setTransform(d,0,0,d,0,0),c.clearRect(0,0,o,s),c.translate(i.left,i.top),fy(c,r.children,{images:this._images,theme:t.theme,requestRepaint:()=>this._repaint()})}_ensure(t){if(this._canvas&&this._canvas.parentNode===t)return;const n=document.createElement("canvas");n.style.display="block",t.appendChild(n),this._canvas=n,this._2d=n.getContext("2d"),X8(n,()=>this._ctx)}_repaint(){const t=this._ctx,n=this._2d;if(!t||!n)return;const{scene:r,width:o,height:s,margins:i}=t,a=typeof window<"u"&&window.devicePixelRatio||1;n.setTransform(a,0,0,a,0,0),n.clearRect(0,0,o,s),n.translate(i.left,i.top),fy(n,r.children,{images:this._images,theme:t.theme,requestRepaint:()=>this._repaint()})}}const Z8={default:{},survey:{ink:"#4f46e5",accent:"#4f46e5",muted:"#94a3b8",font:{family:'"Inter", system-ui, -apple-system, Segoe UI, Roboto, sans-serif',size:11,labelSize:13,titleSize:15},axis:{stroke:"#cbd5e1",labelFill:"#475569",fontSize:11,handle:"#4f46e5"},grid:{stroke:"#f1f5f9",strokeWidth:1},constraint:{color:"#e11d48"},widget:{accent:"#4f46e5",ring:"#cbd5e1",track:"#e2e8f0",cellFill:"#f8fafc",cellStroke:"#e2e8f0",label:"#475569",question:"#1e293b",labelSize:13,questionSize:15,radius:12}},dark:{background:"#0f172a",ink:"#38bdf8",accent:"#38bdf8",muted:"#64748b",axis:{stroke:"#475569",labelFill:"#cbd5e1",fontSize:10,handle:"#38bdf8"},grid:{stroke:"#1e293b"},guide:{rule:{stroke:"#94a3b8",strokeDasharray:"5 4"},region:{fill:"#94a3b8",opacity:.14},legend:{stroke:"#cbd5e1",labelFill:"#cbd5e1",fontSize:11}},constraint:{color:"#fb7185"},widget:{accent:"#38bdf8",ring:"#334155",track:"#1e293b",cellFill:"#1e293b",cellStroke:"#334155",label:"#cbd5e1",question:"#f1f5f9",labelSize:12,questionSize:13,radius:11}}},Q8=Object.freeze(Object.defineProperty({__proto__:null,CanvasRenderer:J8,D3Renderer:U0,DEFAULT_THEME:Hf,Elicit:eb,authoring:j8,constraints:zb,edit:wd,elements:c4,format:eA,guides:v8,plot:yd,resolveTheme:Bf,setTheme:h5,setWarnings:CM,themes:Z8,widgets:D8},Symbol.toStringTag,{value:"Module"})),Dt=e=>e?.__data__,Xe={connect:"connect-step",removeStep:"delete-step",removeArrow:"delete-arrow",flip:"flip-arrow",kind:"set-kind",group:"set-group",boxKind:"set-box-kind",external:"set-external"},e3=[["Move a step","drag its box","move({ channels: [x, y] })","writes steps.x and steps.y"],["Draw a dependency","drag from a dot on a box’s edge to another box","network.connect()","appends a row to depends"],["Add a step after one","press the + beside a box","create() + connect()","adds a step and the arrow into it, together"],["Add a step","double-click empty canvas","create()","mints a row with a fresh steps.id"],["Rename a step","double-click a box","editText()","writes steps.label — and the box resizes to fit"],["Label an arrow","double-click an arrow","editText()","writes depends.label"],["Re-point an arrow","drag either arrow end","network.rewire()","rewrites depends.source or .target"],["Flip a dependency","right-click an arrow, then Flip direction","network.reverse()","swaps depends.source and .target"],["Set what an arrow means","right-click an arrow, then pick its kind","commit({ kind })","writes depends.kind"],["Move to a group","right-click a box, then a group; or drag it into the group’s frame","commit({ group })","writes steps.group"],["Delete","select a box or an arrow, then press Delete; or right-click it","remove()","deletes the row — and, via type: ref, every arrow into it"]],t3=[["Move a box","drag it; a folded frame takes what is in it along","move({ channels: [x, y] })","writes boxes.x and boxes.y"],["Draw an arrow","drag from a dot on a box’s edge to another box: the first uses the second","network.connect()","appends a row to arrows"],["Add a box after one","press the + beside a box","create() + connect()","adds a box and the arrow to it, together"],["Add a box","double-click empty canvas","create()","mints a row with a fresh boxes.id"],["Rename a box","double-click it","editText()","writes boxes.label"],["Say what an arrow is for","double-click an arrow","editText()","writes arrows.label"],["Re-point an arrow","drag either end","network.rewire()","rewrites arrows.source or .target"],["Change what a box is","right-click it, then Change kind: a person, service, component, store or queue","commit({ kind })","writes boxes.kind"],["Make an arrow async","right-click it: it does not wait for the answer","commit({ kind })","writes arrows.kind"],["Put a box in a frame","right-click it, then Move into; or drag it into the frame","commit({ group })","writes boxes.group"],["Fold a frame","press the chevron on its name, or right-click the frame","layout.fold","hides what is inside it; its arrows are drawn to it"],["Delete","select a box or an arrow, then press Delete; or right-click it","remove()","deletes the row, and every arrow into it"]],{sticker:n3,link:r3,text:o3}=yd,{move:i3,editText:dy,remove:hy,network:na}=wd,{unique:s3}=zb,_d=90,yl=60,cn=(e,t)=>typeof document>"u"?t:getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t,Bc=26,Hb=e=>{const t=e==null?"":String(e);if(t.length<=Bc)return t;const n=t.slice(0,Bc-1),r=n.lastIndexOf(" ");return`${(r>Bc/2?n.slice(0,r):n).trimEnd()}…`},Bb=({defaults:e,over:t})=>je({type:"create",gesture:"dblclick",channels:["x","y"],pick:"plane",cardinality:"append",when:n=>!n.data.some(r=>t(r,n.pointer)),apply:n=>{const r=Fn(n,{defaults:e});if(!r)return;const o=new Set(n.data.map(i=>i.id));let s=n.data.length+1;for(;o.has(`step-${s}`);)s++;return[...n.data,{...r,id:`step-${s}`}]}}),Dn=(e,t)=>Object.defineProperty(t,"name",{value:e}),fr=e=>Dn(`byName(${e})`,t=>t.event?.by===e),Co=(e,t)=>je({type:e,name:e,gesture:"commit",pick:"direct",when:fr(e),apply:n=>n.datum&&n.value!==void 0&&n.datum[t]!==n.value?{...n.datum,[t]:n.value}:void 0}),Ub=Object.assign(s3({field:["source","target"],strategy:"reject"}),{table:"links"});function a3(e){const t=jy(e);return t.length||t.push(jt),t}const l3=new Set(["approve","ask","input"]);function c3(e,t){return t?.arrow(e)==="yours"?{stroke:_a.waiting}:{}}function u3(e,{onChange:t,decor:n}){const r=a3(e),o=cn("--ember","#EA5202"),s=cn("--surface","#FFFFFF"),i=cn("--wire","#8F8881"),a=cn("--wire-soft","#C9C3BD"),l=cn("--slate","#69625B"),u=cn("--ink","#19120F"),c=cn("--sans","sans-serif"),d={...Vr,fontFamily:c},{fontSize:f,...p}=d;return{...mr(e),responsive:"scale",focusOutline:!0,axes:!1,margins:{top:xt.y,right:xt.x,bottom:xt.y,left:xt.x},theme:{handle:o,handleStroke:s,background:"transparent",font:{family:c},marks:{text:{fill:u}}},schema:{structure:"network",tables:{steps:{role:"nodes",fields:{id:{type:"categorical",key:!0,open:!0},label:{type:"categorical",open:!0,default:"new step"},group:{type:"categorical",domain:r,open:!0,default:jt},x:{type:"quantitative",domain:[0,e.canvas.width]},y:{type:"quantitative",domain:[0,e.canvas.height]}}},depends:{role:"links",directed:!0,fields:{source:{type:"ref"},target:{type:"ref"},label:{type:"categorical",open:!0,default:""},kind:{type:"categorical",open:!0,default:"needs"}}}}},data:{steps:e.steps,depends:e.depends},onChange:t,...n?{lock:Dn("frozen",(h,y,g)=>n.frozen(h,g))}:{},constraints:[Ub],marks:[r3({curve:"orthogonal",arrowSize:8,inset:3,stroke:h=>c3(h,n).stroke??(h.kind==="after"?a:i),strokeWidth:h=>l3.has(h.kind)?2.6:h.kind==="after"?1.1:1.4,handleSize:4.5,handleColor:a,fill:l,fontSize:11,labelBackground:s,labelPadding:3,format:Hb,channels:{nodeWidth:{fn:Dn("boxWidth",h=>$n(h.label,d).width)},nodeHeight:{fn:Dn("boxHeight",h=>$n(h.label,d).height)},source:{field:"source",edit:na.rewire({channel:"source",threshold:yl,when:h=>h.node?.channel==="source"})},target:{field:"target",edit:na.rewire({channel:"target",threshold:yl,when:h=>h.node?.channel==="target"})},text:{field:"label"}},edits:[na.reverse({name:Xe.flip,when:fr(Xe.flip)}),hy({name:Xe.removeArrow,when:fr(Xe.removeArrow)}),Co(Xe.kind,"kind"),dy()]}),n3({...p,radius:7,stroke:n?Dn("statusEdge",h=>n.stroke(h)??i):i,strokeWidth:n?Dn("statusEdgeWidth",h=>n.strokeWidth(h)??1.5):1.5,...n?{opacity:h=>n.opacity(h)}:{},channels:{x:{field:"x",edit:i3({channels:["x","y"],mode:"relative"})},y:{field:"y",scale:{reverse:!0}},text:{field:"label"},fill:{value:s},fontSize:{value:f}},edits:[na.connect({name:Xe.connect,when:fr(Xe.connect),threshold:_d}),Co(Xe.group,"group"),Bb({defaults:{label:"new step",group:jt},over:(h,y)=>{const{width:g,height:m}=$n(h.label,d);return Math.abs(y.x-h.x)<=g/2&&Math.abs(y.y-h.y)<=m/2}}),hy({name:Xe.removeStep,when:fr(Xe.removeStep)}),dy()]}),...n?[o3({fill:l,fontSize:12,dy:h=>$n(h.label,d).height/2+13,channels:{x:{field:"x"},y:{field:"y",scale:{reverse:!0}},text:{fn:Dn("owner",h=>n.owner(h))}}})]:[]]}}const py={fine:8,coarse:40},f3={ArrowLeft:[-1,0],ArrowRight:[1,0],ArrowUp:[0,-1],ArrowDown:[0,1]},On=e=>e?.tagName==="rect"&&!!Dt(e)?.data&&"group"in Dt(e).data;function d3({frame:e,chart:t,onSelect:n}){e.addEventListener("keydown",s=>{const i=s.target instanceof Element&&On(s.target)?Dt(s.target):null;if(!i)return;const a=f3[s.key];if(a){s.preventDefault(),s.stopPropagation();const l=s.shiftKey?py.coarse:py.fine,u=i.x+i.width/2,c=i.y+i.height/2,d=t();d.emit({type:"dragstart",node:i,x:u,y:c}),d.emit({type:"drag",node:i,x:u+a[0]*l,y:c+a[1]*l}),d.emit({type:"dragend",node:i,x:u+a[0]*l,y:c+a[1]*l}),h3(e,i.data.id)}else s.key===" "&&n?(s.preventDefault(),s.stopPropagation(),n(i.data.id)):(s.key==="Enter"||s.key==="F2")&&(s.preventDefault(),s.stopPropagation(),s.target.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0,cancelable:!0})))},!0),e.addEventListener("focusin",s=>{if(!(s.target instanceof Element)||!On(s.target))return;const i=Dt(s.target).data;s.target.setAttribute("aria-label",`${i.label}. A step: the arrow keys move it, Enter renames it, Delete removes it, the menu key opens its menu.`)});let r=!1;const o=()=>{r=!1;for(const s of e.querySelectorAll('svg [tabindex="0"]'))On(s)||s.setAttribute("tabindex","-1")};new MutationObserver(()=>{r||(r=!0,requestAnimationFrame(o))}).observe(e,{subtree:!0,childList:!0,attributes:!0,attributeFilter:["tabindex"]})}function h3(e,t){requestAnimationFrame(()=>{if(e.contains(document.activeElement)&&On(document.activeElement))return;[...e.querySelectorAll("svg rect.mark")].find(r=>Dt(r)?.data?.id===t)?.focus()})}const yy={x:90,y:50};function Kb(e,t,n=[]){const r=new Set(n.filter(f=>e.nodes[f]&&_r(e,f))),o=f=>$1(e,f,r),s=new Set;for(const f of Object.keys(e.nodes))Py(e,f).some(p=>r.has(p))&&s.add(f);const i=[],a=[],l=new Map;for(const[f,p]of Object.entries(e.nodes)){if(s.has(f))continue;const h={id:f,label:p.label,kind:p.kind,external:!!p.external,...p.tech?{tech:p.tech}:{},...p.in?{parent:p.in}:{}},y=p.in??jt;if(!_r(e,f)){i.push(gy(f,p,y,t.nodes[f]??yy));continue}if(!r.has(f)){a.push(h);continue}const g=Ma(e,f).filter(b=>t.nodes[b]),m=g.length?{x:Math.round(g.reduce((b,w)=>b+t.nodes[w].x,0)/g.length),y:Math.round(g.reduce((b,w)=>b+t.nodes[w].y,0)/g.length)}:yy;l.set(f,{count:Ma(e,f).filter(b=>!_r(e,b)).length}),i.push(gy(f,p,y,m))}const u=new Map,c=new Set;for(const f of e.edges){const p=o(f.from),h=o(f.to);if(p===h)continue;const y=`${p}\0${h}`,g=u.get(y);if((p!==f.from||h!==f.to)&&c.add(y),g){g.n++,g.async+=f.async?1:0,g.label=`${g.n} arrows`,g.tech="";continue}u.set(y,{source:p,target:h,label:f.label??"",kind:"needs",tech:f.tech??"",n:1,async:f.async?1:0})}const d=[...u.values()].map(({n:f,async:p,...h})=>({...h,kind:p===f?"async":"needs"}));return{steps:i,depends:d,lifted:c,folded:l,frames:a,hidden:s,stand:o}}const gy=(e,t,n,r)=>({id:e,label:t.label,group:n,kind:t.kind,external:t.external?"yes":"",x:r.x,y:r.y});function my(e,t,n){const r=typeof n=="function"?n:a=>n.get(a),o=new Map,s=(a,l)=>{const u=o.get(a.id);if(u)return u;if(l.has(a.id))return null;l.add(a.id);const c=t.filter(m=>m.group===a.id).map(m=>m.id),d=[];for(const m of c){const b=r(m);b&&d.push({x:b.x-b.w/2,y:b.y-b.h/2,w:b.w,h:b.h})}for(const m of e.filter(b=>b.parent===a.id)){const b=s(m,l);b&&(d.push({x:b.x,y:b.y,w:b.w,h:b.h}),c.push(...b.members))}if(l.delete(a.id),!d.length)return null;const f=Math.min(...d.map(m=>m.x))-Mo.left,p=Math.max(...d.map(m=>m.x+m.w))+Mo.right,h=Math.min(...d.map(m=>m.y))-Mo.top,y=Math.max(...d.map(m=>m.y+m.h))+Mo.bottom,g={x:f,y:h,w:p-f,h:y-h,members:c};return o.set(a.id,g),g};for(const a of e)s(a,new Set);const i=a=>{let l=0;for(let u=a.parent;u;u=e.find(c=>c.id===u)?.parent)l++;return l};return e.filter(a=>o.has(a.id)).map(a=>({...a,group:a.id,depth:i(a),...o.get(a.id)})).sort((a,l)=>a.depth-l.depth)}class qi extends Error{}const va={label:"new box",kind:"service",external:"",group:jt},by={width:300,height:180};function _o({arch:e,layout:t},{headroom:n=!0}={}){const r=Kb(e,t,t.collapsed??[]),o=t.canvas??{width:640,height:240};return{id:"architecture",title:e.title,plan:e.title,repo:"",source:e.source?.url??"",direction:t.direction,note:e.goal??"",canvas:n?{width:o.width+by.width,height:o.height+by.height}:o,steps:r.steps,depends:r.depends,proj:r}}function Yb(e,t,n){const r=Kb(e,t,t.collapsed??[]),o=structuredClone(e),s=[],i=new Set(n.steps.map(h=>h.id)),a=new Map(r.steps.map(h=>[h.id,h]));for(const h of a.keys())if(!i.has(h)){if(r.folded.has(h))throw new qi(`${e.nodes[h].label} is a folded frame: it stands for everything in it. Unfold it, and take away what you mean to.`);delete o.nodes[h];for(const y of o.flows)y.steps=y.steps.filter(g=>g.from!==h&&g.to!==h)}for(const h of n.steps){const y=a.get(h.id),g=o.nodes[h.id];if(!y||!g){const x={label:h.label,kind:h.kind||va.kind};h.external&&(x.external=!0),h.group&&h.group!==jt&&(x.in=h.group),o.nodes[h.id]=x,s.push({id:h.id,x:Math.round(h.x),y:Math.round(h.y)});continue}h.label!==g.label&&(g.label=h.label),h.kind&&h.kind!==g.kind&&(g.kind=h.kind),!!h.external!=!!g.external&&(h.external?g.external=!0:delete g.external);const m=h.group===jt||!h.group?void 0:h.group;m!==g.in&&(m?g.in=m:delete g.in);const b=Math.round(h.x)-Math.round(y.x),w=Math.round(h.y)-Math.round(y.y);if(!(!b&&!w))if(r.folded.has(h.id))for(const x of Ma(e,h.id))t.nodes[x]&&s.push({id:x,x:Math.round(t.nodes[x].x)+b,y:Math.round(t.nodes[x].y)+w});else s.push({id:h.id,x:Math.round(h.x),y:Math.round(h.y)})}const l=h=>`${h.from}\0${h.to}`,u=h=>r.stand(h.from)===h.from&&r.stand(h.to)===h.to,c=e.edges.filter(h=>!u(h));new Set(n.depends.map(h=>`${h.source}\0${h.target}`));for(const h of r.lifted){const[y,g]=h.split("\0"),m=n.depends.find(w=>w.source===y&&w.target===g),b=r.depends.find(w=>w.source===y&&w.target===g);if(!m||m.label!==b?.label||m.kind==="async"!=(b?.kind==="async"))throw new qi(`That arrow stands for the arrows inside a folded frame, and cannot be changed from here. Unfold ${e.nodes[y]?.label??y} or ${e.nodes[g]?.label??g} to change them.`)}const d=[];for(const h of n.depends){if(r.lifted.has(`${h.source}\0${h.target}`))continue;const y=e.edges.find(m=>m.from===h.source&&m.to===h.target)??e.edges.find(m=>m.from===h.target&&m.to===h.source),g={from:h.source,to:h.target};h.label&&(g.label=h.label),h.tech&&(g.tech=h.tech),h.kind==="async"&&(g.async=!0),y?.via&&(g.via=y.via),y?.planned&&(g.planned=y.planned),y?.retiring&&(g.retiring=y.retiring),d.push(g)}o.edges=[...c,...d].filter(h=>h.from in o.nodes&&h.to in o.nodes);const f=new Map(e.edges.map((h,y)=>[l(h),y]));o.edges.sort((h,y)=>(f.get(l(h))??1e9)-(f.get(l(y))??1e9));for(const h of o.edges)h.via&&!(h.via in o.nodes)&&delete h.via;const p=Wy(o);if(p.length)throw new qi(p[0]);return{after:o,placements:s}}function p3(e,t){const{after:n,placements:r}=Yb(e.arch,e.layout,t),{ops:o}=ag(e.arch,n);for(const s of r){const i=e.layout.nodes[s.id];n.nodes[s.id]&&(!i||Math.round(i.x)!==s.x||Math.round(i.y)!==s.y)&&o.push({op:"layout.place",id:s.id,x:s.x,y:s.y})}return o}function y3(e){const t=_o(e,{headroom:!1});return{...t,steps:t.steps.map(n=>({...n,group:n.group===jt?n.group:e.arch.nodes[n.group]?.label??n.group}))}}const Uc={untouched:.4,offFlow:.22};function g3(e){const t=s=>e()?.arch.nodes[s],n=s=>{const i=e();return i?.footprint&&t(s)?_1(i.arch,i.footprint,s):null},r=()=>{const s=e();if(!s?.flow)return null;const i=new Set;for(const a of s.flow)i.add(s.stand(a.from)),i.add(s.stand(a.to));return i},o=s=>{const i=t(s);return i?.planned?"planned":i?.retiring?"retiring":null};return{edge(s){const i=n(s);return i==="new"||i==="changed"||i==="removed"?{colour:qr[i].colour,width:2.6,dashed:i==="new"||i==="removed"}:o(s)?{width:1.6,dashed:!0}:{width:1.5,dashed:!1}},opacity(s){const i=r();return i?i.has(s)?1:Uc.offFlow:n(s)==="untouched"?Uc.untouched:1},look(s){const i=n(s);if(i==="new"||i==="changed"||i==="removed")return{...qr[i],strike:i==="removed"};const a=o(s);return a==="planned"?{...qr.new,word:`planned by ${t(s)?.planned}`,strike:!1}:a==="retiring"?{...qr.removed,word:`retiring: ${t(s)?.retiring} removes it`,strike:!1}:null},caption(s,i){const a=e(),l=[],u=a?.folded.get(s);u&&l.push(`${u.count} inside`);const c=a?.footprint?.changed.get(s);return c?.length&&l.push(c.length===1?`changed by ${i?.[c[0]]??c[0]}`:`changed by ${c.length} steps`),l.join(" · ")},arrow(s){const i=e();if(!i)return{opacity:1};const a=`${s.source}\0${s.target}`,l=i.flow,c=(l?l.some(f=>i.stand(f.from)===s.source&&i.stand(f.to)===s.target||i.stand(f.from)===s.target&&i.stand(f.to)===s.source):!0)?1:Uc.offFlow;if(i.footprint?.addedArrows.has(a))return{stroke:_a.done,opacity:c,dashed:!0};if(i.footprint?.removedArrows.has(a))return{stroke:_a.failed,opacity:c,dashed:!0};const d=i.arch.edges.find(f=>`${f.from}\0${f.to}`===a);return{opacity:c,...d?.planned||d?.retiring?{dashed:!0}:{}}}}}const{sticker:m3,link:b3,text:w3}=yd,{move:x3,editText:wy,remove:xy,network:ra}=wd;function v3(e,{onChange:t,decor:n,stepLabel:r}){const o=[jt,...e.proj.frames.map(g=>g.id)],s=cn("--ember","#EA5202"),i=cn("--surface","#FFFFFF"),a=cn("--wire","#8F8881"),l=cn("--wire-soft","#C9C3BD"),u=cn("--slate","#69625B"),c=cn("--ink","#19120F"),d=cn("--sans","sans-serif"),f={...Vr,fontFamily:d},{fontSize:p,...h}=f,y=g=>r?.(g);return{...mr(e),responsive:"scale",focusOutline:!0,axes:!1,margins:{top:xt.y,right:xt.x,bottom:xt.y,left:xt.x},theme:{handle:s,handleStroke:i,background:"transparent",font:{family:d},marks:{text:{fill:c}}},schema:{structure:"network",tables:{steps:{role:"nodes",fields:{id:{type:"categorical",key:!0,open:!0},label:{type:"categorical",open:!0,default:va.label},group:{type:"categorical",domain:o,open:!0,default:jt},kind:{type:"categorical",open:!0,default:va.kind},external:{type:"categorical",open:!0,default:""},x:{type:"quantitative",domain:[0,e.canvas.width]},y:{type:"quantitative",domain:[0,e.canvas.height]}}},depends:{role:"links",directed:!0,fields:{source:{type:"ref"},target:{type:"ref"},label:{type:"categorical",open:!0,default:""},kind:{type:"categorical",open:!0,default:"needs"},tech:{type:"categorical",open:!0,default:""}}}}},data:{steps:e.steps,depends:e.depends},onChange:t,constraints:[Ub],marks:[b3({curve:"orthogonal",arrowSize:8,inset:3,stroke:g=>n?.arrow({source:g.source,target:g.target}).stroke??(g.kind==="async"?l:a),strokeWidth:g=>n?.arrow({source:g.source,target:g.target}).stroke?2.2:g.kind==="async"?1.2:1.4,...n?{opacity:g=>n.arrow({source:g.source,target:g.target}).opacity}:{},handleSize:4.5,handleColor:l,fill:u,fontSize:11,labelBackground:i,labelPadding:3,format:Hb,channels:{nodeWidth:{fn:Dn("boxWidth",g=>$n(g.label,f).width)},nodeHeight:{fn:Dn("boxHeight",g=>$n(g.label,f).height)},source:{field:"source",edit:ra.rewire({channel:"source",threshold:yl,when:g=>g.node?.channel==="source"})},target:{field:"target",edit:ra.rewire({channel:"target",threshold:yl,when:g=>g.node?.channel==="target"})},text:{field:"label"}},edits:[ra.reverse({name:Xe.flip,when:fr(Xe.flip)}),xy({name:Xe.removeArrow,when:fr(Xe.removeArrow)}),Co(Xe.kind,"kind"),wy()]}),m3({...h,radius:7,stroke:"transparent",fill:"transparent",strokeWidth:0,...n?{opacity:g=>n.opacity(g.id)}:{},channels:{x:{field:"x",edit:x3({channels:["x","y"],mode:"relative"})},y:{field:"y",scale:{reverse:!0}},text:{field:"label"},fill:{value:"transparent"},fontSize:{value:p}},edits:[ra.connect({name:Xe.connect,when:fr(Xe.connect),threshold:_d}),Co(Xe.group,"group"),Co(Xe.boxKind,"kind"),Co(Xe.external,"external"),Bb({defaults:{...va},over:(g,m)=>{const{width:b,height:w}=$n(g.label,f);return Math.abs(m.x-g.x)<=b/2&&Math.abs(m.y-g.y)<=w/2}}),xy({name:Xe.removeStep,when:fr(Xe.removeStep)}),wy()]}),...n?[w3({fill:u,fontSize:12,dy:g=>$n(g.label,f).height/2+13,...n?{opacity:g=>n.opacity(g.id)}:{},channels:{x:{field:"x"},y:{field:"y",scale:{reverse:!0}},text:{fn:Dn("caption",g=>n.caption(g.id,new Proxy({},{get:(m,b)=>y(String(b))})))}}})]:[]]}}const k3="http://www.w3.org/2000/svg";function ht(e,t={},n){const r=document.createElementNS(k3,e);for(const[o,s]of Object.entries(t))r.setAttribute(o,String(s));return n!==void 0&&(r.innerHTML=n),r}const Hi=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]??t),_n=(e,t)=>getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t;function jn(e){const t=_n("--sans","sans-serif");return e.map(n=>{const{width:r,height:o}=$n(n.label,{...Vr,fontFamily:t});return{id:n.id,group:n.group,x:n.x+xt.x,y:n.y+xt.y,w:r,h:o}})}function sc(e,t,n){e.querySelector(`:scope > .${t}`)?.remove();const{width:r,height:o}=mr({canvas:n});return ht("svg",{class:t,viewBox:`0 0 ${r} ${o}`,"aria-hidden":"true"})}function S3(e,t,n,r=null){if(!e)return;const o=sc(e,"frames",n),s=_n("--ember","#EA5202");for(const i of qy(t)){const a=i.group===r,l=ht("g",{"data-group":i.group}),u=i.members.length===1&&!a;u||l.appendChild(ht("rect",{x:i.x,y:i.y,width:i.w,height:i.h,rx:10,fill:"var(--frame)",stroke:a?s:"var(--frame-edge)","stroke-width":a?2.2:1.2,...a?{"stroke-dasharray":"6 4"}:{}})),l.appendChild(ht("text",u?{x:i.x+Mo.left+16,y:i.y+Mo.top-5,class:"frame-name","font-size":10.5,"font-weight":600,fill:"var(--slate)",opacity:.85}:{x:i.x+12,y:i.y+19,class:"frame-name","font-size":11.5,"font-weight":600,fill:"var(--slate)"},Hi(Hy(i.group,u?i.w+60:i.w)))),o.appendChild(l)}e.prepend(o)}const $3=e=>22+e.length*5.7;function Yu(e,t){const n=e instanceof SVGSVGElement?e:e.querySelector("svg"),r=new Map;for(const i of e.querySelectorAll("path")){const a=Dt(i)?.data;if(!a||a.source===void 0||a.target===void 0)continue;const l=i.getAttribute("fill");if(l&&l!=="none")continue;const u=i.getTotalLength?.()??0,c=`${a.source}\0${a.target}`;u>(r.get(c)?.len??0)&&r.set(c,{path:i,len:u})}const o=new Map,s=n?.getScreenCTM()?.inverse();if(!s)return o;for(const i of t){const a=`${i.source}\0${i.target}`,l=r.get(a);if(!l||l.len<18)continue;const u=l.path.getPointAtLength(i.label?Math.min(16,l.len*.2):l.len*.5),c=l.path.getScreenCTM();if(!c)continue;const d=new DOMPoint(u.x,u.y).matrixTransform(s.multiply(c));o.set(a,{x:d.x,y:d.y})}return o}function Gb(e,{items:t,look:n,arrows:r,size:o}){if(!e)return;const s=sc(e,"marks",o),i=_n("--ink","#19120F"),a=_n("--surface","#FFFFFF"),l=_n("--slate","#69625B");for(const c of t){const d=n(c.id);if(!d)continue;const f=c.x-c.w/2,p=c.x+c.w/2,h=c.y-c.h/2;if(d.strike&&s.appendChild(ht("path",{d:`M${f+7} ${c.y} H${p-7}`,stroke:i,"stroke-width":1.6,"stroke-linecap":"round",opacity:.8})),d.icon){const g=ht("g",{transform:`translate(${f+1} ${h-1})`,class:"chip","data-status":d.word??""});g.appendChild(ht("title",{},Hi(d.word??""))),g.appendChild(ht("circle",{r:9,fill:d.colour??l,stroke:a,"stroke-width":2})),g.appendChild(ht("g",{transform:"translate(-6 -6)",color:"#FFFFFF"},aa(d.icon))),s.appendChild(g)}[d.review?["question","review"]:null,d.atRisk?["exclaim","at risk"]:null].filter(Boolean).forEach((g,m)=>{const[b,w]=g,x=$3(w),S=ht("g",{transform:`translate(${p-x+10} ${h-9-m*19})`,class:"pill","data-badge":w});S.appendChild(ht("rect",{width:x,height:16,rx:8,fill:a,stroke:i,"stroke-width":1})),S.appendChild(ht("g",{transform:"translate(3 2)",color:i},aa(b))),S.appendChild(ht("text",{x:18,y:11.5,"font-size":10.5,"font-weight":600,fill:i},Hi(w))),s.appendChild(S)})}const u=_a.waiting;for(const c of r){const d=c.icon??of[c.kind];if(d){const f=ht("g",{transform:`translate(${c.x} ${c.y})`,class:"gate","data-kind":c.kind,...c.yours?{"data-yours":""}:{}});f.appendChild(ht("circle",{r:9,fill:a,stroke:c.yours?u:"var(--wire)","stroke-width":c.yours?2.4:1.5})),f.appendChild(ht("g",{transform:"translate(-6 -6)",color:c.yours?u:i},aa(d))),s.appendChild(f)}c.tech&&s.appendChild(ht("text",{class:"arrow-tech",x:c.x,y:c.y+(d?21:15),"text-anchor":"middle","font-size":10,fill:l,stroke:a,"stroke-width":3,"paint-order":"stroke"},Hi(c.tech)))}e.insertBefore(s,e.querySelector(":scope > .ghost"))}function _3(e,{frames:t,boxes:n,decor:r,size:o,dropping:s=null}){if(!e)return;const i=sc(e,"frames",o),a=_n("--ember","#EA5202"),l=_n("--surface","#FFFFFF"),u=_n("--wire","#8F8881"),c=_n("--ext-fill","#ECE9E5"),d="6 4";for(const f of t){const p=f.id===s,h=r.edge(f.id),y=ht("g",{"data-group":f.id,class:"frame",opacity:r.opacity(f.id)}),g=p?a:h.colour??"var(--frame-edge)",m=p||h.dashed||f.kind==="group";y.appendChild(ht("rect",{x:f.x,y:f.y,width:f.w,height:f.h,rx:12,fill:f.external?c:"var(--frame)",stroke:g,"stroke-width":p?2.2:h.colour?h.width:1.2,...m?{"stroke-dasharray":d}:{}})),y.appendChild(ht("text",{x:f.x+12,y:f.y+19,class:"frame-name","font-size":11.5,"font-weight":600,fill:"var(--slate)"},Hi(Hy(f.label,f.w-40)))),i.appendChild(y)}for(const f of n){const p=r.edge(f.id),h=ht("g",{class:"shape","data-id":f.id,"data-kind":f.kind,opacity:r.opacity(f.id)});for(const y of M1(f.kind,f,{folded:f.folded})){const{dashed:g,...m}=y.attrs,b=y.role==="line";h.appendChild(ht(y.tag,{...m,class:`part ${y.role}`,fill:b?"none":f.external?c:l,stroke:p.colour??u,"stroke-width":p.width,"stroke-linejoin":"round",...g||p.dashed?{"stroke-dasharray":d}:{}}))}i.appendChild(h)}e.prepend(i)}function Vb(e,t){for(const n of e.querySelectorAll("path")){const r=Dt(n)?.data;if(!r||r.source===void 0||r.target===void 0)continue;const o=n.getAttribute("stroke");if(!o||o==="transparent"||o==="none")continue;const s=n.getAttribute("fill");s&&s!=="none"||(t(r)?n.setAttribute("stroke-dasharray","6 4"):n.removeAttribute("stroke-dasharray"))}}function M3(e,{steps:t,size:n}){if(!e)return;const r=sc(e,"flow",n),o=_n("--ember","#EA5202"),s=_n("--surface","#FFFFFF"),i=_n("--slate","#69625B");for(const a of t){a.gap&&r.appendChild(ht("path",{d:`M${a.gap.from.x} ${a.gap.from.y} L${a.gap.to.x} ${a.gap.to.y}`,stroke:a.current?o:i,"stroke-width":a.current?2.4:1.4,"stroke-dasharray":"5 4",fill:"none",opacity:a.current?1:.7}));const l=ht("g",{transform:`translate(${a.x} ${a.y})`,class:`flow-chip${a.current?" current":""}`,"data-step":a.n});l.appendChild(ht("circle",{r:a.current?11:9,fill:a.current?o:s,stroke:a.current?s:i,"stroke-width":a.current?2:1.4})),l.appendChild(ht("text",{x:0,y:4,"text-anchor":"middle","font-size":a.current?11.5:10.5,"font-weight":700,fill:a.current?"#FFFFFF":i},`${a.n}${a.gap?"?":a.reply?"↩":""}`)),r.appendChild(l)}e.insertBefore(r,e.querySelector(":scope > .ghost"))}const E3=[{kind:"needs",label:"Needs",hint:"it uses what comes before"},{kind:"after",label:"After",hint:"order only"},{kind:"approve",label:"Approve first",hint:"you approve the step before"},{kind:"ask",label:"Ask first",hint:"the agent asks you"},{kind:"input",label:"Needs your input",hint:"it waits for something from you"}],A3="finished work is history: reopen the step first";function T3(e,{groups:t=[],group:n,kind:r="needs",frozen:o=!1}={}){const s=o?A3:void 0;if(e.type==="canvas")return[{id:"add",label:"Add a step here"}];if(e.type==="step"){const i=n&&n!==jt?n:void 0,a=t.filter(l=>l!==jt);return[{id:"rename",label:"Rename",key:"Enter",disabled:s},...a.map((l,u)=>({id:`group:${l}`,label:l,checked:l===i,disabled:s,...u===0?{section:"Move to group"}:{}})),{id:"group:top",label:"No group",checked:!i,disabled:s,...a.length?{}:{section:"Move to group"}},{id:"group:new",label:"New group…",disabled:s,ask:"Name the group"},{id:"delete",label:"Delete",key:"Delete",danger:!0,disabled:s,section:" "}]}return[{id:"label",label:"Label…",disabled:s},{id:"flip",label:"Flip direction",disabled:s},...E3.map((i,a)=>({id:`kind:${i.kind}`,label:i.label,hint:i.hint,checked:i.kind===r,disabled:s,...a===0?{section:"This arrow means"}:{}})),{id:"delete",label:"Delete",key:"Delete",danger:!0,disabled:s,section:" "}]}const O3=[{kind:"needs",label:"Waits for the answer",hint:"a call"},{kind:"async",label:"Does not wait",hint:"an event or a message"}];function oa(e,{kind:t,external:n=!1,group:r,frames:o=[],folded:s=!1,container:i=!1,plan:a=null}={}){if(e.type==="canvas")return[{id:"add",label:"Add a box here"}];const l=(d,f)=>[...o.filter(p=>p.id!==d).map((p,h)=>({id:`${f}${p.id}`,label:p.label,checked:p.id===r,...h===0?{section:"Move into"}:{}})),{id:`${f}top`,label:"Nothing: top level",checked:!r||r===jt,...o.filter(p=>p.id!==d).length?{}:{section:"Move into"}},{id:`${f}new`,label:"A new frame…",ask:"Name the frame"}],u=a?[{id:"plan:planned",label:`Planned by ${a.id}`,hint:"it does not exist yet",checked:a.planned,section:`For the plan ${a.id}`},{id:"plan:retiring",label:`Removed by ${a.id}`,hint:"it goes when the plan is done",checked:a.retiring}]:[];if(e.type==="arrow")return[{id:"label",label:"Label…"},{id:"flip",label:"Flip direction",hint:"who uses whom"},...O3.map((d,f)=>({id:`kind:${d.kind}`,label:d.label,hint:d.hint,checked:d.kind===(t??"needs"),...f===0?{section:"This arrow"}:{}})),{id:"delete",label:"Delete",key:"Delete",danger:!0,section:" "}];const c=d=>Object.keys(la).map((f,p)=>({id:`${d}${f}`,label:la[f],checked:f===t,...i&&f!=="service"&&f!=="group"?{disabled:"it holds boxes: take them out first"}:{},...p===0?{section:"Change kind"}:{}}));return e.type==="frame"?[{id:"fold",label:s?"Unfold":"Fold",hint:s?"show what is inside":"hide what is inside"},{id:"rename",label:"Rename…",ask:"Rename the frame"},...["service","group"].map((d,f)=>({id:`frame-kind:${d}`,label:la[d],checked:d===t,...f===0?{section:"It is a"}:{}})),{id:n?"external:off":"external:on",label:"Someone else runs it",checked:n},...l(e.id??"","into:"),{id:"delete",label:"Remove the frame",hint:"what is inside stays",danger:!0,section:" "}]:[...s?[{id:"fold",label:"Unfold",hint:"show what is inside"}]:[],{id:"rename",label:"Rename",key:"Enter"},...c("boxkind:"),{id:n?"external:off":"external:on",label:"Someone else runs it",checked:n,section:" "},...l(e.id??"","into:"),...u,{id:"delete",label:"Delete",key:"Delete",danger:!0,section:" "}]}const C3="http://www.w3.org/2000/svg";function bn(e,t={},n){const r=document.createElementNS(C3,e);for(const[o,s]of Object.entries(t))r.setAttribute(o,String(s));return n!==void 0&&(r.textContent=n),r}const Kc=(e,t)=>getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t;function vy(e,t){if(Math.abs(t.x-e.x)*.6>=Math.abs(t.y-e.y)){const a=t.x>=e.x?1:-1,l=e.x+a*e.w/2,u=t.x-a*t.w/2,c=(l+u)/2;return`M${l} ${e.y} H${c} V${t.y} H${u}`}const r=t.y>=e.y?1:-1,o=e.y+r*e.h/2,s=t.y-r*t.h/2,i=(o+s)/2;return`M${e.x} ${o} V${i} H${t.x} V${s}`}const ky=(e,t,n=10)=>Math.abs(e.x-t.x)<(e.w+t.w)/2+n&&Math.abs(e.y-t.y)<(e.h+t.h)/2+n;function Xb(e,t){if(!t.some(n=>ky(e,n)))return e;for(let n=1;n<=8;n++)for(const r of[1,-1]){const o={...e,y:e.y+r*n*(e.h+14)};if(o.y-o.h/2>=0&&!t.some(s=>ky(o,s)))return o}return e}function gl(e,t,n,r,o,s=null){e?.querySelector(":scope > .ghost")?.remove();const i=t&&t.applies?t:null;if(!e||!i&&!s)return null;t=i??{applies:!0,addedNodes:[],addedEdges:[],removedNodes:[],removedEdges:[],changedNodes:[]};const l=Kc("--ember","#EA5202"),u=Kc("--ember-deep","#B53D00"),c=Kc("--sans","sans-serif"),d=v=>$n(v,{...Vr,fontFamily:c}),f=new Map;for(const[v,k]of Object.entries(n.nodes)){const _=r.nodes[v];if(!_)continue;const{width:A,height:L}=d(k.label);f.set(v,{x:_.x+xt.x,y:_.y+xt.y,w:A,h:L})}const p=[...f.values()];for(const v of t.addedNodes){const{width:k,height:_}=d(v.label),A=Xb({x:v.x+xt.x,y:v.y+xt.y,w:k,h:_},p);p.push(A),f.set(v.id,A)}const h=bn("svg",{class:"ghost",viewBox:`0 0 ${mr({canvas:o}).width} ${mr({canvas:o}).height}`,"aria-hidden":"true"});h.appendChild(bn("defs")).innerHTML=[l,u].map((v,k)=>`<marker id="ghost-head-${k}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0 0 L10 5 L0 10 z" fill="${v}"/></marker>`).join("");const y=[],g=(v,k,_=4)=>bn("rect",{x:v.x-v.w/2-_,y:v.y-v.h/2-_,width:v.w+_*2,height:v.h+_*2,rx:9,fill:"none",stroke:k,"stroke-width":1.6,"stroke-dasharray":"5 3"});for(const v of t.removedEdges){const k=f.get(v.from),_=f.get(v.to);k&&_&&y.push(k,_),k&&_&&h.appendChild(bn("path",{d:vy(k,_),fill:"none",stroke:u,"stroke-width":3,"stroke-dasharray":"2 5",opacity:.85}))}for(const v of t.removedNodes){const k=f.get(v);k&&(y.push(k),h.appendChild(g(k,u)),h.appendChild(bn("path",{d:`M${k.x-k.w/2} ${k.y-k.h/2} L${k.x+k.w/2} ${k.y+k.h/2} M${k.x+k.w/2} ${k.y-k.h/2} L${k.x-k.w/2} ${k.y+k.h/2}`,stroke:u,"stroke-width":1.6,opacity:.7})))}for(const v of t.changedNodes){const k=f.get(v.id);if(k&&(y.push(k),h.appendChild(g(k,l)),v.label!==void 0)){const _=d(v.label),A=bn("g",{transform:`translate(${k.x} ${k.y+k.h/2+15})`});A.appendChild(bn("rect",{x:-_.width/2,y:-10,width:_.width,height:20,rx:6,fill:l})),A.appendChild(bn("text",{x:0,y:4,"text-anchor":"middle","font-size":11,"font-family":c,"font-style":"italic",fill:"#FFFFFF"},v.label)),h.appendChild(A)}}for(const v of t.addedEdges){const k=f.get(v.from),_=f.get(v.to);k&&_&&y.push(k,_),k&&_&&h.appendChild(bn("path",{d:vy(k,_),fill:"none",stroke:l,"stroke-width":1.8,"stroke-dasharray":"6 4","marker-end":"url(#ghost-head-0)"}))}for(const v of t.addedNodes){const k=f.get(v.id);k&&(y.push(k),h.appendChild(bn("rect",{x:k.x-k.w/2,y:k.y-k.h/2,width:k.w,height:k.h,rx:7,fill:l,"fill-opacity":.12,stroke:l,"stroke-width":1.6,"stroke-dasharray":"5 3"})),h.appendChild(bn("text",{x:k.x,y:k.y+4,"text-anchor":"middle","font-size":Vr.fontSize,"font-family":c,fill:u},v.label.length>26?`${v.label.slice(0,25)}…`:v.label)))}const m=s?f.get(s):void 0;if(m&&h.appendChild(bn("rect",{x:m.x-m.w/2-5,y:m.y-m.h/2-5,width:m.w+10,height:m.h+10,rx:10,fill:"none",stroke:l,"stroke-width":2.4})),e.appendChild(h),!i||!y.length)return null;const b=Math.min(...y.map(v=>v.x-v.w/2)),w=Math.max(...y.map(v=>v.x+v.w/2)),x=Math.min(...y.map(v=>v.y-v.h/2)),S=Math.max(...y.map(v=>v.y+v.h/2));return{x:b,y:x,w:w-b,h:S-x}}const N3=["label","group","x","y","kind","external"],Sy=e=>typeof e=="number"?Math.round(e):e;function Gu(e,t){const n=new Map(e.steps.map(y=>[y.id,y])),r=new Map(t.steps.map(y=>[y.id,y])),o=[],s=[];for(const[y,g]of r){const m=n.get(y);if(!m){o.push(g);continue}const b={};for(const w of N3)Sy(m[w])!==Sy(g[w])&&(b[w]=g[w]);Object.keys(b).length&&s.push({id:y,...b})}const i=[...n.keys()].filter(y=>!r.has(y)),a=y=>`${y.source}\0${y.target}`,l=new Map(e.depends.map(y=>[a(y),y])),u=new Map(t.depends.map(y=>[a(y),y])),c=new Set(i),d=[],f=[];for(const[y,g]of u){const m=l.get(y);m?((m.label??"")!==(g.label??"")||(m.kind??"needs")!==(g.kind??"needs")||(m.tech??"")!==(g.tech??""))&&f.push({source:g.source,target:g.target,label:g.label,kind:g.kind??"needs",...g.tech!==void 0?{tech:g.tech}:{}}):d.push(g)}const p=[...l].filter(([y,g])=>!u.has(y)&&!c.has(g.source)&&!c.has(g.target)).map(([,y])=>({source:y.source,target:y.target})),h={};return(o.length||s.length||i.length)&&(h.steps={...o.length?{insert:o}:{},...s.length?{update:s}:{},...i.length?{remove:i}:{}}),(d.length||f.length||p.length)&&(h.depends={...d.length?{insert:d}:{},...f.length?{update:f}:{},...p.length?{remove:p}:{}}),Object.keys(h).length?h:null}const I3=new Set(["apply","type","inverts","cardinality","scope","into","constrain","guide","stage","advance","target","targets","table"]),L3=new Set(["build","glyph","xKey","yKey","discreteScale","rawChannels","table"]),ia=e=>" ".repeat(e),$y=e=>`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`,F3=e=>e&&typeof e=="object"&&typeof e.apply=="function"&&typeof e.type=="string",_y=["name","channels","field","gesture","mode","strategy","threshold","when"],R3=([e],[t])=>(_y.indexOf(e)+1||99)-(_y.indexOf(t)+1||99)||(e<t?-1:1),z3=(e,t)=>t==null||t===!1||Array.isArray(t)&&!t.length||e==="pick"&&t==="direct"||e==="gesture"&&t==="drag"||e==="threshold"&&t===0;function ka(e,t,n={}){if(typeof e=="function")return`ƒ ${e.name||"anonymous"}`;if(typeof e=="string")return $y(e);if(e===null||typeof e!="object")return String(e);if(e instanceof Date)return e.toISOString();if(F3(e)){const i=e,a=Object.entries(i).filter(([l,u])=>!I3.has(l)&&!z3(l,u)).sort(R3);return`${i.type}(${a.length?`{ ${a.map(([l,u])=>`${l}: ${ka(u,t,{one:!0})}`).join(", ")} }`:""})`}if(Array.isArray(e)){if(!e.length)return"[]";const i=e.map(l=>ka(l,t+1,{one:!0})),a=`[${i.join(", ")}]`;return n.one&&a.length<=76&&!i.some(l=>l.includes(`
14
+ `))?a:`[
15
+ ${i.map(l=>`${ia(t+1)}${l}`).join(`,
16
+ `)}
17
+ ${ia(t)}]`}const r=Object.entries(e).filter(([i,a])=>a!==void 0&&!(P3(e)&&L3.has(i)));if(!r.length)return"{}";const o=r.map(([i,a])=>`${/^[A-Za-z_$][\w$]*$/.test(i)?i:$y(i)}: ${ka(a,t+1,{one:!0})}`),s=`{ ${o.join(", ")} }`;return n.one&&s.length<=76&&!o.some(i=>i.includes(`
18
+ `))?s:`{
19
+ ${o.map(i=>`${ia(t+1)}${i}`).join(`,
20
+ `)}
21
+ ${ia(t)}}`}const P3=e=>e&&typeof e=="object"&&typeof e.id=="string"&&e.id.includes("/")&&"channels"in e;function Jb(e){return Object.entries(e).filter(([,n])=>n!==void 0).map(([n,r])=>n==="data"&&r&&typeof r=="object"?`data: { ${Object.entries(r).map(([s,i])=>`${s}: [${Array.isArray(i)?`${i.length} row${i.length===1?"":"s"}`:"…"}]`).join(", ")} }`:`${n}: ${ka(r,0,{one:!0})}`).join(`
22
+ `)}const Zb=(e,t)=>JSON.stringify({canvas:e.canvas,steps:t.steps.map(n=>({id:n.id,label:n.label,group:n.group,x:Math.round(n.x),y:Math.round(n.y)})),depends:t.depends.map(n=>({source:n.source,target:n.target,label:n.label??"",...n.kind&&n.kind!=="needs"?{kind:n.kind}:{}}))},null,2),D3={actor:"you",via:"editor"},j3=1500;function W3(e){const{state:t,el:n,esc:r,notice:o,sync:s}=e,i={server:null,local:null,view:null,footprintId:"",planState:null,fp:null,flowId:null,flowAt:null,flowTimer:void 0,proposalId:null,drafts:{},own:new Set,unfollow:null,unfollowPlan:null,exists:null,fileInfo:new Map,calls:new Map},a=()=>t.mode==="architecture",l=()=>t.source==="server",u=()=>l()?i.server?{arch:i.server.arch,layout:i.server.layout}:null:i.local?{arch:i.local.arch,layout:i.local.layout}:null,c=()=>u()?.arch??null,d=()=>Object.fromEntries(Object.entries(i.planState?.plan?.nodes??{}).map(([C,W])=>[C,W.label])),f=()=>c()?.flows.find(C=>C.id===i.flowId)??null,p=()=>{const C=f();return C?i.flowAt===null?C.steps:[C.steps[i.flowAt]??C.steps[0]]:null},h=g3(()=>{const C=u();return!C||!i.view?null:{arch:C.arch,footprint:i.fp,flow:p(),folded:i.view.proj.folded,stand:i.view.proj.stand}}),y=(C,W)=>v3(C,{onChange:W,decor:h,stepLabel:q=>d()[q]});function g(){const C=u(),W=_o(C,{headroom:l()});i.view=W;const q=i.local?.sample;return l()?W:{...W,id:q.id,title:q.title,plan:q.plan,repo:q.repo,source:q.source,note:q.note}}function m(){e.mount(g())}const b=()=>c()?.title??"Architecture";async function w(){i.unfollow?.(),i.own.clear(),i.exists=null,t.selected=null,i.proposalId=null;let C;try{C=await Ea()}catch(W){o(`Could not open the architecture: ${W.message}.`,"error");return}if(!C.exists){i.server=null,i.exists=!1,i.view=null,x(C.error),A(),e.render();return}o(""),i.exists=!0,i.server=C,await F(i.footprintId,{quiet:!0}),m(),ie(),A()}function x(C){e.state.chart?.destroy?.(),e.state.chart=null,e.el("chart").replaceChildren(),e.el("empty").hidden=!1,e.el("board").toggleAttribute("data-empty",!0),e.el("planbar").hidden=!0,e.el("needs").hidden=!0,e.el("planTitle").textContent="No architecture yet",e.el("planMeta").textContent="draw one, import one, or ask";const W=t.root.split(/[\\/]/).filter(Boolean).pop()??t.root;e.el("empty").innerHTML=`
23
+ <div class="card">
24
+ <h2>${C?"The architecture file needs fixing":`No architecture in ${r(W)} yet`}</h2>
25
+ ${C?`<p class="err">${r(C)}</p>`:"<p>The architecture is the system as it is: its services, components and stores, and what uses what. Every plan is a change to it. It is one file, <code>.dcursed/architecture.json</code>.</p>"}
26
+ ${C?"":`<ul>
27
+ <li><button class="primary" data-arch-start="new">Draw it</button><span>Name it, then double-click the board to add boxes, and drag from the dots on a box to draw arrows: the first uses the second.</span></li>
28
+ <li><button data-arch-start="import">Import…</button><span>A Mermaid flowchart or C4 diagram, <code>.mmd</code> or markdown with a Mermaid block.</span></li>
29
+ <li><b>Ask your agent</b><span><q>Draw the architecture of this repository using the dcursed tools.</q></span></li>
30
+ </ul>`}
31
+ </div>`;for(const q of e.el("empty").querySelectorAll("[data-arch-start]"))q.onclick=()=>q.dataset.archStart==="new"?S():v()}function S(){const C=e.el("empty").querySelector(".card");if(!C)return;C.innerHTML='<h2>What is the system called?</h2><form class="new-plan"><input name="title" placeholder="The shop" aria-label="What the system is called" autocomplete="off" required><button type="submit">Create</button></form>';const W=C.querySelector("form"),q=W.elements.namedItem("title");q.focus(),W.onsubmit=async V=>{V.preventDefault();const ee=q.value.trim();if(ee)try{await L1({title:ee}),e.el("empty").hidden=!0,await w()}catch(pe){o(`Not created: ${pe.message}`,"error")}}}function v(){const C=document.createElement("input");C.type="file",C.accept=".md,.markdown,.mmd,.mermaid,.txt",C.onchange=async()=>{const W=C.files?.[0];if(W)try{const{warnings:q}=await F1(W);e.el("empty").hidden=!0,await w(),o(`Imported ${W.name}.${q.length?` ${q.join("; ")}.`:""}`)}catch(q){o(`Not imported: ${q.message}`,"error")}},C.click()}function k(C){D(),i.flowId=null,i.flowAt=null,i.fp=null,i.footprintId="",t.selected=null,i.local={sample:C,arch:structuredClone(C.arch),layout:structuredClone(C.layout)},m()}function _(){i.unfollow?.(),i.unfollow=null,i.unfollowPlan?.(),i.unfollowPlan=null,D()}function A(){i.unfollow?.(),i.unfollow=Ky({change:C=>{if(C.recovered){o(""),N({quiet:!0});return}if(!C.loaded&&!(C.rev!=null&&i.own.has(C.rev))){if(C.created||C.removed){w();return}N({line:C.line})}},problem:C=>o(`The architecture file has a problem: ${C.error}`,"error"),call:C=>{i.calls.set(C.id,C),e.shownCall()===C.id&&e.showCall(C)},open:C=>{e.el("conn").className="conn live",e.el("conn").textContent="saved live",C&&N()},down:()=>{e.el("conn").className="conn down",e.el("conn").textContent="server unreachable"}})}const L=(C,W)=>C?`${C.actor==="you"?C.via==="file"?"An edit to the file":"Another window":`${C.actor}`} changed the architecture (rev ${C.rev}${W?`, was ${W.rev}`:""}).`:"The architecture changed elsewhere.";async function N({quiet:C=!1,reseed:W=!1,line:q}={}){if(!l())return;if(s.pointerDown||s.inFlight){s.stale=!0,q&&(s.staleLine=q);return}const V=s.staleLine;V&&!i.own.has(V.rev)&&(q=V,C=!1),q&&i.own.has(q.rev)&&(q=void 0,C=!0),s.stale=!1,s.staleLine=null;let ee;try{ee=await Ea()}catch(ct){o(`Could not refresh: ${ct.message}.`,"error");return}if(!ee.exists){i.exists&&(i.server=null,i.exists=!1,x(ee.error));return}const pe=i.server;if(i.server=ee,i.exists=!0,s.pending&&!W&&i.own.has(ee.rev)){ie(),e.render();return}if(!t.chart){m(),ie();return}const me=_o(ee);i.view=me;const Oe=ee.layout.canvas??{width:640,height:240},Je=t.domain&&(Oe.width+40>t.domain.width||Oe.height+30>t.domain.height),Ht=JSON.stringify(pe?.layout.collapsed??[])!==JSON.stringify(ee.layout.collapsed??[]),wt=JSON.stringify(pe?_o(pe).proj.frames.map(ct=>ct.id):[])!==JSON.stringify(me.proj.frames.map(ct=>ct.id));if(Je||Ht||wt)m();else if(W)t.chart.setData({steps:me.steps,depends:me.depends}),C||o(`${L(q,pe)} Undo starts again from here.`);else{const ct=Gu(t.chart.getData(),me);ct?("deferred"in t.chart.patch(ct,{history:"keep"})&&(s.stale=!0),C||o(`${L(q,pe)} Your undo history is kept.`)):(e.redraw(),!C&&q&&o(L(q,pe)))}await F(i.footprintId,{quiet:!0,keep:!0}),ie(),e.render()}async function I(){if(!l())return T();const C=i.server;if(!C||s.inFlight||s.refreshing||!s.pending||s.pointerDown)return;s.pending=!1;let W;try{W=p3(C,t.chart.getData())}catch(V){if(!(V instanceof qi))throw V;o(`Not saved: ${V.message}`,"error"),await N({quiet:!0,reseed:!0});return}if(!W.length)return;s.inFlight=!0;let q=null;try{q=await Pd(C.rev,W)}catch{o("Lost the plan server. Your last change is not saved.","error")}finally{s.inFlight=!1}if(q?.status===200){i.own.add(q.body.rev),q.body.kind==="proposed"&&o(`Saved as proposal ${q.body.proposal.id}: the architecture is accepted.`),s.refreshing=!0;try{await N({quiet:!0})}finally{s.refreshing=!1}}else q&&(o(`Not saved: ${q.body.why??q.body.error}. The chart is back to the architecture as it is.`,"error"),await N({quiet:!0,reseed:!0}));s.pending&&e.scheduleSave(60)}function T(){const C=i.local;if(!(!C||!t.chart)){s.pending=!1;try{const{after:W,placements:q}=Yb(C.arch,C.layout,t.chart.getData());C.arch=W;const V={...C.layout.nodes};for(const ee of q)V[ee.id]={x:ee.x,y:ee.y};C.layout=eu(W,{...C.layout,nodes:V}).layout,i.view=_o({arch:C.arch,layout:C.layout},{headroom:!1}),e.render()}catch(W){if(!(W instanceof qi))throw W;o(`Not done: ${W.message}`,"error"),i.view=_o({arch:C.arch,layout:C.layout},{headroom:!1}),m()}}}async function M(C,W,q){if(!l())return $(C,W);for(let ee=0;s.inFlight&&ee<5e3;ee+=40)await new Promise(pe=>setTimeout(pe,40));if(!i.server||s.inFlight)return!1;let V=!1;s.inFlight=!0;try{const{status:ee,body:pe}=await Pd(i.server.rev,C,q);if(ee===200){i.own.add(pe.rev),o(W),V=!0;const me=pe.calls?.[0];me&&e.showCall(i.calls.get(me.id)??me)}else o(`Not done: ${pe.why??pe.error}`,"error")}finally{s.inFlight=!1}return await N({quiet:!0}),V}function $(C,W){const q=i.local;if(!q)return!1;T();const V=Dy(q.arch,C,D3);if(V.kind!=="applied")return o(`Not done: ${V.kind==="rejected"?V.why:"it is not a change you can make"}`,"error"),Promise.resolve(!1);q.arch=V.arch;const ee={...q.layout.nodes};for(const me of V.placements)ee[me.id]={x:me.x,y:me.y};let pe=q.layout.collapsed??[];for(const me of V.folds)pe=me.folded?[...pe.filter(Oe=>Oe!==me.id),me.id]:pe.filter(Oe=>Oe!==me.id);return q.layout=eu(V.arch,{...q.layout,nodes:ee,...pe.length?{collapsed:pe}:{collapsed:void 0}}).layout,pe.length||delete q.layout.collapsed,W&&o(W),m(),Promise.resolve(!0)}async function F(C,{quiet:W=!1,keep:q=!1}={}){if(l()){if(!C){i.unfollowPlan?.(),i.unfollowPlan=null,i.footprintId="",i.planState=null,i.fp=null,W||(e.redraw(),e.render());return}try{const V=await sf(C);if(!V.plan)throw new Error(V.error??"not a plan");i.footprintId=C,i.planState=V,i.fp=i.server?E1(i.server.arch,V.plan):null,q||(i.unfollowPlan?.(),i.unfollowPlan=By(C,{change:()=>{F(C,{quiet:!1,keep:!0})},problem:()=>{},open:()=>{},down:()=>{}}))}catch(V){i.footprintId="",i.planState=null,i.fp=null,W||o(`Could not look at that plan: ${V.message}.`,"error")}(!W||q)&&(e.redraw(),e.render())}}function D(){clearInterval(i.flowTimer),i.flowTimer=void 0}function P(C){D(),i.flowId=C===i.flowId?null:C,i.flowAt=null,e.redraw(),e.render()}function j(C){const W=f();W&&(i.flowAt=C===null?null:Math.max(0,Math.min(W.steps.length-1,C)),e.redraw(),e.render())}function G(){const C=f();if(C){if(i.flowTimer){D(),e.render();return}i.flowAt===null||i.flowAt>=C.steps.length-1?i.flowAt=0:i.flowAt+=1,e.redraw(),i.flowTimer=setInterval(()=>{const W=f();if(!W||i.flowAt===null||i.flowAt>=W.steps.length-1){D(),e.render();return}i.flowAt+=1,e.redraw(),e.render()},j3),e.render()}}function J(C,W){const q=f();if(!q||!i.view||!t.domain){C.querySelector(":scope > .flow")?.remove();return}const V=new Map(jn(W.steps).map(Je=>[Je.id,Je])),{stand:ee}=i.view.proj,pe=W.depends,me=Yu(t.chart,pe),Oe=[];q.steps.forEach((Je,Ht)=>{const wt=ee(Je.from),ct=ee(Je.to);if(wt===ct)return;const Pn=i.flowAt===Ht,An=me.get(`${wt}\0${ct}`),Bt=me.get(`${ct}\0${wt}`);if(An)Oe.push({n:Ht+1,current:Pn,...An});else if(Bt)Oe.push({n:Ht+1,current:Pn,x:Bt.x+14,y:Bt.y+14,reply:!0});else{const Ut=V.get(wt),It=V.get(ct);Ut&&It&&Oe.push({n:Ht+1,current:Pn,x:(Ut.x+It.x)/2,y:(Ut.y+It.y)/2,gap:{from:{x:Ut.x,y:Ut.y},to:{x:It.x,y:It.y}}})}}),M3(C,{steps:Oe,size:t.domain})}function re(C){if(!i.view||!t.chart)return[];const W=t.chart.getData(),q=C?W.steps.filter(V=>V.id!==C):W.steps;return my(i.view.proj.frames,q,new Map(jn(q).map(V=>[V.id,V])))}function Q(C){if(!t.chart||!t.domain||!i.view)return;const W=t.chart.getData(),q=jn(W.steps),V=new Map(q.map(Oe=>[Oe.id,Oe])),ee=my(i.view.proj.frames,W.steps,V);_3(C,{frames:ee,boxes:W.steps.flatMap(Oe=>{const Je=V.get(Oe.id);return Je?[{id:Oe.id,kind:Oe.kind,external:!!Oe.external,x:Je.x,y:Je.y,w:Je.w,h:Je.h,folded:i.view?.proj.folded.has(Oe.id)??!1}]:[]}),decor:h,size:t.domain,dropping:e.interactions().dropping()});const pe=W.depends.filter(Oe=>Oe.kind==="async"),me=pe.length?Yu(t.chart,pe):new Map;Gb(C,{items:[...q,...ee.map(Oe=>({id:Oe.id,group:void 0,x:Oe.x+Oe.w/2,y:Oe.y+Oe.h/2,w:Oe.w,h:Oe.h}))],look:Oe=>h.look(Oe)??void 0,arrows:pe.flatMap(Oe=>{const Je=me.get(`${Oe.source}\0${Oe.target}`);return Je?[{...Je,kind:Oe.kind,icon:"async"}]:[]}),size:t.domain}),Vb(t.chart,Oe=>Oe.kind==="async"||h.arrow(Oe).dashed===!0),J(C,W),be(),e.interactions().paint()}const ve=()=>c()?.proposals??[],Ce=()=>ve().find(C=>C.id===i.proposalId)??ve()[0]??null;let le="";function be(){const C=u(),W=n("chart").querySelector(".canvas");if(!C||!l()){gl(W,null,{},{},t.domain??{width:0,height:0}),e.ghost(null),ce();return}const q=Ce(),V=q?Xd(C.arch,C.layout,q.ops):null;e.ghost(gl(W,V,{nodes:C.arch.nodes},C.layout,t.domain??C.layout.canvas)),ce()}function ce(){const C=n("proposalCard"),W=ve(),q=u();if(!q||!l()||!W.length){C.hidden=!0,le="";return}const V=Ce();if(!V)return;const ee=Xd(q.arch,q.layout,V.ops),pe=R1(V,{at:W.indexOf(V)+1,of:W.length,applies:ee.applies,why:ee.why,arch:c()});pe!==le&&(le=pe,C.innerHTML=pe,C.setAttribute("aria-label",`Proposal ${V.id} from ${V.by}`),ue(C)),C.hidden=!1,e.placeCard()}function Y(C){i.proposalId=C,le="",e.render()}function ue(C){for(const W of C.querySelectorAll("[data-arch-accept-draft]"))W.onclick=()=>M([{op:"arch.set",phase:"accepted"}],"Accepted. From now on an agent’s changes arrive as proposals.","you accepted the architecture");for(const W of C.querySelectorAll("[data-arch-accept]"))W.onclick=()=>M([{op:"proposal.accept",id:W.dataset.archAccept??""}],`Accepted ${W.dataset.archAccept}.`);for(const W of C.querySelectorAll("[data-arch-reject]"))W.onclick=()=>{const q=W.dataset.archReject??"",V=C.querySelector(`[data-arch-why="${CSS.escape(q)}"]`)?.value.trim();M([{op:"proposal.reject",id:q}],`Rejected ${q}.`,V||void 0)};for(const W of C.querySelectorAll("[data-arch-show]"))W.onclick=()=>Y(W.dataset.archShow??"");for(const W of C.querySelectorAll("[data-arch-next]"))W.onclick=()=>{const q=ve(),V=q.findIndex(ee=>ee.id===Ce()?.id);Y(q[(V+1)%q.length].id)}}function ie(){const C=u(),W=n("phase");if(n("phase2").hidden=!0,!C){W.hidden=!0,n("planbar").hidden=!0;return}const q=C.arch;n("planbar").hidden=!l(),n("planNote").hidden=l();const V=q.goal??"";n("goal").hidden=!V,n("goal").innerHTML=V?`<b>Goal</b> ${r(V)}`:"",n("phases").innerHTML=["Draft","Accepted"].map(Ht=>`<li${Ht.toLowerCase()===q.phase?' class="on" aria-current="step"':""}>${Ht}</li>`).join(""),n("rev").textContent=`rev ${i.server?.rev??0} · ${q.phase}`;const ee=q.phase==="draft";W.hidden=!ee,W.textContent="Accept the architecture",W.title="Accept it: from then on an agent’s changes to it arrive as proposals for you to accept",W.classList.add("primary"),W.classList.remove("danger"),delete W.dataset.armed,n("phaseLine").textContent=ee?"An agent drew this. Look it over, then accept it: after that its changes arrive as proposals.":"Yours: an agent’s changes to it arrive as proposals you accept. A plan done asks to make its planned boxes real.";const pe=[...i.server?.recent??[]].reverse().find(Ht=>Ht.actor!=="you")?.actor,me=Uy(q,{by:pe});e.needs(me.length,me.length?`${me.length} thing${me.length===1?"":"s"} wait${me.length===1?"s":""} on you in the architecture`:"");const Oe=n("needsBody");n("needs").hidden=!me.length,me.length||n("needs").removeAttribute("open");const Je=T1(me);Je!==U&&!(Oe.contains(document.activeElement)&&document.activeElement instanceof HTMLInputElement)&&(U=Je,Oe.innerHTML=Je,ue(Oe)),n("planTitle").textContent=q.title,n("planMeta").textContent=`${Object.keys(q.nodes).length} boxes · ${q.edges.length} arrows`}let U="";function we(){c()?.phase==="draft"&&M([{op:"arch.set",phase:"accepted"}],"Accepted. From now on an agent’s changes arrive as proposals.","you accepted the architecture")}function xe(C){const W=c();if(!W)return[];const q=new Set([C,...Ma(W,C)]);return Object.entries(W.nodes).filter(([V,ee])=>!q.has(V)&&(ee.kind==="service"||ee.kind==="group")).map(([V,ee])=>({id:V,label:ee.label}))}function z(C,W){const q=c();if(!q||!i.view)return oa({type:"canvas"});if(C.type==="canvas")return oa({type:"canvas"});if(C.type==="arrow")return oa({type:"arrow"},{kind:W?.kind});const V=C.id,ee=q.nodes[V];if(!ee)return[];const pe=i.footprintId?{id:i.footprintId,planned:ee.planned===i.footprintId,retiring:ee.retiring===i.footprintId}:null;return oa({type:C.type,id:V},{kind:ee.kind,external:!!ee.external,group:ee.in,frames:xe(V),folded:i.view.proj.folded.has(V),container:_r(q,V),plan:pe})}function H(C,W,q){const V=c(),ee=W.id;if(!V||!ee)return;const pe=V.nodes[ee]?.label??ee;if(C==="fold"){de(ee);return}if(C==="delete"){M([{op:"box.remove",id:ee}],`Removed ${pe}${_r(V,ee)?"; what was in it stays":""}.`);return}if(C==="rename"&&q){M([{op:"box.set",id:ee,label:q}],`Renamed ${pe}.`);return}if(C.startsWith("frame-kind:")){M([{op:"box.set",id:ee,kind:C.slice(11)}],`${pe} is a ${C.slice(11)}.`);return}if(C==="external:on"||C==="external:off"){M([{op:"box.set",id:ee,external:C==="external:on"}],C==="external:on"?`${pe} is run by someone else.`:`${pe} is yours.`);return}if(C==="plan:planned"){const me=V.nodes[ee]?.planned!==i.footprintId;M([{op:"box.set",id:ee,planned:me?i.footprintId:null}],me?`${pe} is planned by ${i.footprintId}.`:`${pe} is no longer planned.`);return}if(C==="plan:retiring"){const me=V.nodes[ee]?.retiring!==i.footprintId;M([{op:"box.set",id:ee,retiring:me?i.footprintId:null}],me?`${i.footprintId} removes ${pe}.`:`${pe} is no longer retiring.`);return}if(C==="into:new"&&q){const me=oe(V,q);M([{op:"box.add",id:me,label:q,kind:"group"},{op:"box.set",id:ee,in:me}],`${pe} is in a new frame, ${q}.`);return}if(C.startsWith("into:")){const me=C.slice(5);M([{op:"box.set",id:ee,in:me==="top"?null:me}],me==="top"?`${pe} is out of its frame.`:`${pe} is in ${V.nodes[me]?.label??me}.`)}}const oe=(C,W)=>{const q=W.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)||"frame";let V=q;for(let ee=2;V in C.nodes;ee++)V=`${q}-${ee}`;return V};function de(C){const W=c(),q=u();if(!W||!q||!_r(W,C))return;const V=(q.layout.collapsed??[]).includes(C);M([{op:"layout.fold",id:C,folded:!V}],"")}function ke(C){const W=C.dataset.box,q=C.dataset.boxField,V=c();if(!W||!q||!V?.nodes[W])return;const ee=V.nodes[W];if(q==="detail"){const pe=C.value.replace(/\s+$/,"");if(pe===(ee.detail??"")){W===t.selected&&delete i.drafts.detail;return}M([{op:"box.set",id:W,detail:pe}],`Saved what ${ee.label} is for.`,`you edited the detail of ${W}`).then(me=>{me&&(delete i.drafts.detail,e.render())})}else if(q==="tech"){const pe=C.value.trim();if(pe===(ee.tech??"")){delete i.drafts.tech;return}M([{op:"box.set",id:W,tech:pe}],`Saved what ${ee.label} runs on.`,`you edited the tech of ${W}`).then(me=>{me&&(delete i.drafts.tech,e.render())})}else if(q==="kind"){const pe=C.value;pe!==ee.kind&&M([{op:"box.set",id:W,kind:pe}],`${ee.label} is a ${pe}.`)}else if(q==="external"){const pe=C.checked;M([{op:"box.set",id:W,external:pe}],pe?`${ee.label} is run by someone else.`:`${ee.label} is yours.`)}}const he={samples:["Flows","Changes"],server:["Boxes","Flows","Changes"]},$e=()=>l()?he.server:he.samples;function Te(){return l()?`<div class="footprint-pick"><label for="footprintPick">Look at a plan on it</label>
32
+ <select id="footprintPick"><option value="">No plan</option>${e.plans().filter(W=>!W.error).map(W=>`<option value="${r(W.id)}"${W.id===i.footprintId?" selected":""}>${r(W.title??W.id)}</option>`).join("")}</select>
33
+ <p class="help">${i.fp?"New is green, changed amber, removed red, and what the plan leaves alone fades.":"Pick a plan to see what it adds, changes and removes."}</p></div>`:""}function Se(C){const W=u();if(!W)return'<p class="lede">No architecture open.</p>';if(C==="Boxes"){const q=t.selected?O1({arch:W.arch,id:t.selected,footprint:i.fp,steps:i.planState?.plan?.nodes??{},drafts:i.drafts,fileInfo:ze(),recent:i.server?.recent??[],editable:l()}):"";return t.selected&&!q&&(t.selected=null),`${q}${Te()}${C1({arch:W.arch,selected:t.selected,folded:W.layout.collapsed??[],footprint:i.fp})}`}return C==="Flows"?`${N1({arch:W.arch,flowId:i.flowId,at:i.flowAt,playing:!!i.flowTimer})}`:l()?I1(i.server?.recent??[]):e.changesPanel(t.chart?.getData())}function ae(){const C=n("panel");for(const q of C.querySelectorAll("[data-fold]"))q.onclick=()=>de(q.dataset.fold??"");for(const q of C.querySelectorAll("[data-flow]"))q.onclick=()=>P(q.dataset.flow??null);for(const q of C.querySelectorAll("[data-flow-at]"))q.onclick=()=>{D(),j(Number(q.dataset.flowAt))};f(),C.querySelector("[data-flow-play]")?.addEventListener("click",G),C.querySelector("[data-flow-next]")?.addEventListener("click",()=>{D(),j((i.flowAt??-1)+1)}),C.querySelector("[data-flow-prev]")?.addEventListener("click",()=>{D(),j((i.flowAt??1)-1)}),C.querySelector("[data-flow-clear]")?.addEventListener("click",()=>{D(),i.flowAt=null,e.redraw(),e.render()});const W=C.querySelector("#footprintPick");W&&(W.onchange=()=>F(W.value));for(const q of C.querySelectorAll("[data-box-field]")){const V=q,ee=V.dataset.boxField;ee==="detail"||ee==="tech"?(V.addEventListener("input",()=>{i.drafts[ee]=V.value}),V.addEventListener("blur",()=>ke(V)),V.addEventListener("keydown",pe=>{const me=pe;me.key==="Enter"&&(ee==="tech"||me.metaKey||me.ctrlKey)&&(me.preventDefault(),ke(V))})):V.addEventListener("change",()=>ke(V))}ue(C)}const _e=5e3,ze=()=>Object.fromEntries([...i.fileInfo].map(([C,W])=>[C,W.info])),Z=()=>{const C=t.selected,W=C?c()?.nodes[C]:void 0;return C&&W?{id:C,files:W.files??[]}:null};function vt(C,W){const q=c()?.nodes[C];return q?M([{op:"box.set",id:C,files:W}],`Saved the files for ${q.label}.`,`you edited the files of ${C}`):Promise.resolve(!1)}function rt(C){const W=Z();if(!W||!l())return;const q=Date.now(),V=W.files.filter(ee=>!((i.fileInfo.get(ee)?.at??0)>q-_e)&&!dt.has(ee));if(V.length){for(const ee of V)dt.add(ee);af(V).then(ee=>{for(const pe of ee)i.fileInfo.set(pe.path,{at:Date.now(),info:{kind:pe.kind,matches:pe.matches}})}).catch(()=>{}).finally(()=>{for(const ee of V)dt.delete(ee);C()})}}const dt=new Set;function gt(){const C=t3.map(([W,q,V,ee])=>`<div><dt>${r(W)}</dt><dd>${r(q)}</dd>${l()?"":`<dd><code>${r(V)}</code></dd>`}<dd>${r(ee)}</dd></div>`).join("");return`
34
+ <h4>Edit the architecture</h4>
35
+ <p>An arrow from A to B means <b>A uses B</b>: a call, not an order. ${l()?"Each gesture is saved as a change to the architecture, which is how your agents hear about it.":"Every gesture below is one line of <code>archspec.js</code>: nothing in this app implements dragging or hit-testing. Nothing is kept: it is a demo."}</p>
36
+ <dl class="gestures">${C}</dl>
37
+ <h4>Look around</h4>
38
+ <p>Scroll, or hold Space and drag. + and − zoom; 0 shows the whole architecture.</p>`}function Wt(){const C=q=>`<li><span class="kind-key kind-${q}" aria-hidden="true"></span><b>${r(la[q])}</b> ${r({person:"a user or a role",service:"something that runs",component:"a part inside a service",store:"where data lives",queue:"a message channel",group:"a frame round other boxes"}[q])}</li>`,W=q=>`<span class="chip" style="background:${qr[q].colour}">${Eo(qr[q].icon,{size:12})}</span>`;return`
39
+ <h4>Boxes</h4><ul>${["person","service","component","store","queue","group"].map(C).join("")}<li><span class="kind-key external" aria-hidden="true"></span><b>Grey</b> someone else runs it</li></ul>
40
+ <h4>Arrows</h4><ul><li><span class="wire"></span>A uses B: a call, and A waits for the answer</li><li><span class="gate">${Eo("async",{size:12})}</span>A does not wait for the answer <i>(lighter, with this mark)</i></li></ul>
41
+ <h4>A plan on it</h4><ul>${["new","changed","removed"].map(q=>`<li>${W(q)}${r(qr[q].word)}${q==="removed"?" <i>(struck through)</i>":""}</li>`).join("")}<li><span class="frame-key"></span>faded: the plan leaves it alone</li></ul>
42
+ <h4>Marks</h4><ul><li><span class="frame-key"></span>a frame holds boxes; the chevron folds it</li><li><span class="ember-key"></span>ember: what you hold or just changed</li></ul>`}function At(C,W){const q=u();if(!q)return"";if(C==="Data"){const V=l()?`${Aw(q.arch)}`:Zb({...t.plan,canvas:t.domain??t.plan.canvas},W);return`
43
+ <p class="lede">${l()?"The architecture as the file holds it. Edit it and press Apply: the difference is sent as operations, under the same rules as a gesture.":"The diagram as data: its boxes and its arrows. Edit it and press Apply to load it back in; that starts Undo over from here."}</p>
44
+ <textarea id="json" spellcheck="false" aria-label="The architecture as JSON">${r(V)}</textarea>
45
+ <p class="err" id="jsonErr" hidden></p>
46
+ <div class="row"><button id="applyJson" class="primary">Apply</button><button data-copy="json">Copy</button></div>`}return C==="Mermaid"?`
47
+ <p class="lede">The architecture as a Mermaid flowchart, ready to paste: a shape for each kind, a frame as a subgraph, a dotted arrow where A does not wait. Flows and positions are dropped: Mermaid has nowhere to put them.</p>
48
+ <textarea id="mermaid" spellcheck="false" readonly aria-label="The architecture as Mermaid">${r(A1(q.arch,q.layout.direction))}</textarea>
49
+ <div class="row"><button data-copy="mermaid" class="primary">Copy</button></div>`:`
50
+ <p class="lede">The ElicitJS chart spec this diagram is built from: what a box and an arrow are, how each is drawn, and each edit as the call that made it. Functions show by name. It is made from the architecture, so there is nothing here to edit.</p>
51
+ <pre class="spec" id="spec" tabindex="0" aria-label="The chart spec">${r(Jb({...t.spec,data:W}))}</pre>
52
+ <div class="row"><button data-copy="spec" class="primary">Copy</button></div>`}function Jt(C){const W=JSON.parse(C);if(l()){const ee=Wy(W);if(ee.length)throw new Error(ee[0]);const pe=i.server;if(!pe)throw new Error("there is no architecture to change");const{ops:me}=ag(pe.arch,{...W,rev:pe.arch.rev});me.length&&M(me,`Applied ${me.length} operation${me.length===1?"":"s"}.`);return}if(!Array.isArray(W.steps)||!Array.isArray(W.depends))throw new Error("needs a `steps` array and a `depends` array");const q=new Set(W.steps.map(ee=>ee.id)),V=W.depends.filter(ee=>!q.has(ee.source)||!q.has(ee.target));if(V.length)throw new Error(V.length===1?`an arrow names a box that is not in steps (${V[0].source} → ${V[0].target})`:`${V.length} arrows name boxes that are not in steps`);t.chart.setData({steps:W.steps,depends:W.depends}),e.render()}function qt(){if(l())return N({reseed:!0,quiet:!0});i.local&&(i.local.arch=structuredClone(i.local.sample.arch),i.local.layout=structuredClone(i.local.sample.layout),m())}function Zn(C){i.drafts={}}return{active:a,current:u,openServer:w,openSample:k,leave:_,specFor:y,mount:m,paint:Q,panel:Se,panels:$e,wirePanel:ae,save:I,catchUp:N,send:M,saveFiles:vt,pickedBox:Z,askFileInfo:rt,knownFileInfo:ze,renderStatus:ie,pressPhase:we,help:gt,legend:Wt,drawerBody:At,applyJSON:Jt,reset:qt,title:b,onSelect:Zn,showProposal:Y,fold:de,choosePlan:F,fp:()=>i.fp,footprintId:()=>i.footprintId,proposals:ve,refreshPlans:()=>{a()&&e.render()},host:{frames:C=>a()?re(C):void 0,newRow:C=>a()?{kind:["person","queue","store"].includes(C.kind)||C.kind==="group"?"service":C.kind,external:""}:void 0,newArrow:()=>a()?{tech:""}:void 0,menu:(C,W)=>a()?z(C,W):void 0,act:(C,W,q)=>{a()&&H(C,W,q)},fold:C=>{a()&&de(C)},folded:()=>a()&&i.view?[...i.view.proj.folded.keys()]:void 0,frozen:()=>!1,groups:()=>[]},_state:i}}function q3(e,t={}){const n={};for(const o of e.steps||[])n[o.id]={label:String(o.label??""),...o.group&&o.group!==jt?{group:o.group}:{}};const r=(e.depends||[]).map(o=>({from:o.source,to:o.target,...o.label?{label:o.label}:{},...o.kind&&o.kind!=="needs"?{kind:o.kind}:{}}));return z1({nodes:n,edges:r},t.direction==="TD"?"TD":"LR")}function Qb(e,t){const n=[],r=new Map(e.steps.map(f=>[f.id,f])),o=new Map(t.steps.map(f=>[f.id,f]));for(const[f,p]of o){const h=r.get(f);if(!h){n.push(["add",`step ${f} — “${p.label}”`]);continue}h.label!==p.label&&n.push(["edit",`${f}: “${h.label}” → “${p.label}”`]),h.group!==p.group&&n.push(["edit",`${f}: group ${h.group} → ${p.group}`]),h.kind!==p.kind&&p.kind&&n.push(["edit",`${f}: ${h.kind} → ${p.kind}`]),(h.external??"")!==(p.external??"")&&p.external!==void 0&&n.push(["edit",`${f}: ${p.external?"run by someone else":"run by you"}`]),(Math.round(h.x)!==Math.round(p.x)||Math.round(h.y)!==Math.round(p.y))&&n.push(["move",`${f}: ${Math.round(h.x)},${Math.round(h.y)} → ${Math.round(p.x)},${Math.round(p.y)}`])}const s=new Set([...r.keys()].filter(f=>!o.has(f))),i=f=>s.has(f.source)||s.has(f.target);for(const f of s){const p=e.depends.filter(h=>h.source===f||h.target===f).length;n.push(["drop",p?`step ${f}, and ${p} arrow${p===1?"":"s"} with it`:`step ${f}`])}const a=f=>f.map(p=>`${p.source} → ${p.target}`),l=f=>f.split(" → ").reverse().join(" → "),u=a(e.depends.filter(f=>!i(f))),c=[];for(const f of a(t.depends)){const p=u.indexOf(f);p>=0?u.splice(p,1):c.push(f)}for(let f=u.length-1;f>=0;f--){const p=c.indexOf(l(u[f]));p<0||(n.push(["edit",`${u[f]} flipped`]),c.splice(p,1),u.splice(f,1))}for(let f=u.length-1;f>=0;f--){const[p,h]=u[f].split(" → "),y=c.findIndex(g=>{const[m,b]=g.split(" → ");return m===p||b===h});y<0||(n.push(["edit",`${u[f]} becomes ${c[y]}`]),c.splice(y,1),u.splice(f,1))}for(const f of u)n.push(["drop",f]);for(const f of c)n.push(["add",f]);const d=new Map(e.depends.map(f=>[`${f.source}>${f.target}`,f.label||""]));for(const f of t.depends){const p=d.get(`${f.source}>${f.target}`);p!==void 0&&p!==(f.label||"")&&n.push(["edit",`${f.source} → ${f.target}: label “${p}” → “${f.label||""}”`])}return n}function H3(e,t){const n=e.split(`
53
+ `),r=t.split(`
54
+ `),o=Array.from({length:n.length+1},()=>new Array(r.length+1).fill(0));for(let l=n.length-1;l>=0;l--)for(let u=r.length-1;u>=0;u--)o[l][u]=n[l]===r[u]?o[l+1][u+1]+1:Math.max(o[l+1][u],o[l][u+1]);const s=[];let i=0,a=0;for(;i<n.length&&a<r.length;)n[i]===r[a]?(s.push([" ",n[i]]),i++,a++):o[i+1][a]>=o[i][a+1]?(s.push(["-",n[i]]),i++):(s.push(["+",r[a]]),a++);for(;i<n.length;)s.push(["-",n[i++]]);for(;a<r.length;)s.push(["+",r[a++]]);return s}const B3=(e,t)=>e?t?H3(e,t):e.split(`
55
+ `).map(n=>["-",n]):t?t.split(`
56
+ `).map(n=>["+",n]):[];function U3(e,t){const n=new Map,r=new Map,o=(s,i,a,l)=>{const u=n.get(s)??a;n.set(s,l);const c=r.get(s);if(u===l&&!c)return;const d=c?c.before:u;r.set(s,{where:i,before:d,after:l,diff:B3(d,l)})};for(const s of t)(s.op==="node.set"||s.op==="node.add")&&s.id&&typeof s.detail=="string"&&o(`${s.id}\0detail`,`${s.id}: detail`,e.nodes[s.id]?.detail??"",s.detail),s.op==="plan.set"&&typeof s.goal=="string"&&o("goal","the goal",e.goal??"",s.goal);return[...r.values()].filter(s=>s.before!==s.after)}const an={min:.25,max:2.5,step:1.2,autoMin:.85,autoMax:1.6},or=(e,t,n)=>Math.max(t,Math.min(n,e));function K3(e,t,n){if(e.mode==="manual")return or(e.scale,an.min,an.max);const r=Math.min(n.width/t.width,n.height/t.height);return e.mode==="fit"?or(r,an.min,an.autoMax):or(r,an.autoMin,an.autoMax)}const My=22,Ey=12,Ay={width:176,height:150};function Y3(e){const{frame:t,zoomOut:n,zoomIn:r,zoomFit:o,zoomLevel:s,minimap:i}=e,a={mode:"auto",scale:1};let l=null,u={width:1,height:1},c=[];t.style.setProperty("--mx",String(xt.x)),t.style.setProperty("--my",String(xt.y));const d=document.createElement("div");d.className="mm-art";const f=document.createElement("div");f.className="mm-here",i.replaceChildren(d,f);const p=()=>({width:Math.max(1,t.offsetWidth-t.clientLeft*2-My*2-Ey),height:Math.max(1,t.offsetHeight-t.clientTop*2-My*2-Ey)});function h(M=null){if(!l)return;const $=l.getBoundingClientRect(),F=Number(t.style.getPropertyValue("--scale"))||1,D=K3(a,u,p()),P=M??(()=>{const re=t.getBoundingClientRect();return{x:re.left+re.width/2,y:re.top+re.height/2}})(),j=(P.x-$.left)/F,G=(P.y-$.top)/F;l.style.width=`${Math.round(u.width*D)}px`,t.style.setProperty("--scale",String(D));const J=l.getBoundingClientRect();t.scrollLeft+=J.left+j*D-P.x,t.scrollTop+=J.top+G*D-P.y,s.textContent=`${Math.round(D*100)}%`,n.disabled=D<=an.min+1e-6,r.disabled=D>=an.max-1e-6,o.setAttribute("aria-pressed",String(a.mode==="fit")),w(),b()}function y(M,$=null){a.mode="manual",a.scale=or(M,an.min,an.max),h($)}const g=()=>Number(t.style.getPropertyValue("--scale"))||1,m=M=>y(g()*M);function b(){if(!l)return;const M=t.getBoundingClientRect(),$=l.getBoundingClientRect(),F=or((M.left-$.left)/$.width,0,1),D=or((M.right-$.left)/$.width,0,1),P=or((M.top-$.top)/$.height,0,1),j=or((M.bottom-$.top)/$.height,0,1),[G,J,re,Q]=[F*u.width,D*u.width,P*u.height,j*u.height];i.hidden=c.every(ve=>ve.x>=G&&ve.x<=J&&ve.y>=re&&ve.y<=Q),Object.assign(f.style,{left:`${F*100}%`,top:`${P*100}%`,width:`${(D-F)*100}%`,height:`${(j-P)*100}%`})}function w(){const M=Math.min(Ay.width,t.clientWidth*.28)/u.width,$=Math.min(Ay.height,t.clientHeight*.38)/u.height,F=Math.min(M,$);i.style.width=`${Math.round(u.width*F)}px`,i.style.height=`${Math.round(u.height*F)}px`}function x(){if(!l)return;w();const M=e.view();c=M.steps.map($=>({x:$.x+xt.x,y:$.y+xt.y})),d.innerHTML=Yy(M,{title:"The whole plan, small",margin:xt}),b()}function S(M){if(!l)return;const $=i.getBoundingClientRect(),F=l.getBoundingClientRect(),D=t.getBoundingClientRect();t.scrollLeft+=F.left+(M.clientX-$.left)/$.width*F.width-(D.left+D.width/2),t.scrollTop+=F.top+(M.clientY-$.top)/$.height*F.height-(D.top+D.height/2)}let v=!1;i.addEventListener("pointerdown",M=>{v=!0,i.setPointerCapture(M.pointerId),S(M),M.preventDefault()}),i.addEventListener("pointermove",M=>{v&&S(M)});const k=()=>{v=!1};i.addEventListener("pointerup",k),i.addEventListener("pointercancel",k),t.addEventListener("scroll",b,{passive:!0}),t.addEventListener("wheel",M=>{if(!(M.ctrlKey||M.metaKey))return;M.preventDefault();const $=M.deltaMode===1?16:1;y(g()*Math.exp(-or(M.deltaY*$,-30,30)*.01),{x:M.clientX,y:M.clientY})},{passive:!1});let _=!1,A=null;const L=M=>M instanceof HTMLElement&&!!M.closest("input, textarea, select, button, [contenteditable]");document.addEventListener("keydown",M=>{M.code!=="Space"||L(M.target)||_||(_=!0,t.classList.add("can-pan"),M.preventDefault())});const N=()=>{_=!1,t.classList.remove("can-pan")};document.addEventListener("keyup",M=>{M.code==="Space"&&N()}),addEventListener("blur",N),t.addEventListener("pointerdown",M=>{(M.button===1||M.button===0&&_)&&(M.preventDefault(),M.stopPropagation(),A={x:M.clientX,y:M.clientY,left:t.scrollLeft,top:t.scrollTop},t.setPointerCapture(M.pointerId),t.classList.add("panning"))},!0),t.addEventListener("pointermove",M=>{A&&(t.scrollLeft=A.left-(M.clientX-A.x),t.scrollTop=A.top-(M.clientY-A.y))});const I=()=>{A=null,t.classList.remove("panning")};t.addEventListener("pointerup",I),t.addEventListener("pointercancel",I),n.addEventListener("click",()=>m(1/an.step)),r.addEventListener("click",()=>m(an.step)),s.addEventListener("click",()=>y(1)),o.addEventListener("click",()=>{a.mode="fit",h(),t.scrollTo(0,0)});const T=typeof ResizeObserver>"u"?null:new ResizeObserver(M=>{M.some($=>$.target===t)?h():b()});return T?.observe(t),{attach(M,$,{keep:F=!1}={}){l=M,T?.disconnect(),T?.observe(t),T?.observe(M),u=mr($),F||(a.mode="auto"),h(),F||t.scrollTo(0,0),x()},refresh:(()=>{let M=!1;return()=>{M||(M=!0,requestAnimationFrame(()=>{M=!1,x()}))}})(),layout:h,zoomIn:()=>m(an.step),zoomOut:()=>m(1/an.step),fit(){a.mode="fit",h(),t.scrollTo(0,0)},actual:()=>y(1)}}const G3="http://www.w3.org/2000/svg";function V3({frame:e,canvas:t,chart:n,size:r,direction:o=()=>"LR",host:s}){let i=null,a=null,l,u=null,c=null,d=null,f=null,p=null;const h=()=>getComputedStyle(document.documentElement).getPropertyValue("--ember").trim()||"#EA5202",y=()=>getComputedStyle(document.documentElement).getPropertyValue("--surface").trim()||"#FFFFFF",g=()=>n()?.querySelector("svg")??null,m=()=>n()?.getData()??{steps:[],depends:[]};function b(z,H){const oe=g()?.getScreenCTM()?.inverse();if(!oe)return null;const de=new DOMPoint(z,H).matrixTransform(oe);return{x:de.x,y:de.y}}const w=z=>({x:z.x-xt.x,y:z.y-xt.y}),x=z=>{for(const H of n()?.querySelectorAll("rect")??[])if(On(H)&&Dt(H).data.id===z)return Dt(H);return null},S=z=>[...n()?.querySelectorAll("rect")??[]].find(H=>On(H)&&Dt(H).data.id===z)??null;function v(z,H){let oe=null,de=0;for(const ke of n()?.querySelectorAll("path")??[]){const he=Dt(ke)?.data;if(he?.source!==z||he?.target!==H)continue;const $e=ke.getAttribute("fill");if($e&&$e!=="none")continue;const Te=ke.getTotalLength?.()??0;Te>de&&(oe=ke,de=Te)}return{el:oe,node:oe?Dt(oe):null}}const k=(z,H)=>{const oe=H.node;n().emit({editName:z,rawEvent:{by:z},...oe?{x:oe.cx??0,y:oe.cy??0}:{},...H})},_=(z,H)=>!z||!H?z===H:z.type===H.type&&(z.type==="step"?z.id===H.id:z.from===H.from&&z.to===H.to);function A(z,{silent:H=!1}={}){_(i,z)||(i=z,H||s.select?.(z),xe())}function L(z,H){const oe=b(z,H);if(!oe)return null;const de=jn(m().steps).filter(ke=>Math.abs(oe.x-ke.x)<=ke.w/2&&Math.abs(oe.y-ke.y)<=ke.h/2);return de.length?de[de.length-1].id:null}function N(z){if(!(z instanceof Element))return null;if(On(z))return{type:"step",id:Dt(z).data.id};const H=Dt(z)?.data;return H&&H.source!==void 0&&H.target!==void 0?{type:"arrow",from:H.source,to:H.target}:null}function I(z){const H=N(z.target);if(H)return H;const oe=L(z.clientX,z.clientY);return oe?{type:"step",id:oe}:null}e.addEventListener("pointerdown",z=>{p={x:z.clientX,y:z.clientY}},!0),e.addEventListener("click",z=>{!(z.target instanceof Element)||z.target.closest(".handles")||p&&Math.hypot(z.clientX-p.x,z.clientY-p.y)>4||A(I(z))});function T(){if(!i)return!1;if(s.frozen?.(i))return s.say?.("Finished work is history: reopen the step to change it.","error"),!1;const z=i.type==="step"?x(i.id):v(i.from,i.to).node;return z?(k(i.type==="step"?Xe.removeStep:Xe.removeArrow,{type:"click",node:z}),A(null),!0):!1}const M=z=>{const H=z.target;return H instanceof HTMLElement&&(H.tagName==="INPUT"||H.tagName==="TEXTAREA"||H.isContentEditable)?!1:H===document.body||H instanceof Node&&e.contains(H)};function $(z){if(z.key==="Escape"){if(f){z.preventDefault(),F(!0);return}if(u){z.preventDefault(),le();return}M(z)&&i&&A(null);return}if(!(!M(z)||z.metaKey||z.ctrlKey||z.altKey)){if((z.key==="Delete"||z.key==="Backspace")&&i){z.preventDefault(),T();return}if(z.key==="ContextMenu"||z.key==="F10"&&z.shiftKey){const H=document.activeElement&&On(document.activeElement)?N(document.activeElement):null;if(H&&A(H),!i)return;z.preventDefault();const oe=i.type==="step"?S(i.id)?.getBoundingClientRect():v(i.from,i.to).el?.getBoundingClientRect();oe&&j(i,{x:oe.left+oe.width/2,y:oe.top+oe.height/2})}}}document.addEventListener("keydown",$);function F(z=!1){if(!f)return;const H=f._from;f.remove(),f=null,z&&H instanceof HTMLElement&&H.isConnected&&H.focus()}document.addEventListener("pointerdown",z=>{f&&!(z.target instanceof Node&&f.contains(z.target))&&F()},!0);function D(z,H,oe){F();const de=document.createElement("div");de.className="ctxmenu",de.setAttribute("role","menu"),de._from=document.activeElement;for(const he of z){if(he.section&&he.section.trim()){const Se=document.createElement("div");Se.className="ctx-sec",Se.setAttribute("role","presentation"),Se.textContent=he.section,de.append(Se)}else if(he.section){const Se=document.createElement("div");Se.className="ctx-sep",Se.setAttribute("role","separator"),de.append(Se)}const $e=document.createElement("button");$e.type="button",$e.tabIndex=-1,$e.className=`ctx-item${he.danger?" danger":""}`,$e.setAttribute("role",he.checked!==void 0?"menuitemradio":"menuitem"),he.checked!==void 0&&$e.setAttribute("aria-checked",String(he.checked)),he.disabled&&($e.setAttribute("aria-disabled","true"),$e.title=he.disabled),$e.dataset.item=he.id;const Te=document.createElement("span");if(Te.textContent=he.label,$e.append(Te),he.hint){const Se=document.createElement("i");Se.textContent=he.hint,$e.append(Se)}if(he.key){const Se=document.createElement("kbd");Se.textContent=he.key,$e.append(Se)}$e.addEventListener("click",()=>{if(!he.disabled){if(he.ask){P(de,$e,oe,he.id,he.ask);return}F(!1),oe(he.id)}}),de.append($e)}de.addEventListener("keydown",he=>{const $e=[...de.querySelectorAll('.ctx-item:not([aria-disabled="true"])')],Te=$e.indexOf(document.activeElement);he.key==="ArrowDown"?(he.preventDefault(),$e[(Te+1)%$e.length]?.focus()):he.key==="ArrowUp"?(he.preventDefault(),$e[(Te-1+$e.length)%$e.length]?.focus()):he.key==="Home"?(he.preventDefault(),$e[0]?.focus()):he.key==="End"?(he.preventDefault(),$e[$e.length-1]?.focus()):he.key==="Tab"&&F(!0)}),document.body.append(de),f=de;const ke=de.getBoundingClientRect();de.style.left=`${Math.max(6,Math.min(H.x,innerWidth-ke.width-6))}px`,de.style.top=`${Math.max(6,Math.min(H.y,innerHeight-ke.height-6))}px`,de.querySelector('.ctx-item:not([aria-disabled="true"])')?.focus()}function P(z,H,oe,de,ke){const he=document.createElement("input");he.className="ctx-input",he.placeholder=ke,he.setAttribute("aria-label",ke),H.replaceWith(he),he.focus(),he.addEventListener("keydown",$e=>{if($e.stopPropagation(),$e.key==="Escape")$e.preventDefault(),F(!0);else if($e.key==="Enter"){$e.preventDefault();const Te=he.value.trim();if(!Te)return;F(!1),oe(de,Te)}})}function j(z,H){const oe=m(),de=z.type==="step"?oe.steps.find(Te=>Te.id===z.id):z.type==="arrow"?oe.depends.find(Te=>Te.source===z.from&&Te.target===z.to):null;if(z.type!=="canvas"&&z.type!=="frame"&&!de)return;const ke=s.groups?.()??[],he=s.menu?.(z,de)??T3(z,{groups:ke,group:de?.group,kind:de?.kind,frozen:z.type!=="canvas"&&z.type!=="frame"&&!!s.frozen?.(z)}),$e=z.type==="canvas"?b(H.x,H.y):null;D(he,H,(Te,Se)=>G(z,Te,Se,$e))}function G(z,H,oe,de){if(z.type==="frame"){s.act?.(H,z,oe);return}if(z.type==="canvas"){if(H==="add"&&de){const $e=w(de);n().emit({type:"dblclick",x:$e.x,y:$e.y,rawEvent:{}})}return}if(H==="delete"){T();return}if(z.type==="step"){const $e=x(z.id);if(H==="rename"){S(z.id)?.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0,cancelable:!0}));return}if(!$e)return;if(H.startsWith("boxkind:")){k(Xe.boxKind,{type:"commit",node:$e,value:H.slice(8)});return}if(H==="external:on"||H==="external:off"){k(Xe.external,{type:"commit",node:$e,value:H==="external:on"?"yes":""});return}if(H.startsWith("into:")&&H!=="into:new"){k(Xe.group,{type:"commit",node:$e,value:H==="into:top"?jt:H.slice(5)});return}if(!H.startsWith("group:")&&H!=="into:new"){s.act?.(H,z,oe);return}if(H==="into:new"){s.act?.(H,z,oe);return}const Te=H==="group:top"?jt:H==="group:new"?oe:H.slice(6);Te&&k(Xe.group,{type:"commit",node:$e,value:Te});return}const{el:ke,node:he}=v(z.from,z.to);he&&(H==="flip"?k(Xe.flip,{type:"click",node:he}):H==="label"?ke?.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0,cancelable:!0})):H.startsWith("kind:")&&k(Xe.kind,{type:"commit",node:he,value:H.slice(5)}),A({type:"arrow",from:z.from,to:z.to},{silent:!0}))}e.addEventListener("contextmenu",z=>{if(!(z.target instanceof Element)||z.target.closest(".handles"))return;z.preventDefault();const H={x:z.clientX,y:z.clientY},oe=I(z);if(oe){A(oe),j(oe,H);return}const de=b(H.x,H.y),ke=s.frames?.(),he=ke&&de?Dd(ke,de.x,de.y):void 0;A(null),j(he?{type:"frame",id:he.group}:{type:"canvas"},H)});function J(z){if(clearTimeout(l),z!==a){if(z===null){l=setTimeout(()=>{a=null,xe()},160);return}a=z,xe()}}e.addEventListener("pointermove",z=>{if(z.buttons||u||f)return;const H=z.target;if(H instanceof Element){if(H.closest(".handles")){clearTimeout(l);return}J(On(H)?Dt(H).data.id:L(z.clientX,z.clientY))}}),e.addEventListener("pointerleave",()=>{u||J(null)});function re(z,H){let oe=null,de=_d;for(const ke of jn(m().steps)){if(ke.id===H)continue;const he=Math.hypot(ke.x-z.x,ke.y-z.y);he<=de&&(oe=ke.id,de=he)}return oe}function Q(z,H){const oe=x(H),de=b(z.clientX,z.clientY);!oe||!de||(z.preventDefault(),z.stopPropagation(),u={id:H,node:oe,p:de,to:null},k(Xe.connect,{type:"dragstart",node:oe,x:w(de).x,y:w(de).y}),window.addEventListener("pointermove",ve),window.addEventListener("pointerup",Ce),window.addEventListener("pointercancel",le),xe())}function ve(z){if(!u)return;const H=b(z.clientX,z.clientY);H&&(u.p=H,u.to=re(H,u.id),k(Xe.connect,{type:"drag",node:u.node,x:w(H).x,y:w(H).y}),xe())}function Ce(z){if(!u)return;const H=b(z.clientX,z.clientY)??u.p,{node:oe}=u;be(),k(Xe.connect,{type:"dragend",node:oe,x:w(H).x,y:w(H).y}),xe()}function le(){if(!u)return;const{node:z}=u;be(),k(Xe.connect,{type:"dragend",node:z,x:-1e6,y:-1e6}),xe()}function be(){u=null,window.removeEventListener("pointermove",ve),window.removeEventListener("pointerup",Ce),window.removeEventListener("pointercancel",le)}function ce(z){const H=m(),oe=H.steps.find(gt=>gt.id===z);if(!oe)return;const de=jn(H.steps),ke=de.find(gt=>gt.id===z);if(!ke)return;const he=new Set(H.steps.map(gt=>gt.id));let $e=H.steps.length+1;for(;he.has(`step-${$e}`);)$e++;const Te=`step-${$e}`,Se=Math.max(Vr.minWidth,78),ae=Vr.minHeight,_e=70,Z=o()==="LR"?{x:ke.x+ke.w/2+_e+Se/2,y:ke.y,w:Se,h:ae}:{x:ke.x,y:ke.y+ke.h/2+_e/1.4+ae/2,w:Se,h:ae},vt=Xb(Z,de),rt=r(),dt={id:Te,label:`new ${s.noun??"step"}`,group:oe.group??jt,x:Math.round(Math.min(Math.max(vt.x-xt.x,0),rt.width)),y:Math.round(Math.min(Math.max(vt.y-xt.y,0),rt.height)),...s.newRow?.(oe)??{}};n().patch({steps:{insert:[dt]},depends:{insert:[{source:z,target:Te,label:"",kind:"needs",...s.newArrow?.()??{}}]}},{history:"record"}),s.changed(),A({type:"step",id:Te}),requestAnimationFrame(()=>requestAnimationFrame(()=>S(Te)?.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0,cancelable:!0}))))}const Y=z=>s.frames?.(z)??qy(jn(m().steps).filter(H=>H.id!==z));function ue(z){z.button!==0||!(z.target instanceof Element)||!On(z.target)||(c={id:Dt(z.target).data.id,x:z.clientX,y:z.clientY,active:!1},window.addEventListener("pointermove",ie),window.addEventListener("pointerup",U))}function ie(z){if(!c||(!c.active&&Math.hypot(z.clientX-c.x,z.clientY-c.y)>5&&(c.active=!0,J(null),a=null),!c.active))return;const H=jn(m().steps).find(de=>de.id===c?.id),oe=H?Dd(Y(H.id),H.x,H.y)?.group??null:null;oe!==d&&(d=oe,s.repaint())}function U(){window.removeEventListener("pointermove",ie),window.removeEventListener("pointerup",U);const z=c,H=d;c=null,d&&(d=null,s.repaint()),!(!z?.active||!H)&&requestAnimationFrame(()=>{const oe=m().steps.find(ke=>ke.id===z.id),de=x(z.id);oe&&de&&oe.group!==H&&!s.frozen?.({type:"step",id:z.id})&&k(Xe.group,{type:"commit",node:de,value:H})})}e.addEventListener("pointerdown",ue,!0);function we(z,H={}){const oe=document.createElementNS(G3,z);for(const[de,ke]of Object.entries(H))oe.setAttribute(de,String(ke));return oe}function xe(){const z=t();if(!z||!n())return;z.querySelector(":scope > .handles")?.remove();const H=m(),oe=i?.type==="step"&&!H.steps.some(ae=>ae.id===i.id)||i?.type==="arrow"&&!H.depends.some(ae=>ae.source===i.from&&ae.target===i.to);oe&&(i=null),a&&!H.steps.some(ae=>ae.id===a)&&(a=null);const{width:de,height:ke}=mr({canvas:r()}),he=we("svg",{class:"handles",viewBox:`0 0 ${de} ${ke}`,"aria-hidden":"true"}),$e=jn(H.steps),Te=h(),Se=y();if(i?.type==="step"){const ae=$e.find(_e=>_e.id===i.id);ae&&he.append(we("rect",{class:"halo",x:ae.x-ae.w/2-5,y:ae.y-ae.h/2-5,width:ae.w+10,height:ae.h+10,rx:10,fill:"none",stroke:Te,"stroke-width":2.4}))}else if(i?.type==="arrow"){const{el:ae}=v(i.from,i.to),_e=g()?.getScreenCTM()?.inverse(),ze=ae?.getScreenCTM();if(ae&&_e&&ze){const Z=_e.multiply(ze);he.append(we("path",{class:"halo",d:ae.getAttribute("d")??"",transform:`matrix(${Z.a} ${Z.b} ${Z.c} ${Z.d} ${Z.e} ${Z.f})`,fill:"none",stroke:Te,"stroke-width":5,"stroke-linecap":"round",opacity:.45}))}}if(u){const ae=$e.find(ze=>ze.id===u?.id);ae&&he.append(we("path",{class:"band",d:`M${ae.x} ${ae.y} L${u.p.x} ${u.p.y}`,stroke:Te,"stroke-width":2,"stroke-dasharray":"6 4",fill:"none","stroke-linecap":"round"}));const _e=$e.find(ze=>ze.id===u?.to);_e&&he.append(we("rect",{class:"landing",x:_e.x-_e.w/2-5,y:_e.y-_e.h/2-5,width:_e.w+10,height:_e.h+10,rx:10,fill:Te,"fill-opacity":.12,stroke:Te,"stroke-width":2.4}))}else if(a&&!c?.active&&!f){const ae=$e.find(_e=>_e.id===a);if(ae){const _e=[["right",ae.x+ae.w/2,ae.y],["left",ae.x-ae.w/2,ae.y],["top",ae.x,ae.y-ae.h/2],["bottom",ae.x,ae.y+ae.h/2]];for(const[gt,Wt,At]of _e){const Jt=we("circle",{class:"dot",cx:Wt,cy:At,r:6,fill:Se,stroke:Te,"stroke-width":2,"data-side":gt,"data-id":ae.id});Jt.setAttribute("pointer-events","all"),Jt.addEventListener("pointerdown",qt=>Q(qt,ae.id)),he.append(Jt)}const ze=o()==="LR",Z=ze?ae.x+ae.w/2+24:ae.x,vt=ze?ae.y:ae.y+ae.h/2+24,rt=we("g",{class:"plus",transform:`translate(${Z} ${vt})`,role:"presentation"});rt.append(we("circle",{r:10,fill:Se,stroke:Te,"stroke-width":1.8}),we("path",{d:"M-4.2 0H4.2M0 -4.2V4.2",stroke:Te,"stroke-width":1.9,"stroke-linecap":"round",fill:"none"}));const dt=we("title");dt.textContent=`Add a ${s.noun??"step"} after this one`,rt.append(dt),rt.setAttribute("pointer-events","all"),rt.addEventListener("pointerdown",gt=>gt.stopPropagation()),rt.addEventListener("click",gt=>{gt.stopPropagation(),ce(ae.id)}),he.append(rt)}}if(s.fold){const ae=(_e,ze,Z,vt,rt)=>{const dt=we("g",{class:"fold-chip",transform:`translate(${ze} ${Z})`,"data-id":_e,role:"presentation"});dt.append(we("circle",{r:9,fill:Se,stroke:"var(--wire)","stroke-width":1.4}));const gt=we("g",{transform:"translate(-6 -6)",color:"var(--ink)"});gt.innerHTML=aa(vt?"unfold":"fold");const Wt=we("title");Wt.textContent=rt,dt.append(gt,Wt),dt.setAttribute("pointer-events","all"),dt.addEventListener("pointerdown",At=>At.stopPropagation()),dt.addEventListener("click",At=>{At.stopPropagation(),s.fold?.(_e)}),he.append(dt)};for(const _e of s.frames?.()??[])ae(_e.group,_e.x+_e.w-16,_e.y+15,!1,"Fold: hide what is inside, and draw its arrows to the frame");for(const _e of s.folded?.()??[]){const ze=$e.find(Z=>Z.id===_e);ze&&ae(_e,ze.x+ze.w/2-2,ze.y-ze.h/2+2,!0,"Unfold: show what is inside")}}z.append(he),oe&&queueMicrotask(()=>s.select?.(null))}return{select:A,paint:xe,selection:()=>i,dropping:()=>d,deleteSelection:T,openMenuFor:j,destroy(){document.removeEventListener("keydown",$),be(),F()}}}const B=e=>document.getElementById(e),He=e=>String(e).replace(/[&<>"]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[t]),ml=/Mac|iPhone|iPad/i.test(navigator.userAgentData?.platform??navigator.platform??"")?"⌘":"Ctrl+",X3={samples:["Changes"],server:["Steps","Changes"]},O={mode:"plan",source:"samples",root:"",plans:[],plan:Xr[0]??Jd,chart:null,spec:null,drawer:{open:!1,tab:"Data"},start:Ii(Xr[0]??Jd),panel:"Changes",selected:null,server:null,domain:null};document.body.dataset.mode=O.mode;let dr=null;const Is=()=>O.chart?O.chart.getData():Ii(O.plan),Bi=Y3({frame:B("chart"),zoomOut:B("zoomOut"),zoomIn:B("zoomIn"),zoomFit:B("zoomFit"),zoomLevel:B("zoomLevel"),minimap:B("minimap"),view:()=>({...O.plan,...Is()})});let oo={};const Yc=new Set;async function Sa(e){const{field:t,step:n}=e.dataset,r=n?O.server?.plan.nodes[n]:void 0;if(!n||!r||t!=="detail")return;const o=W1(n,t,e.value);if((o.detail??"")===(r.detail??"")){n===O.selected&&delete oo[t];return}const i=`${n}\0${t}`;if(!Yc.has(i)){Yc.add(i);try{await ln([o],`Saved what done means for ${r.label}.`,`you edited the ${t} of ${n}`)&&n===O.selected&&(delete oo[t],rn())}finally{Yc.delete(i)}}}window.addEventListener("blur",()=>{const e=document.activeElement;e instanceof HTMLTextAreaElement&&e.dataset.field&&B("panel").contains(e)&&Sa(e)});function Yo(e){e!==O.selected&&(oo={},B("panel").contains(document.activeElement)&&document.activeElement.blur()),O.selected=e,Ve.onSelect(e),e&&O.mode==="plan"&&i7(),Go.select(e?{type:"step",id:e}:null,{silent:!0});const t=O.mode==="architecture"?"Boxes":"Steps";e&&O.panel!==t&&(O.mode!=="architecture"||O.source==="server")?hr(t):rn(),e&&B("panel").querySelector(".inspector")?.scrollIntoView({block:"nearest"})}const Go=V3({frame:B("chart"),canvas:()=>B("chart").querySelector(".canvas"),chart:()=>O.chart,size:()=>O.domain??{width:0,height:0},direction:()=>O.plan?.direction==="TD"?"TD":"LR",host:{select:e=>{if(O.source==="server"){if(e?.type==="step"){e.id!==O.selected&&Yo(e.id);return}O.selected&&(oo={},O.selected=null,rn())}},frozen:e=>!!dr&&(e.type==="step"?dr.frozen({id:e.id},"steps"):dr.frozen({target:e.to},"depends")),groups:()=>jy({steps:Is().steps}),frames:e=>Ve.host.frames(e),newRow:e=>Ve.host.newRow(e),newArrow:()=>Ve.host.newArrow(),menu:(e,t)=>Ve.host.menu(e,t),act:(e,t,n)=>Ve.host.act(e,t,n),fold:e=>Ve.host.fold(e),folded:()=>Ve.host.folded(),get noun(){return O.mode==="architecture"?"box":"step"},changed:()=>Vo(),repaint:()=>Od(),say:(e,t)=>Qe(e,t)}});d3({frame:B("chart"),chart:()=>O.chart,onSelect:e=>{O.source==="server"?Yo(e):Go.select({type:"step",id:e})}});function ho(e){const t=!!O.chart&&O.plan?.id===e.id;gs(null),O.plan=e,O.start=Ii(e),O.domain=e.canvas,O.chart&&O.chart.destroy?.();const n=document.createElement("div");n.className="canvas",B("chart").replaceChildren(n),dr=O.source==="server"&&O.mode==="plan"?Ow(()=>O.server):null,O.spec=O.mode==="architecture"?Ve.specFor({...e,...Ii(e)},Vo):u3({...e,...Ii(e)},{onChange:Vo,decor:dr??void 0}),O.chart=eb(O.spec),n.appendChild(O.chart),Bi.attach(n,e,{keep:t}),o7(),Z3(),J3(),B("source").hidden=!e.source,B("source").href=e.source||"#",B("planNote").textContent=e.note,n1(e),rn()}function J3(){if(O.mode==="architecture"){B("helpBody").innerHTML=Ve.help();return}const e=O.source==="server",t=e3.map(([n,r,o,s])=>`
57
+ <div><dt>${He(n)}</dt><dd>${He(r)}</dd>${e?"":`<dd><code>${He(o)}</code></dd>`}<dd>${He(s)}</dd></div>`).join("");B("helpBody").innerHTML=`
58
+ <h4>Edit the diagram</h4>
59
+ <p>${e?"Each one is saved as a change to the plan, which is how your agents hear about it.":"Every gesture below is one line of <code>spec.js</code>: nothing in this app implements dragging, hit-testing or snapping."}</p>
60
+ <dl class="gestures">${t}</dl>
61
+ <h4>Look around</h4>
62
+ <p>Scroll, or hold Space and drag. ${He(ml)}scroll or + and − zoom; 0 shows the whole plan. ${He(ml)}Z undoes.</p>`}function Z3(){if(O.mode==="architecture"){B("legendBody").innerHTML=Ve.legend();return}const e=O.source==="server",t=(o,s)=>`<span class="chip" style="background:${o}">${Eo(s,{size:12})}</span>`,n=(o,s)=>`<h4>${o}</h4><ul>${s.map(i=>`<li>${i}</li>`).join("")}</ul>`,r=[e?n("Status",ew.map(o=>`${t(yi[o].colour,yi[o].icon)}${He(yi[o].word)}${yi[o].strike?" <i>(struck through)</i>":""}`)):"",e?n("Arrows",['<span class="wire"></span>needs: it uses what comes before','<span class="wire soft"></span>after: order only',...Object.entries(of).map(([o,s])=>`<span class="gate">${Eo(s,{size:12})}</span>${He(aw[o])}: you come in <i>(amber while it waits for you)</i>`)]):"",e?n("Badges",[`<span class="pill">${Eo("question",{size:11})}review</span>a change upstream may affect it`,`<span class="pill">${Eo("exclaim",{size:11})}at risk</span>a step before it failed`]):"",n("Marks",['<span class="frame-key"></span>a frame is a group','<span class="ember-key"></span>ember: what you hold or just changed'])];B("legendBody").innerHTML=r.join("")}const Re={pending:!1,inFlight:!1,pointerDown:!1,refreshing:!1,stale:!1,staleLine:null,own:new Set,timer:void 0,unfollow:null};addEventListener("pointerdown",()=>{Re.pointerDown=!0},!0);addEventListener("pointerup",()=>{Re.pointerDown=!1,Re.pending?ds(60):Re.stale&&Bn()},!0);const Ve=W3({state:O,el:B,esc:He,sync:Re,notice:(e,t,n)=>Qe(e,t,n),interactions:()=>Go,mount:e=>ho(e),render:()=>rn(),redraw:()=>Md(),renderTabs:()=>Gi(),setPanel:e=>hr(e),select:e=>Yo(e),changesPanel:e=>a1(e),ghost:e=>{hn=e},placeCard:()=>ac(),plans:()=>O.plans,scheduleSave:e=>ds(e),needs:(e,t)=>{wl=e,xl(),Ju(e>0),B("needsText").textContent=t},showCall:e=>ps(e),shownCall:()=>hs});function Vo(){if(Bi.refresh(),rn(),O.mode==="architecture"){(O.source!=="server"||Ve.current())&&(Re.pending=!0,Re.pointerDown||ds(O.source==="server"?180:60));return}O.source!=="server"||!O.server||(Re.pending=!0,Re.pointerDown||ds(180))}const ds=e=>{clearTimeout(Re.timer),Re.timer=setTimeout(Q3,e)};async function Q3(){if(O.mode==="architecture")return Ve.save();if(!O.server||Re.inFlight||Re.refreshing||!Re.pending||Re.pointerDown)return;Re.pending=!1;const e=Zy(O.server,O.chart.getData());if(!e.length)return;Re.inFlight=!0;let t=null;try{t=await Jy(O.server.id,O.server.rev,e)}catch{Qe("Lost the plan server. Your last change is not saved.","error")}finally{Re.inFlight=!1}if(t?.status===200){Re.own.add(t.body.rev),t.body.kind==="proposed"&&Qe(`Saved as proposal ${t.body.proposal.id}: the plan is executing.`),Re.refreshing=!0;try{await Bn({quiet:!0})}finally{Re.refreshing=!1}}else t&&(Qe(`Not saved: ${t.body.why??t.body.error}. The chart is back to the plan as it is.`,"error"),await Bn({quiet:!0,reseed:!0}));Re.pending&&ds(60)}async function Bn({quiet:e=!1,reseed:t=!1,line:n}={}){if(O.mode==="architecture")return Ve.catchUp({quiet:e,reseed:t,line:n});if(!O.server)return;if(Re.pointerDown||Re.inFlight){Re.stale=!0,n&&(Re.staleLine=n);return}const r=Re.staleLine;r&&!Re.own.has(r.rev)&&(n=r,e=!1),n&&Re.own.has(n.rev)&&(n=void 0,e=!0),Re.stale=!1,Re.staleLine=null;let o;try{o=await sf(O.server.id)}catch(l){Qe(`Could not refresh: ${l.message}.`,"error");return}if(!o.plan){Qe(o.error??"The plan file is not a plan.","error");return}const s=O.server;if(O.server=o,Re.pending&&!t&&Re.own.has(o.rev)){Er(),rn();return}const i=o.layout.canvas;O.domain&&(i.width+40>O.domain.width||i.height+30>O.domain.height)?ho(Vy(o)):t?(O.chart.setData(dc(o)),e||Qe(`${Gc(n,s)} Undo starts again from here.`)):Gu(O.chart.getData(),dc(o))?("deferred"in O.chart.patch(Gu(O.chart.getData(),dc(o)),{history:"keep"})&&(Re.stale=!0),e||Qe(`${Gc(n,s)} Your undo history is kept.`)):(Md(),!e&&n&&Qe(Gc(n,s))),Er(),rn()}const Md=()=>O.chart.setStage(O.chart.getStage());function Gc(e,t){return e?`${e.actor==="you"?e.via==="file"?"An edit to the file":"Another window":`${e.actor}`} changed the plan (rev ${e.rev}${t?`, was ${t.rev}`:""}).`:"The plan changed elsewhere."}async function Nr(e){O.mode==="architecture"&&pr("plan",{open:!1}),Re.unfollow?.(),Re.pending=!1,Re.own.clear(),O.selected=null,Cd=null,Yi="",bl="";let t;try{t=await sf(e)}catch(n){Qe(`Could not open ${e}: ${n.message}.`,"error");return}if(O.server=t,!t.plan){Qe(t.error??"Not a plan.","error");return}Qe(""),ho(Vy(t)),Er(),Re.unfollow=By(e,{change:n=>{if(n.id===e){if(n.recovered){Qe(""),Bn({quiet:!0});return}n.loaded||n.rev!=null&&Re.own.has(n.rev)||Bn({line:n.line})}},problem:n=>{n.id===e&&Qe(`The plan file has a problem: ${n.error}`,"error")},reconcile:n=>{n.plan!==e||!O.server||(O.server={...O.server,reconcile:n},rn(),Er(),n.state!=="running"&&Bn({quiet:!0}))},presence:n=>{O.server?.plan&&(O.server={...O.server,presence:n.presence,reads:n.reads??[],drift:n.drift??[],listening:n.listening??O.server.listening??[],stopping:n.stopping??[],derived:{...O.server.derived,stalled:n.stalled}},Md(),rn(),Er())},call:n=>{n.plan!==e||!O.server||(O.server={...O.server,calls:[n,...(O.server.calls??[]).filter(r=>r.id!==n.id)]},(hs===n.id||n.kind==="changed"&&(n.state==="delivered"||n.state==="failed"))&&ps(n))},open:n=>{Ty("live"),n&&Bn()},down:()=>Ty("down")})}let $a=!1;function Ty(e){B("conn").className=`conn ${e}`,B("conn").textContent=e==="live"?"saved live":"server unreachable",e==="down"&&!$a?(Qe("The plan server is not answering. What you change is not saved until it is back.","error"),$a=!0):e==="live"&&$a&&Qe("")}function Er(){if(O.mode==="architecture"){Ve.renderStatus();return}const e=O.server,t=B("phase");if(!e?.plan){t.hidden=!0,B("phase2").hidden=!0,B("planbar").hidden=!0,B("planNote").hidden=!1,B("needs").hidden=!0,bl="",wl=0,xl(),Ju(!1);return}const n=e.derived?.progress;B("planbar").hidden=!1,B("planNote").hidden=!0;const r=e.plan.goal??"";B("goal").hidden=!r,B("goal").innerHTML=r?`<b>Goal</b> ${He(r)}`:"",B("goal").title=r;const o=e.plan.phase==="paused"?jd.map(c=>c==="executing"?"paused":c):[...jd],s=o.includes(e.plan.phase)?o:[...o,e.plan.phase];if(B("phases").innerHTML=s.map(c=>`<li${c===e.plan.phase?' class="on" aria-current="step"':""}>${He(c[0].toUpperCase()+c.slice(1))}</li>`).join(""),B("rev").textContent=`rev ${e.rev} · ${e.plan.phase}${n?.total?` · ${n.done}/${n.total} done`:""}`,n){const c=`${e.id} · ${n.done}/${n.total} done`,d=B("plans").querySelector(`[data-id="${CSS.escape(e.id)}"] .meta`);d&&(d.textContent=c),B("planMeta").textContent=c}const i=Gy(e.plan.phase,n,e.listening??[]);Vu(t,i);const a=B("phase2");a.hidden=!i.second,i.second&&Vu(a,i.second),B("phaseLine").textContent=e.plan.phase==="planning"&&Xo?.phase==="draft"?`${i.line} The architecture it was drawn on is still a draft: approving the plan accepts it too.`:i.line;const l=J1(e);wl=l.total,xl(),Ju(l.total>0);const u=Xy(e);B("needs").hidden=!u.length,u.length||B("needs").removeAttribute("open"),B("needsText").textContent=Z1(l),e7(u,e)}let bl="";function e7(e,t){const n=B("needsBody"),r=n.contains(document.activeElement)&&document.activeElement instanceof HTMLInputElement,o=sw(e,t);r||o===bl||(bl=o,n.innerHTML=o,lc(n))}function Vu(e,t){e.hidden=!1;const n=e.dataset.armed===t.label;e.textContent=n&&t.confirm?t.confirm:t.label,e.title=t.hint,e.classList.toggle("primary",t.primary),e.classList.toggle("danger",n)}function Qe(e,t="info",n){$a=!1,hs=void 0;const r=B("notice");if(r.hidden=!e,r.className=`notice ${t}`,r.setAttribute("role",t==="error"?"alert":"status"),r.textContent=e,e&&n){const o=document.createElement("button");o.textContent=n.label,o.onclick=n.run,r.append(" ",o)}}let hs;function ps(e){const t=Q1(e);if(!t){hs===e.id&&Qe("");return}const n=t.copy;Qe(t.text,t.kind,n?{label:"Copy a prompt for it",run:async()=>{try{await navigator.clipboard.writeText(n),Qe("Copied. Paste it to your agent.")}catch{Qe(`Say to your agent: ${n}`)}}}:void 0),hs=e.id}let ys=[];function ln(e,t,n){return Vc=Vc.catch(()=>!1).then(()=>t7(e,t,n)),Vc}let Vc=Promise.resolve(!1);async function t7(e,t,n){for(let o=0;Re.inFlight&&o<5e3;o+=40)await new Promise(s=>setTimeout(s,40));if(!O.server||Re.inFlight)return!1;let r=!1;Re.inFlight=!0,ys=[];try{const{status:o,body:s}=await Jy(O.server.id,O.server.rev,e,n);o===200?(Re.own.add(s.rev),Qe(t),r=!0,ys=s.calls??[]):Qe(`Not done: ${s.why??s.error}`,"error")}finally{Re.inFlight=!1}return await Bn({quiet:!0}),r}function Ed(e){return O.mode==="architecture"?O.source==="server"?(pr("plan",{open:!1}),Nr(e)):(history.replaceState(null,"",`#architecture/${e}`),Ve.openSample(cf(e))):(history.replaceState(null,"",`#${e}`),O.source==="server"?Nr(e):ho(Sl(e)))}const e1=()=>O.mode==="architecture"?O.source==="server"?[]:Vi.map(e=>e.id):O.source==="server"?O.plans.filter(e=>!e.error).map(e=>e.id):Xr.map(e=>e.id),n7=()=>O.mode==="architecture"?O.source==="server"?void 0:O.plan?.id:O.source==="server"?O.server?.id:O.plan?.id,Xu=document.title;let t1=Xu,wl=0;const xl=()=>{document.title=iw(t1,wl)},Ju=e=>{const t=document.querySelector('link[rel="icon"]');t&&t.setAttribute("href",e?"/favicon-needs.svg":"/favicon.svg")};function n1(e){B("planTitle").textContent=e.title||e.id||"Plans",t1=e.title?`${e.title} · ${Xu}`:Xu,xl(),B("planMeta").textContent=e.repo||e.id||"";for(const n of B("plans").querySelectorAll("[data-id]"))n.dataset.id===e.id?n.setAttribute("aria-current","true"):n.removeAttribute("aria-current");const t=e1();B("prevPlan").disabled=B("nextPlan").disabled=t.length<2}function r1(e){const t=e1();if(t.length<2)return;const n=t.indexOf(n7()??"");Ed(t[(n+e+t.length)%t.length])}const vl=()=>!B("plans").hidden;function Ad(){B("plans").hidden=!1,B("planBtn").setAttribute("aria-expanded","true");const e=[...B("plans").querySelectorAll(".plan")];(e.find(t=>t.hasAttribute("aria-current"))??e[0])?.focus()}function io(e=!1){B("plans").hidden=!0,B("planBtn").setAttribute("aria-expanded","false"),e&&B("planBtn").focus(),Qu&&Td()}B("planBtn").onclick=()=>vl()?io():Ad();B("prevPlan").onclick=()=>r1(-1);B("nextPlan").onclick=()=>r1(1);document.addEventListener("pointerdown",e=>{vl()&&!B("switcher").contains(e.target)&&io()});B("switcher").addEventListener("keydown",e=>{if(e.key==="Escape"&&vl()){io(!0),e.stopPropagation();return}if(e.target===B("planBtn")&&e.key==="ArrowDown"){e.preventDefault(),vl()||Ad();return}const t=e.target;if(!t.classList.contains("plan"))return;const n=[...B("plans").querySelectorAll(".plan")],r=n.indexOf(t),o={ArrowDown:r+1,ArrowRight:r+1,ArrowUp:r-1,ArrowLeft:r-1,Home:0,End:n.length-1}[e.key];o!==void 0&&(e.preventDefault(),n[(o+n.length)%n.length].focus())});function Oy(){B("plans").classList.remove("plain");const e=O.mode==="architecture";B("plans").innerHTML=(e?Vi:Xr).map(t=>{const n=e?y3(t):t,r=e?`${Object.keys(t.arch.nodes).length} boxes, ${t.arch.edges.length} arrows`:`${t.steps.length} steps, ${t.depends.length} arrows`;return`
63
+ <button class="plan" data-id="${He(t.id)}">
64
+ <span class="thumb" aria-hidden="true">${Yy(n,{title:""})}</span>
65
+ <span class="txt"><b>${He(t.title)}</b><span class="meta">${He(t.repo)}</span><span class="shape">${r}</span></span>
66
+ </button>`}).join(""),o1()}function o1(){for(const e of B("plans").querySelectorAll("[data-id]"))e.onclick=()=>{io(!0),Ed(e.dataset.id??"")}}async function zo(){O.plans=await H1(),B("plans").classList.add("plain"),B("plans").innerHTML=O.plans.map(e=>`
67
+ <button class="plan" data-id="${He(e.id)}">
68
+ <span class="txt"><b>${He(e.title??e.id)}</b><span class="meta">${e.error?"needs fixing":`${He(e.id)} · ${e.done}/${e.steps} done`}</span></span>
69
+ </button>`).join("")+`<div class="foot">
70
+ <button id="newPlan">+ New plan</button>
71
+ <button id="importPlan" title="A Cursor .plan.md, markdown with a Mermaid block, or a .mmd file">Import…</button>
72
+ <input type="file" id="importFile" accept=".md,.markdown,.mmd,.mermaid,.txt" hidden>
73
+ </div>`,o1(),!O.plans.length&&O.mode==="plan"&&(B("planTitle").textContent="No plans yet",B("planMeta").textContent="start one, or import one"),B("newPlan").onclick=()=>{const e=document.createElement("form");e.className="new-plan",e.innerHTML='<input name="title" placeholder="What is the plan for?" aria-label="What is the plan for?" autocomplete="off" required><button type="submit">Create</button>',B("newPlan").replaceWith(e);const t=e.elements.namedItem("title");t.focus(),t.onkeydown=n=>{n.key==="Escape"&&(n.stopPropagation(),zo())},e.onsubmit=async n=>{n.preventDefault();const r=t.value.trim();if(r)try{const o=await Cy(()=>B1({title:r}));await zo(),io(),history.replaceState(null,"",`#${o.id}`),Nr(o.id)}catch(o){Qe(`Not created: ${o.message}`,"error")}}},B("importPlan").onclick=()=>B("importFile").click(),B("importFile").onchange=async e=>{const t=e.target.files?.[0];if(e.target.value="",!!t)try{const{id:n,warnings:r}=await Cy(()=>U1(t));await zo(),io(),history.replaceState(null,"",`#${n}`),await Nr(n),Qe(`Imported ${t.name}.${r.length?` ${r.join("; ")}.`:""}`)}catch(n){Qe(`Not imported: ${n.message}`,"error")}},O.server&&O.mode==="plan"&&n1({id:O.server.id,title:O.server.plan?.title})}let Zu=0;async function Cy(e){Zu++;try{return await e()}finally{setTimeout(()=>{Zu--},1500)}}let Qu=!1;async function Td(){if(B("plans").querySelector(".new-plan")){Qu=!0;return}Qu=!1;try{await zo()}catch{}}async function r7(e){if(await Td(),O.mode==="architecture"){Ve.refreshPlans();return}if(e.kind==="removed"||Zu&&e.kind==="created")return;if(!O.server){history.replaceState(null,"",`#${e.id}`),Nr(e.id);return}if(e.id===O.server.id)return;const t=O.plans.find(n=>n.id===e.id)?.title??e.id;Qe(`A plan was added: “${t}”.`,"info",{label:"Open it",run:()=>{Qe(""),Ed(e.id)}})}function gs(e){const t=B("empty");if(t.hidden=!e,B("board").toggleAttribute("data-empty",!!e),!e)return;const n=O.root.split(/[\\/]/).filter(Boolean).pop()??O.root;t.innerHTML=e==="server"?`
74
+ <div class="card">
75
+ <h2>No plan server is answering</h2>
76
+ <p>The editor needs one: it owns the plan files. In your repository, run this, and leave it running:</p>
77
+ <ul><li><b>Start it</b><span><code>diacode serve</code> (or <code>npx diacode serve</code>), then reload this page.</span></li></ul>
78
+ </div>`:`
79
+ <div class="card">
80
+ <h2>No plans in ${He(n)} yet</h2>
81
+ ${Ui.length?`<p class="waits"><b>${He(Ui[0].title)}.</b> ${He(Ui[0].detail??"")} <button class="primary" data-start="arch">Look at the architecture</button></p>`:""}
82
+ ${No.some(r=>r.permission)?`<ul class="inbox">${Y1(Xy({presence:No}),{})}</ul>`:No.length?G1(No,Date.now(),[]):""}
83
+ <p>A plan is a file in <code>.dcursed/plans</code>. It appears here the moment it exists.</p>
84
+ <ul>
85
+ <li><button class="primary" data-start="new">+ New plan</button><span>Name it, then double-click the board to add steps, and drag from the dots on a box to draw arrows between them.</span></li>
86
+ <li><button data-start="import">Import…</button><span>A Cursor <code>.plan.md</code>, markdown with a Mermaid block, or a <code>.mmd</code> file.</span></li>
87
+ <li><b>Ask your agent</b><span><q>Draft a plan for … using the dcursed tools.</q></span></li>
88
+ </ul>
89
+ </div>`,lc(t);for(const r of t.querySelectorAll("[data-start]"))r.onclick=()=>{if(r.dataset.start==="arch"){pr("architecture");return}Ad(),B(r.dataset.start==="new"?"newPlan":"importPlan").click()}}let Ui=[],No=[];async function sa(){if(O.source!=="server")return;const[e,t]=await Promise.all([Ea().catch(()=>null),K1().catch(()=>[])]),n=e?.exists?[...e.recent??[]].reverse().find(a=>a.actor!=="you")?.actor:void 0,r=e?.exists?Uy(e.arch,{by:n}):[],o=t.filter(a=>a.state!=="gone"),s=JSON.stringify([r,o.map(a=>[a.actor,a.state,a.detail,a.permission?.id])])!==JSON.stringify([Ui,No.map(a=>[a.actor,a.state,a.detail,a.permission?.id])]);Ui=r,No=o;const i=B("modeArch");i.dataset.count=r.length?String(r.length):"",i.title=r.length?`${r.length===1?"One thing waits":`${r.length} things wait`} on you in the architecture`:"",s&&!B("empty").hidden&&!O.server?.plan&&O.mode==="plan"&&B("empty").querySelector('[data-start="new"]')&&gs("none")}function Od(){const e=B("chart").querySelector(".canvas");if(!e||!O.chart||!O.domain)return;if(O.mode==="architecture"){Ve.paint(e);return}const t=O.chart.getData(),n=jn(t.steps);S3(e,n,O.domain,Go.dropping()),Vb(O.chart,i=>i.kind==="after");const r=O.server,o=t.depends.filter(i=>of[i.kind]),s=dr&&o.length?Yu(O.chart,o):new Map;Gb(e,{items:n,look:i=>dr&&r?.plan?.nodes[i]?dr.look({id:i}):void 0,arrows:o.flatMap(i=>{const a=s.get(`${i.source}\0${i.target}`);return a?[{...a,kind:i.kind,yours:dr?.arrow(i)==="yours"}]:[]}),size:O.domain}),Go.paint()}let Xc=null;function o7(){Xc?.disconnect();let e=!1;Xc=new MutationObserver(()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1,Od()}))}),Xc.observe(O.chart,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["d","x","y","transform"]})}function rn(){const e=Is();if(g7(),Od(),B("panel").contains(document.activeElement)&&(document.activeElement instanceof HTMLTextAreaElement||document.activeElement instanceof HTMLInputElement)){Ly(),ef(),ms();return}B("panel").innerHTML={Boxes:()=>Ve.panel("Boxes"),Flows:()=>Ve.panel("Flows"),Steps:()=>{if(!O.server?.plan)return'<p class="lede">No plan open.</p>';const n=O.selected?V1({plan:O.server.plan,id:O.selected,derived:O.server.derived,review:O.server.review,recent:O.server.recent,drafts:oo,fileInfo:l1(),arch:Xo}):"";return O.selected&&!n&&(O.selected=null),n+X1(O.server)},Changes:()=>O.mode==="architecture"?Ve.panel("Changes"):O.source==="server"?f7():a1(e)}[O.panel](),p7(),O.mode==="architecture"&&Ve.wirePanel(),h7(),nf(),Ly(),O.mode!=="architecture"&&kl(),ef()}let Xo=null;function i7(){O.source==="server"&&Ea().then(e=>{const t=e.exists?e.arch:null;JSON.stringify(t)!==JSON.stringify(Xo)&&(Xo=t,O.mode==="plan"&&O.selected&&rn())}).catch(()=>{})}let Ki=null,Cd=null,hn=null,Yi="";const i1=()=>{const e=O.server?.plan?.proposals??[];return e.find(t=>t.id===Cd)??e[0]??null};function kl(){const e=O.server,t=B("chart").querySelector(".canvas");if(!e?.plan){gl(t,null,{},{},O.domain??{width:0,height:0}),hn=null,Iy();return}const n=i1(),r=n?sg(e.plan,e.layout,n.ops):null,o=O.panel==="Steps"&&Ki&&Ki in e.plan.nodes?Ki:null;hn=gl(t,r,e.plan,e.layout,O.domain??e.layout.canvas,o),Iy()}function Nd(e){Cd=e,Yi="",kl(),s7()}async function Ny(e){if(O.source==="server"){if(e.architecture){e.proposal&&O.mode==="architecture"&&Ve.showProposal(e.proposal);return}e.step?s1(e.step):e.proposal&&Nd(e.proposal)}}function s1(e){if(!(e in(O.server?.plan?.nodes??{})))return;Yo(e),[...B("chart").querySelectorAll("rect")].find(n=>On(n)&&Dt(n).data.id===e)?.scrollIntoView({block:"center",inline:"center",behavior:"smooth"})}function s7(){const e=B("chart").querySelector(".canvas");if(!hn||!e||!O.domain)return;const t=e.getBoundingClientRect().width/mr({canvas:O.domain}).width,n=B("chart");n.scrollTo({left:e.offsetLeft+(hn.x+hn.w/2)*t-n.clientWidth/2,top:e.offsetTop+(hn.y+hn.h/2)*t-n.clientHeight/2,behavior:"smooth"})}function a7(e){const t=e.diff.map(([n,r])=>`<span class="${n==="+"?"add":n==="-"?"del":"same"}"><i aria-hidden="true">${n==="-"?"−":n==="+"?"+":" "}</i><span class="sr">${n==="+"?"added: ":n==="-"?"removed: ":""}</span>${He(r)||"&nbsp;"}</span>`).join("");return`<div class="words"><div class="where">${He(e.where)}, now and as proposed</div><div class="diff" tabindex="0" role="group" aria-label="${He(e.where)}: what it says now and what it would say">${t}</div></div>`}function l7(e,t,n,r){const o=sg(e.plan,e.layout,t.ops),s=i=>/remove$/.test(i)?"−":/\.add$/.test(i)?"+":"~";return`
90
+ <div class="pc-head">
91
+ <span><b>Proposal ${He(t.id)}</b> from <code>${He(t.by)}</code></span>
92
+ ${r>1?`<span class="pc-step"><button class="plain small" data-prev aria-label="The proposal before this one">◀</button><span>${n+1} of ${r}</span><button class="plain small" data-next aria-label="The proposal after this one">▶</button></span>`:""}
93
+ </div>
94
+ ${t.reason?`<div class="reason">${He(t.reason)}</div>`:""}
95
+ <ul class="ops">${t.ops.map(i=>`<li><span class="mark">${s(i.op)}</span>${He(Qy(i))}</li>`).join("")}</ul>
96
+ ${U3(e.plan,t.ops).map(a7).join("")}
97
+ ${o.applies?"":`<p class="err">No longer applies: ${He(o.why??"the plan has moved on")}.</p>`}
98
+ <div class="row">
99
+ <button class="primary" data-accept="${He(t.id)}" ${o.applies?"":"disabled"}>Accept</button>
100
+ <button data-reject="${He(t.id)}">Reject</button>
101
+ <input data-why="${He(t.id)}" placeholder="why not? (the agent is told)" aria-label="Why you reject ${He(t.id)}">
102
+ </div>
103
+ ${r>1?`<div class="row"><button class="plain small" data-accept-all>Accept all ${r}</button><button class="plain small" data-reject-all>Reject all</button></div>`:""}`}function Iy(){const e=B("proposalCard"),t=O.server,n=t?.plan?.proposals??[];if(!t?.plan||!n.length){e.hidden=!0,Yi="";return}const r=i1();if(!r)return;const o=l7(t,r,n.indexOf(r),n.length);if(!(e.contains(document.activeElement)&&document.activeElement instanceof HTMLInputElement&&document.activeElement.dataset.why===r.id)&&o!==Yi){Yi=o,e.innerHTML=o,e.setAttribute("aria-label",`Proposal ${r.id} from ${r.by}`),lc(e);const i=a=>Nd(n[(n.indexOf(r)+a+n.length)%n.length].id);e.querySelector("[data-prev]")?.addEventListener("click",()=>i(-1)),e.querySelector("[data-next]")?.addEventListener("click",()=>i(1))}e.hidden=!1,ac()}function ac(){const e=B("proposalCard");if(e.hidden)return;const t=B("board").getBoundingClientRect(),n=B("chart").querySelector(".canvas"),[r,o,s,i]=[e.offsetWidth,e.offsetHeight,14,52];let a=null;if(hn&&n&&O.domain){const y=n.getBoundingClientRect(),g=y.width/mr({canvas:O.domain}).width;a={x:y.left-t.left+hn.x*g,y:y.top-t.top+hn.y*g,w:hn.w*g,h:hn.h*g}}const l=[[t.width-r-10,i],[10,i],[t.width-r-10,t.height-o-10],[10,t.height-o-10]],u=a?[[a.x+a.w+s,a.y],[a.x-r-s,a.y],[a.x,a.y+a.h+s],[a.x,a.y-o-s],...l]:[[(t.width-r)/2,i],...l],c=([y,g])=>y>=10&&g>=i&&y+r<=t.width-10&&g+o<=t.height-10,d=([y,g])=>!a||y+r<=a.x-6||y>=a.x+a.w+6||g+o<=a.y-6||g>=a.y+a.h+6;let f=u.find(y=>c(y)&&d(y));if(!f&&a){const y={x:a.x+a.w/2,y:a.y+a.h/2};f=[...l].sort((g,m)=>Math.hypot(m[0]+r/2-y.x,m[1]+o/2-y.y)-Math.hypot(g[0]+r/2-y.x,g[1]+o/2-y.y))[0]}const[p,h]=f??l[0];e.style.left=`${Math.round(Math.max(10,Math.min(p,t.width-r-10)))}px`,e.style.top=`${Math.round(Math.max(i,Math.min(h,t.height-o-10)))}px`}B("chart").addEventListener("scroll",ac);new ResizeObserver(()=>ac()).observe(B("board"));function Ly(){B("undo").disabled=!O.chart?.canUndo?.(),B("redo").disabled=!O.chart?.canRedo?.()}const c7=["Data","Mermaid","Spec"];function u7(e,t){return O.mode==="architecture"?Ve.drawerBody(e,t):e==="Data"?`
104
+ <p class="lede">${O.source==="server"?"The plan as the chart holds it. Edit it and press Apply: the difference is sent as operations, under the same rules as a gesture.":"The plan as data: its steps and its dependencies. Edit it and press Apply to load it back in; that starts Undo over from here."}</p>
105
+ <textarea id="json" spellcheck="false" aria-label="The plan as JSON">${He(Zb(O.plan,t))}</textarea>
106
+ <p class="err" id="jsonErr" hidden></p>
107
+ <div class="row"><button id="applyJson" class="primary">Apply</button><button data-copy="json">Copy</button></div>`:e==="Mermaid"?`
108
+ <p class="lede">The same graph as a Mermaid block, ready to paste over the original. Positions are dropped: Mermaid has no way to say where a node is.</p>
109
+ <textarea id="mermaid" spellcheck="false" readonly aria-label="The plan as Mermaid">${He(q3(t,O.plan))}</textarea>
110
+ <div class="row"><button data-copy="mermaid" class="primary">Copy</button></div>`:`
111
+ <p class="lede">The ElicitJS chart spec this diagram is built from: what a step and a dependency are, how each is drawn, and each edit as the call that made it. Functions show by name. It is made from the plan, so there is nothing here to edit.</p>
112
+ <pre class="spec" id="spec" tabindex="0" aria-label="The chart spec">${He(Jb({...O.spec,data:t}))}</pre>
113
+ <div class="row"><button data-copy="spec" class="primary">Copy</button></div>`}let Fy="";function ef(){if(B("board").toggleAttribute("data-drawer",O.drawer.open),B("drawer").inert=!O.drawer.open,B("sourceBtn").setAttribute("aria-expanded",String(O.drawer.open)),!O.drawer.open||!O.chart)return;const t=B("drawerBody").contains(document.activeElement)&&document.activeElement instanceof HTMLTextAreaElement&&!document.activeElement.readOnly;if(!B("drawerTabs").children.length){B("drawerTabs").innerHTML=c7.map(o=>`<button role="tab" data-drawer-tab="${o}">${o}</button>`).join("");for(const o of B("drawerTabs").children)o.onclick=()=>Jo(!0,o.dataset.drawerTab)}for(const o of B("drawerTabs").children)o.setAttribute("aria-selected",String(o.dataset.drawerTab===O.drawer.tab));if(t)return;const n=u7(O.drawer.tab,Is());if(n===Fy)return;Fy=n,B("drawerBody").innerHTML=n;for(const o of B("drawerBody").querySelectorAll("[data-copy]"))o.onclick=async()=>{const s=o.dataset.copy??"";await navigator.clipboard.writeText(B(s).value??B(s).textContent);const i=o.textContent;o.textContent="Copied",setTimeout(()=>{o.textContent=i},1200)};const r=B("applyJson");r&&(r.onclick=()=>y7())}function Jo(e,t){const n=O.drawer.open;O.drawer={open:e,tab:t??O.drawer.tab},ef(),e&&!n&&B("drawerTabs").querySelector('[aria-selected="true"]')?.focus(),!e&&n&&B("sourceBtn").focus()}B("sourceBtn").onclick=()=>Jo(!O.drawer.open);B("drawerClose").onclick=()=>Jo(!1);B("drawer").addEventListener("keydown",e=>{e.key==="Escape"&&(e.stopPropagation(),Jo(!1))});function a1(e){const t=Qb(O.start,e);return t.length?`
114
+ <p class="lede">${t.length} change${t.length===1?"":"s"} since the diagram was drawn.</p>
115
+ <ul class="changes">${t.map(([n,r])=>`
116
+ <li class="${n}"><span>${n}</span>${He(r)}</li>`).join("")}</ul>`:`<p class="lede">Nothing has changed yet: this is the diagram exactly as it was drawn.</p>
117
+ <p class="lede">Drag a box, draw an arrow, rename a step. Each edit is listed here as you make it, and comes out as a diff in <b>Data</b> and as a Mermaid block in <b>Mermaid</b>.</p>`}function f7(){const e=[...O.server?.recent??[]].reverse();if(!e.length)return'<p class="lede">No changes yet. Everything you do here is logged, with who did it.</p>';const t=Qy;return`
118
+ <p class="lede">The plan's log, newest first. It is committed with the plan, so a pull request shows who did what.</p>
119
+ <ul class="log">${e.map(n=>`
120
+ <li><span class="rev">rev ${n.rev}</span> <code>${He(n.actor)}</code> <span class="via">via ${He(n.via)}</span>
121
+ ${n.proposed?`<span class="via">→ proposal ${He(n.proposed)}</span>`:""}
122
+ <div>${n.ops.map(r=>He(t(r))).join(" · ")}</div></li>`).join("")}</ul>`}const tf=new Map,Jc=new Set,d7=5e3,l1=()=>O.mode==="architecture"?Ve.knownFileInfo():Object.fromEntries([...tf].map(([e,t])=>[e,t.info]));function c1(){if(O.mode==="architecture")return Ve.pickedBox();const e=O.selected,t=e?O.server?.plan?.nodes[e]:void 0;return e&&t?{id:e,files:t.files??[]}:null}function nf(){if(O.mode==="architecture"){Ve.askFileInfo(ms);return}const e=c1();if(!e||O.source!=="server")return;const t=Date.now(),n=e.files.filter(r=>!Jc.has(r)&&!((tf.get(r)?.at??0)>t-d7));if(n.length){for(const r of n)Jc.add(r);af(n).then(r=>{for(const o of r)tf.set(o.path,{at:Date.now(),info:{kind:o.kind,matches:o.matches}})}).catch(()=>{}).finally(()=>{for(const r of n)Jc.delete(r);ms()})}}function ms(){const e=c1(),t=B("panel").querySelector(".files .chips");if(!e||!t)return;const n=rw(e.id,e.files,l1());t.innerHTML!==n&&(t.innerHTML=n)}async function Ry(e,t){if(O.mode==="architecture"){const o=await Ve.saveFiles(e,t);return ms(),nf(),o}const n=O.server?.plan.nodes[e];if(!n)return!1;const r=await ln([{op:"node.set",id:e,files:t}],`Saved the files for ${n.label}.`,`you edited the files of ${e}`);return ms(),nf(),r}function h7(){const e=B("panel").querySelector("[data-files-input]"),t=B("panel").querySelector(".files-menu"),n=B("panel").querySelector(".files .chips");if(!e||!t||!n)return;const r=e.dataset.filesInput;let o=[],s=-1,i=0,a=!1,l;const u=()=>(O.mode==="architecture"?Ve.current()?.arch.nodes[r]?.files:O.server?.plan.nodes[r]?.files)??[];n.addEventListener("click",h=>{const y=h.target instanceof Element?h.target.closest("[data-remove-file]"):null;y&&Ry(r,ow(u(),y.dataset.removeFile??""))});const c=()=>{t.hidden=!0,e.setAttribute("aria-expanded","false"),e.removeAttribute("aria-activedescendant"),s=-1},d=()=>{const h=e.value.trim();t.innerHTML=o.length?o.map((y,g)=>`<li role="option" id="insp-files-opt-${g}" data-row="${g}" aria-selected="${g===s}" class="${y.kind}"><code>${He(y.path)}</code>${y.note?`<span>${He(y.note)}</span>`:""}</li>`).join(""):`<li class="none" role="presentation">${h?"Nothing in the repository has that in its path. Enter adds it as you typed it.":"No files to offer."}</li>`,t.hidden=!1,e.setAttribute("aria-expanded","true"),s>=0?e.setAttribute("aria-activedescendant",`insp-files-opt-${s}`):e.removeAttribute("aria-activedescendant")};async function f(){const h=++i,y=e.value;try{const[g,m]=await Promise.all([cw(y),y.trim()?af([uw(y)]):Promise.resolve([])]);if(h!==i)return;o=fw(y,g.files,m[0],u()),s=o.length&&y.trim()?0:-1,a=!1,d()}catch{h===i&&(o=[],a=!1,d())}}async function p(h){const y=dw(u(),h);e.value="",y!==u()&&await Ry(r,y),f()}e.addEventListener("input",()=>{a=!0,clearTimeout(l),l=setTimeout(f,120)}),e.addEventListener("focus",()=>f()),e.addEventListener("blur",()=>{clearTimeout(l),setTimeout(()=>{document.activeElement!==e&&c()},120)}),e.addEventListener("keydown",h=>{if(h.key==="ArrowDown"||h.key==="ArrowUp"){if(t.hidden){f();return}h.preventDefault(),o.length&&(s=(s+(h.key==="ArrowDown"?1:-1)+o.length)%o.length),d()}else h.key==="Enter"?(h.preventDefault(),(async()=>{a&&(clearTimeout(l),await f());const y=e.value.trim();s>=0&&o[s]?p(o[s].path):y&&p(y)})()):h.key==="Escape"&&!t.hidden&&(h.preventDefault(),h.stopPropagation(),c())}),t.addEventListener("mousedown",h=>h.preventDefault()),t.addEventListener("click",h=>{const y=h.target instanceof Element?h.target.closest("[data-row]"):null,g=y?o[Number(y.dataset.row)]:void 0;g&&p(g.path)})}function p7(){for(const e of B("panel").querySelectorAll("[data-inspect]"))e.onclick=()=>Yo(e.dataset.inspect??null);for(const e of B("panel").querySelectorAll("[data-close-inspector]"))e.onclick=()=>Yo(null);for(const e of B("panel").querySelectorAll("textarea[data-field]"))e.addEventListener("input",()=>{oo[e.dataset.field]=e.value}),e.addEventListener("blur",()=>Sa(e)),e.addEventListener("keydown",t=>{const n=t;n.key==="Enter"&&(n.metaKey||n.ctrlKey)&&(n.preventDefault(),Sa(e))});for(const e of B("panel").querySelectorAll("[data-remove-touch]"))e.onclick=()=>{const t=e.dataset.step??"",n=e.dataset.removeTouch??"",r=O.server?.plan.nodes[t]?.touches??[];ln([{op:"node.set",id:t,touches:r.filter(o=>o!==n)}],`${O.server?.plan.nodes[t]?.label??t} no longer changes ${Xo?.nodes[n]?.label??n}.`,`you edited the boxes ${t} changes`)};for(const e of B("panel").querySelectorAll("select[data-touch-add]"))e.onchange=()=>{const t=e.dataset.touchAdd??"",n=e.value;if(!n)return;const r=O.server?.plan.nodes[t]?.touches??[];ln([{op:"node.set",id:t,touches:[...r,n]}],`${O.server?.plan.nodes[t]?.label??t} changes ${Xo?.nodes[n]?.label??n}.`,`you edited the boxes ${t} changes`)};for(const e of B("panel").querySelectorAll("[data-save-field]"))e.onclick=()=>{const t=B("panel").querySelector(`#insp-${e.dataset.saveField}`);t&&Sa(t)};for(const e of B("panel").querySelectorAll("li.step[data-step]")){const t=e.dataset.step;e.addEventListener("mouseenter",()=>{Ki=t,kl()}),e.addEventListener("mouseleave",()=>{Ki=null,kl()})}lc(B("panel"))}function lc(e){for(const s of e.querySelectorAll("[data-act]"))s.onclick=async()=>{if(s.dataset.act==="replan"||s.dataset.act==="drift"){try{const l=await Wd(O.server.id,s.dataset.act==="replan"?{kind:"failure",step:s.dataset.step}:{kind:"drift"});O.server={...O.server,reconcile:l},rn(),Er()}catch(l){Qe(`The re-planner was not asked: ${l.message}.`,"error")}return}const i=e.querySelector(`[data-answer="${CSS.escape(s.dataset.step??"")}"]`),a=tw(s.dataset.act,s.dataset.step,i?.value??"");a?ln(a.ops,a.message,a.reason).then(l=>{const u=l&&ys.find(c=>c.kind==="answered");u&&ps(rf(u))}):s.dataset.act==="answer"&&i?.focus()};for(const s of e.querySelectorAll("[data-gate]"))s.onclick=()=>{const{gate:i,from:a,to:l}=s.dataset,u=e.querySelector(`[data-gate-text][data-from="${CSS.escape(a??"")}"][data-to="${CSS.escape(l??"")}"]`),c=nw(i??"",a??"",l??"",u?.value??"");if(!c){u?.focus();return}ln(c.ops,c.message,c.reason).then(d=>{const f=d&&ys.find(p=>p.kind==="passed"||p.kind==="sentBack");f&&ps(rf(f))})};for(const s of e.querySelectorAll("[data-gate-text]"))s.addEventListener("keydown",i=>{if(i.key!=="Enter")return;const{from:a,to:l}=s.dataset,u=`[data-from="${CSS.escape(a??"")}"][data-to="${CSS.escape(l??"")}"]`;(e.querySelector(`[data-gate="give"]${u}`)??e.querySelector(`[data-gate="pass"]${u}`))?.click()});for(const s of e.querySelectorAll("[data-answer]"))s.addEventListener("keydown",i=>{i.key==="Enter"&&e.querySelector(`[data-act="answer"][data-step="${CSS.escape(s.dataset.answer??"")}"]`)?.click()});for(const s of e.querySelectorAll("[data-reconcile]"))s.onclick=async()=>{try{const i=await Wd(O.server.id);O.server={...O.server,reconcile:i},rn(),Er()}catch(i){Qe(`The re-planner was not asked: ${i.message}.`,"error")}};for(const s of e.querySelectorAll("[data-review]"))s.onclick=()=>ln([{op:"review",ids:[s.dataset.review]}],`Marked ${s.dataset.review} as reviewed.`);for(const s of e.querySelectorAll("[data-accept]"))s.onclick=()=>ln([{op:"proposal.accept",id:s.dataset.accept}],`Accepted ${s.dataset.accept}.`);for(const s of e.querySelectorAll("[data-finish]"))s.onclick=()=>ln([{op:"plan.set",phase:"done"}],"Plan marked done.","you marked the plan done");const t=async(s,i)=>{const a=e.querySelector(`[data-permit-why="${CSS.escape(s)}"]`)?.value.trim(),{status:l}=await lw(s,i,i==="deny"?a:void 0);Qe(l===200?i==="allow"?"Allowed: the agent carries on.":"Denied: the agent is told why.":"That prompt was already answered in the agent's window.",l===200?"info":"error"),O.server&&Bn({quiet:!0})};for(const s of e.querySelectorAll("[data-permit]"))s.onclick=()=>t(s.dataset.permit??"","allow");for(const s of e.querySelectorAll("[data-deny]"))s.onclick=()=>t(s.dataset.deny??"","deny");for(const s of e.querySelectorAll("[data-reject]"))s.onclick=()=>{const i=e.querySelector(`[data-why="${CSS.escape(s.dataset.reject??"")}"]`)?.value.trim();ln([{op:"proposal.reject",id:s.dataset.reject,...i?{reason:i}:{}}],`Rejected ${s.dataset.reject}.`)};const n=(O.server?.plan?.proposals??[]).map(s=>s.id),r=e.querySelector("[data-accept-all]");r&&(r.onclick=()=>ln(n.map(s=>({op:"proposal.accept",id:s})),`Accepted ${n.length} proposals.`));const o=e.querySelector("[data-reject-all]");o&&(o.onclick=()=>ln(n.map(s=>({op:"proposal.reject",id:s})),`Rejected ${n.length} proposals.`));for(const s of e.querySelectorAll("[data-show-step]"))s.onclick=()=>s1(s.dataset.showStep??"");for(const s of e.querySelectorAll("[data-show-proposal]"))s.onclick=()=>Nd(s.dataset.showProposal??"")}function y7(){const e=B("jsonErr");try{if(O.mode==="architecture"){Ve.applyJSON(B("json").value),e.hidden=!0;return}const t=JSON.parse(B("json").value);if(!Array.isArray(t.steps)||!Array.isArray(t.depends))throw new Error("needs a `steps` array and a `depends` array");const n=new Set(t.steps.map(o=>o.id)),r=t.depends.filter(o=>!n.has(o.source)||!n.has(o.target));if(r.length)throw new Error(r.length===1?`a dependency names a step that is not in steps (${r[0].source} → ${r[0].target})`:`${r.length} dependencies name steps that are not in steps`);if(e.hidden=!0,O.source==="server"){const o=Zy(O.server,{steps:t.steps,depends:t.depends});o.length&&ln(o,`Applied ${o.length} operation${o.length===1?"":"s"}.`);return}O.chart.setData({steps:t.steps,depends:t.depends}),rn()}catch(t){e.hidden=!1,e.textContent=`Not applied — ${t.message}`}}function hr(e){O.panel=e;for(const t of B("tabs").children)t.setAttribute("aria-selected",String(t.dataset.panel===e));rn()}function Gi(){B("tabs").innerHTML=(O.mode==="architecture"?Ve.panels():X3[O.source]).map(e=>`<button role="tab" aria-selected="false" data-panel="${e}">${e}${e==="Changes"&&O.source==="samples"?'<span class="count" hidden></span>':""}</button>`).join("");for(const e of B("tabs").children)e.onclick=()=>hr(e.dataset.panel??"")}function g7(){const e=B("tabs").querySelector(".count");if(!e||!O.start)return;const t=Qb(O.start,Is()).length;e.hidden=!t,e.textContent=String(t)}function u1(e,t){if(O.mode==="architecture"){Ve.pressPhase();return}const n=O.server;if(!n?.plan)return;const r=Gy(n.plan.phase,n.derived?.progress,n.listening??[]),o=t?r.second:r;if(o){if(o.confirm&&e.dataset.armed!==o.label){e.dataset.armed=o.label,Vu(e,o),setTimeout(()=>{e.dataset.armed===o.label&&(delete e.dataset.armed,Er())},4e3);return}delete e.dataset.armed,ln(o.ops,o.message,o.reason).then(s=>{if(!s)return;const i=ys.find(a=>a.kind==="approved"||a.kind==="resumed"||a.kind==="stopped");i?ps(rf(i)):o.ops[0]?.op==="plan.stop"&&O.server?.stopping?.length&&Qe(`Stopped. ${q1(O.server.stopping)} ${O.server.stopping.length===1?"stops":"stop"} at the next tool call; the plan is back in planning.`)})}}B("phase").onclick=()=>u1(B("phase"),!1);B("phase2").onclick=()=>u1(B("phase2"),!0);const rf=e=>O.server?.calls?.find(t=>t.id===e.id)??e,f1=()=>Ni(location.hash).sample??null;async function pr(e,{open:t=!0,id:n}={}){if(e===O.mode&&t&&O.chart||(O.mode==="architecture"&&e!=="architecture"&&Ve.leave(),e==="architecture"&&(Re.unfollow?.(),Re.unfollow=null,Re.pending=!1),O.mode=e,O.selected=null,oo={},document.body.dataset.mode=e,B("modePlan").setAttribute("aria-pressed",String(e==="plan")),B("modeArch").setAttribute("aria-pressed",String(e==="architecture")),B("modeBadge").innerHTML=e==="plan"?"<b>Plan</b> an arrow A → B means B comes after A":"<b>Architecture</b> an arrow A → B means A uses B",B("chart").setAttribute("aria-label",e==="plan"?"Plan board. Tab to a step: the arrow keys move it, Enter renames it, Delete removes it. Scroll to look around.":"Architecture board. Tab to a box: the arrow keys move it, Enter renames it, Delete removes it. Scroll to look around."),B("planbar").hidden=!0,B("needs").hidden=!0,Qe(""),io(),!t))return;if(Gi(),e==="architecture"){if(O.source==="server")history.replaceState(null,"","#architecture"),hr("Boxes"),await Ve.openServer();else{const o=cf(n??f1()??Vi[0]?.id);history.replaceState(null,"",`#architecture/${o.id}`),Oy(),hr("Flows"),Ve.openSample(o)}return}const r=n??Ni(location.hash).plan??"";if(O.source==="server"){hr("Steps"),await zo();const o=O.plans.find(s=>s.id===r)??O.plans[0];o?(history.replaceState(null,"",`#${o.id}`),Nr(o.id)):gs("none")}else{hr("Changes"),Oy();const o=Sl(r);history.replaceState(null,"",`#${o.id}`),ho(o)}}B("modePlan").onclick=()=>pr("plan");B("modeArch").onclick=()=>pr("architecture");B("undo").title=`Undo (${ml}Z)`;B("redo").title=`Redo (${ml==="⌘"?"⇧⌘Z":"Ctrl+Shift+Z"})`;B("undo").onclick=()=>{O.chart.undo(),Vo()};B("redo").onclick=()=>{O.chart.redo(),Vo()};B("reset").onclick=()=>O.mode==="architecture"?Ve.reset():O.source==="server"?Bn({reseed:!0,quiet:!0}):ho(Sl(O.plan.id));document.addEventListener("keydown",e=>{const t=e.target;if(!(t instanceof HTMLElement&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))){if((e.metaKey||e.ctrlKey)&&e.key.toLowerCase()==="z"){e.preventDefault(),e.shiftKey?O.chart.redo():O.chart.undo(),Vo();return}if(!(e.metaKey||e.ctrlKey||e.altKey)){if(e.key==="Escape"&&O.drawer.open&&!e.defaultPrevented&&(document.activeElement===document.body||B("drawer").contains(document.activeElement))){Jo(!1);return}if(e.key==="s"||e.key==="S"){Jo(!O.drawer.open);return}if(e.key==="?"){const n=B("help");n.open=!n.open;return}if(e.key==="+"||e.key==="="){Bi.zoomIn();return}if(e.key==="-"||e.key==="_"){Bi.zoomOut();return}if(e.key==="0"){Bi.fit();return}}}});await P1();const pi=await D1();if(pi){O.source="server",O.root=pi.root,document.body.dataset.source="server";const e=pi.root.split(/[\\/]/).filter(Boolean).pop()??pi.root;B("descr").textContent=`Plans in ${e}/.dcursed/plans. Every gesture is saved as you make it, and changes made elsewhere show up here.`,B("descr").title=`${pi.root}/.dcursed/plans`,B("reset").textContent="Reload",B("reset").title="Reload the plan as the server holds it",Gi(),hr("Steps"),await zo(),j1({plans:r=>r7(r),open:r=>{r&&Td()}}),await sa(),Ky({change:()=>sa(),problem:()=>{},call:()=>{},open:()=>sa(),down:()=>{}}),setInterval(()=>{document.hidden||sa()},5e3);const t=Ni(location.hash),n=O.plans.find(r=>r.id===t.plan)??O.plans[0];t.architecture?await pr("architecture"):n?await Nr(n.id):gs("none"),await Ny(t),addEventListener("hashchange",async()=>{const r=Ni(location.hash);!r.architecture&&r.plan&&(r.plan!==O.server?.id||O.mode==="architecture")?await Nr(r.plan):r.architecture&&await pr("architecture"),await Ny(r)})}else if(!Xr.length)B("descr").textContent="",B("switcher").hidden=!0,Gi(),hr("Steps"),gs("server");else{const e=()=>{const t=f1(),n=!!t||location.hash==="#architecture",r=Ni(location.hash).plan??"";return n&&O.mode==="architecture"?Ve.openSample(cf(t??"")):!n&&O.mode==="plan"&&O.chart?ho(Sl(r)):n?pr("architecture",{id:t??void 0}):pr("plan",{id:r})};Gi(),await e(),addEventListener("hashchange",e)}Object.assign(window,{elicit:Q8,app:O,interactions:Go});