trebol 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/README.md +18 -3
  2. package/dist/cli.js +13790 -11417
  3. package/dist/fonts/OFL.txt +93 -0
  4. package/dist/fonts/inter-cyrillic-ext.woff2 +0 -0
  5. package/dist/fonts/inter-cyrillic.woff2 +0 -0
  6. package/dist/fonts/inter-greek-ext.woff2 +0 -0
  7. package/dist/fonts/inter-greek.woff2 +0 -0
  8. package/dist/fonts/inter-latin-ext.woff2 +0 -0
  9. package/dist/fonts/inter-latin.woff2 +0 -0
  10. package/dist/fonts/inter-vietnamese.woff2 +0 -0
  11. package/dist/lib/core/access.d.ts +10 -0
  12. package/dist/lib/core/access.js +210 -0
  13. package/dist/lib/core/base.d.ts +4 -0
  14. package/dist/lib/core/base.js +50 -0
  15. package/dist/lib/core/bitset.d.ts +9 -0
  16. package/dist/lib/core/bitset.js +75 -0
  17. package/dist/lib/core/boot.d.ts +18 -0
  18. package/dist/lib/core/boot.js +73 -0
  19. package/dist/lib/core/compare.d.ts +9 -0
  20. package/dist/lib/core/compare.js +156 -0
  21. package/dist/lib/core/ctx.d.ts +36 -0
  22. package/dist/lib/core/ctx.js +251 -0
  23. package/dist/lib/core/dec.d.ts +28 -0
  24. package/dist/lib/core/dec.js +158 -0
  25. package/dist/lib/core/errors.d.ts +15 -0
  26. package/dist/lib/core/errors.js +44 -0
  27. package/dist/lib/core/escapes.d.ts +14 -0
  28. package/dist/lib/core/escapes.js +80 -0
  29. package/dist/lib/core/eval.d.ts +220 -0
  30. package/dist/lib/core/eval.js +666 -0
  31. package/dist/lib/core/func.d.ts +68 -0
  32. package/dist/lib/core/func.js +129 -0
  33. package/dist/lib/core/hash.d.ts +5 -0
  34. package/dist/lib/core/hash.js +155 -0
  35. package/dist/lib/core/index.d.ts +18 -0
  36. package/dist/lib/core/index.js +20 -0
  37. package/dist/lib/core/int64.d.ts +22 -0
  38. package/dist/lib/core/int64.js +113 -0
  39. package/dist/lib/core/kinds.d.ts +67 -0
  40. package/dist/lib/core/kinds.js +134 -0
  41. package/dist/lib/core/lexer.d.ts +13 -0
  42. package/dist/lib/core/lexer.js +702 -0
  43. package/dist/lib/core/mezz.d.ts +1 -0
  44. package/dist/lib/core/mezz.js +360 -0
  45. package/dist/lib/core/mold.d.ts +20 -0
  46. package/dist/lib/core/mold.js +434 -0
  47. package/dist/lib/core/natives/control.d.ts +1 -0
  48. package/dist/lib/core/natives/control.js +374 -0
  49. package/dist/lib/core/natives/csv.d.ts +15 -0
  50. package/dist/lib/core/natives/csv.js +315 -0
  51. package/dist/lib/core/natives/data.d.ts +11 -0
  52. package/dist/lib/core/natives/data.js +367 -0
  53. package/dist/lib/core/natives/define.d.ts +17 -0
  54. package/dist/lib/core/natives/define.js +47 -0
  55. package/dist/lib/core/natives/encode.d.ts +3 -0
  56. package/dist/lib/core/natives/encode.js +187 -0
  57. package/dist/lib/core/natives/json.d.ts +5 -0
  58. package/dist/lib/core/natives/json.js +273 -0
  59. package/dist/lib/core/natives/math.d.ts +3 -0
  60. package/dist/lib/core/natives/math.js +500 -0
  61. package/dist/lib/core/natives/parse.d.ts +1 -0
  62. package/dist/lib/core/natives/parse.js +600 -0
  63. package/dist/lib/core/natives/series.d.ts +4 -0
  64. package/dist/lib/core/natives/series.js +519 -0
  65. package/dist/lib/core/natives/text.d.ts +1 -0
  66. package/dist/lib/core/natives/text.js +487 -0
  67. package/dist/lib/core/natives/xml.d.ts +9 -0
  68. package/dist/lib/core/natives/xml.js +242 -0
  69. package/dist/lib/core/series.d.ts +26 -0
  70. package/dist/lib/core/series.js +73 -0
  71. package/dist/lib/core/symbols.d.ts +9 -0
  72. package/dist/lib/core/symbols.js +44 -0
  73. package/dist/lib/core/values.d.ts +206 -0
  74. package/dist/lib/core/values.js +223 -0
  75. package/dist/lib/host/browser.d.ts +4 -0
  76. package/dist/lib/host/browser.js +4974 -0
  77. package/dist/lib/host/chart.d.ts +26 -0
  78. package/dist/lib/host/chart.js +158 -0
  79. package/dist/lib/host/compress.d.ts +1 -0
  80. package/dist/lib/host/compress.js +37 -0
  81. package/dist/lib/host/devlog.d.ts +11 -0
  82. package/dist/lib/host/devlog.js +13 -0
  83. package/dist/lib/host/devtools.d.ts +23 -0
  84. package/dist/lib/host/devtools.js +626 -0
  85. package/dist/lib/host/draw.d.ts +31 -0
  86. package/dist/lib/host/draw.js +348 -0
  87. package/dist/lib/host/fonts/OFL.txt +93 -0
  88. package/dist/lib/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  89. package/dist/lib/host/fonts/inter-cyrillic.woff2 +0 -0
  90. package/dist/lib/host/fonts/inter-greek-ext.woff2 +0 -0
  91. package/dist/lib/host/fonts/inter-greek.woff2 +0 -0
  92. package/dist/lib/host/fonts/inter-latin-ext.woff2 +0 -0
  93. package/dist/lib/host/fonts/inter-latin.woff2 +0 -0
  94. package/dist/lib/host/fonts/inter-vietnamese.woff2 +0 -0
  95. package/dist/lib/host/fonts.d.ts +11 -0
  96. package/dist/lib/host/fonts.js +29 -0
  97. package/dist/lib/host/icons.d.ts +3 -0
  98. package/dist/lib/host/icons.js +97 -0
  99. package/dist/lib/host/index.d.ts +40 -0
  100. package/dist/lib/host/index.js +192 -0
  101. package/dist/lib/host/js.d.ts +5 -0
  102. package/dist/lib/host/js.js +130 -0
  103. package/dist/lib/host/locale.d.ts +40 -0
  104. package/dist/lib/host/locale.js +241 -0
  105. package/dist/lib/host/markdown.d.ts +30 -0
  106. package/dist/lib/host/markdown.js +161 -0
  107. package/dist/lib/host/modules.d.ts +14 -0
  108. package/dist/lib/host/modules.js +300 -0
  109. package/dist/lib/host/natives.d.ts +6 -0
  110. package/dist/lib/host/natives.js +98 -0
  111. package/dist/lib/host/net.d.ts +12 -0
  112. package/dist/lib/host/net.js +549 -0
  113. package/dist/lib/host/orbit.d.ts +121 -0
  114. package/dist/lib/host/orbit.js +374 -0
  115. package/dist/lib/host/page.d.ts +9 -0
  116. package/dist/lib/host/page.js +55 -0
  117. package/dist/lib/host/rows.d.ts +29 -0
  118. package/dist/lib/host/rows.js +109 -0
  119. package/dist/lib/host/scheduler.d.ts +51 -0
  120. package/dist/lib/host/scheduler.js +197 -0
  121. package/dist/lib/host/theme.d.ts +58 -0
  122. package/dist/lib/host/theme.js +1667 -0
  123. package/dist/lib/ui/i18n.trb +117 -0
  124. package/dist/lib/ui/test.trb +565 -0
  125. package/dist/lib/ui/ui.trb +1678 -0
  126. package/dist/trebol.js +1427 -138
  127. package/editors/vscode/README.md +15 -0
  128. package/editors/vscode/language-configuration.json +28 -0
  129. package/editors/vscode/package.json +42 -0
  130. package/editors/vscode/syntaxes/trebol.tmLanguage.json +237 -0
  131. package/package.json +23 -7
  132. package/src/core/boot.ts +1 -1
  133. package/src/core/func.ts +4 -0
  134. package/src/core/natives/control.ts +1 -1
  135. package/src/core/natives/series.ts +9 -1
  136. package/src/core/natives/text.ts +2 -0
  137. package/src/host/browser.ts +1235 -83
  138. package/src/host/devlog.ts +16 -0
  139. package/src/host/devtools.ts +641 -0
  140. package/src/host/fonts/OFL.txt +93 -0
  141. package/src/host/fonts/inter-cyrillic-ext.woff2 +0 -0
  142. package/src/host/fonts/inter-cyrillic.woff2 +0 -0
  143. package/src/host/fonts/inter-greek-ext.woff2 +0 -0
  144. package/src/host/fonts/inter-greek.woff2 +0 -0
  145. package/src/host/fonts/inter-latin-ext.woff2 +0 -0
  146. package/src/host/fonts/inter-latin.woff2 +0 -0
  147. package/src/host/fonts/inter-vietnamese.woff2 +0 -0
  148. package/src/host/fonts.ts +39 -0
  149. package/src/host/index.ts +5 -3
  150. package/src/host/js.ts +127 -0
  151. package/src/host/markdown.ts +9 -0
  152. package/src/host/modules.ts +41 -2
  153. package/src/host/net.ts +9 -1
  154. package/src/host/orbit.ts +432 -0
  155. package/src/host/rows.ts +30 -0
  156. package/src/host/scheduler.ts +62 -36
  157. package/src/host/theme.ts +270 -6
  158. package/src/ui/i18n.trb +10 -0
  159. package/src/ui/test.trb +565 -0
  160. package/src/ui/ui.trb +564 -90
package/dist/trebol.js CHANGED
@@ -1,24 +1,24 @@
1
- var ru=Object.defineProperty;var ou=(e,t)=>{for(var n in t)ru(e,n,{get:t[n],enumerable:!0})};var a={Unset:0,None:1,Logic:2,Integer:3,Decimal:4,Percent:5,Money:6,Char:7,Pair:8,Tuple:9,Date:10,Time:11,String:12,File:13,Email:14,Url:15,Tag:16,Binary:17,Bitset:18,Word:19,SetWord:20,GetWord:21,LitWord:22,Refinement:23,Issue:24,Block:25,Paren:26,Path:27,SetPath:28,GetPath:29,LitPath:30,Map:31,Object:32,Error:33,Function:34,Native:35,Op:36,Datatype:37,Typeset:38,Handle:39},Qn=["unset!","none!","logic!","integer!","decimal!","percent!","money!","char!","pair!","tuple!","date!","time!","string!","file!","email!","url!","tag!","binary!","bitset!","word!","set-word!","get-word!","lit-word!","refinement!","issue!","block!","paren!","path!","set-path!","get-path!","lit-path!","map!","object!","error!","function!","native!","op!","datatype!","typeset!","handle!"],Ks=Qn.length,Ro=new Map;Qn.forEach((e,t)=>Ro.set(e,t));function wn(e){return Ro.get(e.toLowerCase())}function re(e){return Qn[e]??"?!"}function Br(e){let t=re(e);return("aeiou".includes(t[0])?"an ":"a ")+t}function V(e){return e>=a.String&&e<=a.Tag}function oe(e){return e>=a.Word&&e<=a.Issue}function U(e){return e>=a.Block&&e<=a.LitPath}function Gs(e){return e>=a.String&&e<=a.Binary||U(e)}function $r(e){let t=[];for(let n=0;n<Ks;n++)t.push((e&1n<<BigInt(n))!==0n);return t}function ke(e){return 1n<<BigInt(e)}function _t(e,t){let n=0n;for(let r=e;r<=t;r++)n|=1n<<BigInt(r);return n}var qs=_t(a.Unset,Ks-1),er={"any-type!":qs,"any-value!":qs&~ke(a.Unset),"number!":ke(a.Integer)|ke(a.Decimal)|ke(a.Percent),"scalar!":_t(a.Logic,a.Time)&~ke(a.Logic),"any-string!":_t(a.String,a.Tag),"series!":_t(a.String,a.Binary)|_t(a.Block,a.LitPath),"any-word!":_t(a.Word,a.Issue),"any-block!":_t(a.Block,a.LitPath),"any-path!":_t(a.Path,a.LitPath),"any-object!":ke(a.Object)|ke(a.Error),"any-function!":ke(a.Function)|ke(a.Native)|ke(a.Op)};function Vs(e){let t=e.toLowerCase(),n=Ro.get(t);return n!==void 0?ke(n):er[t]}var Fo=[],Nr=[],Zs=new Map;function A(e){let t=Zs.get(e);if(t!==void 0)return t;let n=e.toLowerCase(),r=Fo.length;return Fo.push(e),Zs.set(e,r),n===e?Nr.push(r):(Nr.push(-1),Nr[r]=A(n)),r}function E(e){let t=Fo[e];if(t===void 0)throw new RangeError(`unknown symbol ${e}`);return t}function L(e){return Nr[e]??e}function Ys(e,t){return e===t||L(e)===L(t)}var he={};ou(he,{add:()=>Ho,cmp:()=>on,fromBig:()=>Fe,fromNumber:()=>qo,isZero:()=>Ut,mul:()=>_o,neg:()=>Or,parse:()=>Sn,quot:()=>Uo,rem:()=>Cn,sub:()=>zo,toNumber:()=>q,toString:()=>tr});var au=-(2n**63n),su=2n**63n-1n,iu=BigInt(Number.MIN_SAFE_INTEGER),lu=BigInt(Number.MAX_SAFE_INTEGER);function Fe(e){return e>=iu&&e<=lu?Number(e):e<au||e>su?null:e}function ct(e){return typeof e=="bigint"?e:BigInt(e)}function Ho(e,t){if(typeof e=="number"&&typeof t=="number"){let n=e+t;if(Number.isSafeInteger(n))return n}return Fe(ct(e)+ct(t))}function zo(e,t){if(typeof e=="number"&&typeof t=="number"){let n=e-t;if(Number.isSafeInteger(n))return n}return Fe(ct(e)-ct(t))}function _o(e,t){if(typeof e=="number"&&typeof t=="number"){let n=e*t;if(Number.isSafeInteger(n))return n===0?0:n}return Fe(ct(e)*ct(t))}function Or(e){return typeof e=="number"?e===0?0:-e:Fe(-e)}function Uo(e,t){if(t===0)return null;if(typeof e=="number"&&typeof t=="number"){let n=Math.trunc(e/t);return n===0?0:n}return Fe(ct(e)/ct(t))}function Cn(e,t){if(t===0)return null;if(typeof e=="number"&&typeof t=="number"){let n=e%t;return n===0?0:n}return Fe(ct(e)%ct(t))}function on(e,t){if(typeof e=="number"&&typeof t=="number")return e<t?-1:e>t?1:0;let n=ct(e),r=ct(t);return n<r?-1:n>r?1:0}function Ut(e){return e===0||e===0n}function q(e){return typeof e=="number"?e:Number(e)}function qo(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e);return Number.isSafeInteger(t)?t===0?0:t:Fe(BigInt(t))}function Sn(e){let t=e.replace(/'/g,"");if(!/^[+-]?\d+$/.test(t))return null;if(t.replace(/^[+-]/,"").length<=15){let n=Number(t);return n===0?0:n}return Fe(BigInt(t))}function tr(e){return typeof e=="bigint"?e.toString():String(e)}function Dt(e,t){for(;t>0&&e%10n===0n;)e/=10n,t--;return e===0n&&(t=0),{d:e,e:t}}function Js(e){let t=e.replace(/'/g,"").replace(",","."),n=/^([+-]?)(\d*)(?:\.(\d*))?$/.exec(t);if(!n)return null;let r=n[2]??"",o=n[3]??"";if(r===""&&o==="")return null;let s=BigInt((r||"0")+o);return Dt(n[1]==="-"?-s:s,o.length)}function Mt(e,t=0){let n=e.d<0n,r=(n?-e.d:e.d).toString(),o=Math.max(e.e,t);return r=r+"0".repeat(o-e.e),o>0&&(r=r.padStart(o+1,"0"),r=r.slice(0,r.length-o)+"."+r.slice(r.length-o)),(n?"-":"")+r}function Dr(e,t){return e.d===t.d&&e.e===t.e}function ut(e){return Number(e.d)/10**e.e}function Pr(e,t){let n=Math.max(e.e,t.e);return[e.d*10n**BigInt(n-e.e),t.d*10n**BigInt(n-t.e),n]}function Qs(e,t){let[n,r,o]=Pr(e,t);return Dt(n+r,o)}function ei(e,t){let[n,r,o]=Pr(e,t);return Dt(n-r,o)}function ti(e,t){return Dt(e.d*t.d,e.e+t.e)}var Xs=18;function ni(e,t){if(t.d===0n)return null;let n=e.d*10n**BigInt(Xs+t.e),r=t.d*10n**BigInt(e.e);r<0n&&(n=-n,r=-r);let o=n/r,s=n%r,i=(s<0n?-s:s)*2n;return(i>r||i===r&&o%2n!==0n)&&(o+=n<0n?-1n:1n),Dt(o,Xs)}function ri(e,t){let[n,r]=Pr(e,t);return n<r?-1:n>r?1:0}function Pt(e){if(!Number.isFinite(e))return null;let t=/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]\d+))?$/.exec(String(e));if(!t)return null;let n=t[3]??"",r=BigInt(t[2]+n),o=n.length-Number(t[4]??0);return o<0&&(r*=10n**BigInt(-o),o=0),Dt(t[1]==="-"?-r:r,o)}function oi(e){return Dt(e,0)}function ai(e,t){if(t.d===0n)return null;let[n,r,o]=Pr(e,t);return Dt(n%r,o)}function Ko(e,t,n){if(t.d===0n)return null;let r=e.d*10n**BigInt(t.e),o=t.d*10n**BigInt(e.e);o<0n&&(r=-r,o=-o);let s=r/o,i=r%o;if(i!==0n){let l=r<0n?-1n:1n,c=(i<0n?-i:i)*2n,u=c>o?1:c===o?0:-1;switch(n){case"half-away":u>=0&&(s+=l);break;case"half-down":u>0&&(s+=l);break;case"half-ceiling":(u>0||u===0&&r>0n)&&(s+=l);break;case"even":(u>0||u===0&&s%2n!==0n)&&(s+=l);break;case"down":break;case"floor":r<0n&&(s-=1n);break;case"ceiling":r>0n&&(s+=1n);break}}return Dt(s*t.d,t.e)}function ht(e){e.sharedMeta===!0&&(e.nl&&(e.nl=e.nl.slice()),e.pos&&(e.pos=e.pos.slice()),e.sharedMeta=void 0)}var ae={t:a.Unset},x={t:a.None},O={t:a.Logic,v:!0},xe={t:a.Logic,v:!1},Z=e=>e?O:xe,R=e=>({t:a.Integer,v:e}),me=e=>({t:a.Decimal,v:e}),mt=e=>({t:a.Percent,v:e}),rt=(e,t="")=>({t:a.Money,v:e,cur:t}),ot=e=>({t:a.Char,v:e}),gt=(e,t)=>({t:a.Pair,x:e,y:t}),Wr=e=>({t:a.Tuple,v:[...e]}),qt=e=>({t:a.Date,v:{...e}}),Te=e=>({t:a.Time,v:e}),Kt=e=>({t:a.Datatype,k:e}),Wt=e=>({t:a.Typeset,bits:e});function ue(e){let t=[];for(let n of e)t.push(n.codePointAt(0));return t}function nr(e){return{data:e}}function Go(e,t){return{t:e,s:nr(ue(t)),i:0}}var D=e=>Go(a.String,e);function jr(e){return{t:a.Binary,s:nr(e),i:0}}function li(e,t=!1){return{t:a.Bitset,s:nr(e),neg:t}}function Je(e,t,n=null){return{t:e,sym:typeof t=="string"?A(t):t,bind:n}}var ci=e=>Je(a.Word,e);function Ge(e,t,n=0){return{t:e,s:nr(t),i:n}}var Qe=e=>Ge(a.Block,e);function an(e){return{t:a.Map,s:nr(e)}}function Rr(e){return{t:a.Object,ctx:e}}function Ae(e=[],t=[],n=null){return{keys:e,vals:t,parent:n}}function $(e){return Oe(e.s.data,e.i)}function Oe(e,t=0,n=e.length){let r="";for(let o=t;o<n;o+=8192)r+=String.fromCodePoint(...e.slice(o,Math.min(o+8192,n)));return r}function ui(e,t){return e*1048576+t}function di(e){return{line:Math.floor(e/1048576),col:e%1048576}}function Fr(e,t){if(e.t!==t.t)return!1;let n=e,r=t;return n.ctx!==void 0?n.ctx===r.ctx:n.s!==void 0?n.s===r.s&&n.i===r.i:at(e,t)}function at(e,t){return Vo(e,t,new Set)}function Vo(e,t,n){if(e===t)return!0;if(e.t!==t.t)return!1;switch(e.t){case a.Unset:case a.None:return!0;case a.Logic:case a.Integer:case a.Char:case a.Time:return e.v===t.v;case a.Decimal:case a.Percent:return Object.is(e.v,t.v)||e.v===t.v;case a.Money:{let r=t;return e.cur.toUpperCase()===r.cur.toUpperCase()&&Dr(e.v,r.v)}case a.Pair:{let r=t;return e.x===r.x&&e.y===r.y}case a.Tuple:{let r=t;return e.v.length===r.v.length&&e.v.every((o,s)=>o===r.v[s])}case a.Date:{let r=e.v,o=t.v;return r.y===o.y&&r.m===o.m&&r.d===o.d&&r.time===o.time&&r.zone===o.zone}case a.String:case a.File:case a.Email:case a.Url:case a.Tag:case a.Binary:{let r=t;return si(e.s.data,e.i,r.s.data,r.i)}case a.Bitset:{let r=t;return e.neg===r.neg&&si(e.s.data,0,r.s.data,0)}case a.Word:case a.SetWord:case a.GetWord:case a.LitWord:case a.Refinement:case a.Issue:return e.sym===t.sym;case a.Block:case a.Paren:case a.Path:case a.SetPath:case a.GetPath:case a.LitPath:{let r=t;return ii(e.s,e.i,r.s,r.i,n)}case a.Map:return ii(e.s,0,t.s,0,n);case a.Object:case a.Error:{let r=e.ctx,o=t.ctx;return r===o?!0:r.keys.length!==o.keys.length?!1:n.has(r)?!0:(n.add(r),r.keys.every((s,i)=>Ys(s,o.keys[i])&&Vo(r.vals[i],o.vals[i],n)))}case a.Datatype:return e.k===t.k;case a.Typeset:return e.bits===t.bits;default:return e===t||e.p===t.p}}function si(e,t,n,r){if(e.length-t!==n.length-r)return!1;for(let o=0;o<e.length-t;o++)if(e[t+o]!==n[r+o])return!1;return!0}function ii(e,t,n,r,o){if(e===n&&t===r)return!0;if(e.data.length-t!==n.data.length-r)return!1;if(o.has(e))return!0;o.add(e);for(let s=0;s<e.data.length-t;s++)if(!Vo(e.data[t+s],n.data[r+s],o))return!1;return o.delete(e),!0}var rr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Hr(e,t){let n=e.replace(/\s+/g,""),r=[];if(t===16){if(!/^(?:[0-9A-Fa-f]{2})*$/.test(n))return null;for(let i=0;i<n.length;i+=2)r.push(parseInt(n.slice(i,i+2),16));return r}if(t===2){if(!/^(?:[01]{8})*$/.test(n))return null;for(let i=0;i<n.length;i+=8)r.push(parseInt(n.slice(i,i+8),2));return r}if(t!==64||!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4===1)return null;let o=0,s=0;for(let i of n.replace(/=+$/,""))o=o<<6|rr.indexOf(i),s+=6,s>=8&&(s-=8,r.push(o>>s&255));return r}function bi(e,t){if(t===16)return e.map(r=>r.toString(16).toUpperCase().padStart(2,"0")).join("");if(t===2)return e.map(r=>r.toString(2).padStart(8,"0")).join("");let n="";for(let r=0;r<e.length;r+=3){let o=e[r]<<16|(e[r+1]??0)<<8|(e[r+2]??0);n+=rr[o>>18&63]+rr[o>>12&63],n+=r+1<e.length?rr[o>>6&63]:"=",n+=r+2<e.length?rr[o&63]:"="}return n}var cu={null:0,back:8,tab:9,line:10,page:12,esc:27,del:127},uu={"/":10,"-":9,"@":0,"~":127,"[":27,"\\":28,"]":29,_:31};function Zo(e,t){let n=e[t];if(n===void 0)return null;if(n==="("){let s=e.indexOf(")",t+1);if(s<0)return null;let i=e.slice(t+1,s),l=cu[i.toLowerCase()];if(l!==void 0)return{cp:l,next:s+1};if(!/^[0-9A-Fa-f]{1,6}$/.test(i))return null;let c=parseInt(i,16);return c>1114111?null:{cp:c,next:s+1}}let r=uu[n];if(r!==void 0)return{cp:r,next:t+1};if(/[A-Za-z]/.test(n))return{cp:n.toUpperCase().charCodeAt(0)-64,next:t+1};let o=e.codePointAt(t);return{cp:o,next:t+(o>65535?2:1)}}function Yo(e,t,n=!1){switch(e){case 94:return"^^";case 10:return n?`
2
- `:"^/";case 9:return"^-";case 0:return"^@";case 127:return"^~"}return t==='"'&&e===34?'^"':e>=1&&e<=26||e===27||e===28||e===29||e===31?"^"+String.fromCharCode(64+e):e<32?"^("+e.toString(16).toUpperCase().padStart(2,"0")+")":String.fromCodePoint(e)}var st=class extends Error{line;col;file;constructor(t,n,r,o){super(`${o?o+":":""}${n}:${r}: ${t}`),this.name="LoadError",this.line=n,this.col=r,this.file=o}};function De(e,t={}){let n=new Xo(e,t.file);return{t:a.Block,s:n.parseSeries(null),i:0}}var Ve={integer:/^[+-]?\d[\d']*$/,decimal:/^[+-]?(?:\d[\d']*(?:[.,]\d*)?|[.,]\d+)(?:e[+-]?\d+)?$/i,percent:/^([+-]?(?:\d[\d']*(?:[.,]\d*)?|[.,]\d+)(?:e[+-]?\d+)?)%$/i,pair:/^([+-]?(?:\d[\d']*(?:[.,]\d*)?|[.,]\d+)(?:e[+-]?\d+)?)x([+-]?(?:\d[\d']*(?:[.,]\d*)?|[.,]\d+)(?:e[+-]?\d+)?)$/i,tuple:/^\d+(?:\.\d+){2,11}$/,time:/^([+-]?)(\d+):(\d+)(?::(\d+(?:[.,]\d+)?))?$/,date:/^(\d+)([-/])([A-Za-z]+|\d+)\2(\d+)(?:[/T](.+))?$/,dateTime:/^(\d+):(\d+)(?::(\d+(?:[.,]\d+)?))?(Z|[+-]\d{1,2}(?::?\d{2})?)?$/i,money:/^([+-]?)([A-Za-z]{3})?\$([+-]?)(\d[\d']*(?:[.,]\d*)?|[.,]\d+)$/,url:/^[A-Za-z][A-Za-z0-9+.-]*:\S+$/,email:/^[^@\s]+@[^@\s]*$/,wordBad:/[\s@#$%^,:'/\\"()[\]{};]/},du=["january","february","march","april","may","june","july","august","september","october","november","december"],pi=1e9;function Mn(e){return e===void 0||e===" "||e===" "||e===`
3
- `||e==="\r"||e==="["||e==="]"||e==="("||e===")"||e==="{"||e==="}"||e==='"'||e===";"||e==="\f"||e==="\v"}function Gt(e){return e===""?!1:e==="%"||e==="%%"?!0:!(Ve.wordBad.test(e)||/^[+-]?\.?\d/.test(e))}function zr(e){return Number(e.replace(/'/g,"").replace(",","."))}function bu(e,t){let n=e.replace(/'/g,"").replace(",","."),r=/^(.*?)(?:e([+-]?\d+))?$/i.exec(n);return+`${r[1]}e${Number(r[2]??0)+t}`}function pu(e,t){return t===2?e%4===0&&e%100!==0||e%400===0?29:28:[4,6,9,11].includes(t)?30:31}var Xo=class{i=0;line=1;lineStart=0;src;file;constructor(t,n){this.src=t.charCodeAt(0)===65279?t.slice(1):t,this.file=n}fail(t,n=this.i){let r=1,o=0;for(let s=0;s<n&&s<this.src.length;s++)this.src[s]===`
4
- `&&(r++,o=s+1);throw new st(t,r,n-o+1,this.file)}col(){return this.i-this.lineStart+1}newline(t){this.line++,this.lineStart=t+1}skipSpace(){let t=!1,n=this.src;for(;this.i<n.length;){let r=n[this.i];if(r===`
1
+ var xf=Object.defineProperty;var Cf=(e,t)=>{for(var n in t)xf(e,n,{get:t[n],enumerable:!0})};var s={Unset:0,None:1,Logic:2,Integer:3,Decimal:4,Percent:5,Money:6,Char:7,Pair:8,Tuple:9,Date:10,Time:11,String:12,File:13,Email:14,Url:15,Tag:16,Binary:17,Bitset:18,Word:19,SetWord:20,GetWord:21,LitWord:22,Refinement:23,Issue:24,Block:25,Paren:26,Path:27,SetPath:28,GetPath:29,LitPath:30,Map:31,Object:32,Error:33,Function:34,Native:35,Op:36,Datatype:37,Typeset:38,Handle:39},Nr=["unset!","none!","logic!","integer!","decimal!","percent!","money!","char!","pair!","tuple!","date!","time!","string!","file!","email!","url!","tag!","binary!","bitset!","word!","set-word!","get-word!","lit-word!","refinement!","issue!","block!","paren!","path!","set-path!","get-path!","lit-path!","map!","object!","error!","function!","native!","op!","datatype!","typeset!","handle!"],yl=Nr.length,za=new Map;Nr.forEach((e,t)=>za.set(e,t));function Vn(e){return za.get(e.toLowerCase())}function ie(e){return Nr[e]??"?!"}function Eo(e){let t=ie(e);return("aeiou".includes(t[0])?"an ":"a ")+t}function X(e){return e>=s.String&&e<=s.Tag}function le(e){return e>=s.Word&&e<=s.Issue}function _(e){return e>=s.Block&&e<=s.LitPath}function wl(e){return e>=s.String&&e<=s.Binary||_(e)}function Mo(e){let t=[];for(let n=0;n<yl;n++)t.push((e&1n<<BigInt(n))!==0n);return t}function Ee(e){return 1n<<BigInt(e)}function un(e,t){let n=0n;for(let r=e;r<=t;r++)n|=1n<<BigInt(r);return n}var vl=un(s.Unset,yl-1),jr={"any-type!":vl,"any-value!":vl&~Ee(s.Unset),"number!":Ee(s.Integer)|Ee(s.Decimal)|Ee(s.Percent),"scalar!":un(s.Logic,s.Time)&~Ee(s.Logic),"any-string!":un(s.String,s.Tag),"series!":un(s.String,s.Binary)|un(s.Block,s.LitPath),"any-word!":un(s.Word,s.Issue),"any-block!":un(s.Block,s.LitPath),"any-path!":un(s.Path,s.LitPath),"any-object!":Ee(s.Object)|Ee(s.Error),"any-function!":Ee(s.Function)|Ee(s.Native)|Ee(s.Op)};function kl(e){let t=e.toLowerCase(),n=za.get(t);return n!==void 0?Ee(n):jr[t]}var _a=[],To=[],xl=new Map;function A(e){let t=xl.get(e);if(t!==void 0)return t;let n=e.toLowerCase(),r=_a.length;return _a.push(e),xl.set(e,r),n===e?To.push(r):(To.push(-1),To[r]=A(n)),r}function M(e){let t=_a[e];if(t===void 0)throw new RangeError(`unknown symbol ${e}`);return t}function I(e){return To[e]??e}function Cl(e,t){return e===t||I(e)===I(t)}var pe={};Cf(pe,{add:()=>qa,cmp:()=>An,fromBig:()=>Ve,fromNumber:()=>Ya,isZero:()=>dn,mul:()=>Ga,neg:()=>Lo,parse:()=>Zn,quot:()=>Va,rem:()=>Yn,sub:()=>Ka,toNumber:()=>q,toString:()=>Pr});var Sf=-(2n**63n),Ef=2n**63n-1n,Mf=BigInt(Number.MIN_SAFE_INTEGER),Tf=BigInt(Number.MAX_SAFE_INTEGER);function Ve(e){return e>=Mf&&e<=Tf?Number(e):e<Sf||e>Ef?null:e}function kt(e){return typeof e=="bigint"?e:BigInt(e)}function qa(e,t){if(typeof e=="number"&&typeof t=="number"){let n=e+t;if(Number.isSafeInteger(n))return n}return Ve(kt(e)+kt(t))}function Ka(e,t){if(typeof e=="number"&&typeof t=="number"){let n=e-t;if(Number.isSafeInteger(n))return n}return Ve(kt(e)-kt(t))}function Ga(e,t){if(typeof e=="number"&&typeof t=="number"){let n=e*t;if(Number.isSafeInteger(n))return n===0?0:n}return Ve(kt(e)*kt(t))}function Lo(e){return typeof e=="number"?e===0?0:-e:Ve(-e)}function Va(e,t){if(t===0)return null;if(typeof e=="number"&&typeof t=="number"){let n=Math.trunc(e/t);return n===0?0:n}return Ve(kt(e)/kt(t))}function Yn(e,t){if(t===0)return null;if(typeof e=="number"&&typeof t=="number"){let n=e%t;return n===0?0:n}return Ve(kt(e)%kt(t))}function An(e,t){if(typeof e=="number"&&typeof t=="number")return e<t?-1:e>t?1:0;let n=kt(e),r=kt(t);return n<r?-1:n>r?1:0}function dn(e){return e===0||e===0n}function q(e){return typeof e=="number"?e:Number(e)}function Ya(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e);return Number.isSafeInteger(t)?t===0?0:t:Ve(BigInt(t))}function Zn(e){let t=e.replace(/'/g,"");if(!/^[+-]?\d+$/.test(t))return null;if(t.replace(/^[+-]/,"").length<=15){let n=Number(t);return n===0?0:n}return Ve(BigInt(t))}function Pr(e){return typeof e=="bigint"?e.toString():String(e)}function Xt(e,t){for(;t>0&&e%10n===0n;)e/=10n,t--;return e===0n&&(t=0),{d:e,e:t}}function El(e){let t=e.replace(/'/g,"").replace(",","."),n=/^([+-]?)(\d*)(?:\.(\d*))?$/.exec(t);if(!n)return null;let r=n[2]??"",o=n[3]??"";if(r===""&&o==="")return null;let a=BigInt((r||"0")+o);return Xt(n[1]==="-"?-a:a,o.length)}function zt(e,t=0){let n=e.d<0n,r=(n?-e.d:e.d).toString(),o=Math.max(e.e,t);return r=r+"0".repeat(o-e.e),o>0&&(r=r.padStart(o+1,"0"),r=r.slice(0,r.length-o)+"."+r.slice(r.length-o)),(n?"-":"")+r}function Ao(e,t){return e.d===t.d&&e.e===t.e}function xt(e){return Number(e.d)/10**e.e}function Io(e,t){let n=Math.max(e.e,t.e);return[e.d*10n**BigInt(n-e.e),t.d*10n**BigInt(n-t.e),n]}function Ml(e,t){let[n,r,o]=Io(e,t);return Xt(n+r,o)}function Tl(e,t){let[n,r,o]=Io(e,t);return Xt(n-r,o)}function Ll(e,t){return Xt(e.d*t.d,e.e+t.e)}var Sl=18;function Al(e,t){if(t.d===0n)return null;let n=e.d*10n**BigInt(Sl+t.e),r=t.d*10n**BigInt(e.e);r<0n&&(n=-n,r=-r);let o=n/r,a=n%r,i=(a<0n?-a:a)*2n;return(i>r||i===r&&o%2n!==0n)&&(o+=n<0n?-1n:1n),Xt(o,Sl)}function Il(e,t){let[n,r]=Io(e,t);return n<r?-1:n>r?1:0}function Qt(e){if(!Number.isFinite(e))return null;let t=/^(-?)(\d+)(?:\.(\d+))?(?:e([+-]\d+))?$/.exec(String(e));if(!t)return null;let n=t[3]??"",r=BigInt(t[2]+n),o=n.length-Number(t[4]??0);return o<0&&(r*=10n**BigInt(-o),o=0),Xt(t[1]==="-"?-r:r,o)}function $l(e){return Xt(e,0)}function Bl(e,t){if(t.d===0n)return null;let[n,r,o]=Io(e,t);return Xt(n%r,o)}function Za(e,t,n){if(t.d===0n)return null;let r=e.d*10n**BigInt(t.e),o=t.d*10n**BigInt(e.e);o<0n&&(r=-r,o=-o);let a=r/o,i=r%o;if(i!==0n){let l=r<0n?-1n:1n,c=(i<0n?-i:i)*2n,u=c>o?1:c===o?0:-1;switch(n){case"half-away":u>=0&&(a+=l);break;case"half-down":u>0&&(a+=l);break;case"half-ceiling":(u>0||u===0&&r>0n)&&(a+=l);break;case"even":(u>0||u===0&&a%2n!==0n)&&(a+=l);break;case"down":break;case"floor":r<0n&&(a-=1n);break;case"ceiling":r>0n&&(a+=1n);break}}return Xt(a*t.d,t.e)}function It(e){e.sharedMeta===!0&&(e.nl&&(e.nl=e.nl.slice()),e.pos&&(e.pos=e.pos.slice()),e.sharedMeta=void 0)}var re={t:s.Unset},k={t:s.None},P={t:s.Logic,v:!0},we={t:s.Logic,v:!1},ee=e=>e?P:we,H=e=>({t:s.Integer,v:e}),ke=e=>({t:s.Decimal,v:e}),$t=e=>({t:s.Percent,v:e}),ft=(e,t="")=>({t:s.Money,v:e,cur:t}),pt=e=>({t:s.Char,v:e}),Bt=(e,t)=>({t:s.Pair,x:e,y:t}),$o=e=>({t:s.Tuple,v:[...e]}),fn=e=>({t:s.Date,v:{...e}}),Ie=e=>({t:s.Time,v:e}),pn=e=>({t:s.Datatype,k:e}),en=e=>({t:s.Typeset,bits:e});function he(e){let t=[];for(let n of e)t.push(n.codePointAt(0));return t}function Dr(e){return{data:e}}function Ja(e,t){return{t:e,s:Dr(he(t)),i:0}}var j=e=>Ja(s.String,e);function Bo(e){return{t:s.Binary,s:Dr(e),i:0}}function jl(e,t=!1){return{t:s.Bitset,s:Dr(e),neg:t}}function st(e,t,n=null){return{t:e,sym:typeof t=="string"?A(t):t,bind:n}}var Pl=e=>st(s.Word,e);function Ye(e,t,n=0){return{t:e,s:Dr(t),i:n}}var it=e=>Ye(s.Block,e);function In(e){return{t:s.Map,s:Dr(e)}}function Oo(e){return{t:s.Object,ctx:e}}function Le(e=[],t=[],n=null){return{keys:e,vals:t,parent:n}}function B(e){return qe(e.s.data,e.i)}function qe(e,t=0,n=e.length){let r="";for(let o=t;o<n;o+=8192)r+=String.fromCodePoint(...e.slice(o,Math.min(o+8192,n)));return r}function Dl(e,t){return e*1048576+t}function Wl(e){return{line:Math.floor(e/1048576),col:e%1048576}}function No(e,t){if(e.t!==t.t)return!1;let n=e,r=t;return n.ctx!==void 0?n.ctx===r.ctx:n.s!==void 0?n.s===r.s&&n.i===r.i:bt(e,t)}function bt(e,t){return Xa(e,t,new Set)}function Xa(e,t,n){if(e===t)return!0;if(e.t!==t.t)return!1;switch(e.t){case s.Unset:case s.None:return!0;case s.Logic:case s.Integer:case s.Char:case s.Time:return e.v===t.v;case s.Decimal:case s.Percent:return Object.is(e.v,t.v)||e.v===t.v;case s.Money:{let r=t;return e.cur.toUpperCase()===r.cur.toUpperCase()&&Ao(e.v,r.v)}case s.Pair:{let r=t;return e.x===r.x&&e.y===r.y}case s.Tuple:{let r=t;return e.v.length===r.v.length&&e.v.every((o,a)=>o===r.v[a])}case s.Date:{let r=e.v,o=t.v;return r.y===o.y&&r.m===o.m&&r.d===o.d&&r.time===o.time&&r.zone===o.zone}case s.String:case s.File:case s.Email:case s.Url:case s.Tag:case s.Binary:{let r=t;return Ol(e.s.data,e.i,r.s.data,r.i)}case s.Bitset:{let r=t;return e.neg===r.neg&&Ol(e.s.data,0,r.s.data,0)}case s.Word:case s.SetWord:case s.GetWord:case s.LitWord:case s.Refinement:case s.Issue:return e.sym===t.sym;case s.Block:case s.Paren:case s.Path:case s.SetPath:case s.GetPath:case s.LitPath:{let r=t;return Nl(e.s,e.i,r.s,r.i,n)}case s.Map:return Nl(e.s,0,t.s,0,n);case s.Object:case s.Error:{let r=e.ctx,o=t.ctx;return r===o?!0:r.keys.length!==o.keys.length?!1:n.has(r)?!0:(n.add(r),r.keys.every((a,i)=>Cl(a,o.keys[i])&&Xa(r.vals[i],o.vals[i],n)))}case s.Datatype:return e.k===t.k;case s.Typeset:return e.bits===t.bits;default:return e===t||e.p===t.p}}function Ol(e,t,n,r){if(e.length-t!==n.length-r)return!1;for(let o=0;o<e.length-t;o++)if(e[t+o]!==n[r+o])return!1;return!0}function Nl(e,t,n,r,o){if(e===n&&t===r)return!0;if(e.data.length-t!==n.data.length-r)return!1;if(o.has(e))return!0;o.add(e);for(let a=0;a<e.data.length-t;a++)if(!Xa(e.data[t+a],n.data[r+a],o))return!1;return o.delete(e),!0}var Wr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function jo(e,t){let n=e.replace(/\s+/g,""),r=[];if(t===16){if(!/^(?:[0-9A-Fa-f]{2})*$/.test(n))return null;for(let i=0;i<n.length;i+=2)r.push(parseInt(n.slice(i,i+2),16));return r}if(t===2){if(!/^(?:[01]{8})*$/.test(n))return null;for(let i=0;i<n.length;i+=8)r.push(parseInt(n.slice(i,i+8),2));return r}if(t!==64||!/^[A-Za-z0-9+/]*={0,2}$/.test(n)||n.length%4===1)return null;let o=0,a=0;for(let i of n.replace(/=+$/,""))o=o<<6|Wr.indexOf(i),a+=6,a>=8&&(a-=8,r.push(o>>a&255));return r}function Rl(e,t){if(t===16)return e.map(r=>r.toString(16).toUpperCase().padStart(2,"0")).join("");if(t===2)return e.map(r=>r.toString(2).padStart(8,"0")).join("");let n="";for(let r=0;r<e.length;r+=3){let o=e[r]<<16|(e[r+1]??0)<<8|(e[r+2]??0);n+=Wr[o>>18&63]+Wr[o>>12&63],n+=r+1<e.length?Wr[o>>6&63]:"=",n+=r+2<e.length?Wr[o&63]:"="}return n}var Lf={null:0,back:8,tab:9,line:10,page:12,esc:27,del:127},Af={"/":10,"-":9,"@":0,"~":127,"[":27,"\\":28,"]":29,_:31};function Qa(e,t){let n=e[t];if(n===void 0)return null;if(n==="("){let a=e.indexOf(")",t+1);if(a<0)return null;let i=e.slice(t+1,a),l=Lf[i.toLowerCase()];if(l!==void 0)return{cp:l,next:a+1};if(!/^[0-9A-Fa-f]{1,6}$/.test(i))return null;let c=parseInt(i,16);return c>1114111?null:{cp:c,next:a+1}}let r=Af[n];if(r!==void 0)return{cp:r,next:t+1};if(/[A-Za-z]/.test(n))return{cp:n.toUpperCase().charCodeAt(0)-64,next:t+1};let o=e.codePointAt(t);return{cp:o,next:t+(o>65535?2:1)}}function es(e,t,n=!1){switch(e){case 94:return"^^";case 10:return n?`
2
+ `:"^/";case 9:return"^-";case 0:return"^@";case 127:return"^~"}return t==='"'&&e===34?'^"':e>=1&&e<=26||e===27||e===28||e===29||e===31?"^"+String.fromCharCode(64+e):e<32?"^("+e.toString(16).toUpperCase().padStart(2,"0")+")":String.fromCodePoint(e)}var rt=class extends Error{line;col;file;constructor(t,n,r,o){super(`${o?o+":":""}${n}:${r}: ${t}`),this.name="LoadError",this.line=n,this.col=r,this.file=o}};function me(e,t={}){let n=new ts(e,t.file);return{t:s.Block,s:n.parseSeries(null),i:0}}var nt={integer:/^[+-]?\d[\d']*$/,decimal:/^[+-]?(?:\d[\d']*(?:[.,]\d*)?|[.,]\d+)(?:e[+-]?\d+)?$/i,percent:/^([+-]?(?:\d[\d']*(?:[.,]\d*)?|[.,]\d+)(?:e[+-]?\d+)?)%$/i,pair:/^([+-]?(?:\d[\d']*(?:[.,]\d*)?|[.,]\d+)(?:e[+-]?\d+)?)x([+-]?(?:\d[\d']*(?:[.,]\d*)?|[.,]\d+)(?:e[+-]?\d+)?)$/i,tuple:/^\d+(?:\.\d+){2,11}$/,time:/^([+-]?)(\d+):(\d+)(?::(\d+(?:[.,]\d+)?))?$/,date:/^(\d+)([-/])([A-Za-z]+|\d+)\2(\d+)(?:[/T](.+))?$/,dateTime:/^(\d+):(\d+)(?::(\d+(?:[.,]\d+)?))?(Z|[+-]\d{1,2}(?::?\d{2})?)?$/i,money:/^([+-]?)([A-Za-z]{3})?\$([+-]?)(\d[\d']*(?:[.,]\d*)?|[.,]\d+)$/,url:/^[A-Za-z][A-Za-z0-9+.-]*:\S+$/,email:/^[^@\s]+@[^@\s]*$/,wordBad:/[\s@#$%^,:'/\\"()[\]{};]/},If=["january","february","march","april","may","june","july","august","september","october","november","december"],Fl=1e9;function Jn(e){return e===void 0||e===" "||e===" "||e===`
3
+ `||e==="\r"||e==="["||e==="]"||e==="("||e===")"||e==="{"||e==="}"||e==='"'||e===";"||e==="\f"||e==="\v"}function bn(e){return e===""?!1:e==="%"||e==="%%"?!0:!(nt.wordBad.test(e)||/^[+-]?\.?\d/.test(e))}function Po(e){return Number(e.replace(/'/g,"").replace(",","."))}function $f(e,t){let n=e.replace(/'/g,"").replace(",","."),r=/^(.*?)(?:e([+-]?\d+))?$/i.exec(n);return+`${r[1]}e${Number(r[2]??0)+t}`}function Bf(e,t){return t===2?e%4===0&&e%100!==0||e%400===0?29:28:[4,6,9,11].includes(t)?30:31}var ts=class{i=0;line=1;lineStart=0;src;file;constructor(t,n){this.src=t.charCodeAt(0)===65279?t.slice(1):t,this.file=n}fail(t,n=this.i){let r=1,o=0;for(let a=0;a<n&&a<this.src.length;a++)this.src[a]===`
4
+ `&&(r++,o=a+1);throw new rt(t,r,n-o+1,this.file)}col(){return this.i-this.lineStart+1}newline(t){this.line++,this.lineStart=t+1}skipSpace(){let t=!1,n=this.src;for(;this.i<n.length;){let r=n[this.i];if(r===`
5
5
  `)this.newline(this.i),t=!0,this.i++;else if(r===" "||r===" "||r==="\r"||r==="\f"||r==="\v")this.i++;else if(r===";")for(;this.i<n.length&&n[this.i]!==`
6
- `;)this.i++;else break}return t}parseSeries(t){let n=[],r=[],o=[],s=this.i-1;for(;;){let l=this.skipSpace(),c=this.src[this.i];if(c===void 0){t!==null&&this.fail(`missing ${t}`,s);break}if(c==="]"||c===")"){c!==t&&this.fail(`unexpected ${c}`),this.i++;break}let u=ui(this.line,this.col());n.push(this.parseValue()),r.push(l),o.push(u)}let i={data:n,nl:r,pos:o};return this.file!==void 0&&(i.file=this.file),i}parseValue(){let t=this.src;switch(t[this.i]){case"[":return this.i++,{t:a.Block,s:this.parseSeries("]"),i:0};case"(":return this.i++,{t:a.Paren,s:this.parseSeries(")"),i:0};case'"':return this.str(a.String,this.quoted());case"{":return this.str(a.String,this.braced());case"}":return this.fail("unexpected }");case"#":return this.hash();case"%":return this.percentSign();case"<":if(/[A-Za-z/!?]/.test(t[this.i+1]??""))return this.tag();break}let r=/^(2|16|64)#\{/.exec(t.slice(this.i,this.i+4));return r?(this.i+=r[1].length+1,this.binary(Number(r[1]))):this.atom()}str(t,n){return{t,s:{data:n},i:0}}quoted(){let t=this.src,n=this.i;this.i++;let r=[];for(;;){let o=t[this.i];if((o===void 0||o===`
7
- `)&&this.fail('missing " to close string',n),o==='"')return this.i++,r;if(o==="^"){let i=Zo(t,this.i+1);i||this.fail("invalid escape in string"),r.push(i.cp),this.i=i.next;continue}let s=t.codePointAt(this.i);r.push(s),this.i+=s>65535?2:1}}braced(){let t=this.src,n=this.i;this.i++;let r=[],o=1;for(;;){let s=t[this.i];if(s===void 0&&this.fail("missing } to close string",n),s==="^"){let l=Zo(t,this.i+1);l||this.fail("invalid escape in string"),r.push(l.cp),this.i=l.next;continue}if(s==="{"&&o++,s==="}"&&--o===0)return this.i++,r;s===`
8
- `&&this.newline(this.i);let i=t.codePointAt(this.i);r.push(i),this.i+=i>65535?2:1}}tag(){let t=this.src,n=this.i;this.i++;let r=null;for(;this.i<t.length;){let o=t[this.i];if(r)o===r&&(r=null);else if(o==='"'||o==="'")r=o;else if(o===">"){let s=t.slice(n+1,this.i);return this.i++,this.str(a.Tag,ue(s))}o===`
9
- `&&this.newline(this.i),this.i++}return this.fail("missing > to close tag",n)}hash(){let t=this.src[this.i+1];if(t==='"'){this.i++;let o=this.i,s=this.quoted();return s.length!==1&&this.fail("a char! must hold exactly one character",o),ot(s[0])}if(t==="{")return this.i++,this.binary(16);if(t==="["){this.i+=2;let o=this.i-2,s=this.parseSeries("]");return this.construct(s,o)}if(t==="("){this.i+=2;let o=this.i-2,s=this.parseSeries(")");return this.mapOf(s,o)}let n=this.i;this.i++;let r=this.span();return r===""&&this.fail("invalid issue",n),{t:a.Issue,sym:A(r),bind:null}}binary(t){let n=this.src,r=this.i,o=n.indexOf("}",this.i);o<0&&this.fail("missing } to close binary",r);let s=n.slice(this.i+1,o);for(let l=this.i;l<o;l++)n[l]===`
10
- `&&this.newline(l);this.i=o+1;let i=Hr(s,t);return i===null&&this.fail(`invalid ${t===16?"hex":`base-${t}`} binary`,r),{t:a.Binary,s:{data:i},i:0}}mapOf(t,n){t.data.length%2!==0&&this.fail("a map! needs key value pairs",n);let r=t.data.map((o,s)=>s%2===0&&o.t===a.SetWord?{t:a.Word,sym:o.sym,bind:null}:o);return{t:a.Map,s:{data:r}}}construct(t,n){let r=t.data,o=r[0],s=()=>this.fail("invalid construction syntax",n);if(!o||o.t!==a.Word)return s();let i=or(o).toLowerCase();if(r.length===1){switch(i){case"none":case"none!":return x;case"unset":case"unset!":return ae;case"true":return O;case"false":return xe}return s()}let l=wn(i);if(l===void 0)return s();let c=r[1];switch(l){case a.Logic:if(r.length===2&&c.t===a.Word){let d=or(c).toLowerCase();if(d==="true")return O;if(d==="false")return xe}return s();case a.Datatype:{if(r.length!==2||c.t!==a.Word)return s();let d=wn(or(c));return d===void 0?s():Kt(d)}case a.Typeset:{if(r.length!==2||c.t!==a.Block)return s();let d=0n;for(let f of c.s.data){let p=f.t===a.Word?wn(or(f)):void 0;if(p===void 0)return s();d|=1n<<BigInt(p)}return Wt(d)}case a.Bitset:{let d=r.length===3&&c.t===a.Word&&or(c).toLowerCase()==="not",f=d?r[2]:c;return f.t!==a.Binary||r.length!==(d?3:2)?s():li([...f.s.data],d)}case a.Object:{if(r.length!==2||c.t!==a.Block)return s();let d=Ae(),f=c.s.data;for(let p=0;p<f.length;p+=2){let h=f[p];if(h.t!==a.SetWord||p+1>=f.length)return s();d.keys.push(h.sym),d.vals.push(fu(f[p+1]))}return Rr(d)}case a.Map:return r.length!==2||c.t!==a.Block?s():this.mapOf(c.s,n)}let u=r[2];if(r.length===3&&u!==void 0&&u.t===a.Integer){let d=q(u.v)-1;if(!(V(l)&&V(c.t)||U(l)&&U(c.t))||d<0)return s();let p=c;return d>p.s.data.length?s():{...p,t:l,i:d}}return s()}percentSign(){let t=this.src;if(t[this.i+1]==='"')return this.i++,this.str(a.File,this.quoted());let r=this.i;for(;!Mn(t[r]);)r++;if(/^%%?:?$/.test(t.slice(this.i,r)))return this.atom();let o=this.i;this.i++;let s=this.span();try{return this.str(a.File,ue(decodeURIComponent(s)))}catch{return this.fail("invalid file",o)}}span(){let t=this.src,n=this.i;for(;!Mn(t[this.i]);)this.i++;return t.slice(n,this.i)}atom(){let t=this.i,n=this.span();if(n.endsWith("/")&&this.src[this.i]==="("&&n.length>1&&!Ve.url.test(n))return this.i=t,this.path();let r=this.classify(n,t);return r==="path"?(this.i=t,this.path()):r}classify(t,n){let r=t[0];if(r==="'"||r===":"){let o=t.slice(1);return Gt(o)?this.wordCell(r==="'"?a.LitWord:a.GetWord,o):o.includes("/")&&!o.startsWith("/")?"path":this.fail(`invalid ${r==="'"?"lit-word":"get-word"}: ${t}`,n)}if(t.endsWith(":")&&t.length>1){let o=t.slice(0,-1);if(Gt(o))return this.wordCell(a.SetWord,o);if(o.includes("/")&&!o.startsWith("/")&&!/^[+-]?\d/.test(o))return"path"}if(/^[+-]?[\d.,$]/.test(t)&&!Gt(t)){let o=this.number(t,n);if(o)return o}if(Ve.money.test(t))return this.number(t,n);if(Ve.url.test(t))return this.str(a.Url,ue(t));if(Ve.email.test(t)&&r!=="/")return this.str(a.Email,ue(t));if(r==="/"){if(t==="/"||t==="//")return this.wordCell(a.Word,t);let o=t.slice(1);return Gt(o)?this.wordCell(a.Refinement,o):this.fail(`invalid refinement: ${t}`,n)}return t.includes("/")?"path":Gt(t)?this.wordCell(a.Word,t):this.fail(`invalid value: ${t}`,n)}wordCell(t,n){return{t,sym:A(n),bind:null}}number(t,n){let r;if(Ve.integer.test(t)){let o=Sn(t);return o===null&&this.fail(`integer out of 64-bit range: ${t}`,n),R(o)}if(Ve.decimal.test(t))return me(zr(t));if(r=Ve.percent.exec(t))return mt(bu(r[1],-2));if(r=Ve.money.exec(t)){let o=Js(r[4]),s=r[1]==="-"!=(r[3]==="-");return rt(s?{d:-o.d,e:o.e}:o,(r[2]??"").toUpperCase())}if(r=Ve.pair.exec(t))return gt(zr(r[1]),zr(r[2]));if(Ve.tuple.test(t)){let o=t.split(".").map(Number);return o.some(s=>s>255)&&this.fail(`tuple values must be 0-255: ${t}`,n),Wr(o)}if(r=Ve.time.exec(t)){let o=fi(r[2],r[3],r[4]);return Te(r[1]==="-"?-o:o)}return(r=Ve.date.exec(t))?this.dateCell(r,t,n):null}dateCell(t,n,r){let[,o,,s,i,l]=t,c,u;o.length>=3?(c=Number(o),u=Number(i)):(u=Number(o),c=Number(i));let d;if(/^\d+$/.test(s))d=Number(s);else{let p=s.toLowerCase();d=p.length>=3?du.findIndex(h=>h.startsWith(p))+1:0}(d<1||d>12||u<1||u>pu(c,d))&&this.fail(`invalid date: ${n}`,r);let f={y:c,m:d,d:u,time:null,zone:null};if(l!==void 0){let p=Ve.dateTime.exec(l);p||this.fail(`invalid time in date: ${n}`,r),f.time=fi(p[1],p[2],p[3]),p[4]!==void 0&&(f.zone=hu(p[4]))}return qt(f)}path(){let t=this.src,n=this.i,r=a.Path;t[this.i]===":"?(r=a.GetPath,this.i++):t[this.i]==="'"&&(r=a.LitPath,this.i++);let o=[];for(;;){if(t[this.i]==="(")this.i++,o.push({t:a.Paren,s:this.parseSeries(")"),i:0});else{let s=this.i;for(;!Mn(t[this.i])&&t[this.i]!=="/";)this.i++;let i=t.slice(s,this.i);i.endsWith(":")&&Mn(t[this.i])&&r===a.Path&&o.length>0&&(r=a.SetPath,i=i.slice(0,-1)),o.push(this.segment(i,s))}if(t[this.i]==="/"){this.i++,Mn(t[this.i])&&t[this.i]!=="("&&this.fail("path ends with /",n);continue}(!Mn(t[this.i])||t[this.i]==="(")&&this.fail("invalid path",n);break}return o[0].t!==a.Word&&o[0].t!==a.Paren&&this.fail("a path must start with a word",n),{t:r,s:{data:o},i:0}}segment(t,n){if(t===""&&this.fail("empty path segment",n),Ve.integer.test(t)){let r=Sn(t);if(r!==null)return R(r)}return t[0]===":"&&Gt(t.slice(1))?this.wordCell(a.GetWord,t.slice(1)):t[0]==="'"&&Gt(t.slice(1))?this.wordCell(a.LitWord,t.slice(1)):Gt(t)?this.wordCell(a.Word,t):this.fail(`invalid path segment: ${t}`,n)}};function or(e){return"sym"in e?E(e.sym):""}function fu(e){if(e.t===a.Word)switch(E(e.sym).toLowerCase()){case"none":return x;case"true":return O;case"false":return xe}return e}function fi(e,t,n){let r=Number(e)*3600+Number(t)*60,o=n===void 0?0:zr(n);return Math.round(r*pi+o*pi)}function hu(e){if(e==="Z"||e==="z")return 0;let t=/^([+-])(\d{1,2})(?::?(\d{2}))?$/.exec(e),n=Number(t[2])*60+Number(t[3]??0);return t[1]==="-"?-n:n}var mu=8;function ee(e,t){let n=L(t),r=e.keys;if(r.length<=mu&&e.idx===void 0){for(let i=0;i<r.length;i++)if(L(r[i])===n)return i;return-1}let o=e.idx,s=e.idxN??0;for(o===void 0&&(o=new Map,e.idx=o,s=0);s<r.length;s++){let i=L(r[s]);o.has(i)||o.set(i,s)}return e.idxN=s,o.get(n)??-1}function _r(e,t,n=ae){return e.keys.push(t),e.vals.push(n),e.keys.length-1}function mi(e,t){let n=ee(e,t);return n>=0?n:_r(e,t)}function ge(e){let t=e.bind;if(t!==null&&e.idx!==void 0)return t.vals[e.idx];for(let n=t;n!==null;n=n.parent){let r=ee(n,e.sym);if(r>=0)return n.vals[r];if(n.self===!0&&L(e.sym)===gi)return{t:a.Object,ctx:n}}return null}var gi=L(A("self"));function ar(e,t,n=new Set){if(n.has(e))return;n.add(e);let r=e.data;for(let o=0;o<r.length;o++){let s=r[o];Ur(s)&&L(s.sym)===gi?r[o]={t:s.t,sym:s.sym,bind:t}:U(s.t)&&ar(s.s,t,n)}}function Jo(e,t,n){e.vals[t]=n,e.watch!==void 0&&e.dirty!==!0&&(e.dirty=!0,e.watch.push(e))}function Ie(e,t){let n=e.bind;return n===null?!1:(Jo(n,e.idx??mi(n,e.sym),t),!0)}function Ur(e){return e.t===a.Word||e.t===a.SetWord||e.t===a.GetWord||e.t===a.LitWord}function ve(e,t,n=!1,r=new Set){if(r.has(e))return;r.add(e);let o=e.data;for(let s=0;s<o.length;s++){let i=o[s];if(Ur(i)){if(i.bind===t&&i.idx!==void 0)continue;let l=ee(t,i.sym);l<0&&n&&(l=_r(t,i.sym,gu(t,i.sym))),l>=0&&(o[s]={t:i.t,sym:i.sym,bind:t,idx:l})}else U(i.t)&&ve(i.s,t,n,r)}}function gu(e,t){for(let n=e.parent;n!==null;n=n.parent){let r=ee(n,t);if(r>=0)return n.vals[r]}return ae}function qr(e,t,n){let r=e.data;for(let o=t;o<r.length;o++){let s=r[o];s.t===a.SetWord&&mi(n,s.sym)}}var hi=new WeakMap;function vu(e,t){let n=new Map,r=new Set,o=!1,s=i=>{if(r.has(i)){o=!0;return}r.add(i);let l=[],c=[];i.data.forEach((u,d)=>{Ur(u)&&u.bind===t?l.push(d):U(u.t)&&(c.push(d),s(u.s))}),n.set(i,{words:l,blocks:c})};return s(e),o?null:n}function vi(e,t,n){let r=hi.get(e);if(r===void 0&&(r=vu(e,t),hi.set(e,r)),r===null)return we(e,0,t,n);let o=r,s=i=>{let l=o.get(i),c={data:i.data.slice()};(i.nl||i.pos)&&(c.nl=i.nl,c.pos=i.pos,c.sharedMeta=!0),i.file!==void 0&&(c.file=i.file);let u=c.data;for(let d of l.words){let f=u[d];u[d]=f.idx===void 0?{t:f.t,sym:f.sym,bind:n}:{t:f.t,sym:f.sym,bind:n,idx:f.idx}}for(let d of l.blocks){let f=u[d];u[d]={t:f.t,s:s(f.s),i:f.i}}return c};return s(e)}function we(e,t=0,n=null,r=null){return yi(e,t,n,r,new Map)}function yi(e,t,n,r,o){let s=t===0;if(s){let c=o.get(e);if(c!==void 0)return c}let i={data:[]};s&&o.set(e,i),e.nl&&(i.nl=e.nl.slice(t)),e.pos&&(i.pos=e.pos.slice(t)),e.file!==void 0&&(i.file=e.file);let l=e.data;for(let c=t;c<l.length;c++){let u=l[c];if(n!==null&&Ur(u)&&u.bind===n)i.data.push(u.idx===void 0?{t:u.t,sym:u.sym,bind:r}:{t:u.t,sym:u.sym,bind:r,idx:u.idx});else if(U(u.t)){let d=u;i.data.push({t:d.t,s:yi(d.s,0,n,r,o),i:d.i})}else i.data.push(u)}return i}var yu=["type","id","message","near","where","at"],ku=yu.map(e=>A(e));function X(e,t,n){let r={keys:[...ku],vals:[Je(a.Word,e),Je(a.Word,t),D(n),x,x,x],parent:null};return{t:a.Error,ctx:r}}function En(e,t){let n=ee(e.ctx,A(t));return n>=0?e.ctx.vals[n]:x}function sn(e,t,n){let r=ee(e.ctx,A(t));r>=0&&e.ctx.vals[r].t===a.None&&(e.ctx.vals[r]=n)}function Tn(e){let t=En(e,"type"),n=En(e,"message"),r=t.t===a.Word?E(t.sym):"user",o=n.t===a.String?$(n):"";return`${r.charAt(0).toUpperCase()}${r.slice(1)} error: ${o}`}function J(e,t={}){let n=new ea(t.all??!1);return t.only&&(e.t===a.Block||e.t===a.Paren)?n.contents(e.s,e.i,-1):n.value(e,0),n.out}function j(e){switch(e.t){case a.Unset:return"";case a.String:case a.File:case a.Email:case a.Url:return Oe(e.s.data,e.i);case a.Char:return String.fromCodePoint(e.v);case a.Word:case a.SetWord:case a.GetWord:case a.LitWord:case a.Refinement:case a.Issue:return E(e.sym);case a.Block:case a.Paren:return e.s.data.slice(e.i).map(j).join(" ");case a.Object:return e.ctx.keys.map((t,n)=>`${E(t)}: ${j(e.ctx.vals[n])}`).join(`
11
- `);case a.Error:return xu(e);default:return J(e)}}function xu(e){let t=[`** ${Tn(e)}`],n=En(e,"where"),r=En(e,"near"),o=En(e,"at");return n.t!==a.None&&t.push(`** Where: ${j(n)}`),r.t!==a.None&&t.push(`** Near: ${J(r)}`),o.t!==a.None&&t.push(`** At: ${j(o)}`),t.join(`
12
- `)}var wu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function xi(e,t=!0){if(Number.isNaN(e))return"1.#NaN";if(!Number.isFinite(e))return e>0?"1.#INF":"-1.#INF";let n=String(t?e:Number(e.toPrecision(15)));if(n.includes("e")){n=n.replace("e+","e");let[r,o]=n.split("e");n=(r.includes(".")?r:r+".0")+"e"+o}else n.includes(".")||(n+=".0");return n}function Cu(e,t){t||(e=Number(e.toPrecision(15)));for(let n=1;n<=17;n++){let r=String(Number((e*100).toPrecision(n))).replace("e+","e"),[o,s]=r.split("e");if(+`${o}e${Number(s??0)-2}`===e)return r+"%"}return String(e*100).replace("e+","e")+"%"}function ki(e){return Number.isInteger(e)?String(e):String(e).replace("e+","e")}function sr(e){let t=Math.floor(e/1e9),n=e-t*1e9,r=Math.floor(t/3600),o=Math.floor(t/60)%60,s=t%60,i=`${r}:${String(o).padStart(2,"0")}`;return(s!==0||n!==0)&&(i+=":"+String(s).padStart(2,"0"),n!==0&&(i+="."+String(n).padStart(9,"0").replace(/0+$/,""))),i}function Su(e){let t=e<0?"-":"+",n=Math.abs(e);return`${t}${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function wi(e){let t=`${e.d}-${wu[e.m-1]}-${e.y}`;return e.time!==null&&(t+="/"+sr(e.time),e.zone!==null&&(t+=Su(e.zone))),t}function Mu(e,t){let n=!1,r=0,o=!0;for(let i=t;i<e.length;i++){let l=e[i];(l===10||l===34)&&(n=!0),l===123&&r++,l===125&&--r<0&&(o=!1)}r!==0&&(o=!1);let s=n?"{":'"';for(let i=t;i<e.length;i++){let l=e[i];n&&!o&&(l===123||l===125)?s+="^"+String.fromCodePoint(l):s+=Yo(l,n?"}":'"',n)}return s+(n?"}":'"')}var Eu=/[A-Za-z0-9._~/:+\-!*',=@&$?#\u0080-\u{10FFFF}]/u;function Tu(e,t){if(e.length===t)return'%""';let n="%";for(let r=t;r<e.length;r++){let o=String.fromCodePoint(e[r]);n+=Eu.test(o)?o:[...new TextEncoder().encode(o)].map(s=>"%"+s.toString(16).toUpperCase().padStart(2,"0")).join("")}return n}function Qo(e,t=0){let n="";for(let r=t;r<e.length;r++)n+=e[r].toString(16).toUpperCase().padStart(2,"0");return n}var Kr=" ",ea=class{out="";all;active=new Set;constructor(t){this.all=t}value(t,n){let r=this.all;switch(t.t){case a.Unset:this.out+=r?"#[unset]":"";return;case a.None:this.out+=r?"#[none]":"none";return;case a.Logic:this.out+=r?`#[${t.v}]`:String(t.v);return;case a.Integer:this.out+=tr(t.v);return;case a.Decimal:this.out+=xi(t.v,r);return;case a.Percent:this.out+=Cu(t.v,r);return;case a.Money:{let o=t.v.d<0n,s=o?{d:-t.v.d,e:t.v.e}:t.v;this.out+=(o?"-":"")+t.cur+"$"+Mt(s,2);return}case a.Char:this.out+='#"'+Yo(t.v,'"')+'"';return;case a.Pair:this.out+=ki(t.x)+"x"+ki(t.y);return;case a.Tuple:this.out+=t.v.join(".");return;case a.Date:this.out+=wi(t.v);return;case a.Time:this.out+=(t.v<0?"-":"")+sr(Math.abs(t.v));return;case a.String:this.indexed(t,()=>Mu(t.s.data,r?0:t.i));return;case a.File:this.indexed(t,()=>Tu(t.s.data,r?0:t.i));return;case a.Email:case a.Url:this.indexed(t,()=>Oe(t.s.data,r?0:t.i));return;case a.Tag:this.indexed(t,()=>"<"+Oe(t.s.data,r?0:t.i)+">");return;case a.Binary:this.indexed(t,()=>"#{"+Qo(t.s.data,r?0:t.i)+"}");return;case a.Bitset:{let o=(t.neg?"not ":"")+"#{"+Qo(t.s.data)+"}";this.out+=r?`#[bitset! ${o}]`:`make bitset! ${t.neg?"[not bits ":""}#{${Qo(t.s.data)}}${t.neg?"]":""}`;return}case a.Word:this.out+=E(t.sym);return;case a.SetWord:this.out+=E(t.sym)+":";return;case a.GetWord:this.out+=":"+E(t.sym);return;case a.LitWord:this.out+="'"+E(t.sym);return;case a.Refinement:this.out+="/"+E(t.sym);return;case a.Issue:this.out+="#"+E(t.sym);return;case a.Block:this.blockLike(t,"[","]",n);return;case a.Paren:this.blockLike(t,"(",")",n);return;case a.Path:case a.SetPath:case a.GetPath:case a.LitPath:this.path(t,n);return;case a.Map:this.map(t.s,n);return;case a.Object:this.object(t.ctx,n,r?null:"make object!");return;case a.Error:this.object(t.ctx,n,"make error!");return;case a.Datatype:this.out+=r?`#[datatype! ${re(t.k)}]`:re(t.k);return;case a.Typeset:{let o=[];for(let s=0;s<64;s++)t.bits>>BigInt(s)&1n&&o.push(re(s));this.out+=r?`#[typeset! [${o.join(" ")}]]`:`make typeset! [${o.join(" ")}]`;return}case a.Function:{if(r)break;let o=t.p;this.out+="func ",this.blockLike(o.specBlock,"[","]",n),this.out+=" ",this.blockLike({t:a.Block,s:o.body,i:0},"[","]",n);return}}this.out+=`#[${re(t.t)}]`}indexed(t,n){this.all&&t.i>0?this.out+=`#[${re(t.t)} ${n()} ${t.i+1}]`:this.out+=n()}blockLike(t,n,r,o){if(this.all&&t.i>0){this.out+=`#[${re(t.t)} `,this.blockLike({...t,i:0},n,r,o),this.out+=` ${t.i+1}]`;return}if(this.active.has(t.s)){this.out+=n+"..."+r;return}this.out+=n,this.contents(t.s,t.i,o)&&(this.out+=`
13
- `+Kr.repeat(o)),this.out+=r}contents(t,n,r){this.active.add(t);let o=!1,s=Kr.repeat(r+1);for(let i=n;i<t.data.length;i++)t.nl?.[i]&&(i>n||r>=0)?(this.out+=`
14
- `+s,o=!0):i>n&&(this.out+=" "),this.value(t.data[i],r+1);return this.active.delete(t),o}path(t,n){t.t===a.GetPath&&(this.out+=":"),t.t===a.LitPath&&(this.out+="'"),t.s.data.slice(t.i).forEach((r,o)=>{o>0&&(this.out+="/"),this.value(r,n)}),t.t===a.SetPath&&(this.out+=":")}map(t,n){if(this.active.has(t)){this.out+="#(...)";return}this.active.add(t),this.out+="#(";for(let r=0;r<t.data.length;r+=2){r>0&&(this.out+=" ");let o=t.data[r];o.t===a.Word?this.out+=E(o.sym)+":":this.value(o,n+1),this.out+=" ",this.value(t.data[r+1],n+1)}this.out+=")",this.active.delete(t)}object(t,n,r){if(this.active.has(t)){this.out+=r===null?"#[object! [...]]":r+" [...]";return}this.active.add(t),this.out+=r===null?"#[object! [":r+" [";let o=Kr.repeat(n+1);t.keys.forEach((s,i)=>{let l=t.vals[i];this.out+=`
15
- `+o+E(s)+": ",r!==null&&(l.t===a.Word||l.t===a.Path)&&(this.out+="'"),this.value(l,n+1)}),t.keys.length>0&&(this.out+=`
16
- `+Kr.repeat(n)),this.out+=r===null?"]]":"]",this.active.delete(t)}};function ta(e,t){let n=e.pos?.[t];if(n===void 0||n<0)return null;let{line:r,col:o}=di(n);return`${e.file?e.file+":":""}${r}:${o}`}var Be={Arg:0,Lit:1,Get:2,Ref:3,Local:4},Iu=er["any-value!"],Ci=ke(a.Logic)|ke(a.None),Lu=A("local"),Au=A("return");function na(e){let t=[],n=[],r=null,o=-1,s=!1,i=e.s.data;for(let l=e.i;l<i.length;l++){let c=i[l];switch(c.t){case a.String:continue;case a.Word:case a.LitWord:case a.GetWord:{if(t.some(p=>L(p.sym)===L(c.sym)))return`duplicate parameter ${E(c.sym)}`;let u=s?Be.Local:c.t===a.Word?Be.Arg:c.t===a.LitWord?Be.Lit:Be.Get;if(s&&c.t!==a.Word)return`bad local ${E(c.sym)}`;let d=Iu,f=i[l+1];if(!s&&f!==void 0&&f.t===a.Block){let p=In(f);if(typeof p=="string")return p;d=p,l++}u!==Be.Local&&o<0&&n.push(t.length),t.push({sym:c.sym,kind:u,types:d,allows:$r(d),ref:s?-1:o});continue}case a.Refinement:{if(L(c.sym)===L(Lu)){s=!0;continue}if(s)return`refinement /${E(c.sym)} after /local`;if(t.some(u=>L(u.sym)===L(c.sym)))return`duplicate parameter ${E(c.sym)}`;o=t.length,t.push({sym:c.sym,kind:Be.Ref,types:Ci,allows:$r(Ci),ref:-1});continue}case a.SetWord:{let u=i[l+1];if(L(c.sym)!==L(Au)||u===void 0||u.t!==a.Block)return`bad spec item ${E(c.sym)}:`;let d=In(u);if(typeof d=="string")return d;r=d,l++;continue}default:return"bad spec item"}}return{params:t,base:n,ret:r,retAllows:r===null?null:$r(r),blank:t.map(()=>x)}}function In(e){let t=0n;for(let n of e.s.data.slice(e.i)){let r=n.t===a.Word?Vs(E(n.sym)):n.t===a.Datatype?ke(n.k):n.t===a.Typeset?n.bits:void 0;if(r===void 0)return"bad type in spec";t|=r}return t}function Si(e,t){let n=na(e);if(typeof n=="string")return n;let r=Ae(n.params.map(s=>s.sym)),o=we(t.s,t.i);return ve(o,r),{spec:n,specBlock:{t:a.Block,s:we(e.s,e.i),i:0},body:o,tmpl:r}}var Gr=e=>e.t===a.Integer||e.t===a.Decimal||e.t===a.Percent||e.t===a.Money;function Et(e){switch(e.t){case a.Integer:return typeof e.v=="bigint"?oi(e.v):Pt(e.v);case a.Decimal:case a.Percent:return Pt(e.v);case a.Money:return e.v}return null}function Ii(e,t){if(e.t===a.Integer&&t.t===a.Integer)return on(e.v,t.v);if(e.t===a.Money&&t.t===a.Money&&e.cur!==""&&t.cur!==""&&e.cur.toUpperCase()!==t.cur.toUpperCase())return null;let n=Et(e),r=Et(t);if(n===null||r===null){let o=e.t===a.Decimal||e.t===a.Percent?e.v:NaN,s=t.t===a.Decimal||t.t===a.Percent?t.v:NaN;return Number.isNaN(o)||Number.isNaN(s)?null:o<s?-1:o>s?1:0}return ri(n,r)}function Li(e,t){let n=e.s.data,r=t.s.data,o=Math.min(n.length-e.i,r.length-t.i);for(let l=0;l<o;l++){let c=Pe(n[e.i+l]),u=Pe(r[t.i+l]);if(c!==u)return c<u?-1:1}let s=n.length-e.i,i=r.length-t.i;return s<i?-1:s>i?1:0}function Pe(e){if(e>=65&&e<=90)return e+32;if(e<128)return e;let t=String.fromCodePoint(e).toLowerCase();return t.length===1||t.codePointAt(0)>65535?t.codePointAt(0):e}var Bu=10n,Ai=new Float64Array(1),$u=new BigInt64Array(Ai.buffer);function Mi(e){Ai[0]=e;let t=$u[0];return t<0n?-(t&0x7fffffffffffffffn):t}function Nu(e,t){if(e===t)return!0;if(!Number.isFinite(e)||!Number.isFinite(t))return!1;let n=Mi(e)-Mi(t);return(n<0n?-n:n)<=Bu}var Ei=e=>e.t===a.Decimal||e.t===a.Percent;function dt(e,t){if(e===t)return!0;if(Gr(e)&&Gr(t)){if((Ei(e)||Ei(t))&&e.t!==a.Money&&t.t!==a.Money){let n=r=>r.t===a.Integer?q(r.v):r.v;return Nu(n(e),n(t))}return Ii(e,t)===0}if(V(e.t)&&V(t.t))return Li(e,t)===0;if(e.t===a.Char&&t.t===a.Char)return Pe(e.v)===Pe(t.v);if(oe(e.t)&&oe(t.t))return L(e.sym)===L(t.sym);if(U(e.t)&&e.t===t.t){let n=e,r=t,o=n.s.data.length-n.i;if(o!==r.s.data.length-r.i)return!1;for(let s=0;s<o;s++)if(!dt(n.s.data[n.i+s],r.s.data[r.i+s]))return!1;return!0}return at(e,t)}function ln(e,t){if(Gr(e)&&Gr(t))return Ii(e,t);if(V(e.t)&&V(t.t))return Li(e,t);if(e.t===a.Char&&t.t===a.Char){let n=Pe(e.v),r=Pe(t.v);return n<r?-1:n>r?1:0}if(e.t===a.Time&&t.t===a.Time)return e.v<t.v?-1:e.v>t.v?1:0;if(e.t===a.Date&&t.t===a.Date){let n=Ti(e.v),r=Ti(t.v);return n<r?-1:n>r?1:0}if(e.t===a.Pair&&t.t===a.Pair)return e.y!==t.y?e.y<t.y?-1:1:e.x<t.x?-1:e.x>t.x?1:0;if(e.t===a.Tuple&&t.t===a.Tuple){let n=Math.max(e.v.length,t.v.length);for(let r=0;r<n;r++){let o=e.v[r]??0,s=t.v[r]??0;if(o!==s)return o<s?-1:1}return 0}if(e.t===a.Logic&&t.t===a.Logic)return e.v===t.v?0:e.v?1:-1;if(oe(e.t)&&oe(t.t)){let n=E(L(e.sym)),r=E(L(t.sym));return n<r?-1:n>r?1:0}return null}function Ti(e){return Date.UTC(e.y,e.m-1,e.d)+(e.time??0)/1e6-(e.zone??0)*6e4}function Di(e,t){return oe(e.t)&&oe(t.t)?L(e.sym)===L(t.sym):at(e,t)}function Pi(e,t){for(let n=0;n<e.data.length;n+=2)if(Di(e.data[n],t))return n+1;return-1}function Zr(e,t,n){for(let r=t;r<e.data.length;r++)if(Di(e.data[r],n))return r;return-1}function Vt(e){return e.t!==a.Integer?null:q(e.v)-1}var Ou=["year","month","day","time","zone","date","weekday","yearday","hour","minute","second"],Bi=["hour","minute","second"],$i=36e11,ra=6e10,Ni=864e5;function Vr(e){return oe(e.t)?E(L(e.sym)):null}function bt(e,t){switch(e.t){case a.Url:case a.File:if(oe(t.t)||V(t.t)||t.t===a.Integer){let n=e.s.data.slice(e.i),r=ue(oe(t.t)?E(t.sym):V(t.t)?Oe(t.s.data,t.i):J(t)),o=n[n.length-1]===47?[]:[47],s=r[0]===47?r.slice(1):r;return{t:e.t,s:{data:[...n,...o,...s]},i:0}}break;case a.Email:{let n=Vr(t);if(n==="user"||n==="host"){let r=e.s.data.slice(e.i),o=r.indexOf(64),s=n==="user"?o<0?r:r.slice(0,o):o<0?[]:r.slice(o+1);return{t:a.String,s:{data:s},i:0}}break}case a.Object:case a.Error:{if(!oe(t.t))return`cannot pick ${J(t)} in an object`;let n=ee(e.ctx,t.sym);return n<0?`${J(t)} is not a field of the object`:e.ctx.vals[n]}case a.Map:{let n=Pi(e.s,t);return n<0?x:e.s.data[n]}case a.Pair:{let n=Vr(t),r=Vt(t);return n==="x"||r===0?Oi(e.x):n==="y"||r===1?Oi(e.y):`cannot pick ${J(t)} in a pair`}case a.Tuple:{let n=Vt(t);if(n===null)return`cannot pick ${J(t)} in a tuple`;let r=e.v[n];return r===void 0?x:R(r)}case a.Date:{let n=Vr(t)??Ou[Vt(t)??-1]??null,r=e.v;switch(n){case"year":return R(r.y);case"month":return R(r.m);case"day":return R(r.d);case"time":return r.time===null?x:Te(r.time);case"zone":return r.zone===null?x:Te(r.zone*ra);case"date":return qt({y:r.y,m:r.m,d:r.d,time:null,zone:null});case"weekday":return R((Date.UTC(r.y,r.m-1,r.d)/Ni%7+10)%7+1);case"yearday":return R((Date.UTC(r.y,r.m-1,r.d)-Date.UTC(r.y,0,1))/Ni+1);case"hour":case"minute":case"second":return r.time===null?x:bt(Te(r.time),t.t===a.Integer?R(Bi.indexOf(n)+1):t)}return`cannot pick ${J(t)} in a date`}case a.Time:{let n=Vr(t)??Bi[Vt(t)??-1]??null,r=Math.abs(e.v),o=e.v<0?-1:1;switch(n){case"hour":return R(o*Math.floor(r/$i));case"minute":return R(o*Math.floor(r%$i/ra));case"second":{let s=r%ra/1e9;return Number.isInteger(s)?R(o*s):me(o*s)}}return`cannot pick ${J(t)} in a time`}}if(U(e.t)){let n=e,r=Vt(t);if(r!==null)return(r>=0?n.s.data[n.i+r]:void 0)??x;let o=Zr(n.s,n.i,t);return o<0?x:n.s.data[o+1]??x}if(V(e.t)||e.t===a.Binary){let n=e,r=Vt(t);if(r===null)return`cannot pick ${J(t)} in ${Br(e.t)}`;let o=r>=0?n.s.data[n.i+r]:void 0;return o===void 0?x:e.t===a.Binary?R(o):ot(o)}return`cannot pick ${J(t)} in ${Br(e.t)}`}function Oi(e){return Number.isInteger(e)?R(e):me(e)}function Ln(e,t,n){switch(e.t){case a.Object:case a.Error:{if(!oe(t.t))return`cannot set ${J(t)} in an object`;let r=ee(e.ctx,t.sym);return r<0?`${J(t)} is not a field of the object`:(Jo(e.ctx,r,n),null)}case a.Map:{let r=Pi(e.s,t);if(r>=0)e.s.data[r]=n;else{let o=oe(t.t)?{t:a.Word,sym:t.sym,bind:null}:t;e.s.data.push(o,n)}return null}}if(U(e.t)){let r=e,o=Vt(t);if(o!==null)return o<0||r.i+o>=r.s.data.length?`index ${o+1} is out of range`:(r.s.data[r.i+o]=n,null);let s=Zr(r.s,r.i,t);return s<0||s+1>=r.s.data.length?`${J(t)} not found in the block`:(r.s.data[s+1]=n,null)}if(e.t===a.String){let r=e,o=Vt(t);return o===null||n.t!==a.Char?`cannot set ${J(t)} in a string`:o<0||r.i+o>=r.s.data.length?`index ${o+1} is out of range`:(r.s.data[r.i+o]=n.v,null)}return`cannot set ${J(t)} in ${Br(e.t)}`}function Wi(e){return Math.max(0,e.s.data.length-e.i)}function Bn(e,t){return Math.max(0,Math.min(e.s.data.length,t))}function He(e,t){return{...e,i:Bn(e,t)}}function ze(e,t,n,r,o){ht(e),e.data.splice(t,n,...r),e.nl!==void 0&&e.nl.splice(t,n,...r.map((s,i)=>o?.[i]??!1)),e.pos!==void 0&&e.pos.splice(t,n,...r.map(()=>-1))}function cn(e){return[...new TextEncoder().encode(e)]}function $n(e,t,n){if(U(e)){if(!n&&t.t===a.Block){let r=t;return{add:r.s.data.slice(r.i),nl:r.s.nl?.slice(r.i)}}return{add:[t]}}if(e===a.Binary)return t.t===a.Binary?{add:t.s.data.slice(t.i)}:t.t===a.Integer?{add:[Number(t.v)&255]}:t.t===a.Char?{add:cn(String.fromCodePoint(t.v))}:{add:cn(An(t))};if(t.t===a.Char)return{add:[t.v]};if(V(t.t)&&(t.t!==a.Tag||e===a.Tag)){let r=t;return{add:r.s.data.slice(r.i)}}return{add:ue(An(t))}}function An(e){return e.t===a.Block?e.s.data.slice(e.i).map(An).join(""):j(e)}var F={Error:0,Break:1,Continue:2,Return:3,Throw:4},Xr=new Set(["mezzanines"]),Ri=e=>e.file!==void 0&&Xr.has(e.file);function Yr(e){for(let t=e.stack.length-2;t>=0;t--){let n=e.stack[t];if(n.k===Q.Expr||n.k===Q.Do||n.k===Q.Set)return Ri(n.feed.s)}return!1}var Q={Do:0,Expr:1,Set:2,Args:3,Native:4,Call:5,Path:6},Nn={Call:0,Get:1,Set:2},Tt={Start:0,Walk:1,WaitKey:2,WaitValue:3},dn=[];function ia(e,t){let n={...e,id:dn.length};return dn.push({def:n,fn:t}),{t:a.Native,p:n}}function Fi(){return dn.map(e=>e.def)}function ir(e,t,n=0){let r={rt:e,stack:[],v:null,thrown:null,waiting:null};return Dn(r,t,n),r}function la(e,t){e.waiting=null,e.v=t}function ca(e,t){e.waiting=null,e.thrown={kind:F.Error,v:t,name:null}}function lr(e,t=1/0){if(e.waiting!==null)return{k:"await",p:e.waiting};for(let n=0;n<t;n++){if(e.thrown!==null){let o=Du(e);if(o!==null)return o;continue}let r=e.stack[e.stack.length-1];if(r===void 0)return{k:"done",v:e.v??ae};switch(r.k){case Q.Do:r.state===0?Pu(e,r):oa(e,r);break;case Q.Expr:r.state===0?sa(e,r):oa(e,r);break;case Q.Set:r.state===0?sa(e,r):oa(e,r);break;case Q.Args:Hi(e,r);break;case Q.Native:{let o=e.v;e.v=null,Qr(e,r,dn[r.def.id].fn(e,r,o));break}case Q.Call:{let o=e.v??ae;e.v=null,e.stack.pop(),zi(e,r,o);break}case Q.Path:Hu(e,r);break}if(e.waiting!==null)return{k:"await",p:e.waiting}}return{k:"yield"}}function ua(e){for(let t=e.stack.length-1;t>=0;t--){let n=e.stack[t];if((n.k===Q.Do||n.k===Q.Expr)&&n.feed.s.file!==void 0)return n.feed.s.file}return null}function te(e,t,n){return{k:"throw",e:{kind:F.Error,v:X(e,t,n),name:null}}}function Ne(e,t,n,r){e.v=null,e.thrown={kind:F.Error,v:X(t,n,r),name:null}}var On=e=>e===null?"function":E(e);function Du(e){let t=e.thrown,n=e.stack[e.stack.length-1];if(n===void 0)return e.thrown=null,{k:"error",e:ji(t)};let r=t.kind===F.Error?t.v:null;switch(n.k){case Q.Native:if(n.trap&1<<t.kind)return n.thrown=t,e.thrown=null,e.v=null,Qr(e,n,dn[n.def.id].fn(e,n,null)),null;r!==null&&n.name!==null&&!Yr(e)&&sn(r,"where",{t:a.Word,sym:n.name,bind:null});break;case Q.Call:if(t.kind===F.Return)return e.stack.pop(),e.thrown=null,zi(e,n,t.v),null;if(t.kind===F.Break||t.kind===F.Continue)return e.thrown={kind:F.Error,v:ji(t),name:null},null;r!==null&&n.name!==null&&!Yr(e)&&sn(r,"where",{t:a.Word,sym:n.name,bind:null});break;case Q.Args:r!==null&&n.name!==null&&!Yr(e)&&sn(r,"where",{t:a.Word,sym:n.name,bind:null});break;case Q.Do:case Q.Expr:case Q.Set:if(r!==null&&(n.k!==Q.Do||n.state===1)&&!Ri(n.feed.s)){let o=n.feed.s,s=Math.max(n.feed.i,n.start+1);sn(r,"near",Ge(a.Block,o.data.slice(n.start,Math.min(s,n.start+4))));let i=ta(o,n.start);i!==null&&sn(r,"at",D(i))}break}return e.stack.pop(),null}function ji(e){switch(e.kind){case F.Error:return e.v;case F.Break:return X("script","no-loop","break used outside of a loop");case F.Continue:return X("script","no-loop","continue used outside of a loop");case F.Return:return X("script","no-function","return used outside of a function");default:return X("script","no-catch","throw has no catch")}}function Dn(e,t,n){e.stack.push({k:Q.Do,feed:{s:t,i:n},out:ae,infix:!0,start:n,state:0})}function da(e,t,n){e.stack.push({k:Q.Expr,feed:t,infix:n,start:t.i,state:0})}function Pu(e,t){if(e.v!==null&&(t.out=e.v,e.v=null),t.feed.i>=t.feed.s.data.length){e.stack.pop(),e.v=t.out;return}sa(e,t)}function sa(e,t){let n=t.feed,r=n.s.data;t.start=n.i,t.state=1;let o=r[n.i++];switch(o.t){case a.Word:{let s=ge(o);if(s===null)return un(e,o);switch(s.t){case a.Function:case a.Native:return Pn(e,n,s,o.sym,null,null);case a.Op:return Ne(e,"script","no-op-arg",`${E(o.sym)} operator is missing its left argument`);case a.Unset:return Ne(e,"script","no-value",`${E(o.sym)} has no value`)}e.v=s;return}case a.SetWord:{if(n.i>=r.length)return Ne(e,"script","need-value",`${E(o.sym)}: needs a value`);let s=Jr(r[n.i]);if(s!==null&&s.t!==a.Unset&&!ba(r[n.i+1])){if(n.i++,!Ie(o,s))return un(e,o);e.v=s;return}e.stack.push({k:Q.Set,w:o,feed:n,infix:!0,start:n.i,state:0});return}case a.GetWord:{let s=ge(o);if(s===null)return un(e,o);e.v=s;return}case a.LitWord:e.v={t:a.Word,sym:o.sym,bind:o.bind};return;case a.Paren:Dn(e,o.s,o.i);return;case a.Path:case a.GetPath:e.stack.push({k:Q.Path,feed:n,path:o,mode:o.t===a.Path?Nn.Call:Nn.Get,state:Tt.Start,j:0,cur:x,setv:x});return;case a.SetPath:if(n.i>=r.length)return Ne(e,"script","need-value","set-path needs a value");e.stack.push({k:Q.Path,feed:n,path:o,mode:Nn.Set,state:Tt.WaitValue,j:0,cur:x,setv:x}),da(e,n,!0);return;case a.LitPath:e.v={t:a.Path,s:o.s,i:o.i};return;case a.Function:case a.Native:return Pn(e,n,o,null,null,null)}e.v=o}function oa(e,t){if(t.infix){let n=t.feed.s.data[t.feed.i];if(n!==void 0&&n.t===a.Word){let r=ge(n);if(r!==null&&r.t===a.Op){t.feed.i++;let o=e.v;e.v=null;let s=r.p.fn;Wu(e,t.feed,s,n.sym,o)||Pn(e,t.feed,s,n.sym,null,o);return}}}t.k===Q.Do?t.state=0:t.k===Q.Set?ju(e,t):e.stack.pop()}function Wu(e,t,n,r,o){if(n.t!==a.Native)return!1;let s=n.p,i=s.spec.params;if(i.length!==2||i[0].kind!==Be.Arg||i[1].kind!==Be.Arg)return!1;let l=t.s.data[t.i],c=l===void 0?null:Jr(l);if(c===null||!i[0].allows[o.t]||!i[1].allows[c.t])return!1;t.i++;let u={k:Q.Native,def:s,args:[o,c],phase:0,data:null,trap:0,thrown:null,name:r};return e.stack.push(u),Qr(e,u,dn[s.id].fn(e,u,null)),!0}function ju(e,t){let n=e.v;if(e.stack.pop(),n.t===a.Unset)return Ne(e,"script","need-value",`${E(t.w.sym)}: needs a value`);if(!Ie(t.w,n))return un(e,t.w)}function un(e,t){t.bind===null?Ne(e,"script","not-bound",`${E(t.sym)} is not bound to a context`):Ne(e,"script","no-value",`${E(t.sym)} has no value`)}function Ru(e){return e.t===a.Native,e.p.spec}function Pn(e,t,n,r,o,s){if(n.t!==a.Function&&n.t!==a.Native)return Ne(e,"script","not-function",`${On(r)} is not a function`);let i=Ru(n),l=i.blank.slice(),c=i.base;if(o!==null&&o.length>0){c=c.slice();for(let f of o){let p=f.t===a.Word?i.params.findIndex(h=>h.kind===Be.Ref&&L(h.sym)===L(f.sym)):-1;if(p<0){let h=f.t===a.Word?E(f.sym):"that";return Ne(e,"script","bad-refine",`${On(r)} has no refinement called ${h}`)}l[p]=O,i.params.forEach((h,y)=>{h.ref===p&&c.push(y)})}}let u=0;if(s!==null){if(c.length<2)return Ne(e,"script","bad-op",`${On(r)} needs two arguments to be an operator`);l[c[0]]=s,u=1}let d={k:Q.Args,feed:t,fn:n,spec:i,vals:l,plan:c,n:u,name:r,op:s!==null};if(e.stack.push(d),t!==null&&s===null){let f=t.s.data;for(;d.n<c.length;){let p=i.params[c[d.n]],h=f[t.i];if(h===void 0||p.kind!==Be.Arg)break;let y=Jr(h);if(y===null||ba(f[t.i+1]))break;t.i++,l[c[d.n++]]=y}d.n===c.length&&Hi(e,d)}}function Jr(e){switch(e.t){case a.Word:case a.GetWord:{let t=ge(e);return t===null||e.t===a.Word&&(t.t===a.Function||t.t===a.Native||t.t===a.Op||t.t===a.Unset)?null:t}case a.SetWord:case a.LitWord:case a.Paren:case a.Path:case a.GetPath:case a.SetPath:case a.LitPath:case a.Function:case a.Native:return null}return e}function ba(e){if(e===void 0||e.t!==a.Word)return!1;let t=ge(e);return t!==null&&t.t===a.Op}function Hi(e,t){e.v!==null&&(t.vals[t.plan[t.n++]]=e.v,e.v=null);let n=t.spec.params;if(t.n<t.plan.length){let i=n[t.plan[t.n]],l=t.feed;if(l===null||l.i>=l.s.data.length)return Ne(e,"script","no-arg",`${On(t.name)} is missing its ${E(i.sym)} argument`);if(i.kind===Be.Arg){let u=Jr(l.s.data[l.i]);if(u!==null&&(t.op||!ba(l.s.data[l.i+1]))){l.i++,e.v=u;return}return da(e,l,!t.op)}let c=l.s.data[l.i++];if(i.kind===Be.Lit&&c.t===a.Paren)return Dn(e,c.s,c.i);if(i.kind===Be.Lit&&c.t===a.GetWord){let u=ge(c);if(u===null)return un(e,c);e.v=u;return}e.v=c;return}for(let i of t.plan){let l=n[i],c=t.vals[i];if(!l.allows[c.t])return Ne(e,"script","expect-arg",`${On(t.name)} does not allow ${re(c.t)} for its ${E(l.sym)} argument`)}if(e.stack.pop(),t.fn.t===a.Native){let i=t.fn.p,l={k:Q.Native,def:i,args:t.vals,phase:0,data:null,trap:0,thrown:null,name:t.name};e.stack.push(l),Qr(e,l,dn[i.id].fn(e,l,null));return}let r=t.fn.p,o={keys:r.tmpl.keys,vals:t.vals,parent:null},s=vi(r.body,r.tmpl,o);e.stack.push({k:Q.Call,def:r,name:t.name}),Dn(e,s,0)}function zi(e,t,n){if(t.def.spec.ret!==null&&!t.def.spec.retAllows[n.t])return Ne(e,"script","bad-return",`${On(t.name)} does not allow ${re(n.t)} as its result`);e.v=n}function Qr(e,t,n){switch(n.k){case"value":e.stack.pop(),e.v=n.v;return;case"do":Dn(e,n.s,n.i);return;case"expr":da(e,n.feed,!0);return;case"call":{let r=e.stack.length;Pn(e,null,n.fn,t.name,null,null);let o=e.stack[e.stack.length-1];if(e.stack.length>r&&o!==void 0&&o.k===Q.Args){if(n.full){Fu(o,n.args);return}let s=Math.min(n.args.length,o.plan.length);for(let i=0;i<s;i++)o.vals[o.plan[i]]=n.args[i];o.n=s}return}case"await":e.waiting=n.p;return;case"throw":{let r=n.e;r.kind===F.Error&&t.name!==null&&!Yr(e)&&sn(r.v,"where",{t:a.Word,sym:t.name,bind:null}),e.stack.pop(),e.thrown=r;return}}}function Fu(e,t){let n=e.spec.params;e.plan=[];let r=0,o=!0;for(let s=0;s<n.length;s++){let i=n[s];if(i.kind===Be.Local)continue;let l=t[r++]??x;i.kind===Be.Ref?(o=l.t!==a.None&&!(l.t===a.Logic&&!l.v),e.vals[s]=o?O:x):(i.ref<0||o)&&(e.vals[s]=l,e.plan.push(s))}e.n=e.plan.length}function Hu(e,t){let n=t.path.s.data;switch(t.state){case Tt.WaitValue:if(t.setv=e.v,e.v=null,t.setv.t===a.Unset)return Ne(e,"script","need-value","set-path needs a value");t.state=Tt.Start;return;case Tt.Start:{let r=n[t.path.i];if(r===void 0||r.t!==a.Word)return Ne(e,"script","bad-path","a path must start with a word");let o=ge(r);return o===null?un(e,r):o.t===a.Unset?Ne(e,"script","no-value",`${E(r.sym)} has no value`):(t.cur=o,t.j=t.path.i+1,t.state=Tt.Walk,t.mode===Nn.Call&&(o.t===a.Function||o.t===a.Native)?(e.stack.pop(),Pn(e,t.feed,o,r.sym,n.slice(t.j),null)):void 0)}case Tt.WaitKey:{let r=e.v;return e.v=null,t.state=Tt.Walk,aa(e,t,r)}case Tt.Walk:{if(t.j>=n.length){e.stack.pop(),e.v=t.cur;return}let r=n[t.j];if(r.t===a.Paren){t.state=Tt.WaitKey,Dn(e,r.s,r.i);return}if(r.t===a.GetWord){let o=ge(r);return o===null?un(e,r):aa(e,t,o)}return aa(e,t,r)}}}function aa(e,t,n){let r=t.path.s.data,o=r[t.j];if(t.j++,t.mode===Nn.Set&&t.j>=r.length){let i=Ln(t.cur,n,t.setv);if(i!==null)return Ne(e,"script","bad-path-set",i);e.stack.pop(),e.v=t.setv;return}let s=bt(t.cur,n);if(typeof s=="string")return Ne(e,"script","bad-path",s);t.cur=s,t.mode===Nn.Call&&(s.t===a.Function||s.t===a.Native)&&(e.stack.pop(),Pn(e,t.feed,s,o.t===a.Word?o.sym:null,r.slice(t.j),null))}function g(e,t,n){let r=De(t).s.data[0],o=na(r);if(typeof o=="string")throw new Error(`bad spec for native ${e}: ${o}`);ia({name:e,spec:o,specBlock:r},n)}var pa=[];function Ce(e,t){pa.push([e,t])}var b=e=>({k:"value",v:e}),B=te;function Le(e){return!(e.t===a.None||e.t===a.Logic&&!e.v)}function de(e){return{k:"do",s:e.s,i:e.i}}function bn(e,t,n,r){let o=ee(e.rt.lib,A(t)),s=o<0?void 0:e.rt.lib.vals[o];return s===void 0||s.t!==a.Native&&s.t!==a.Function?te("access","no-host",`this host cannot ${r}`):{k:"call",fn:s,args:n}}var zu=L(A("trebol"));function jt(e){let t=e.s.data,n=t[e.i],r=t[e.i+1];return n?.t===a.Word&&L(n.sym)===zu&&r?.t===a.Block?{header:r,start:e.i+2}:{header:null,start:e.i}}function _u(e){let{start:t}=jt(e);t!==e.i&&(ze(e.s,e.i,t-e.i,[]),e.s.nl!==void 0&&e.s.nl.length>e.i&&(e.s.nl[e.i]=!1))}function eo(e,t){let n;try{n=De($(t))}catch(r){if(r instanceof st)return B("syntax","load",r.message);throw r}return _u(n),ve(n.s,e.user,!0),b(n)}g("load",'["Reads Trebol source text, or a file of it, into values: the value itself, or a block when there are several." source [string! binary! file! url!] /all "Gives a block even for one value"]',(e,t,n)=>{let r=t.args[0];if(r.t===a.Binary&&(r=D(new TextDecoder().decode(new Uint8Array(r.s.data.slice(r.i))))),t.phase===0&&r.t!==a.String)return t.phase=1,bn(e,"read",[r],"read files");let o=eo(e.rt,t.phase===1?n:r);if(o.k!=="value"||t.args[1]===O)return o;let s=o.v;return s.s.data.length===1?b(s.s.data[0]):o});g("mold",'["The value as Trebol source text, the way you would type it." value [any-type!] /only /all]',(e,t)=>b(D(J(t.args[0],{only:t.args[1]===O,all:t.args[2]===O}))));g("form",'["The value as text for people to read." value [any-type!]]',(e,t)=>b(D(j(t.args[0]))));function Uu(e,t,n){let r=Ae();if(e!==null){r.keys.push(...e.keys);for(let s of e.vals)r.vals.push(qu(s,e,r))}qr(t.s,t.i,r);let o=we(t.s,t.i);return ve(o,r),n===a.Object&&(r.self=!0,ar(o,r)),{obj:{t:n,ctx:r},body:o}}function qu(e,t,n){if(U(e.t)){let r=e;return{t:r.t,s:we(r.s,0,t,n),i:r.i}}if(e.t===a.Function){let r=e.p;return{t:a.Function,p:{...r,body:we(r.body,0,t,n)}}}if(V(e.t)||e.t===a.Binary){let r=e;return{t:r.t,s:{data:r.s.data.slice()},i:r.i}}return e}function Ku(e,t){switch(e){case a.Function:{if(t.t!==a.Block)break;let[n,r]=t.s.data.slice(t.i);if(n?.t!==a.Block||r?.t!==a.Block)return"make function! needs [spec body]";let o=Si(n,r);return typeof o=="string"?`bad function spec: ${o}`:{t:a.Function,p:o}}case a.Op:{if(t.t!==a.Function&&t.t!==a.Native)break;return{t:a.Op,p:{fn:t}}}case a.Map:{if(t.t!==a.Block)break;let n=t.s.data.slice(t.i);return n.length%2!==0?"make map! needs key value pairs":{t:a.Map,s:{data:n.map((r,o)=>o%2===0&&oe(r.t)?{t:a.Word,sym:r.sym,bind:null}:r)}}}case a.Block:case a.Paren:if(t.t===a.Integer)return{t:e,s:{data:[]},i:0};if(U(t.t))return{t:e,s:{data:t.s.data.slice(t.i)},i:0};break;case a.String:case a.File:case a.Email:case a.Url:case a.Tag:return t.t===a.Integer?{t:e,s:{data:[]},i:0}:{t:e,s:{data:ue(j(t))},i:0};case a.Pair:{if(t.t!==a.Block)break;let[n,r]=t.s.data.slice(t.i),o=l=>l?.t===a.Integer?q(l.v):l?.t===a.Decimal?l.v:null,s=o(n),i=o(r);return s===null||i===null?"make pair! needs two numbers":gt(s,i)}case a.Typeset:{if(t.t!==a.Block)break;let n=In(t);return typeof n=="string"?n:Wt(n)}case a.Error:if(t.t===a.String)return X("user","message",$(t));break}return`cannot make ${re(e)} from ${re(t.t)}`}g("make",'["Makes a new value of a type, or from a prototype object." type [any-value!] spec [any-value!]]',(e,t)=>{if(t.phase===1)return b(t.data);let n=t.args[0],r=t.args[1],o=null,s=a.Object;if(n.t===a.Datatype&&(n.k===a.Object||n.k===a.Error&&r.t===a.Block))n.k===a.Error&&(o=X("user","message","").ctx,s=a.Error);else if(n.t===a.Object||n.t===a.Error)o=n.ctx,s=n.t;else if(n.t===a.Datatype){let c=Ku(n.k,r);return typeof c=="string"?B("script","bad-make",c):b(c)}else return B("script","bad-make",`cannot make from ${re(n.t)}`);if(r.t!==a.Block)return B("script","bad-make",`make ${re(s)} needs a block`);let{obj:i,body:l}=Uu(o,r,s);return t.phase=1,t.data=i,{k:"do",s:l,i:0}});g("get",'["The value a word refers to." word [any-word!] /any]',(e,t)=>{let n=t.args[0],r=ge(n);return r===null?B("script","not-bound",`${E(n.sym)} is not bound to a context`):r.t===a.Unset&&t.args[1]!==O?B("script","no-value",`${E(n.sym)} has no value`):b(r)});g("set",'["Sets a word, or each word of a block, to a value." word [any-word! block!] value [any-type!]]',(e,t)=>{let n=t.args[0],r=t.args[1],o=n.t===a.Block?n.s.data.slice(n.i):[n];for(let s=0;s<o.length;s++){let i=o[s];if(!oe(i.t))return B("script","bad-set",`cannot set ${J(i)}`);let l=n.t===a.Block&&r.t===a.Block?r.s.data[r.i+s]??x:r;if(!Ie(i,l))return B("script","not-bound",`${E(i.sym)} is not bound to a context`)}return b(r)});g("value?",'["True if the word has a value." word [any-word!]]',(e,t)=>{let n=ge(t.args[0]);return b(n!==null&&n.t!==a.Unset?O:xe)});g("type?",'["The datatype of a value." value [any-type!]]',(e,t)=>b(Kt(t.args[0].t)));var fa=e=>e.t===a.Op?e.p.fn:e;g("spec-of",`["A copy of a function's spec block." value [any-function!]]`,(e,t)=>{let n=fa(t.args[0]),r=n.p,o=(n.t===a.Function,r.specBlock);return b({t:a.Block,s:we(o.s,o.i),i:0})});g("body-of",`["A copy of a function's body block, or none for a native." value [any-function!]]`,(e,t)=>{let n=fa(t.args[0]);return b(n.t===a.Function?{t:a.Block,s:we(n.p.body),i:0}:x)});g("words-of",'["The words of an object or map, or the arguments, refinements and local words of a function." value [any-object! map! any-function!]]',(e,t)=>{let n=fa(t.args[0]);if(n.t===a.Object||n.t===a.Error)return b(Ge(a.Block,n.ctx.keys.map(l=>Je(a.Word,l))));if(n.t===a.Map)return b(Ge(a.Block,n.s.data.filter((l,c)=>c%2===0)));let r=n.p,o=(n.t===a.Function,r.spec),s=[],i=!1;for(let l of o.params)l.kind===Be.Local&&!i&&(s.push(Je(a.Refinement,A("local"))),i=!0),s.push(Je(l.kind===Be.Ref?a.Refinement:a.Word,l.sym));return b(Ge(a.Block,s))});g("values-of",'["The values of an object or map." value [any-object! map!]]',(e,t)=>{let n=t.args[0];return n.t===a.Map?b(Ge(a.Block,n.s.data.filter((r,o)=>o%2===1))):b(Ge(a.Block,n.ctx.vals.slice()))});g("bind",'["Binds the words of a block to a context." words [block! any-word!] context [any-word! any-object!] /new /copy "Binds a deep copy and leaves the block as it was"]',(e,t)=>{let n=t.args[0],r=t.args[1],o=r.t===a.Object||r.t===a.Error?r.ctx:r.bind;if(o===null)return B("script","not-bound",`${J(r)} is not bound to a context`);let s=t.args[2]===O;if(n.t!==a.Block){let i=n;return!s&&ee(o,i.sym)<0?b(i):b({t:i.t,sym:i.sym,bind:o})}return t.args[3]===O&&(n={t:n.t,s:we(n.s,n.i),i:0}),ve(n.s,o,s),b(n)});g("context?",'["The context a word is bound to, or none." word [any-word!]]',(e,t)=>{let n=t.args[0].bind;return b(n===null?x:Rr(n))});g("unset",'["Takes the value away from a word, or from each word of a block." word [any-word! block!]]',(e,t)=>{let n=t.args[0],r=n.t===a.Block?n.s.data.slice(n.i):[n];for(let o of r){if(!oe(o.t))return B("script","bad-set",`cannot unset ${J(o)}`);if(!Ie(o,ae))return B("script","not-bound",`${E(o.sym)} is not bound to a context`)}return b(ae)});g("in",'["The word of an object, bound to it, or none if the object has no such word." object [any-object!] word [any-word!]]',(e,t)=>{let n=t.args[0],r=t.args[1];return b(ee(n.ctx,r.sym)>=0?{t:a.Word,sym:r.sym,bind:n.ctx}:x)});g("use",'["Evaluates a block with words of its own, which exist only inside it." words [block! word!] body [block!]]',(e,t,n)=>{if(t.phase===1)return b(n);let r=t.args[0],o=r.t===a.Block?r.s.data.slice(r.i):[r];if(o.some(c=>!oe(c.t)))return B("script","bad-words","use needs a block of words");let s=Ae(o.map(c=>c.sym),o.map(()=>x)),i=t.args[1],l=we(i.s,i.i);return ve(l,s),t.phase=1,de({t:a.Block,s:l,i:0})});g("length?",`["The number of values from the series' position to its tail." series [series! map! object!]]`,(e,t)=>{let n=t.args[0];if(n.t===a.Map)return b({t:a.Integer,v:n.s.data.length/2});if(n.t===a.Object||n.t===a.Error)return b({t:a.Integer,v:n.ctx.keys.length});let r=n;return b({t:a.Integer,v:Math.max(0,r.s.data.length-r.i)})});g("pick",'["The value at a position or key." series [any-value!] index [any-value!]]',(e,t)=>{let n=bt(t.args[0],t.args[1]);return typeof n=="string"?B("script","bad-pick",n):b(n)});g("poke",'["Sets the value at a position or key; gives the value." series [any-value!] index [any-value!] value [any-value!]]',(e,t)=>{let n=Ln(t.args[0],t.args[1],t.args[2]);return n!==null?B("script","bad-poke",n):b(t.args[2])});g("put",'["Sets the value of a key; gives the value." series [map! object! block!] key [any-value!] value [any-value!]]',(e,t)=>{let[n,r,o]=t.args;if(n.t===a.Block){let i=Zr(n.s,n.i,r);if(i<0||i+1>=n.s.data.length){let l=i<0?[r,o]:[o];ht(n.s),n.s.data.push(...l),n.s.nl&&n.s.nl.push(...l.map(()=>!1)),n.s.pos&&n.s.pos.push(...l.map(()=>-1))}else n.s.data[i+1]=o;return b(o)}let s=Ln(n,r,o);return s!==null?B("script","bad-poke",s):b(o)});var cr=1<<F.Break|1<<F.Continue;function Wn(e){let t=e.thrown;return e.thrown=null,t}g("do",'["Evaluates a block, source text or a script file; gives the last value." value [any-type!] /next "Evaluates only the first expression of a block" position [word!] "Set to the block after it"]',(e,t,n)=>{if(t.phase===1)return b(n);let r=t.args[0];if(t.args[1]===O){if(r.t===a.String&&t.phase===0){let s=eo(e.rt,r);if(s.k!=="value")return s;r=t.args[0]=s.v}if(r.t!==a.Block&&r.t!==a.Paren)return Ie(t.args[2],x),r.t===a.Error?{k:"throw",e:{kind:F.Error,v:r,name:null}}:b(r);let o=r;if(t.phase===2){let s=t.data;return Ie(t.args[2],He(o,s.i)),b(n)}return o.i>=o.s.data.length?(Ie(t.args[2],o),b(ae)):(t.phase=2,t.data={s:o.s,i:o.i},{k:"expr",feed:t.data})}switch(r.t){case a.Block:case a.Paren:return t.phase=1,{k:"do",s:r.s,i:r.i};case a.String:{let o=eo(e.rt,r);return o.k!=="value"?o:(t.phase=1,de(o.v))}case a.File:case a.Url:return t.phase=1,bn(e,"do-file",[r],"read files");case a.Error:return{k:"throw",e:{kind:F.Error,v:r,name:null}}}return b(r)});g("reduce",'["Evaluates each expression of a block; gives a block of the values." value [any-value!]]',(e,t,n)=>{let r=t.args[0];if(r.t!==a.Block)return b(r);t.phase===0&&(t.phase=1,t.data={feed:{s:r.s,i:r.i},out:[]});let o=t.data;return n!==null&&o.out.push(n),o.feed.i>=o.feed.s.data.length?b(Qe(o.out)):{k:"expr",feed:o.feed}});g("quote",'["The value as it is, not evaluated." :value [any-type!]]',(e,t)=>b(t.args[0]));g("if",'["Evaluates the block if the condition is true; gives its value, or none." condition [any-value!] body [block!]]',(e,t,n)=>t.phase===1?b(n):Le(t.args[0])?(t.phase=1,de(t.args[1])):b(x));g("unless",'["Evaluates the block if the condition is not true; gives its value, or none." condition [any-value!] body [block!]]',(e,t,n)=>t.phase===1?b(n):Le(t.args[0])?b(x):(t.phase=1,de(t.args[1])));g("either",'["Evaluates the first block if the condition is true, the second if not." condition [any-value!] true-body [block!] false-body [block!]]',(e,t,n)=>t.phase===1?b(n):(t.phase=1,de(t.args[Le(t.args[0])?1:2])));g("not",'["True if the value is false or none, false otherwise." value [any-value!]]',(e,t)=>b({t:a.Logic,v:!Le(t.args[0])}));function _i(e,t,n){let r=e.args[0];e.phase===0&&(e.phase=1,e.data={s:r.s,i:r.i});let o=e.data;if(t!==null){if(Le(t)===n)return b(n?t:x);if(o.i>=o.s.data.length)return b(n?x:t)}else if(o.i>=o.s.data.length)return b(n?x:{t:a.Logic,v:!0});return{k:"expr",feed:o}}g("all",'["Evaluates expressions while they are true; gives the last value, or none at the first false one." block [block!]]',(e,t,n)=>_i(t,n,!1));g("any",'["Evaluates expressions until one is true; gives it, or none." block [block!]]',(e,t,n)=>_i(t,n,!0));g("case",'["Evaluates the block after the first true condition." cases [block!] /all]',(e,t,n)=>{let r=t.args[0],o=t.args[1].t===a.Logic;t.phase===0&&(t.data={feed:{s:r.s,i:r.i},out:x});let s=t.data,i=s.feed.s.data;if(t.phase===1){let l=i[s.feed.i];if(l===void 0)return B("script","case-body","case condition has no block after it");if(s.feed.i++,Le(n))return l.t!==a.Block?b(l):(t.phase=2,de(l))}else if(t.phase===2){if(!o)return b(n);s.out=n}return s.feed.i>=i.length?b(s.out):(t.phase=1,{k:"expr",feed:s.feed})});g("switch",'["Evaluates the block after the value that is equal to the one given." value [any-value!] cases [block!] /default case [block!]]',(e,t,n)=>{if(t.phase===1)return b(n);let r=t.args[0],o=t.args[1],s=o.s.data;for(let i=o.i;i<s.length;i++){let l=s[i];if(l.t!==a.Block&&dt(l,r)){let c=i+1;for(;c<s.length&&s[c].t!==a.Block;)c++;let u=s[c];return u===void 0?b(x):(t.phase=1,de(u))}}return t.args[2].t===a.Logic?(t.phase=1,de(t.args[3])):b(x)});function ha(e,t,n){let r=Wn(e);if(r!==null){if(r.kind===F.Break)return b(r.v)}else n!==null&&(t.out=n);return null}g("loop",'["Evaluates a block a number of times." count [integer!] body [block!]]',(e,t,n)=>{t.phase===0&&(t.phase=1,t.trap=cr,t.data={left:q(t.args[0].v),out:x});let r=t.data,o=ha(t,r,n);return o!==null?o:r.left<=0?b(r.out):(r.left--,de(t.args[1]))});function Ui(e,t){let n=e.t===a.Block?e.s.data.slice(e.i):[e],r=Ae(n.map(s=>s.sym),n.map(()=>x)),o=we(t.s,t.i);return ve(o,r),{ctx:r,body:{t:a.Block,s:o,i:0}}}g("repeat",`["Evaluates a block a number of times, with a word counting from 1." 'word [word!] count [integer!] body [block!]]`,(e,t,n)=>{if(t.phase===0){t.phase=1,t.trap=cr;let s=q(t.args[1].v);t.data={...Ui(t.args[0],t.args[2]),n:s,i:0,out:x}}let r=t.data,o=ha(t,r,n);return o!==null?o:r.i>=r.n?b(r.out):(r.i++,r.ctx.vals[0]={t:a.Integer,v:r.i},de(r.body))});g("foreach",`["Evaluates a block for each value of a series, with a word set to it; for a map, each key, or each key and value." 'word [word! block!] data [series! map!] body [block!]]`,(e,t,n)=>{let r=t.args[1];if(t.phase===0){t.phase=1,t.trap=cr;let l=t.args[0];if(l.t===a.Block&&(l.s.data.length===l.i||l.s.data.slice(l.i).some(u=>u.t!==a.Word)))return B("script","bad-words","foreach needs one or more words");let c=Ui(l,t.args[2]);if(r.t===a.Map&&c.ctx.keys.length>2)return B("script","bad-words","foreach over a map takes a key, or a key and a value");t.data={...c,at:r.t===a.Map?0:r.i,pairs:r.t===a.Map?r.s.data.slice():null,out:x}}let o=t.data,s=ha(t,o,n);if(s!==null)return s;if(o.pairs!==null)return o.at>=o.pairs.length?b(o.out):(o.ctx.vals[0]=o.pairs[o.at],o.ctx.vals.length===2&&(o.ctx.vals[1]=o.pairs[o.at+1]),o.at+=2,de(o.body));let i=r.s.data;if(o.at>=i.length)return b(o.out);for(let l=0;l<o.ctx.vals.length;l++)o.ctx.vals[l]=Gu(r,o.at+l);return o.at+=o.ctx.vals.length,de(o.body)});function Gu(e,t){if(e.t===a.Binary){let n=e.s.data[t];return n===void 0?x:{t:a.Integer,v:n}}if(e.t>=a.String&&e.t<=a.Tag){let n=e.s.data[t];return n===void 0?x:{t:a.Char,v:n}}return e.s.data[t]??x}g("while",'["Evaluates the body as long as the condition block is true." condition [block!] body [block!]]',(e,t,n)=>{t.phase===0&&(t.trap=cr,t.data={out:x});let r=t.data,o=Wn(t);return o!==null&&o.kind===F.Break?b(o.v):t.phase===1&&o===null?Le(n)?(t.phase=2,de(t.args[1])):b(r.out):(t.phase===2&&o===null&&(r.out=n),t.phase=1,de(t.args[0]))});g("until",'["Evaluates the block until it gives true." body [block!]]',(e,t,n)=>{let r=Wn(t);return r!==null&&r.kind===F.Break?b(r.v):t.phase===1&&r===null&&Le(n)?b(n):(t.phase=1,t.trap=cr,de(t.args[0]))});g("break",'["Leaves the loop it is in." /return value [any-value!]]',(e,t)=>({k:"throw",e:{kind:F.Break,v:t.args[0].t===a.Logic?t.args[1]:x,name:null}}));g("continue",'["Goes on with the next turn of the loop it is in." ]',()=>({k:"throw",e:{kind:F.Continue,v:ae,name:null}}));g("return",'["Leaves the function it is in, giving a value." value [any-type!]]',(e,t)=>({k:"throw",e:{kind:F.Return,v:t.args[0],name:null}}));g("exit",'["Leaves the function it is in, giving no value." ]',()=>({k:"throw",e:{kind:F.Return,v:ae,name:null}}));g("try",'["Evaluates a block; gives an error as a value instead of raising it." body [block!]]',(e,t,n)=>{let r=Wn(t);return r!==null?b(r.v):t.phase===1?b(n):(t.phase=1,t.trap=1<<F.Error,de(t.args[0]))});g("attempt",'["Evaluates a block; gives none if it raises an error." body [block!]]',(e,t,n)=>Wn(t)!==null?b(x):t.phase===1?b(n):(t.phase=1,t.trap=1<<F.Error,de(t.args[0])));g("catch",'["Evaluates a block; gives the value a throw inside it threw." body [block!] /name word [word! block!]]',(e,t,n)=>{let r=Wn(t);if(r!==null){let o=t.args[1].t===a.Logic,s=t.args[2],i=s.t===a.Block?s.s.data.slice(s.i):[s];return(o?r.name!==null&&i.some(c=>dt(c,r.name)):r.name===null)?b(r.v):{k:"throw",e:r}}return t.phase===1?b(n):(t.phase=1,t.trap=1<<F.Throw,de(t.args[0]))});g("throw",'["Throws a value to the catch around it." value [any-value!] /name word [word!]]',(e,t)=>({k:"throw",e:{kind:F.Throw,v:t.args[0],name:t.args[1].t===a.Logic?t.args[2]:null}}));g("cause-error",'["Raises an error of a type and an id." type [word!] id [word!] args [any-value!]]',(e,t)=>{let[n,r,o]=t.args,s=X(E(n.sym),E(r.sym),j(o));return{k:"throw",e:{kind:F.Error,v:s,name:null}}});var G={Add:0,Sub:1,Mul:2,Div:3,Rem:4},Vu=["add","subtract","multiply","divide","take the remainder of"],vt=()=>B("math","zero-divide","attempt to divide by zero"),Yt=()=>B("math","overflow","math or number overflow");function va(e){switch(e.t){case a.Integer:return q(e.v);case a.Decimal:case a.Percent:return e.v}return null}function ma(e,t,n){switch(e){case G.Add:return t+n;case G.Sub:return t-n;case G.Mul:return t*n;case G.Div:return n===0?null:t/n;case G.Rem:return n===0?null:t%n}}function Zu(e,t,n){let r;switch(e){case G.Add:r=Ho(t,n);break;case G.Sub:r=zo(t,n);break;case G.Mul:r=_o(t,n);break;case G.Rem:if(Ut(n))return vt();r=Cn(t,n);break;case G.Div:{if(Ut(n))return vt();let o=Cn(t,n);if(o!==null&&Ut(o)){r=Uo(t,n);break}return b(me(q(t)/q(n)))}}return r===null?Yt():b(R(r))}function Yu(e,t,n){let r=Et(t),o=Et(n);if(r===null||o===null)return null;let s=t.t===a.Money?t.cur:"",i=n.t===a.Money?n.cur:"";if(s!==""&&i!==""&&s.toUpperCase()!==i.toUpperCase())return B("math","currency",`cannot mix ${s} and ${i}`);let l=s||i,c=t.t===a.Money&&n.t===a.Money,u;switch(e){case G.Add:u=Qs(r,o);break;case G.Sub:u=ei(r,o);break;case G.Mul:if(c)return null;u=ti(r,o);break;case G.Div:return u=ni(r,o),u===null?vt():b(c?me(ut(u)):rt(u,l));case G.Rem:u=ai(r,o);break}return u===null?vt():b(rt(u,l))}function ur(e,t,n){if(t.t===a.Integer&&n.t===a.Integer)return Zu(e,t.v,n.v);let r=va(t),o=va(n);if(t.t===a.Money||n.t===a.Money){let s=Yu(e,t,n);if(s!==null)return s}else if(t.t===a.Pair||n.t===a.Pair){let s=t.t===a.Pair?t.x:r,i=t.t===a.Pair?t.y:r,l=n.t===a.Pair?n.x:o,c=n.t===a.Pair?n.y:o;if(s!==null&&i!==null&&l!==null&&c!==null){let u=ma(e,s,l),d=ma(e,i,c);return u===null||d===null?vt():b(gt(u,d))}}else if(t.t===a.Date){let s=Ju(e,t,n);if(s!==null)return s}else if(t.t===a.Time||n.t===a.Time){let s=Xu(e,t,n,r,o);if(s!==null)return s}else if(r!==null&&o!==null){let s=ma(e,r,o);if(s===null)return vt();if(!Number.isFinite(s))return Yt();let i=t.t===a.Percent&&(n.t===a.Percent?e!==G.Div:e===G.Mul||e===G.Div);return b(i?mt(s):me(s))}return B("script","bad-math",`cannot ${Vu[e]} ${re(t.t)} and ${re(n.t)}`)}function Xu(e,t,n,r,o){if(t.t===a.Time&&n.t===a.Time){switch(e){case G.Add:return b(Te(t.v+n.v));case G.Sub:return b(Te(t.v-n.v));case G.Div:return n.v===0?vt():b(me(t.v/n.v));case G.Rem:return n.v===0?vt():b(Te(t.v%n.v))}return null}if(t.t===a.Time&&o!==null){if(e===G.Mul)return b(Te(Math.round(t.v*o)));if(e===G.Div)return o===0?vt():b(Te(Math.round(t.v/o)))}return n.t===a.Time&&r!==null&&e===G.Mul?b(Te(Math.round(n.v*r))):null}var to=864e11;function no(e){return Date.UTC(e.y,e.m-1,e.d)/864e5}function qi(e,t,n){let r=new Date(e*864e5);return qt({y:r.getUTCFullYear(),m:r.getUTCMonth()+1,d:r.getUTCDate(),time:t,zone:n})}function Ju(e,t,n){let r=t.v;if(n.t===a.Integer&&(e===G.Add||e===G.Sub)){let o=q(n.v);return b(qi(no(r)+(e===G.Add?o:-o),r.time,r.zone))}if(n.t===a.Time&&(e===G.Add||e===G.Sub)){let o=(r.time??0)+(e===G.Add?n.v:-n.v),s=Math.floor(o/to);return b(qi(no(r)+s,o-s*to,r.zone))}if(n.t===a.Date&&e===G.Sub){let o=ya(r,n.v);return b(r.time===null&&n.v.time===null?R(Math.round(o/to)):Te(o))}return null}function ya(e,t){return(no(e)-no(t))*to+((e.time??0)-(e.zone??0)*6e10)-((t.time??0)-(t.zone??0)*6e10)}var it="[number! money! time! pair! date!]";g("add",`["The sum of two values." a ${it} b ${it}]`,(e,t)=>ur(G.Add,t.args[0],t.args[1]));g("subtract",`["The difference of two values." a ${it} b ${it}]`,(e,t)=>ur(G.Sub,t.args[0],t.args[1]));g("multiply",`["The product of two values." a ${it} b ${it}]`,(e,t)=>ur(G.Mul,t.args[0],t.args[1]));g("divide",`["The first value divided by the second." a ${it} b ${it}]`,(e,t)=>ur(G.Div,t.args[0],t.args[1]));g("remainder",`["What is left after dividing the first value by the second." a ${it} b ${it}]`,(e,t)=>ur(G.Rem,t.args[0],t.args[1]));g("negate",`["The value with its sign changed." value ${it}]`,(e,t)=>{let n=t.args[0];switch(n.t){case a.Integer:{let r=Or(n.v);return r===null?Yt():b(R(r))}case a.Decimal:return b(me(-n.v));case a.Percent:return b(mt(-n.v));case a.Money:return b(rt({d:-n.v.d,e:n.v.e},n.cur));case a.Time:return b(Te(-n.v));case a.Pair:return b(gt(-n.x,-n.y))}return B("script","bad-math",`cannot negate ${re(n.t)}`)});var Qu=["even","down","half-down","floor","ceiling","half-ceiling"];g("round",'["The value rounded to the nearest whole number, or to a multiple of a scale." value [number! money! time!] /to scale [number! money! time!] /even /down /half-down /floor /ceiling /half-ceiling]',(e,t)=>{let n=t.args[0],r=t.args[1]===O,o=Qu.find((l,c)=>t.args[3+c]===O)??"half-away";if(n.t===a.Time){let l=r?t.args[2]:R(1),c=l.t===a.Time?l.v:(va(l)??ut(Et(l)))*1e9,u=Ko(Pt(n.v),Pt(c),o);return u===null?vt():b(Te(ut(u)))}let s=r?t.args[2]:n.t===a.Percent?mt(.01):R(1);if(s.t===a.Time)return B("script","bad-math","cannot round a number to a time!");let i=Ko(Et(n),Et(s),o);if(i===null)return vt();if(n.t===a.Money||s.t===a.Money)return b(rt(i,n.t===a.Money?n.cur:s.cur));if(s.t===a.Integer&&(r||n.t===a.Integer)){let l=i.e===0?Fe(i.d):null;return l===null?Yt():b(R(l))}return b(n.t===a.Percent?mt(ut(i)):me(ut(i)))});g("abs",`["The value without its sign." value ${it}]`,(e,t)=>{let n=t.args[0];switch(n.t){case a.Integer:{if(on(n.v,0)>=0)return b(n);let r=Or(n.v);return r===null?Yt():b(R(r))}case a.Decimal:return b(me(Math.abs(n.v)));case a.Percent:return b(mt(Math.abs(n.v)));case a.Money:return b(rt({d:n.v.d<0n?-n.v.d:n.v.d,e:n.v.e},n.cur));case a.Time:return b(Te(Math.abs(n.v)));case a.Pair:return b(gt(Math.abs(n.x),Math.abs(n.y)))}return B("script","bad-math",`cannot take abs of ${re(n.t)}`)});g("zero?",`["True if the value is zero." value ${it}]`,(e,t)=>{let n=t.args[0];switch(n.t){case a.Integer:return b(Z(Ut(n.v)));case a.Money:return b(Z(Dr(n.v,{d:0n,e:0})));case a.Pair:return b(Z(n.x===0&&n.y===0));case a.Decimal:case a.Percent:case a.Time:return b(Z(n.v===0))}return b(Z(!1))});g("even?",'["True if the integer is even." value [integer!]]',(e,t)=>b(Z(Ut(Cn(t.args[0].v,2)))));g("odd?",'["True if the integer is odd." value [integer!]]',(e,t)=>b(Z(!Ut(Cn(t.args[0].v,2)))));g("sign?",'["Gives -1, 0 or 1 by the sign of the value." value [number! money! time!]]',(e,t)=>b(R(ka(t.args[0]))));g("negative?",'["True if the value is less than zero." value [number! money! time!]]',(e,t)=>b(Z(ka(t.args[0])<0)));g("positive?",'["True if the value is more than zero." value [number! money! time!]]',(e,t)=>b(Z(ka(t.args[0])>0)));function ka(e){return e.t===a.Integer?on(e.v,0):e.t===a.Money?Math.sign(Number(e.v.d)):Math.sign(e.v)}var yt="[number!]";function Rt(e){return e.t===a.Integer?q(e.v):e.v}function Xt(e){return b(me(e))}g("power",`["The number raised to the exponent." number ${yt} exponent ${yt}]`,(e,t)=>{let[n,r]=t.args;if(n.t===a.Integer&&r.t===a.Integer&&on(r.v,0)>=0){let o=BigInt(n.v),s=BigInt(r.v);if(s>64n&&o!==0n&&o!==1n&&o!==-1n)return Yt();let i=Fe(o**(s>64n?s%2n+2n:s));return i===null?Yt():b(R(i))}return Xt(Math.pow(Rt(n),Rt(r)))});g("square-root",`["The square root of the number." value ${yt}]`,(e,t)=>Xt(Math.sqrt(Rt(t.args[0]))));g("exp",`["e raised to the power of the number." power ${yt}]`,(e,t)=>Xt(Math.exp(Rt(t.args[0]))));function xa(e,t){return Xt(t(Rt(e.args[0])))}g("log-e",`["The natural logarithm of the number." value ${yt}]`,(e,t)=>xa(t,Math.log));g("log-10",`["The base-10 logarithm of the number." value ${yt}]`,(e,t)=>xa(t,Math.log10));g("log-2",`["The base-2 logarithm of the number." value ${yt}]`,(e,t)=>xa(t,Math.log2));var wa=Math.PI/180;function Ca(e){return Math.abs(e)<1e-15?0:e}function Sa(e,t,n){g(e,`["${t}" angle ${yt} /radians "The angle is in radians"]`,(r,o)=>{let s=Rt(o.args[0])*(o.args[1]===O?1:wa);if(e==="tangent"&&Math.abs(Math.cos(s))<1e-15)return Xt(Math.sin(s)>0?1/0:-1/0);let i=n(s);return Xt(o.args[1]===O?i:Ca(i))})}Sa("sine","The sine of an angle, in degrees.",Math.sin);Sa("cosine","The cosine of an angle, in degrees.",Math.cos);Sa("tangent","The tangent of an angle, in degrees.",Math.tan);function Ma(e,t,n,r){g(e,`["${t}" value ${yt} /radians "Give the angle in radians"]`,(o,s)=>{let i=Rt(s.args[0]);return Xt(s.args[1]===O?n(i):Ca(n(i)/wa))})}Ma("arcsine","The angle whose sine is the value, in degrees.",Math.asin,!0);Ma("arccosine","The angle whose cosine is the value, in degrees.",Math.acos,!0);Ma("arctangent","The angle whose tangent is the value, in degrees.",Math.atan,!1);g("arctangent2",`["The angle of the point x, y, in degrees." y ${yt} x ${yt} /radians "Give the angle in radians"]`,(e,t)=>{let n=Math.atan2(Rt(t.args[0]),Rt(t.args[1]));return Xt(t.args[2]===O?n:Ca(n/wa))});var pn={a:BigInt(Date.now())|1n,b:0x9e3779b97f4a7c15n};function Zt(){let e=pn.a,t=pn.b;return pn.a=t,e^=e<<23n&0xffffffffffffffffn,pn.b=e^t^e>>17n^t>>26n,Number(pn.b+t&0x1fffffffffffffn)/2**53}function ga(e){return Math.floor(Zt()*e)+1}g("random",'["A random value: an integer from 1 to it, a decimal up to it, a shuffled series." value [any-value!] /seed "Start the sequence from this value; gives nothing" /only "Pick one element of a series"]',(e,t)=>{let n=t.args[0];if(t.args[1]===O){let r=0x811c9dc5n;for(let o of J(n))r=(r^BigInt(o.codePointAt(0)))*0x100000001b3n&0xffffffffffffffffn;pn.a=r|1n,pn.b=r*0x9e3779b97f4a7c15n&0xffffffffffffffffn|1n;for(let o=0;o<8;o++)Zt();return b(ae)}switch(n.t){case a.Integer:{let r=q(n.v);return r===0?b(R(0)):b(R(Math.sign(r)*ga(Math.abs(r))))}case a.Decimal:return b(me(Zt()*n.v));case a.Percent:return b(mt(Zt()*n.v));case a.Money:return b(rt(Pt(Math.floor(Zt()*ut(n.v)*100)/100),n.cur));case a.Logic:return b(Z(Zt()<.5));case a.Time:return b(Te(Math.floor(Zt()*n.v)));case a.Char:return b({t:a.Char,v:ga(n.v)})}if(Gs(n.t)){let r=n,o=r.s.data.length-r.i;if(t.args[2]===O)return o<=0?b(x):b(bt(n,R(ga(o))));ht(r.s);let s=[r.s.data,r.s.nl,r.s.pos].filter(i=>i!==void 0);for(let i=o-1;i>0;i--){let l=Math.floor(Zt()*(i+1));for(let c of s)[c[r.i+i],c[r.i+l]]=[c[r.i+l],c[r.i+i]]}return b(n)}return B("script","bad-random",`cannot make a random ${re(n.t)}`)});function ro(e,t,n,r){let o=BigInt(e),s=BigInt(Math.max(0,Math.min(64,t))),i;return n?i=BigInt.asIntN(64,o<<s):r?i=BigInt.asIntN(64,BigInt.asUintN(64,o)>>s):i=o>>s,R(Fe(i))}var oo='data [integer!] bits [integer!] "How many bits"';g("shift",`["Shifts the bits of an integer right, or left with /left." ${oo} /left "Shift to the left" /logical "Shift zeros in, not the sign"]`,(e,t)=>b(ro(t.args[0].v,q(t.args[1].v),t.args[2]===O,t.args[3]===O)));g("shift-left",`["Shifts the bits of an integer left." ${oo}]`,(e,t)=>b(ro(t.args[0].v,q(t.args[1].v),!0,!1)));g("shift-right",`["Shifts the bits of an integer right, keeping its sign." ${oo}]`,(e,t)=>b(ro(t.args[0].v,q(t.args[1].v),!1,!1)));g("shift-logical",`["Shifts the bits of an integer right, shifting zeros in." ${oo}]`,(e,t)=>b(ro(t.args[0].v,q(t.args[1].v),!1,!0)));g("equal?",'["True if the values are equal." a [any-type!] b [any-type!]]',(e,t)=>b(Z(dt(t.args[0],t.args[1]))));g("not-equal?",'["True if the values are not equal." a [any-type!] b [any-type!]]',(e,t)=>b(Z(!dt(t.args[0],t.args[1]))));g("strict-equal?",'["True if the values are equal and of the same type and case." a [any-type!] b [any-type!]]',(e,t)=>b(Z(at(t.args[0],t.args[1]))));g("same?",'["True if the values are the very same: the same series at the same position, the same object." a [any-type!] b [any-type!]]',(e,t)=>b(Z(Fr(t.args[0],t.args[1]))));g("strict-not-equal?",'["True if the values are not strictly equal." a [any-type!] b [any-type!]]',(e,t)=>b(Z(!at(t.args[0],t.args[1]))));function ao(e,t,n){let r=ln(e,t);return r===null?B("script","bad-compare",`cannot compare ${re(e.t)} with ${re(t.t)}`):b(Z(n(r)))}g("lesser?",'["True if the first value is less than the second." a [any-value!] b [any-value!]]',(e,t)=>ao(t.args[0],t.args[1],n=>n<0));g("greater?",'["True if the first value is more than the second." a [any-value!] b [any-value!]]',(e,t)=>ao(t.args[0],t.args[1],n=>n>0));g("lesser-or-equal?",'["True if the first value is less than or equal to the second." a [any-value!] b [any-value!]]',(e,t)=>ao(t.args[0],t.args[1],n=>n<=0));g("greater-or-equal?",'["True if the first value is more than or equal to the second." a [any-value!] b [any-value!]]',(e,t)=>ao(t.args[0],t.args[1],n=>n>=0));function Ki(e,t,n){let r=ln(e,t);return r===null?B("script","bad-compare",`cannot compare ${re(e.t)} with ${re(t.t)}`):b(r>=0===n?e:t)}g("max",'["The greater of two values." a [any-value!] b [any-value!]]',(e,t)=>Ki(t.args[0],t.args[1],!0));g("min",'["The lesser of two values." a [any-value!] b [any-value!]]',(e,t)=>Ki(t.args[0],t.args[1],!1));function Ea(e,t,n,r){if(e.t===a.Integer&&t.t===a.Integer){let o=Fe(BigInt.asIntN(64,n(BigInt(e.v),BigInt(t.v))));return o===null?Yt():b(R(o))}if(e.t===a.Binary&&t.t===a.Binary){let o=e.s.data.slice(e.i),s=t.s.data.slice(t.i),i=[],l=Math.max(o.length,s.length);for(let c=0;c<l&&o.length>0&&s.length>0;c++)i.push(Number(n(BigInt(o[c%o.length]),BigInt(s[c%s.length]))&255n));return b({t:a.Binary,s:{data:i},i:0})}return b(Z(r(Le(e),Le(t))))}g("and~",'["Both values: bitwise for integers and binaries, logical for anything else." a [any-value!] b [any-value!]]',(e,t)=>Ea(t.args[0],t.args[1],(n,r)=>n&r,(n,r)=>n&&r));g("or~",'["Either value: bitwise for integers and binaries, logical for anything else." a [any-value!] b [any-value!]]',(e,t)=>Ea(t.args[0],t.args[1],(n,r)=>n|r,(n,r)=>n||r));g("xor~",'["One value or the other but not both: bitwise for integers and binaries, logical for anything else." a [any-value!] b [any-value!]]',(e,t)=>Ea(t.args[0],t.args[1],(n,r)=>n^r,(n,r)=>n!==r));Ce("+","add");Ce("-","subtract");Ce("*","multiply");Ce("/","divide");Ce("//","remainder");Ce("**","power");Ce("<<","shift-left");Ce(">>","shift-right");Ce(">>>","shift-logical");Ce("=","equal?");Ce("<>","not-equal?");Ce("==","strict-equal?");Ce("!==","strict-not-equal?");Ce("<","lesser?");Ce(">","greater?");Ce("<=","lesser-or-equal?");Ce(">=","greater-or-equal?");Ce("and","and~");Ce("or","or~");Ce("xor","xor~");var kt=e=>q(e.v),se=e=>e===O;function Ta(e,t){let n=e.s.data[t];return n===void 0?x:U(e.t)?n:e.t===a.Binary?R(n):ot(n)}function Ia(e,t){return t===null||t.t===a.None?e.s.data.length:t.t===a.Integer?Bn(e,e.i+kt(t)):Bn(e,t.i)}function Gi(e,t){let n=t.t===a.Integer?Bn(e,e.i+kt(t)):Bn(e,t.i);return n<e.i?[n,e.i]:[e.i,n]}function Vi(e,t,n,r,o){let{add:s,nl:i}=$n(e.t,t,n);if(r!==null){let l=r.t===a.Integer?Math.max(0,kt(r)):Math.max(0,r.i-t.i);s=s.slice(0,l),i=i?.slice(0,l)}if(o!==null){let l=Math.max(0,kt(o)),c=s,u=i;s=[],i=u===void 0?void 0:[];for(let d=0;d<l;d++)s.push(...c),i!==void 0&&i.push(...u)}return i===void 0?{add:s}:{add:s,nl:i}}g("next",'["The series one position on." series [series!]]',(e,t)=>b(He(t.args[0],t.args[0].i+1)));g("back",'["The series one position back." series [series!]]',(e,t)=>b(He(t.args[0],t.args[0].i-1)));g("head",'["The series at its first position." series [series!]]',(e,t)=>b(He(t.args[0],0)));g("tail",'["The series just past its last value." series [series!]]',(e,t)=>b(He(t.args[0],1/0)));g("skip",'["The series moved on, or back, by an offset." series [series!] offset [integer!]]',(e,t)=>{let n=t.args[0];return b(He(n,n.i+kt(t.args[1])))});g("at",'["The series at a position, counted from where it is." series [series!] index [integer!]]',(e,t)=>{let n=t.args[0],r=kt(t.args[1]);return b(He(n,n.i+(r>0?r-1:r)))});g("index?",'["The position of the series, from 1." series [series!]]',(e,t)=>b(R(t.args[0].i+1)));g("head?",'["True if the series is at its head." series [series!]]',(e,t)=>b(Z(t.args[0].i===0)));g("tail?",'["True if the series is at its tail." series [series!]]',(e,t)=>b(Z(Wi(t.args[0])===0)));var Zi='series [series!] value [any-value!] /part "Put in only part of the value" range [integer! series!] /only "A block goes in as one value" /dup "Put it in several times" count [integer!]',Yi=e=>Vi(e.args[0],e.args[1],se(e.args[4]),se(e.args[2])?e.args[3]:null,se(e.args[5])?e.args[6]:null);g("append",`["Puts a value at the tail of a series; gives the series at its head." ${Zi}]`,(e,t)=>{let n=t.args[0],{add:r,nl:o}=Yi(t);return ze(n.s,n.s.data.length,0,r,o),b(He(n,0))});g("insert",`["Puts a value where the series is; gives the series just after it." ${Zi}]`,(e,t)=>{let n=t.args[0],{add:r,nl:o}=Yi(t);return ze(n.s,n.i,0,r,o),b(He(n,n.i+r.length))});g("change",'["Puts a value over what the series holds where it is; gives the series just after it." series [series!] value [any-value!] /part "Change this much of the series" range [integer! series!] /only "A block goes in as one value" /dup "Put the value in several times" count [integer!]]',(e,t)=>{let n=t.args[0],{add:r,nl:o}=Vi(n,t.args[1],se(t.args[4]),null,se(t.args[5])?t.args[6]:null),s=se(t.args[2])?Ia(n,t.args[3]):Math.min(n.s.data.length,n.i+r.length);return ze(n.s,n.i,Math.max(0,s-n.i),r,o),b(He(n,n.i+r.length))});g("remove",'["Removes what the series holds where it is; gives the series." series [series!] /part "Remove this much" range [integer! series!]]',(e,t)=>{let n=t.args[0],[r,o]=se(t.args[1])?Gi(n,t.args[2]):[n.i,Math.min(n.s.data.length,n.i+1)];return ze(n.s,r,Math.max(0,o-r),[]),b(He(n,r))});g("clear",`["Removes everything from the series' position to its tail." series [series! map!]]`,(e,t)=>{let n=t.args[0];if(n.t===a.Map)return n.s.data.length=0,b(n);let r=n;return ze(r.s,r.i,r.s.data.length-r.i,[]),b(r)});g("copy",'["A copy of the series, map, object or bitset." value [series! map! object! bitset!] /part length [integer! series!] /deep]',(e,t)=>{let n=t.args[0],r=se(t.args[3]);if(n.t===a.Map)return b({t:a.Map,s:r?we(n.s):{data:n.s.data.slice()}});if(n.t===a.Object||n.t===a.Error){let l=Ae(n.ctx.keys.slice(),n.ctx.vals.slice());return n.ctx.self&&(l.self=!0),b({t:n.t,ctx:l})}if(n.t===a.Bitset)return b({t:a.Bitset,s:{data:n.s.data.slice()},neg:n.neg});let o=n,[s,i]=se(t.args[1])?Gi(o,t.args[2]):[o.i,o.s.data.length];if(U(o.t)){let l=o,c={data:l.s.data.slice(s,i)};return l.s.nl&&(c.nl=l.s.nl.slice(s,i)),b({t:l.t,s:r?we(c):c,i:0})}return b({t:o.t,s:{data:o.s.data.slice(s,i)},i:0})});g("reverse",`["Reverses the order of the values from the series' position." series [series!] /part length [integer! series!]]`,(e,t)=>{let n=t.args[0],r=se(t.args[1])?Ia(n,t.args[2]):n.s.data.length,o=n.s.data;ht(n.s);let s=n.s.nl;for(let i=n.i,l=r-1;i<l;i++,l--)[o[i],o[l]]=[o[l],o[i]],s&&([s[i],s[l]]=[s[l],s[i]]);return b(n)});function ed(e,t,n){return t.t===a.Datatype&&e.t!==a.Datatype?e.t===t.k:t.t===a.Typeset&&e.t!==a.Typeset?(t.bits&ke(e.t))!==0n:n?at(e,t):dt(e,t)}function td(e,t,n,r,o=!1){if(U(e.t))return{run:!n&&U(t.t)?t.s.data.slice(t.i):[t],eq:o?(c,u)=>Fr(c,u):(c,u)=>ed(c,u,r)};let s=$n(e.t,t,!1).add,i=r||e.t===a.Binary?(l,c)=>l===c:(l,c)=>Pe(l)===Pe(c);return{run:s,eq:i}}var nd=42,rd=63;function od(e,t,n,r,o){let s=[],i=0,l=t;for(;;){if(i===r.length)return l-t;let c=r[i];if(c===nd){s.push([i+1,l]),i++;continue}if(l<n&&(c===rd||o(e[l],c))){i++,l++;continue}let u=s.pop();if(u===void 0||u[1]>=n)return-1;i=u[0],l=u[1]+1,s.push([i,l])}}function Xi(e,t,n){let r=e.s.data,{run:o,eq:s}=td(e,t,n.only,n.cased,n.same),i=n.wild===!0&&!U(e.t),l=o.length,c=u=>{if(i)return l=od(r,u,n.end,o,s),l>=0;if(u+o.length>n.end)return!1;for(let d=0;d<o.length;d++)if(!s(r[u+d],o[d]))return!1;return!0};if(n.match)return{at:c(e.i)?e.i:-1,len:l};if(n.reverse){for(let u=e.i-n.skip;u>=0;u-=n.skip)if(c(u))return{at:u,len:l}}else if(n.last){for(let u=n.end-(i?0:o.length);u>=e.i;u--)if((u-e.i)%n.skip===0&&c(u))return{at:u,len:l}}else for(let u=e.i;u+(i?0:o.length)<=n.end;u+=n.skip)if(c(u))return{at:u,len:l};return{at:-1,len:l}}g("find",'["Finds a value in a series; gives the series where it is, or none." series [series! none! typeset!] value [any-type!] /part "Look only this far" length [integer! series!] /only "A block is one value" /case "Capitals matter" /skip "Look only at every so many" size [integer!] /last "Find the last one" /tail "Give the series just after it" /match "Only where the series is" /reverse "Look back from where the series is" /any "In a string, * is any run of characters and ? any one" /same "In a block, the very same value (same?), not an equal one"]',(e,t)=>{let n=t.args[0];if(n.t===a.None)return b(x);if(n.t===a.Typeset){let l=t.args[1];return b(Z(l.t===a.Datatype&&(n.bits&ke(l.k))!==0n))}let r=n,o=t.args,s={only:se(o[4]),cased:se(o[5]),skip:se(o[6])?Math.max(1,kt(o[7])):1,last:se(o[8]),match:se(o[10]),end:se(o[2])?Ia(r,o[3]):r.s.data.length,reverse:se(o[11]),wild:se(o[12]),same:se(o[13])},i=Xi(r,o[1],s);return i.at<0?b(x):b(He(r,se(o[9])||s.match?i.at+i.len:i.at))});g("select",'["The value after the one found, or none." series [series! map! object! none!] value [any-type!] /only /case /skip size [integer!] /last]',(e,t)=>{let n=t.args[0],r=t.args;if(n.t===a.None)return b(x);if(n.t===a.Map||n.t===a.Object||n.t===a.Error){let l=bt(n,r[1]);return b(typeof l=="string"?x:l)}let o=n,s=se(r[4])?Math.max(1,kt(r[5])):1,i=Xi(o,r[1],{only:se(r[2]),cased:se(r[3]),skip:s,last:se(r[6]),match:!1,end:o.s.data.length});return i.at<0?b(x):b(Ta(o,i.at+i.len))});function ad(e,t,n){let r=e.src.length;for(;;){if(e.width>=r)return null;if(!e.merging){if(e.lo>=r){[e.src,e.dst]=[e.dst,e.src],e.width*=2,e.lo=0;continue}e.mid=Math.min(e.lo+e.width,r),e.hi=Math.min(e.lo+2*e.width,r),e.i=e.lo,e.j=e.mid,e.k=e.lo,e.merging=!0}for(;e.k<e.hi;)if(e.i<e.mid&&e.j<e.hi){let o=n;if(n=null,o===null&&(o=t(e.src[e.j],e.src[e.i])),o===null)return[e.src[e.j],e.src[e.i]];e.dst[e.k++]=o?e.src[e.j++]:e.src[e.i++]}else e.i<e.mid?e.dst[e.k++]=e.src[e.i++]:e.dst[e.k++]=e.src[e.j++];e.merging=!1,e.lo+=2*e.width}}g("sort",'["Sorts the series in place." series [series!] /case /skip size [integer!] /compare comparator [any-function! integer!] /reverse]',(e,t,n)=>{let r=t.args[0],o=t.args,s=se(o[1]),i=se(o[2])?Math.max(1,kt(o[3])):1,l=se(o[4])&&o[5].t===a.Integer?kt(o[5]):null;if(l!==null&&(l<1||l>i))return B("script","out-of-range",`sort cannot compare field ${l} of records of ${i}`);let c=se(o[4])&&l===null?o[5]:null,u=se(o[6]);if(t.phase===0){let v=r.s.data,C=[];for(let S=r.i;S<v.length;S+=i)C.push(v.slice(S,S+i));t.data={src:C,dst:C.slice(),width:1,lo:0,mid:0,hi:0,i:0,j:0,k:0,merging:!1},t.phase=1}let d=t.data,f=null;n!==null&&(f=n.t===a.Integer?kt(n)<0:Le(n),u&&(f=!f));let p=(v,C=0)=>Ta({...r,s:{data:v},i:0},C),h=!1,k=ad(d,(v,C)=>{if(c!==null)return null;let S=l===null?0:l-1,I=sd(p(v,S),p(C,S),s);return I===null&&(h=!0),u?(I??0)>0:(I??0)<0},f);if(h)return B("script","bad-compare","sort cannot compare those values");if(k!==null)return{k:"call",fn:c,args:[p(k[0]),p(k[1])]};let M=d.src.flat(),w=r.s.data;for(let v=0;v<M.length;v++)w[r.i+v]=M[v];return ht(r.s),r.s.nl&&r.s.nl.fill(!1,r.i),b(r)});function sd(e,t,n){if(n&&e.t===a.String&&t.t===a.String){let o=e.s.data.slice(e.i),s=t.s.data.slice(t.i);for(let i=0;i<Math.min(o.length,s.length);i++)if(o[i]!==s[i])return o[i]<s[i]?-1:1;return o.length<s.length?-1:o.length>s.length?1:0}if(n&&e.t===a.Char&&t.t===a.Char)return e.v<t.v?-1:e.v>t.v?1:0;let r=ln(e,t);return r!==null?r:e.t!==t.t?e.t<t.t?-1:1:e.t===a.None?0:null}function Ji(e){let t=e.args[0],n=t.t===a.Block?t.s.data.slice(t.i):[t],r=Ae(n.map(i=>i.sym),n.map(()=>x)),o=e.args[2],s=we(o.s,o.i);return ve(s,r),{ctx:r,body:{t:a.Block,s,i:0}}}function Qi(e,t,n){let r=n.s.data;if(t.pos>=r.length)return null;for(let o=0;o<t.ctx.vals.length;o++)t.ctx.vals[o]=Ta(n,t.pos+o);return t.pos+=t.ctx.vals.length,e.trap=1<<F.Break|1<<F.Continue,de(t.body)}g("remove-each",`["Removes the values of a series for which the block gives true." 'word [word! block!] data [series!] body [block!]]`,(e,t,n)=>{let r=t.args[1];t.phase===0&&(t.phase=1,t.data={...Ji(t),pos:r.i,out:[],keep:r.s.data.slice(0,r.i)});let o=t.data,s=o.ctx.vals.length,i=t.thrown;t.thrown=null;let l=i!==null&&i.kind===F.Break;if(n!==null||i!==null){let u=o.pos-s,d=r.s.data.slice(u,Math.min(u+s,r.s.data.length));(l||n===null||!Le(n))&&o.keep.push(...d)}let c=l?null:Qi(t,o,r);return c!==null?c:(l&&o.keep.push(...r.s.data.slice(o.pos)),ze(r.s,0,r.s.data.length,o.keep),b(r))});g("map-each",`["A block of what the block gives for each value of a series." 'word [word! block!] data [series!] body [block!]]`,(e,t,n)=>{let r=t.args[1];t.phase===0&&(t.phase=1,t.data={...Ji(t),pos:r.i,out:[],keep:[]});let o=t.data,s=t.thrown;return t.thrown=null,s!==null&&s.kind===F.Break?b({t:a.Block,s:{data:o.out},i:0}):(n!==null&&n.t!==a.Unset&&(n.t===a.Block?o.out.push(...n.s.data.slice(n.i)):o.out.push(n)),Qi(t,o,r)??b({t:a.Block,s:{data:o.out},i:0}))});function id(e,t){return U(e)?(n,r)=>t?at(n,r):dt(n,r):t||e===a.Binary?(n,r)=>n===r:(n,r)=>Pe(n)===Pe(r)}function dr(e,t){let n=[];for(let r of e)n.some(o=>t(r,o))||n.push(r);return n}function ld(e,t){return{t:e.t,s:{data:t},i:0}}function br(e,t,n){let r=e.args[0],o=t?e.args[1]:null;if(o!==null&&U(r.t)!==U(o.t))return B("script","bad-set","both series must be of the same kind");let s=id(r.t,se(e.args[t?2:1])),i=r.s.data.slice(r.i),l=o===null?[]:o.s.data.slice(o.i);return b(ld(r,n(i,l,s)))}g("unique",'["The values of the series, each once." set [series!] /case]',(e,t)=>br(t,!1,(n,r,o)=>dr(n,o)));g("union",'["The values that are in either series, each once." a [series!] b [series!] /case]',(e,t)=>br(t,!0,(n,r,o)=>dr([...n,...r],o)));g("intersect",'["The values that are in both series." a [series!] b [series!] /case]',(e,t)=>br(t,!0,(n,r,o)=>dr(n.filter(s=>r.some(i=>o(s,i))),o)));g("difference",'["The values that are in one series but not the other; of two dates, the time between them." a [series! date!] b [series! date!] /case]',(e,t)=>{let[n,r]=t.args;return n.t===a.Date||r.t===a.Date?n.t!==a.Date||r.t!==a.Date?B("script","bad-set","difference takes two dates or two series"):b(Te(ya(n.v,r.v))):br(t,!0,(o,s,i)=>dr([...o.filter(l=>!s.some(c=>i(l,c))),...s.filter(l=>!o.some(c=>i(c,l)))],i))});g("exclude",'["The values of the first series that are not in the second." a [series!] b [series!] /case]',(e,t)=>br(t,!0,(n,r,o)=>dr(n.filter(s=>!r.some(i=>o(s,i))),o)));var xt=e=>e===O,Ft=e=>q(e.v),so=e=>e===32||e===9||e===10||e===13||e===160;function el(e){return(t,n)=>{let r=n.args[0],o=l=>{let c=String.fromCodePoint(l),u=e?c.toUpperCase():c.toLowerCase();return u.length===c.length?u.codePointAt(0):l};if(r.t===a.Char)return b(ot(o(r.v)));let s=r,i=xt(n.args[1])?Math.min(s.s.data.length,s.i+Ft(n.args[2])):s.s.data.length;for(let l=s.i;l<i;l++)s.s.data[l]=o(s.s.data[l]);return b(s)}}g("uppercase",'["Changes the text to capitals." string [any-string! char!] /part length [integer!]]',el(!0));g("lowercase",'["Changes the text to small letters." string [any-string! char!] /part length [integer!]]',el(!1));g("trim",'["Removes spaces at both ends, or with refinements other spaces too." series [any-string! block!] /head /tail /lines /all]',(e,t)=>{let n=t.args[0];if(n.t===a.Block){let u=n.s.data.filter((d,f)=>f<n.i||d.t!==a.None);return n.s.data.splice(0,n.s.data.length,...u),ht(n.s),n.s.nl&&(n.s.nl.length=0),n.s.pos&&(n.s.pos.length=0),b(n)}let r=n,o=r.s.data.slice(r.i),[s,i,l,c]=[xt(t.args[1]),xt(t.args[2]),xt(t.args[3]),xt(t.args[4])];if(c)o=o.filter(u=>!so(u));else if(l){let u=[];for(let d of o)so(d)?u.length>0&&u[u.length-1]!==32&&u.push(32):u.push(d);u[u.length-1]===32&&u.pop(),o=u}else{let u=0,d=o.length;if(s||!i)for(;u<d&&so(o[u]);)u++;if(i||!s)for(;d>u&&so(o[d-1]);)d--;o=o.slice(u,d)}return r.s.data.splice(r.i,r.s.data.length-r.i,...o),b(r)});g("split",'["Splits a series at a delimiter, or into pieces of a size." series [any-string! block!] dlm [any-string! char! integer!]]',(e,t)=>{let n=t.args[0],r=t.args[1],o=n.s.data.slice(n.i),s=(u,d)=>({t:n.t,s:{data:o.slice(u,d)},i:0}),i=[];if(r.t===a.Integer){let u=Math.max(1,Ft(r));for(let d=0;d<o.length;d+=u)i.push(s(d,d+u));return b({t:a.Block,s:{data:i},i:0})}if(U(n.t))return B("script","bad-split","a block splits only into pieces of a size");let l=r.t===a.Char?[r.v]:r.s.data.slice(r.i);if(l.length===0)return B("script","bad-split","the delimiter is empty");let c=0;for(let u=0;u+l.length<=o.length;)l.every((d,f)=>Pe(o[u+f])===Pe(d))?(i.push(s(c,u)),u+=l.length,c=u):u++;return i.push(s(c,o.length)),b({t:a.Block,s:{data:i},i:0})});function pr(e,t){try{let n=De(e),r=n.s.data[0];return n.s.data.length===1&&r!==void 0&&t.includes(r.t)?r:null}catch(n){if(n instanceof st)return null;throw n}}var cd=[a.Integer,a.Decimal,a.Percent,a.Money];function La(e){return e.t===a.Integer||e.t===a.Decimal||e.t===a.Percent||e.t===a.Money?e:e.t===a.Char?R(e.v):e.t===a.Logic?R(e.v?1:0):V(e.t)?pr($(e).trim(),cd):null}function ud(e,t){let n=()=>`cannot convert ${re(t.t)} to ${re(e)}`;switch(e){case a.String:case a.File:case a.Email:case a.Url:case a.Tag:return t.t===a.Binary?{t:e,s:{data:ue(new TextDecoder().decode(new Uint8Array(t.s.data.slice(t.i))))},i:0}:oe(t.t)?{t:e,s:{data:ue(E(t.sym))},i:0}:t.t===a.Char?{t:e,s:{data:[t.v]},i:0}:{t:e,s:{data:ue(An(t))},i:0};case a.Binary:return t.t===a.Binary?{t:a.Binary,s:{data:t.s.data.slice(t.i)},i:0}:t.t===a.Block?{t:a.Binary,s:{data:t.s.data.slice(t.i).map(r=>r.t===a.Integer?Ft(r)&255:0)},i:0}:{t:a.Binary,s:{data:cn(An(t))},i:0};case a.Word:case a.SetWord:case a.GetWord:case a.LitWord:case a.Refinement:case a.Issue:{if(oe(t.t))return{t:e,sym:t.sym,bind:t.bind};if(V(t.t)||t.t===a.Char){let r=t.t===a.Char?String.fromCodePoint(t.v):$(t);return pr(r,[a.Word])===null&&e!==a.Issue&&e!==a.Refinement?`${JSON.stringify(r)} is not a valid word`:{t:e,sym:A(r),bind:null}}return t.t===a.Datatype?{t:e,sym:A(re(t.k)),bind:null}:n()}case a.Integer:{let r=t.t===a.Time?me(t.v/1e9):La(t);if(r===null)return n();if(r.t===a.Integer)return r;let o=r.t===a.Money?ut(r.v):r.v,s=qo(Math.trunc(o));return s===null?"number is too big for integer!":R(s)}case a.Decimal:case a.Percent:{let r=t.t===a.Time&&e===a.Decimal?me(t.v/1e9):La(t);if(r===null)return n();let o=r.t===a.Money?ut(r.v):r.t===a.Integer?q(r.v):r.v;return e===a.Decimal?me(o):mt(o)}case a.Money:{let r=La(t),o=r===null?null:Et(r);return o===null?n():rt(o,r.t===a.Money?r.cur:"")}case a.Char:return t.t===a.Char?t:t.t===a.Integer?ot(Ft(t)):V(t.t)&&t.s.data.length>t.i?ot(t.s.data[t.i]):n();case a.Logic:return Z(Le(t));case a.None:return x;case a.Block:case a.Paren:case a.Path:case a.SetPath:case a.GetPath:case a.LitPath:{if(U(t.t))return{t:e,s:{data:t.s.data.slice(t.i)},i:0};if(V(t.t))try{let r=De($(t));return{t:e,s:r.s,i:0}}catch(r){if(r instanceof st)return r.message;throw r}if(t.t===a.Map)return{t:e,s:{data:t.s.data.slice()},i:0};if(t.t===a.Object||t.t===a.Error){let r=[];return t.ctx.keys.forEach((o,s)=>r.push({t:a.SetWord,sym:o,bind:null},t.ctx.vals[s])),{t:e,s:{data:r},i:0}}return{t:e,s:{data:[t]},i:0}}case a.Map:{if(t.t===a.Map)return{t:a.Map,s:{data:t.s.data.slice()}};if(t.t===a.Block){let r=t.s.data.slice(t.i);return r.length%2!==0?"a map needs key value pairs":{t:a.Map,s:{data:r.map((o,s)=>s%2===0&&oe(o.t)?{t:a.Word,sym:o.sym,bind:null}:o)}}}if(t.t===a.Object){let r=[];return t.ctx.keys.forEach((o,s)=>r.push({t:a.Word,sym:o,bind:null},t.ctx.vals[s])),{t:a.Map,s:{data:r}}}return n()}case a.Pair:{if(t.t===a.Pair)return t;if(t.t===a.Integer||t.t===a.Decimal){let r=t.t===a.Integer?Ft(t):t.v;return gt(r,r)}if(t.t===a.Block){let[r,o]=t.s.data.slice(t.i),s=c=>c?.t===a.Integer?Ft(c):c?.t===a.Decimal?c.v:null,i=s(r),l=s(o);return i===null||l===null?n():gt(i,l)}return V(t.t)?pr($(t),[a.Pair])??n():n()}case a.Tuple:return t.t===a.Tuple?t:t.t===a.Block&&t.s.data.slice(t.i).every(r=>r.t===a.Integer)?Wr(t.s.data.slice(t.i).map(Ft)):V(t.t)?pr($(t),[a.Tuple])??n():n();case a.Date:case a.Time:return t.t===e?t:e===a.Time&&(t.t===a.Integer||t.t===a.Decimal)?{t:a.Time,v:Math.round((t.t===a.Integer?Ft(t):t.v)*1e9)}:V(t.t)?pr($(t),[e])??n():n();case a.Datatype:if(t.t===a.Datatype)return t;if(oe(t.t)){let r=E(L(t.sym)),o=wn(r);return o===void 0?n():Kt(o)}return n();case a.Typeset:{if(t.t===a.Typeset)return t;if(t.t===a.Datatype)return Wt(ke(t.k));if(t.t!==a.Block)return n();let r=In(t);return typeof r=="string"?r:Wt(r)}}return n()}g("to",'["Converts a value to another type." type [datatype! any-value!] value [any-type!]]',(e,t)=>{let n=t.args[0],r=n.t===a.Datatype?n.k:n.t,o=ud(r,t.args[1]);return typeof o=="string"?B("script","bad-to",o):b(o)});g("construct",'["Makes an object from a block without evaluating its values." block [block!]]',(e,t)=>{let n=t.args[0],r=[],o=[],s={none:x,true:O,false:xe,on:O,off:xe,yes:O,no:xe},i=n.s.data;for(let l=n.i;l<i.length;l++){if(i[l].t!==a.SetWord)continue;let u=l+1;for(;u<i.length&&i[u].t===a.SetWord;)u++;let d=i[u]??x;d.t===a.Word?d=s[E(L(d.sym))]??d:d.t===a.LitWord&&(d={t:a.Word,sym:d.sym,bind:null});for(let f=l;f<u;f++)r.push(i[f].sym),o.push(d);l=u}return b({t:a.Object,ctx:{keys:r,vals:o,parent:null}})});g("compose",'["Evaluates the parens in a block and puts their values in a copy of it." value [any-value!] /deep /only]',(e,t,n)=>{let r=t.args[0];if(r.t!==a.Block)return b(r);let o=xt(t.args[1]),s=xt(t.args[2]);t.phase===0&&(t.phase=1,t.data=[{src:r,i:r.i,out:[],nl:[]}]);let i=t.data;if(n!==null){let l=i[i.length-1],c=l.src.s.nl?.[l.i-1]??!1;n.t===a.Block&&!s?n.s.data.slice(n.i).forEach((u,d)=>{l.out.push(u),l.nl.push(d===0?c:n.s.nl?.[n.i+d]??!1)}):n.t!==a.Unset&&(l.out.push(n),l.nl.push(c))}for(;;){let l=i[i.length-1],c=l.src.s.data;if(l.i>=c.length){i.pop();let d={t:l.src.t,s:{data:l.out,nl:l.nl},i:0};if(i.length===0)return b(d);let f=i[i.length-1];f.out.push(d),f.nl.push(f.src.s.nl?.[f.i-1]??!1);continue}let u=c[l.i++];if(u.t===a.Paren)return{k:"do",s:u.s,i:u.i};if(o&&U(u.t)){i.push({src:u,i:u.i,out:[],nl:[]});continue}l.out.push(u),l.nl.push(l.src.s.nl?.[l.i-1]??!1)}});g("collect-words",'["The words used in a block, each once." block [block!] /deep /set /ignore words [block!]]',(e,t)=>{let n=xt(t.args[1]),r=xt(t.args[2]),o=xt(t.args[3])?t.args[4].s.data.filter(d=>oe(d.t)).map(d=>L(d.sym)):[],s=new Set(o),i=[],l=[],c=(d,f)=>{if(!l.includes(d)){l.push(d);for(let p=f;p<d.data.length;p++){let h=d.data[p];(r?h.t===a.SetWord:h.t>=a.Word&&h.t<=a.LitWord)&&!s.has(L(h.sym))?(s.add(L(h.sym)),i.push({t:a.Word,sym:h.sym,bind:null})):n&&U(h.t)&&c(h.s,h.i)}l.pop()}},u=t.args[0];return c(u.s,u.i),b({t:a.Block,s:{data:i},i:0})});function tl(e,t){return(n,r,o)=>{let s=r.args[0],i=e(r.args);if(r.phase===0){let d=ge(s);if(d===null||!(U(d.t)||V(d.t)))return B("script","bad-walk",`${E(s.sym)} must refer to a series`);r.phase=1,r.trap=1<<F.Break|1<<F.Continue,r.data={start:d,cur:d,out:x,first:!0}}let l=r.data,c=r.thrown;r.thrown=null;let u=d=>(Ie(s,l.start),b(d));return c!==null&&c.kind===F.Break?u(c.v):(o!==null&&(l.out=o),l.first||(l.cur=He(l.cur,l.cur.i+i)),l.first=!1,l.cur.i>=l.cur.s.data.length?u(l.out):(Ie(s,l.cur),de(r.args[t])))}}g("forall",`["Evaluates a block for each position of the series a word refers to." 'word [word!] body [block!]]`,tl(()=>1,1));g("forskip",`["Evaluates a block at every so many positions of the series a word refers to." 'word [word!] size [integer!] body [block!]]`,tl(e=>Math.max(1,Ft(e[1])),2));g("apply",'["Calls a function with the arguments in a block." func [any-function!] block [block!] /only]',(e,t,n)=>{let r=t.args[0],o=t.args[1];if(t.phase===2)return b(n);if(t.phase===0){if(xt(t.args[2]))return t.phase=2,{k:"call",fn:r,args:o.s.data.slice(o.i),full:!0};t.phase=1,t.data={feed:{s:o.s,i:o.i},out:[]}}let s=t.data;return n!==null&&s.out.push(n),s.feed.i<s.feed.s.data.length?{k:"expr",feed:s.feed}:(t.phase=2,{k:"call",fn:r,args:s.out,full:!0})});function nl(e){let t=4294967295;for(let n of e){t^=n;for(let r=0;r<8;r++)t=t&1?t>>>1^3988292384:t>>>1}return(t^4294967295)>>>0}function rl(e){let t=1,n=0;for(let r of e)t=(t+r)%65521,n=(n+t)%65521;return(n<<16|t)>>>0}function Aa(e,t){let n=e.slice(),r=e.length*8;for(n.push(128);n.length%64!==56;)n.push(0);let o=[];for(let s=0;s<8;s++)o.push(Math.floor(r/2**(8*s))&255);return n.push(...t?o.reverse():o),n}function Ba(e,t,n){let r=[];for(let o=0;o<16;o++){let s=t+o*4;r.push(n?(e[s]<<24|e[s+1]<<16|e[s+2]<<8|e[s+3])>>>0:(e[s]|e[s+1]<<8|e[s+2]<<16|e[s+3]<<24)>>>0)}return r}function $a(e,t){let n=[];for(let r of e){let o=[r>>>24&255,r>>>16&255,r>>>8&255,r&255];n.push(...t?o:o.reverse())}return n}var io=(e,t)=>(e<<t|e>>>32-t)>>>0,It=(e,t)=>(e>>>t|e<<32-t)>>>0,dd=[7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21],bd=Array.from({length:64},(e,t)=>Math.floor(Math.abs(Math.sin(t+1))*2**32)>>>0);function ol(e){let t=Aa(e,!1),n=[1732584193,4023233417,2562383102,271733878];for(let r=0;r<t.length;r+=64){let o=Ba(t,r,!1),[s,i,l,c]=n;for(let u=0;u<64;u++){let d,f;u<16?(d=i&l|~i&c,f=u):u<32?(d=c&i|~c&l,f=(5*u+1)%16):u<48?(d=i^l^c,f=(3*u+5)%16):(d=l^(i|~c),f=7*u%16);let p=c;c=l,l=i,i=i+io(s+d+bd[u]+o[f]>>>0,dd[(u>>4)*4+u%4])>>>0,s=p}n[0]=n[0]+s>>>0,n[1]=n[1]+i>>>0,n[2]=n[2]+l>>>0,n[3]=n[3]+c>>>0}return $a(n,!1)}function al(e){let t=Aa(e,!0),n=[1732584193,4023233417,2562383102,271733878,3285377520];for(let r=0;r<t.length;r+=64){let o=Ba(t,r,!0);for(let d=16;d<80;d++)o.push(io(o[d-3]^o[d-8]^o[d-14]^o[d-16],1));let[s,i,l,c,u]=n;for(let d=0;d<80;d++){let[f,p]=d<20?[i&l|~i&c,1518500249]:d<40?[i^l^c,1859775393]:d<60?[i&l|i&c|l&c,2400959708]:[i^l^c,3395469782],h=io(s,5)+f+u+p+o[d]>>>0;u=c,c=l,l=io(i,30),i=s,s=h}[s,i,l,c,u].forEach((d,f)=>{n[f]=n[f]+d>>>0})}return $a(n,!0)}var pd=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function sl(e){let t=Aa(e,!0),n=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];for(let r=0;r<t.length;r+=64){let o=Ba(t,r,!0);for(let h=16;h<64;h++){let y=It(o[h-15],7)^It(o[h-15],18)^o[h-15]>>>3,k=It(o[h-2],17)^It(o[h-2],19)^o[h-2]>>>10;o.push(o[h-16]+y+o[h-7]+k>>>0)}let[s,i,l,c,u,d,f,p]=n;for(let h=0;h<64;h++){let y=p+(It(u,6)^It(u,11)^It(u,25))+(u&d^~u&f)+pd[h]+o[h]>>>0,k=(It(s,2)^It(s,13)^It(s,22))+(s&i^s&l^i&l)>>>0;p=f,f=d,d=u,u=c+y>>>0,c=l,l=i,i=s,s=y+k>>>0}[s,i,l,c,u,d,f,p].forEach((h,y)=>{n[y]=n[y]+h>>>0})}return $a(n,!0)}var fd=/^[A-Za-z_][A-Za-z0-9_-]*$/;function hd(e){return fd.test(e)?{t:a.Word,sym:A(e),bind:null}:D(e)}function fr(e){let t=0,n=[],r=null,o=()=>{for(;t<e.length&&`
17
- \r`.includes(e[t]);)t++},s=c=>`invalid JSON at ${t+1}: ${c}`,i=()=>{let c="";for(t++;t<e.length;){let u=e[t++];if(u==='"')return c;if(u!=="\\"){c+=u;continue}let d=e[t++];switch(d){case'"':case"\\":case"/":c+=d;break;case"b":c+="\b";break;case"f":c+="\f";break;case"n":c+=`
18
- `;break;case"r":c+="\r";break;case"t":c+=" ";break;case"u":{let f=e.slice(t,t+4);if(!/^[0-9a-fA-F]{4}$/.test(f))return null;c+=String.fromCharCode(parseInt(f,16)),t+=4;break}default:return null}}return null},l=c=>{let u=n[n.length-1];return u===void 0?(r=c,null):(u.kind==="array"?u.out.push(c):(u.out.push(u.key,c),u.key=null),null)};for(;;){o();let c=n[n.length-1];if(c!==void 0&&c.kind==="object"&&c.key===null)if(e[t]==="}"&&c.out.length===0)t++,n.pop(),l({t:a.Map,s:{data:c.out}});else{if(e[t]!=='"')return s("expected a key");let u=i();if(u===null)return s("bad string");if(o(),e[t]!==":")return s("expected :");t++,c.key=hd(u);continue}else if(r===null||c!==void 0)if(c!==void 0&&c.kind==="array"&&e[t]==="]"&&c.out.length===0)t++,n.pop(),l({t:a.Block,s:{data:c.out},i:0});else{let u=e[t];if(u===void 0)return s("unexpected end");if(u==="{"){t++,n.push({kind:"object",out:[],key:null});continue}if(u==="["){t++,n.push({kind:"array",out:[],key:null});continue}let d;if(u==='"'){let f=i();if(f===null)return s("bad string");d=D(f)}else if(e.startsWith("true",t))t+=4,d=O;else if(e.startsWith("false",t))t+=5,d=xe;else if(e.startsWith("null",t))t+=4,d=x;else{let f=/^-?(?:0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(e.slice(t,t+400));if(f===null)return s("unexpected character");t+=f[0].length;let p=f[1]===void 0&&f[2]===void 0?Sn(f[0]):null;d=p!==null?R(p):me(Number(f[0]))}l(d)}for(;;){o();let u=n[n.length-1];if(u===void 0)return t<e.length?s("extra text after the value"):r;let d=e[t];if(d===","){t++;break}if(u.kind==="array"&&d==="]"||u.kind==="object"&&d==="}"){t++,n.pop(),l(u.kind==="array"?{t:a.Block,s:{data:u.out},i:0}:{t:a.Map,s:{data:u.out}});continue}return s(d===void 0?"unexpected end":`expected , or ${u.kind==="array"?"]":"}"}`)}}}function fn(e){return JSON.stringify(e)}var il=e=>e.t===a.Function||e.t===a.Native||e.t===a.Op;function pt(e,t=new Set){switch(e.t){case a.None:case a.Unset:return"null";case a.Logic:return e.v?"true":"false";case a.Integer:return tr(e.v);case a.Decimal:case a.Percent:return Number.isFinite(e.v)?String(e.v):"null";case a.Money:return Mt(e.v);case a.Char:return fn(String.fromCodePoint(e.v));case a.Date:{let n=e.v,r=(s,i=2)=>String(s).padStart(i,"0"),o=`${r(n.y,4)}-${r(n.m)}-${r(n.d)}`;if(n.time!==null){let s=n.time/1e9,i=Math.floor(s%60),l=s%1===0?"":String(Number((s%1).toFixed(9))).slice(1);if(o+=`T${r(Math.floor(s/3600))}:${r(Math.floor(s%3600/60))}:${r(i)}${l}`,n.zone!==null){let c=Math.abs(n.zone);o+=n.zone===0?"Z":`${n.zone<0?"-":"+"}${r(Math.floor(c/60))}:${r(c%60)}`}}return fn(o)}case a.Time:return fn(sr(e.v));case a.Pair:return`[${e.x},${e.y}]`;case a.Tuple:return`[${e.v.join(",")}]`;case a.Map:{if(t.has(e.s))return"null";t.add(e.s);let n=[];for(let r=0;r+1<e.s.data.length;r+=2){let o=e.s.data[r];if(il(e.s.data[r+1]))continue;let s=oe(o.t)?E(o.sym):V(o.t)?$(o):pt(o);n.push(`${fn(s)}:${pt(e.s.data[r+1],t)}`)}return t.delete(e.s),`{${n.join(",")}}`}case a.Object:case a.Error:{if(t.has(e.ctx))return"null";t.add(e.ctx);let n=e.ctx.keys.flatMap((r,o)=>il(e.ctx.vals[o])?[]:[`${fn(E(r))}:${pt(e.ctx.vals[o],t)}`]);return t.delete(e.ctx),`{${n.join(",")}}`}case a.Block:case a.Paren:{if(t.has(e.s))return"null";t.add(e.s);let n=`[${e.s.data.slice(e.i).map(r=>pt(r,t)).join(",")}]`;return t.delete(e.s),n}}return V(e.t)?fn($(e)):oe(e.t)?fn(E(e.sym)):"null"}g("load-json",'["Reads JSON text into Trebol values: objects as maps, lists as blocks." source [string! binary!]]',(e,t)=>{let n=t.args[0],r=n.t===a.Binary?new TextDecoder().decode(new Uint8Array(n.s.data.slice(n.i))):$(n),o=fr(r);return typeof o=="string"?B("syntax","json",o):b(o)});g("to-json",'["Writes a value as JSON text." value [any-type!]]',(e,t)=>b(D(pt(t.args[0]))));var wt=e=>e===O,lo=13,hr=10,md=34,gd=65279;function ul(e){if(e.t===a.Char)return[e.v];if(e.t===a.String){let t=e.s.data.slice(e.i);return t.length===0?null:t}return[44]}var Na=e=>e===32||e===9;function vd(e,t){let n=[],r=e.length,o=t.delim,s=d=>{for(let f=0;f<o.length;f++)if(e[d+f]!==o[f])return!1;return!0},i=d=>e[d]===lo||e[d]===hr,l=e[0]===gd?1:0,c=1,u=[];for(;l<r;){if(u.length===0&&i(l)){l+=e[l]===lo&&e[l+1]===hr?2:1,c++;continue}let d=[];if(t.trim)for(;Na(e[l]);)l++;let f=e[l]===t.quote;if(f){let p=c;for(l++;;){if(l>=r)return`a quoted field on line ${p} has no closing quote`;let h=e[l];if(h===t.quote){if(e[l+1]===t.quote){d.push(h),l+=2;continue}l++;break}(h===hr||h===lo&&e[l+1]!==hr)&&c++,d.push(h),l++}if(t.trim)for(;Na(e[l]);)l++}for(;l<r&&!i(l)&&!s(l);)d.push(e[l++]);if(t.trim&&!f)for(;Na(d[d.length-1]);)d.pop();if(u.push(Oe(d)),l<r&&s(l))if(l+=o.length,l>=r||i(l))u.push("");else continue;n.push(u),u=[],l<r&&(l+=e[l]===lo&&e[l+1]===hr?2:1,c++)}return n}function yd(e){let t="";for(let n=e+1;n>0;n=Math.floor((n-1)/26))t=String.fromCharCode(65+(n-1)%26)+t;return t}function kd(e,t){let n=[],r=new Set;for(let o=0;o<t;o++){let s=e!==null&&o<e.length?e[o]:yd(o),i=s;for(let l=2;r.has(L(A(i)));l++)i=`${s} ${l}`;r.add(L(A(i))),n.push(i)}return n}var ll=(e,t)=>t<e.length?D(e[t]):x;g("load-csv",'["Reads CSV text into a block of rows, each a block of strings." data [string! binary!] /with "Another delimiter than a comma" delimiter [char! string!] /header "The first line names the columns; gives columns unless /as-records" /as-columns "A map of columns: name and block of values" /as-records "A block of maps, one per row; implies /header" /flat "One block with every field" /trim "Leave out spaces around fields" /quote "Another quote character than a double quote" qt-char [char!]]',(e,t)=>{let n=t.args,r=n[0],o=r.t===a.Binary?ue(new TextDecoder().decode(new Uint8Array(r.s.data.slice(r.i)))):r.s.data.slice(r.i),s=wt(n[1])?ul(n[2]):[44];if(s===null)return B("script","bad-delimiter","load-csv needs a delimiter that is not empty");let i=wt(n[3]),l=wt(n[4]),c=wt(n[5]),u=wt(n[6]);if(u&&(i||l||c))return B("script","bad-refines","load-csv/flat cannot have a header, columns or records");if(l&&c)return B("script","bad-refines","load-csv gives columns or records, not both");let d=vd(o,{delim:s,quote:wt(n[8])?n[9].v:md,trim:wt(n[7])});if(typeof d=="string")return B("syntax","csv",d);if(u)return b(Qe(d.flat().map(k=>D(k))));if(!i&&!l&&!c)return b(Qe(d.map(k=>Qe(k.map(M=>D(M))))));let f=i||c,p=f?d[0]??[]:null,h=f?d.slice(1):d,y=kd(p,h.reduce((k,M)=>Math.max(k,M.length),p?.length??0));return c?b(Qe(h.map(k=>an(y.flatMap((M,w)=>[D(M),ll(k,w)]))))):b(an(y.flatMap((k,M)=>[D(k),Qe(h.map(w=>ll(w,M)))])))});function Lt(e){return e.t===a.None||e.t===a.Unset?"":e.t===a.Date?JSON.parse(pt(e)).replace("T"," "):e.t===a.Money?Mt(e.v,2):V(e.t)&&e.t!==a.Binary?Oe(e.s.data,e.i):oe(e.t)?E(e.sym):j(e)}function xd(e,t,n){return e.includes(t)||e.includes(n)||e.includes(`
19
- `)||e.includes("\r")||e.length>0&&(e[0]===" "||e[e.length-1]===" ")?n+e.split(n).join(n+n)+n:e}function dl(e){return e.t===a.Map?e.s.data.filter((t,n)=>n%2===0):e.t===a.Object?e.ctx.keys.map(t=>({t:a.Word,sym:t,bind:null})):[]}var co=e=>L(A(Lt(e)));function bl(e,t){if(e.t===a.Map){let n=e.s.data;for(let r=0;r+1<n.length;r+=2)if(co(n[r])===t)return n[r+1];return x}if(e.t===a.Object){let n=e.ctx.keys.findIndex(r=>L(r)===t);return n<0?x:e.ctx.vals[n]}return x}function wd(e){let t=[],n=new Set;for(let r of e)for(let o of dl(r)){let s=co(o);n.has(s)||(n.add(s),t.push(o))}return[t,...e.map(r=>t.map(o=>bl(r,co(o))))]}var Oa=e=>e.t===a.Map||e.t===a.Object,Cd=e=>e.t===a.Block?e.s.data.slice(e.i):[e],Sd=new Set([a.Decimal,a.Percent,a.Money,a.Date,a.Time]);function cl(e,t,n){return e.map(r=>r.map(o=>xd(o,t,n)).join(t)+`
20
- `).join("")}function Md(e){let t=e[0];if(Oa(t)){let r=dl(t),o=r.map(l=>Cd(bl(t,co(l)))),s=o.reduce((l,c)=>Math.max(l,c.length),0),i=[r];for(let l=0;l<s;l++)i.push(o.map(c=>c[l]??x));return i}let n=t.s.data.slice(t.i);if(wt(e[3])){let r=q(e[4].v);if(r<1)return B("script","bad-skip","to-csv/skip needs a size of 1 or more");let o=[];for(let s=0;s<n.length;s+=r)o.push(n.slice(s,s+r));return o}return n.length>0&&n.every(Oa)?wd(n):n.length>0&&n[0].t===a.Block?n.every(r=>r.t===a.Block)?n.map(r=>r.s.data.slice(r.i)):B("script","bad-rows","to-csv needs every row to be a block"):n.some(r=>r.t===a.Block||Oa(r))?B("script","bad-rows","to-csv needs rows all of one kind: blocks, maps or objects"):n.length===0?[]:[n]}g("to-csv",'["Writes CSV text from rows: a block of blocks, of maps or objects (a header from their keys), a flat block with /skip, or a map of columns." data [block! map! object!] /with "Another delimiter than a comma" delimiter [char! string!] /skip "A flat block, so many fields to a row" size [integer!] /quote "Another quote character than a double quote" qt-char [char!] /language "Dates and amounts as a language writes them, and a semicolon where its decimals have a comma" lang [word! string!]]',(e,t,n)=>{let r=t.args,o=wt(r[5])?String.fromCodePoint(r[6].v):'"',s=null;if(wt(r[1])){let c=ul(r[2]);if(c===null)return B("script","bad-delimiter","to-csv needs a delimiter that is not empty");s=Oe(c)}let i=r[8];if(t.phase===0){let c=Md(r);if(!Array.isArray(c))return c;let u=c.map(f=>f.map(Lt));if(!wt(r[7]))return b(D(cl(u,s??",",o)));let d=[];return c.forEach((f,p)=>f.forEach((h,y)=>{Sd.has(h.t)&&d.push([p,y])})),t.data={rows:c,texts:u,todo:d,at:0,delim:s},t.phase=1,bn(e,"format-local",[me(1.5),i],"write values in a language")}let l=t.data;if(t.phase===1)l.delim===null&&(l.delim=$(n).includes(",")?";":","),t.phase=2;else{let[c,u]=l.todo[l.at++],d=$(n);l.texts[c][u]=l.rows[c][u].t===a.Date?d.replace(", "," "):d}if(l.at<l.todo.length){let[c,u]=l.todo[l.at];return bn(e,"format-local",[l.rows[c][u],i],"write values in a language")}return b(D(cl(l.texts,l.delim,o)))});function pl(e){return e.t===a.Binary?e.s.data.slice(e.i):cn($(e))}function fl(e,t){if(e.args[t]!==O)return 64;let n=q(e.args[t+1].v);return n===2||n===16||n===64?n:null}g("enbase",'["Writes bytes as text in base 64, or another base." value [binary! any-string!] /base "2, 16 or 64" base-value [integer!]]',(e,t)=>{let n=fl(t,1);return n===null?B("script","bad-base","the base must be 2, 16 or 64"):b({t:a.String,s:{data:ue(bi(pl(t.args[0]),n))},i:0})});g("debase",'["Reads bytes written as text in base 64, or another base." value [any-string! binary!] /base "2, 16 or 64" base-value [integer!]]',(e,t)=>{let n=fl(t,1);if(n===null)return B("script","bad-base","the base must be 2, 16 or 64");let r=t.args[0],o=r.t===a.Binary?new TextDecoder().decode(new Uint8Array(r.s.data.slice(r.i))):$(r),s=Hr(o,n);return s===null?B("script","bad-base",`the text is not valid base ${n}`):b({t:a.Binary,s:{data:s},i:0})});g("to-hex",'["The value in hexadecimal, as an issue." value [integer! tuple!] /size "Use this many digits" len [integer!]]',(e,t)=>{let n=t.args[0],r;if(n.t===a.Tuple?r=n.v.map(o=>o.toString(16).toUpperCase().padStart(2,"0")).join(""):r=BigInt.asUintN(64,BigInt(n.v)).toString(16).toUpperCase().padStart(16,"0"),t.args[1]===O){let o=Math.max(1,q(t.args[2].v));r=r.length>o?r.slice(r.length-o):r.padStart(o,"0")}return b({t:a.Issue,sym:A(r),bind:null})});function hl(e){let t=[],n=[],r=()=>{n.length>0&&t.push(...ue(new TextDecoder().decode(new Uint8Array(n)))),n=[]};for(let o=0;o<e.length;o++){let s=o+2<e.length?String.fromCodePoint(e[o+1],e[o+2]):"";e[o]===37&&/^[0-9A-Fa-f]{2}$/.test(s)?(n.push(parseInt(s,16)),o+=2):(r(),t.push(e[o]))}return r(),t}g("dehex",'["Turns %xx escapes in a string or URL back into characters." value [any-string!]]',(e,t)=>{let n=t.args[0];return b({t:n.t,s:{data:hl(n.s.data.slice(n.i))},i:0})});var Da=/^[A-Za-z0-9\-_.!~*'()]$/,Ed=/^[A-Za-z0-9\-_.!~*'();/?:@&=+$,#]$/;function Pa(e,t,n){let r="";for(let o of e){let s=String.fromCodePoint(o);if(n&&o===32)r+="+";else if(t.test(s))r+=s;else for(let i of cn(s))r+="%"+i.toString(16).toUpperCase().padStart(2,"0")}return r}g("enhex",'["Writes the characters a URL cannot hold as %xx escapes." value [any-string!] /uri "Write spaces as +, as forms send them"]',(e,t)=>{let n=t.args[0],r=n.t===a.Url||n.t===a.File?Ed:Da;return b({t:n.t,s:{data:ue(Pa(n.s.data.slice(n.i),r,t.args[1]===O))},i:0})});function uo(e){let t=[];e.t===a.Map?t.push(...e.s.data):e.t===a.Block?t.push(...e.s.data.slice(e.i)):e.t===a.Object&&e.ctx.keys.forEach((o,s)=>t.push({t:a.Word,sym:o,bind:null},e.ctx.vals[s]));let n=[],r=(o,s)=>{s.t!==a.None&&n.push(Pa(ue(o),Da,!1)+"="+Pa(ue(Lt(s)),Da,!1))};for(let o=0;o+1<t.length;o+=2){let s=t[o];if(!(s.t>=a.Word&&s.t<=a.Issue)&&s.t!==a.String)return null;let i=Lt(s),l=t[o+1];if(l.t===a.Block)for(let c of l.s.data.slice(l.i))r(i,c);else r(i,l)}return n.join("&")}g("to-query",'["Writes names and values as the query of a URL: q=caf%C3%A9&page=2." values [map! object! block!]]',(e,t)=>{let n=uo(t.args[0]);return n===null?B("script","bad-query","a query takes words or strings as names"):b(D(n))});var Td=/^[A-Za-z_][A-Za-z0-9_-]*$/;g("load-query",'["Reads the query of a URL as a map of strings; a name given twice holds a block." source [any-string!]]',(e,t)=>{let n=t.args[0],r=Oe(n.s.data,n.i);n.t===a.Url&&(r=r.includes("?")?r.slice(r.indexOf("?")+1):""),r.includes("#")&&(r=r.slice(0,r.indexOf("#"))),r.startsWith("?")&&(r=r.slice(1));let o=[],s=[];for(let l of r.split("&")){if(l==="")continue;let c=l.indexOf("="),u=h=>Oe(hl(ue(h.replace(/\+/g," ")))),d=u(c<0?l:l.slice(0,c)),f=D(c<0?"":u(l.slice(c+1))),p=o.indexOf(d);p<0?(o.push(d),s.push([f])):s[p].push(f)}let i=[];return o.forEach((l,c)=>{i.push(Td.test(l)?{t:a.Word,sym:A(l),bind:null}:D(l)),i.push(s[c].length===1?s[c][0]:Qe(s[c]))}),b(an(i))});var Id={md5:ol,sha1:al,sha256:sl};g("checksum",'["A checksum or hash of the bytes: md5 sha1 sha256 give a binary, crc32 adler32 an integer." data [binary! any-string!] method [word!]]',(e,t)=>{let n=pl(t.args[0]),r=E(L(t.args[1].sym)).toLowerCase();if(r==="crc32")return b(R(nl(n)));if(r==="adler32")return b(R(rl(n)));let o=Id[r];return o===void 0?B("script","bad-method",`checksum has no method ${r}: use md5 sha1 sha256 crc32 adler32`):b({t:a.Binary,s:{data:o(n)},i:0})});var Ld=e=>e===O,Ad=/^[A-Za-z_][A-Za-z0-9_-]*$/;function Wa(e){return Ad.test(e)?{t:a.Word,sym:A(e),bind:null}:D(e)}var Bd={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function ja(e){return e.replace(/&(#x[0-9A-Fa-f]+|#[0-9]+|[A-Za-z]+);/g,(t,n)=>{if(n[0]==="#"){let r=n[1]==="x"?parseInt(n.slice(2),16):parseInt(n.slice(1),10);return r>0&&r<=1114111?String.fromCodePoint(r):t}return Bd[n]??t})}function $d(e){let t=e.charCodeAt(0)===65279?1:0,n=e.length,r=[],o=[],s="",i=f=>{let p=1;for(let h=0;h<f;h++)e.charCodeAt(h)===10&&p++;return p},l=()=>r.length>0?r[r.length-1].out:o,c=()=>{s!==""&&/\S/.test(s)&&l().push(x,D(s),x),s=""},u=(f,p)=>{let h=e.indexOf(f,t);return h<0?`${p} on line ${i(t)} never ends`:h+f.length};for(;t<n;){let f=e.indexOf("<",t);if(f<0){s+=ja(e.slice(t));break}s+=ja(e.slice(t,f)),t=f;let p;if(e.startsWith("<!--",t))p=u("-->","a comment");else if(e.startsWith("<![CDATA[",t))p=u("]]>","a CDATA section"),typeof p=="number"&&(s+=e.slice(t+9,p-3));else if(e.startsWith("<?",t))p=u("?>","a processing instruction");else if(e.startsWith("<!",t)){let h=e.indexOf("[",t),y=e.indexOf(">",t);h>=0&&y>=0&&h<y?(t=h,p=u("]","a DOCTYPE"),typeof p=="number"&&(t=p,p=u(">","a DOCTYPE"))):p=u(">","a DOCTYPE")}else if(e[t+1]==="/"){let h=/^<\/([^\s>]+)\s*>/.exec(e.slice(t,t+512));if(h===null)return`a closing tag on line ${i(t)} is not written right`;c();let y=r.pop();if(y===void 0)return`</${h[1]}> on line ${i(t)} closes no tag`;if(y.name!==h[1])return`</${h[1]}> on line ${i(t)} closes <${y.name}> of line ${i(y.at)}`;l().push(Wa(y.name),Qe(y.out),y.atts),p=t+h[0].length}else{let h=/^<([^\s/>=]+)/.exec(e.slice(t,t+512));if(h===null)return`a < on line ${i(t)} starts no tag; write it &lt;`;c();let y=h[1],k=t+h[0].length,M=[];for(;;){for(;k<n&&/\s/.test(e[k]);)k++;if(k>=n)return`<${y}> on line ${i(t)} never ends`;if(e[k]===">"||e.startsWith("/>",k))break;let v=/^([^\s/>=]+)\s*=\s*("[^"]*"|'[^']*')/.exec(e.slice(k,k+4096));if(v===null)return`an attribute of <${y}> on line ${i(k)} is not written right`;M.push(Wa(v[1]),D(ja(v[2].slice(1,-1)))),k+=v[0].length}let w=M.length===0?x:an(M);e[k]==="/"?(l().push(Wa(y),Qe([]),w),p=k+2):(r.push({name:y,atts:w,out:[],at:t}),p=k+1)}if(typeof p=="string")return p;t=p}let d=r.pop();return d!==void 0?`<${d.name}> on line ${i(d.at)} is never closed`:(c(),o)}g("load-xml",'["Reads XML text into a block of nodes, each its name, content and attributes; a text is none, the text and none." source [string! binary!]]',(e,t)=>{let n=t.args[0],r=n.t===a.Binary?new TextDecoder().decode(new Uint8Array(n.s.data.slice(n.i))):Oe(n.s.data,n.i),o=$d(r);return typeof o=="string"?B("syntax","xml",o):b(Qe(o))});var Ra=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Nd=e=>Ra(e).replace(/"/g,"&quot;");function ml(e){return e.t===a.Word||e.t===a.SetWord||e.t===a.LitWord?E(e.sym):e.t===a.String?Oe(e.s.data,e.i):null}var bo=e=>e.t===a.None||e.t===a.Word&&E(e.sym).toLowerCase()==="none";function Od(e){let t=[];if(bo(e))return"";if(e.t===a.Map)t.push(...e.s.data);else if(e.t===a.Block)t.push(...e.s.data.slice(e.i));else if(e.t===a.Object)e.ctx.keys.forEach((r,o)=>t.push({t:a.Word,sym:r,bind:null},e.ctx.vals[o]));else return null;let n="";for(let r=0;r+1<t.length;r+=2){let o=ml(t[r]);if(o===null)return null;bo(t[r+1])||(n+=` ${o}="${Nd(Lt(t[r+1]))}"`)}return n}function Dd(e){let t="",n=[{nodes:e,at:0}];for(;n.length>0;){let r=n[n.length-1];if(typeof r=="string"||r.at>=r.nodes.length){n.pop(),typeof r=="string"&&(t+=r);continue}if(r.at+3>r.nodes.length)return{error:"every node is three values: name, content and attributes"};let[o,s,i]=[r.nodes[r.at],r.nodes[r.at+1],r.nodes[r.at+2]];if(r.at+=3,bo(o)){t+=Ra(Lt(s));continue}let l=ml(o);if(l===null)return{error:`a node's name is a word or a string, not ${Lt(o)}`};let c=Od(i);if(c===null)return{error:`the attributes of <${l}> are a map, an object or a block`};let u=s.t===a.Block?s.s.data.slice(s.i):bo(s)?[]:null;u===null?t+=`<${l}${c}>${Ra(Lt(s))}</${l}>`:u.length===0?t+=`<${l}${c}/>`:(t+=`<${l}${c}>`,n.push(`</${l}>`,{nodes:u,at:0}))}return{xml:t}}g("to-xml",'["Writes XML text from a block of nodes, each its name, content and attributes, as load-xml gives them." nodes [block!] /declaration "Start with the <?xml ...?> line a whole document needs"]',(e,t)=>{let n=t.args[0],r=Dd(n.s.data.slice(n.i));return"error"in r?B("script","bad-xml",r.error):b(D((Ld(t.args[1])?`<?xml version="1.0" encoding="UTF-8"?>
21
- `:"")+r.xml))});function vl(e,t){let n=e.s.data[t>>3];return(n!==void 0&&(n&128>>(t&7))!==0)!==e.neg}function po(e,t){let n=t>>3;for(;e.length<=n;)e.push(0);e[n]|=128>>(t&7)}function Fa(e,t){switch(e.t){case a.Char:return po(t,e.v),null;case a.Integer:return po(t,q(e.v)),null;case a.String:case a.File:case a.Email:case a.Url:case a.Tag:for(let n of e.s.data.slice(e.i))po(t,n);return null;case a.Binary:return e.s.data.slice(e.i).forEach((n,r)=>{t[r]=(t[r]??0)|n}),null;case a.Block:{let n=e.s.data.slice(e.i);for(let r=0;r<n.length;r++){let o=n[r],s=n[r+1];if(s!==void 0&&s.t===a.Word&&n[r+2]!==void 0&&Pd(s)){let l=gl(o),c=gl(n[r+2]);if(l===null||c===null||c<l)return"bad range in bitset spec";for(let u=l;u<=c;u++)po(t,u);r+=2;continue}let i=Fa(o,t);if(i!==null)return i}return null}}return"bad bitset spec"}function Pd(e){return e.t===a.Word&&E(e.sym)==="-"}function gl(e){return e.t===a.Char?e.v:e.t===a.Integer?q(e.v):null}var T={Some:0,Any:1,Opt:2,While:3,Not:4,Ahead:5,To:6,Thru:7,Set:8,Copy:9,Into:10,If:11,Collect:12,Keep:13,End:14,Skip:15,None:16,Fail:17,Break:18,Quote:19,Bar:20,Remove:21,Insert:22,Change:23,Only:24,Accept:25,Reject:26,Return:27},Wd=new Map([["some",T.Some],["any",T.Any],["opt",T.Opt],["while",T.While],["not",T.Not],["ahead",T.Ahead],["to",T.To],["thru",T.Thru],["set",T.Set],["copy",T.Copy],["into",T.Into],["if",T.If],["collect",T.Collect],["keep",T.Keep],["end",T.End],["skip",T.Skip],["none",T.None],["fail",T.Fail],["break",T.Break],["quote",T.Quote],["remove",T.Remove],["insert",T.Insert],["change",T.Change],["only",T.Only],["accept",T.Accept],["reject",T.Reject],["return",T.Return],["|",T.Bar]].map(([e,t])=>[L(A(e)),t]));function _e(e){return e!==void 0&&e.t===a.Word?Wd.get(L(e.sym))??-1:-1}function Ua(e,t){for(;;){let n=e[t];if(n===void 0)return-1;if(n.t===a.Integer){t+=e[t+1]?.t===a.Integer?2:1;continue}switch(_e(n)){case T.Some:case T.Any:case T.Opt:case T.While:case T.Not:case T.Ahead:case T.To:case T.Thru:case T.Into:case T.Keep:case T.Remove:case T.Return:t+=1;continue;case T.Insert:{let r=t+(_e(e[t+1])===T.Only?2:1);return r<e.length?r+1:-1}case T.Change:{let r=Ua(e,t+(_e(e[t+1])===T.Only?2:1));return r>=0&&r<e.length?r+1:-1}case T.Set:case T.Copy:t+=2;continue;case T.Collect:t+=_e(e[t+1])===T.Set?3:1;continue;case T.If:return e[t+1]?.t===a.Paren?t+2:-1;case T.Quote:return t+1<e.length?t+2:-1}return t+1}}var ne={Block:0,Rep:1,Look:2,Scan:3,Cap:4,Into:5,Coll:6,Act:7,Edit:8};function Ze(e,t){return e.err=t,null}var mr=e=>e.input.s.data.length;function Ha(e,t){let n=e.input.s.data.slice(t,e.pos);return{t:e.input.t,s:{data:n},i:0}}function yl(e,t){let n=e.input.s.data[t];return n===void 0?x:U(e.input.t)?n:e.input.t===a.Binary?{t:a.Integer,v:n}:{t:a.Char,v:n}}function za(e,t){let n=e.input.s.data,r=e.pos;if(U(e.input.t)){let i=n[r];if(i===void 0)return-1;switch(t.t){case a.Datatype:return i.t===t.k?r+1:-1;case a.Typeset:return(t.bits&ke(i.t))!==0n?r+1:-1;case a.LitWord:return i.t===a.Word&&L(i.sym)===L(t.sym)?r+1:-1}return(e.cased?at(i,t):dt(i,t))?r+1:-1}let o=e.input.t===a.Binary,s=(i,l)=>e.cased||o?i===l:Pe(i)===Pe(l);if(t.t===a.Bitset){let i=n[r];return i!==void 0&&vl(t,i)?r+1:-1}if(t.t===a.Char||V(t.t)||t.t===a.Binary||o&&t.t===a.Integer){let i=$n(e.input.t,t,!1).add;if(r+i.length>n.length)return-1;for(let l=0;l<i.length;l++)if(!s(n[r+l],i[l]))return-1;return r+i.length}return Ze(e,`cannot match ${t.t===a.Integer?"an integer":"that value"} in a string`),-1}function _a(e,t,n,r,o){let{add:s,nl:i}=$n(e.input.t,r,o);return ze(e.input.s,t,n-t,s,i),e.pos=t+s.length,e.edits++,Ee(e,!0)}function kl(e,t,n,r,o,s){let i=t.data[n];if(i.t===a.Paren)return e.stack.push({k:ne.Act,how:"put",from:r,to:o,only:s}),{k:"do",s:i.s,i:i.i};if(i.t===a.Word){let l=ge(i);return l===null||l.t===a.Unset?Ze(e,"the value to put in has no value"):_a(e,r,o,l,s)}return _a(e,r,o,i,s)}function xl(e,t){return e.ret=t,e.stack.length=0,null}var jd=e=>E(e.sym);function Ee(e,t){return e.res=t,null}function Rd(e,t,n){let r=t.data[n];if(r!==void 0&&r.t===a.Block)return r;if(r!==void 0&&r.t===a.Word){let o=ge(r);if(o!==null&&o.t===a.Block)return o}return Ze(e,"into needs a rule block")}function fo(e,t){return e.stack.push({k:ne.Block,rules:t.s,ip:t.i,next:0,alt:0,mark:null,markLen:0,started:!1}),null}function Jt(e,t,n){let r=t.data,o=r[n];switch(o.t){case a.Integer:{let c=q(o.v),u=r[n+1],d=u?.t===a.Integer;return e.stack.push({k:ne.Rep,rules:t,sub:n+(d?2:1),min:c,max:d?q(u.v):c,n:0,from:e.pos,edits:e.edits,stall:!1}),null}case a.SetWord:return Ie(o,{...e.input,i:e.pos}),Ee(e,!0);case a.GetWord:{let c=ge(o);return c===null||!(U(c.t)||V(c.t))||c.s!==e.input.s?Ze(e,"a get-word in parse must refer to a position in the input"):(e.pos=c.i,Ee(e,!0))}case a.Paren:return e.stack.push({k:ne.Act,how:"action"}),{k:"do",s:o.s,i:o.i};case a.Block:return fo(e,o);case a.Word:break;default:{let c=za(e,o);return c<0?Ee(e,!1):(e.pos=c,Ee(e,!0))}}let s=o;switch(_e(s)){case T.Some:return e.stack.push({k:ne.Rep,rules:t,sub:n+1,min:1,max:1/0,n:0,from:e.pos,edits:e.edits,stall:!1}),null;case T.Any:case T.While:return e.stack.push({k:ne.Rep,rules:t,sub:n+1,min:0,max:1/0,n:0,from:e.pos,edits:e.edits,stall:_e(s)===T.While}),null;case T.Opt:return e.stack.push({k:ne.Rep,rules:t,sub:n+1,min:0,max:1,n:0,from:e.pos,edits:e.edits,stall:!1}),null;case T.Not:case T.Ahead:return e.stack.push({k:ne.Look,rules:t,sub:n+1,not:_e(s)===T.Not,from:e.pos}),null;case T.To:case T.Thru:return e.stack.push({k:ne.Scan,rules:t,sub:n+1,thru:_e(s)===T.Thru,start:e.pos,at:e.pos}),null;case T.Set:case T.Copy:{let c=r[n+1];return c===void 0||c.t!==a.Word?Ze(e,`${_e(s)===T.Set?"set":"copy"} needs a word`):(e.stack.push({k:ne.Cap,rules:t,sub:n+2,how:_e(s)===T.Set?"set":"copy",word:c,from:e.pos}),null)}case T.Keep:{let c=r[n+1];return c!==void 0&&c.t===a.Paren?(e.stack.push({k:ne.Act,how:"keep"}),{k:"do",s:c.s,i:c.i}):(e.stack.push({k:ne.Cap,rules:t,sub:n+1,how:"keep",word:null,from:e.pos}),null)}case T.Collect:{let c=_e(r[n+1])===T.Set,u=c?r[n+2]:void 0;return c&&(u===void 0||u.t!==a.Word)?Ze(e,"collect set needs a word"):(e.stack.push({k:ne.Coll,rules:t,sub:n+(c?3:1),word:u??null}),null)}case T.Into:{let c=e.input.s.data[e.pos],u=Rd(e,t,n+1);return u===null?null:!U(e.input.t)||c===void 0||!(U(c.t)||V(c.t))?Ee(e,!1):(e.stack.push({k:ne.Into,outer:e.input,outerPos:e.pos}),e.input=c,e.pos=c.i,fo(e,u))}case T.If:{let c=r[n+1];return e.stack.push({k:ne.Act,how:"if"}),{k:"do",s:c.s,i:c.i}}case T.End:return Ee(e,e.pos>=mr(e));case T.Skip:return e.pos>=mr(e)?Ee(e,!1):(e.pos++,Ee(e,!0));case T.None:return Ee(e,!0);case T.Fail:return Ee(e,!1);case T.Break:case T.Accept:case T.Reject:{let c=_e(s)===T.Reject,u=null;for(;e.stack.length>0&&u===null;){let f=e.stack.pop();f.k===ne.Block?u=f:f.k===ne.Into&&(e.input=f.outer,e.pos=f.outerPos)}if(u===null)return Ze(e,`${jd(s)} outside of a rule block`);let d=e.stack[e.stack.length-1];return d!==void 0&&d.k===ne.Rep?(e.stack.pop(),c?(e.pos=d.from,Ee(e,d.n>=d.min)):Ee(e,!0)):c?(e.pos=u.alt,u.mark!==null&&(u.mark.length=u.markLen),Ee(e,!1)):Ee(e,!0)}case T.Return:{let c=r[n+1];return c!==void 0&&c.t===a.Paren?(e.stack.push({k:ne.Act,how:"return"}),{k:"do",s:c.s,i:c.i}):(e.stack.push({k:ne.Cap,rules:t,sub:n+1,how:"return",word:null,from:e.pos}),null)}case T.Quote:{let c=za(e,r[n+1]);return c<0?Ee(e,!1):(e.pos=c,Ee(e,!0))}case T.Remove:return e.stack.push({k:ne.Edit,rules:t,sub:n+1,val:-1,only:!1,from:e.pos}),null;case T.Insert:{let c=_e(r[n+1])===T.Only;return kl(e,t,n+(c?2:1),e.pos,e.pos,c)}case T.Change:{let c=_e(r[n+1])===T.Only,u=n+(c?2:1);return e.stack.push({k:ne.Edit,rules:t,sub:u,val:Ua(r,u),only:c,from:e.pos}),null}case T.Only:return Ze(e,"only goes after insert or change");case T.Bar:return Ze(e,"misplaced |")}let i=ge(s);if(i===null||i.t===a.Unset||i.t===a.None)return Ze(e,"rule word has no value");if(i.t===a.Block)return fo(e,i);let l=za(e,i);return l<0?Ee(e,!1):(e.pos=l,Ee(e,!0))}function Fd(e,t){if(t!==null){let n=e.stack.pop();switch(n.how){case"action":e.res=!0;break;case"if":e.res=Le(t);break;case"keep":{let r=e.colls[e.colls.length-1];if(r===void 0)return Ze(e,"keep outside of collect");t.t!==a.Unset&&r.push(t),e.res=!0;break}case"put":if(t.t===a.Unset)return Ze(e,"the value to put in has no value");_a(e,n.from,n.to,t,n.only);break;case"return":return xl(e,t)}}for(;;){let n=e.stack[e.stack.length-1];if(n===void 0)return null;let r=e.res;e.res=null;let o=Hd(e,n,r);if(o!==null||e.err!==null)return o}}function Hd(e,t,n){let r=o=>(e.stack.pop(),Ee(e,o));switch(t.k){case ne.Block:{let o=t.rules.data;if(!t.started)t.started=!0,t.alt=e.pos,t.mark=e.colls[e.colls.length-1]??null,t.markLen=t.mark?.length??0;else if(n===!0)t.ip=t.next;else if(n===!1){let s=t.ip;for(;s<o.length&&_e(o[s])!==T.Bar;)s++;if(e.pos=t.alt,t.mark!==null&&(t.mark.length=t.markLen),s>=o.length)return r(!1);t.ip=s+1}return t.ip>=o.length||_e(o[t.ip])===T.Bar?r(!0):(t.next=Ua(o,t.ip),t.next<0?Ze(e,"rule ends too early"):Jt(e,t.rules,t.ip))}case ne.Rep:return n===null?(t.from=e.pos,Jt(e,t.rules,t.sub)):n===!1?(e.pos=t.from,r(t.n>=t.min)):(t.n++,!t.stall&&e.pos===t.from&&e.edits===t.edits||t.n>=t.max?r(!0):(t.from=e.pos,t.edits=e.edits,Jt(e,t.rules,t.sub)));case ne.Look:return n===null?(t.from=e.pos,Jt(e,t.rules,t.sub)):(e.pos=t.from,r(t.not?!n:n));case ne.Scan:return n===!0?(t.thru||(e.pos=t.at),r(!0)):n===!1&&(t.at++,t.at>mr(e))?(e.pos=t.start,r(!1)):(e.pos=t.at,Jt(e,t.rules,t.sub));case ne.Cap:{if(n===null)return t.from=e.pos,Jt(e,t.rules,t.sub);if(n===!1)return r(!1);if(t.how==="return")return xl(e,Ha(e,t.from));if(t.how==="set")Ie(t.word,e.pos>t.from?yl(e,t.from):x);else if(t.how==="copy")Ie(t.word,Ha(e,t.from));else{let o=e.colls[e.colls.length-1];if(o===void 0)return Ze(e,"keep outside of collect");e.pos-t.from===1?o.push(yl(e,t.from)):e.pos>t.from&&o.push(Ha(e,t.from))}return r(!0)}case ne.Into:{let o=n===!0&&e.pos>=mr(e);return e.input=t.outer,e.pos=o?t.outerPos+1:t.outerPos,r(o)}case ne.Coll:{if(n===null)return e.colls.push([]),Jt(e,t.rules,t.sub);let o=e.colls.pop();if(n){let s={t:a.Block,s:{data:o},i:0};t.word!==null?Ie(t.word,s):e.colls.length>0?e.colls[e.colls.length-1].push(s):e.out=s}return r(n)}case ne.Edit:return n===null?(t.from=e.pos,Jt(e,t.rules,t.sub)):n===!1?r(!1):(e.stack.pop(),t.val<0?(ze(e.input.s,t.from,e.pos-t.from,[]),e.pos=t.from,e.edits++,Ee(e,!0)):kl(e,t.rules,t.val,t.from,e.pos,t.only));case ne.Act:return Ze(e,"internal: action frame without a value")}}g("parse",'["Checks the input against a block of rules; true if they match all of it." input [series!] rules [block!] /case]',(e,t,n)=>{if(t.phase===0){t.phase=1;let s=t.args[0],i={input:s,pos:s.i,stack:[],res:null,colls:[],out:null,cased:t.args[2]===O,err:null,edits:0,ret:null};fo(i,t.args[1]),t.data=i}let r=t.data,o=Fd(r,n);return r.err!==null?B("script","parse",r.err):o!==null?o:r.ret!==null?b(r.ret):r.out!==null?b(r.out):b(Z(r.res===!0&&r.pos>=mr(r)))});g("charset",'["Makes a bitset of characters, for parse." spec [char! integer! any-string! binary! block!]]',(e,t)=>{let n=[],r=Fa(t.args[0],n);return r!==null?B("script","bad-bitset",r):b({t:a.Bitset,s:{data:n},neg:!1})});g("complement",'["The opposite: a bitset of everything else, a logic negated, an integer with its bits flipped." value [bitset! logic! integer!]]',(e,t)=>{let n=t.args[0];if(n.t===a.Bitset)return b({t:a.Bitset,s:{data:n.s.data.slice()},neg:!n.neg});if(n.t===a.Logic)return b(Z(!n.v));let r=Fe(~BigInt(n.v));return b(r===null?x:{t:a.Integer,v:r})});var wl=String.raw`
6
+ `;)this.i++;else break}return t}parseSeries(t){let n=[],r=[],o=[],a=this.i-1;for(;;){let l=this.skipSpace(),c=this.src[this.i];if(c===void 0){t!==null&&this.fail(`missing ${t}`,a);break}if(c==="]"||c===")"){c!==t&&this.fail(`unexpected ${c}`),this.i++;break}let u=Dl(this.line,this.col());n.push(this.parseValue()),r.push(l),o.push(u)}let i={data:n,nl:r,pos:o};return this.file!==void 0&&(i.file=this.file),i}parseValue(){let t=this.src;switch(t[this.i]){case"[":return this.i++,{t:s.Block,s:this.parseSeries("]"),i:0};case"(":return this.i++,{t:s.Paren,s:this.parseSeries(")"),i:0};case'"':return this.str(s.String,this.quoted());case"{":return this.str(s.String,this.braced());case"}":return this.fail("unexpected }");case"#":return this.hash();case"%":return this.percentSign();case"<":if(/[A-Za-z/!?]/.test(t[this.i+1]??""))return this.tag();break}let r=/^(2|16|64)#\{/.exec(t.slice(this.i,this.i+4));return r?(this.i+=r[1].length+1,this.binary(Number(r[1]))):this.atom()}str(t,n){return{t,s:{data:n},i:0}}quoted(){let t=this.src,n=this.i;this.i++;let r=[];for(;;){let o=t[this.i];if((o===void 0||o===`
7
+ `)&&this.fail('missing " to close string',n),o==='"')return this.i++,r;if(o==="^"){let i=Qa(t,this.i+1);i||this.fail("invalid escape in string"),r.push(i.cp),this.i=i.next;continue}let a=t.codePointAt(this.i);r.push(a),this.i+=a>65535?2:1}}braced(){let t=this.src,n=this.i;this.i++;let r=[],o=1;for(;;){let a=t[this.i];if(a===void 0&&this.fail("missing } to close string",n),a==="^"){let l=Qa(t,this.i+1);l||this.fail("invalid escape in string"),r.push(l.cp),this.i=l.next;continue}if(a==="{"&&o++,a==="}"&&--o===0)return this.i++,r;a===`
8
+ `&&this.newline(this.i);let i=t.codePointAt(this.i);r.push(i),this.i+=i>65535?2:1}}tag(){let t=this.src,n=this.i;this.i++;let r=null;for(;this.i<t.length;){let o=t[this.i];if(r)o===r&&(r=null);else if(o==='"'||o==="'")r=o;else if(o===">"){let a=t.slice(n+1,this.i);return this.i++,this.str(s.Tag,he(a))}o===`
9
+ `&&this.newline(this.i),this.i++}return this.fail("missing > to close tag",n)}hash(){let t=this.src[this.i+1];if(t==='"'){this.i++;let o=this.i,a=this.quoted();return a.length!==1&&this.fail("a char! must hold exactly one character",o),pt(a[0])}if(t==="{")return this.i++,this.binary(16);if(t==="["){this.i+=2;let o=this.i-2,a=this.parseSeries("]");return this.construct(a,o)}if(t==="("){this.i+=2;let o=this.i-2,a=this.parseSeries(")");return this.mapOf(a,o)}let n=this.i;this.i++;let r=this.span();return r===""&&this.fail("invalid issue",n),{t:s.Issue,sym:A(r),bind:null}}binary(t){let n=this.src,r=this.i,o=n.indexOf("}",this.i);o<0&&this.fail("missing } to close binary",r);let a=n.slice(this.i+1,o);for(let l=this.i;l<o;l++)n[l]===`
10
+ `&&this.newline(l);this.i=o+1;let i=jo(a,t);return i===null&&this.fail(`invalid ${t===16?"hex":`base-${t}`} binary`,r),{t:s.Binary,s:{data:i},i:0}}mapOf(t,n){t.data.length%2!==0&&this.fail("a map! needs key value pairs",n);let r=t.data.map((o,a)=>a%2===0&&o.t===s.SetWord?{t:s.Word,sym:o.sym,bind:null}:o);return{t:s.Map,s:{data:r}}}construct(t,n){let r=t.data,o=r[0],a=()=>this.fail("invalid construction syntax",n);if(!o||o.t!==s.Word)return a();let i=Rr(o).toLowerCase();if(r.length===1){switch(i){case"none":case"none!":return k;case"unset":case"unset!":return re;case"true":return P;case"false":return we}return a()}let l=Vn(i);if(l===void 0)return a();let c=r[1];switch(l){case s.Logic:if(r.length===2&&c.t===s.Word){let d=Rr(c).toLowerCase();if(d==="true")return P;if(d==="false")return we}return a();case s.Datatype:{if(r.length!==2||c.t!==s.Word)return a();let d=Vn(Rr(c));return d===void 0?a():pn(d)}case s.Typeset:{if(r.length!==2||c.t!==s.Block)return a();let d=0n;for(let f of c.s.data){let p=f.t===s.Word?Vn(Rr(f)):void 0;if(p===void 0)return a();d|=1n<<BigInt(p)}return en(d)}case s.Bitset:{let d=r.length===3&&c.t===s.Word&&Rr(c).toLowerCase()==="not",f=d?r[2]:c;return f.t!==s.Binary||r.length!==(d?3:2)?a():jl([...f.s.data],d)}case s.Object:{if(r.length!==2||c.t!==s.Block)return a();let d=Le(),f=c.s.data;for(let p=0;p<f.length;p+=2){let h=f[p];if(h.t!==s.SetWord||p+1>=f.length)return a();d.keys.push(h.sym),d.vals.push(Of(f[p+1]))}return Oo(d)}case s.Map:return r.length!==2||c.t!==s.Block?a():this.mapOf(c.s,n)}let u=r[2];if(r.length===3&&u!==void 0&&u.t===s.Integer){let d=q(u.v)-1;if(!(X(l)&&X(c.t)||_(l)&&_(c.t))||d<0)return a();let p=c;return d>p.s.data.length?a():{...p,t:l,i:d}}return a()}percentSign(){let t=this.src;if(t[this.i+1]==='"')return this.i++,this.str(s.File,this.quoted());let r=this.i;for(;!Jn(t[r]);)r++;if(/^%%?:?$/.test(t.slice(this.i,r)))return this.atom();let o=this.i;this.i++;let a=this.span();try{return this.str(s.File,he(decodeURIComponent(a)))}catch{return this.fail("invalid file",o)}}span(){let t=this.src,n=this.i;for(;!Jn(t[this.i]);)this.i++;return t.slice(n,this.i)}atom(){let t=this.i,n=this.span();if(n.endsWith("/")&&this.src[this.i]==="("&&n.length>1&&!nt.url.test(n))return this.i=t,this.path();let r=this.classify(n,t);return r==="path"?(this.i=t,this.path()):r}classify(t,n){let r=t[0];if(r==="'"||r===":"){let o=t.slice(1);return bn(o)?this.wordCell(r==="'"?s.LitWord:s.GetWord,o):o.includes("/")&&!o.startsWith("/")?"path":this.fail(`invalid ${r==="'"?"lit-word":"get-word"}: ${t}`,n)}if(t.endsWith(":")&&t.length>1){let o=t.slice(0,-1);if(bn(o))return this.wordCell(s.SetWord,o);if(o.includes("/")&&!o.startsWith("/")&&!/^[+-]?\d/.test(o))return"path"}if(/^[+-]?[\d.,$]/.test(t)&&!bn(t)){let o=this.number(t,n);if(o)return o}if(nt.money.test(t))return this.number(t,n);if(nt.url.test(t))return this.str(s.Url,he(t));if(nt.email.test(t)&&r!=="/")return this.str(s.Email,he(t));if(r==="/"){if(t==="/"||t==="//")return this.wordCell(s.Word,t);let o=t.slice(1);return bn(o)?this.wordCell(s.Refinement,o):this.fail(`invalid refinement: ${t}`,n)}return t.includes("/")?"path":bn(t)?this.wordCell(s.Word,t):this.fail(`invalid value: ${t}`,n)}wordCell(t,n){return{t,sym:A(n),bind:null}}number(t,n){let r;if(nt.integer.test(t)){let o=Zn(t);return o===null&&this.fail(`integer out of 64-bit range: ${t}`,n),H(o)}if(nt.decimal.test(t))return ke(Po(t));if(r=nt.percent.exec(t))return $t($f(r[1],-2));if(r=nt.money.exec(t)){let o=El(r[4]),a=r[1]==="-"!=(r[3]==="-");return ft(a?{d:-o.d,e:o.e}:o,(r[2]??"").toUpperCase())}if(r=nt.pair.exec(t))return Bt(Po(r[1]),Po(r[2]));if(nt.tuple.test(t)){let o=t.split(".").map(Number);return o.some(a=>a>255)&&this.fail(`tuple values must be 0-255: ${t}`,n),$o(o)}if(r=nt.time.exec(t)){let o=Hl(r[2],r[3],r[4]);return Ie(r[1]==="-"?-o:o)}return(r=nt.date.exec(t))?this.dateCell(r,t,n):null}dateCell(t,n,r){let[,o,,a,i,l]=t,c,u;o.length>=3?(c=Number(o),u=Number(i)):(u=Number(o),c=Number(i));let d;if(/^\d+$/.test(a))d=Number(a);else{let p=a.toLowerCase();d=p.length>=3?If.findIndex(h=>h.startsWith(p))+1:0}(d<1||d>12||u<1||u>Bf(c,d))&&this.fail(`invalid date: ${n}`,r);let f={y:c,m:d,d:u,time:null,zone:null};if(l!==void 0){let p=nt.dateTime.exec(l);p||this.fail(`invalid time in date: ${n}`,r),f.time=Hl(p[1],p[2],p[3]),p[4]!==void 0&&(f.zone=Nf(p[4]))}return fn(f)}path(){let t=this.src,n=this.i,r=s.Path;t[this.i]===":"?(r=s.GetPath,this.i++):t[this.i]==="'"&&(r=s.LitPath,this.i++);let o=[];for(;;){if(t[this.i]==="(")this.i++,o.push({t:s.Paren,s:this.parseSeries(")"),i:0});else{let a=this.i;for(;!Jn(t[this.i])&&t[this.i]!=="/";)this.i++;let i=t.slice(a,this.i);i.endsWith(":")&&Jn(t[this.i])&&r===s.Path&&o.length>0&&(r=s.SetPath,i=i.slice(0,-1)),o.push(this.segment(i,a))}if(t[this.i]==="/"){this.i++,Jn(t[this.i])&&t[this.i]!=="("&&this.fail("path ends with /",n);continue}(!Jn(t[this.i])||t[this.i]==="(")&&this.fail("invalid path",n);break}return o[0].t!==s.Word&&o[0].t!==s.Paren&&this.fail("a path must start with a word",n),{t:r,s:{data:o},i:0}}segment(t,n){if(t===""&&this.fail("empty path segment",n),nt.integer.test(t)){let r=Zn(t);if(r!==null)return H(r)}return t[0]===":"&&bn(t.slice(1))?this.wordCell(s.GetWord,t.slice(1)):t[0]==="'"&&bn(t.slice(1))?this.wordCell(s.LitWord,t.slice(1)):bn(t)?this.wordCell(s.Word,t):this.fail(`invalid path segment: ${t}`,n)}};function Rr(e){return"sym"in e?M(e.sym):""}function Of(e){if(e.t===s.Word)switch(M(e.sym).toLowerCase()){case"none":return k;case"true":return P;case"false":return we}return e}function Hl(e,t,n){let r=Number(e)*3600+Number(t)*60,o=n===void 0?0:Po(n);return Math.round(r*Fl+o*Fl)}function Nf(e){if(e==="Z"||e==="z")return 0;let t=/^([+-])(\d{1,2})(?::?(\d{2}))?$/.exec(e),n=Number(t[2])*60+Number(t[3]??0);return t[1]==="-"?-n:n}var jf=8;function te(e,t){let n=I(t),r=e.keys;if(r.length<=jf&&e.idx===void 0){for(let i=0;i<r.length;i++)if(I(r[i])===n)return i;return-1}let o=e.idx,a=e.idxN??0;for(o===void 0&&(o=new Map,e.idx=o,a=0);a<r.length;a++){let i=I(r[a]);o.has(i)||o.set(i,a)}return e.idxN=a,o.get(n)??-1}function Xn(e,t,n=re){return e.keys.push(t),e.vals.push(n),e.keys.length-1}function zl(e,t){let n=te(e,t);return n>=0?n:Xn(e,t)}function xe(e){let t=e.bind;if(t!==null&&e.idx!==void 0)return t.vals[e.idx];for(let n=t;n!==null;n=n.parent){let r=te(n,e.sym);if(r>=0)return n.vals[r];if(n.self===!0&&I(e.sym)===_l)return{t:s.Object,ctx:n}}return null}var _l=I(A("self"));function Fr(e,t,n=new Set){if(n.has(e))return;n.add(e);let r=e.data;for(let o=0;o<r.length;o++){let a=r[o];Do(a)&&I(a.sym)===_l?r[o]={t:a.t,sym:a.sym,bind:t}:_(a.t)&&Fr(a.s,t,n)}}function ns(e,t,n){e.vals[t]=n,e.watch!==void 0&&e.dirty!==!0&&(e.dirty=!0,e.watch.push(e))}function $e(e,t){let n=e.bind;return n===null?!1:(ns(n,e.idx??zl(n,e.sym),t),!0)}function Do(e){return e.t===s.Word||e.t===s.SetWord||e.t===s.GetWord||e.t===s.LitWord}function be(e,t,n=!1,r=new Set){if(r.has(e))return;r.add(e);let o=e.data;for(let a=0;a<o.length;a++){let i=o[a];if(Do(i)){if(i.bind===t&&i.idx!==void 0)continue;let l=te(t,i.sym);l<0&&n&&(l=Xn(t,i.sym,Pf(t,i.sym))),l>=0&&(o[a]={t:i.t,sym:i.sym,bind:t,idx:l})}else _(i.t)&&be(i.s,t,n,r)}}function Pf(e,t){for(let n=e.parent;n!==null;n=n.parent){let r=te(n,t);if(r>=0)return n.vals[r]}return re}function Wo(e,t,n){let r=e.data;for(let o=t;o<r.length;o++){let a=r[o];a.t===s.SetWord&&zl(n,a.sym)}}var Ul=new WeakMap;function Df(e,t){let n=new Map,r=new Set,o=!1,a=i=>{if(r.has(i)){o=!0;return}r.add(i);let l=[],c=[];i.data.forEach((u,d)=>{Do(u)&&u.bind===t?l.push(d):_(u.t)&&(c.push(d),a(u.s))}),n.set(i,{words:l,blocks:c})};return a(e),o?null:n}function ql(e,t,n){let r=Ul.get(e);if(r===void 0&&(r=Df(e,t),Ul.set(e,r)),r===null)return Me(e,0,t,n);let o=r,a=i=>{let l=o.get(i),c={data:i.data.slice()};(i.nl||i.pos)&&(c.nl=i.nl,c.pos=i.pos,c.sharedMeta=!0),i.file!==void 0&&(c.file=i.file);let u=c.data;for(let d of l.words){let f=u[d];u[d]=f.idx===void 0?{t:f.t,sym:f.sym,bind:n}:{t:f.t,sym:f.sym,bind:n,idx:f.idx}}for(let d of l.blocks){let f=u[d];u[d]={t:f.t,s:a(f.s),i:f.i}}return c};return a(e)}function Me(e,t=0,n=null,r=null){return Kl(e,t,n,r,new Map)}function Kl(e,t,n,r,o){let a=t===0;if(a){let c=o.get(e);if(c!==void 0)return c}let i={data:[]};a&&o.set(e,i),e.nl&&(i.nl=e.nl.slice(t)),e.pos&&(i.pos=e.pos.slice(t)),e.file!==void 0&&(i.file=e.file);let l=e.data;for(let c=t;c<l.length;c++){let u=l[c];if(n!==null&&Do(u)&&u.bind===n)i.data.push(u.idx===void 0?{t:u.t,sym:u.sym,bind:r}:{t:u.t,sym:u.sym,bind:r,idx:u.idx});else if(_(u.t)){let d=u;i.data.push({t:d.t,s:Kl(d.s,0,n,r,o),i:d.i})}else i.data.push(u)}return i}var Wf=["type","id","message","near","where","at"],Rf=Wf.map(e=>A(e));function Y(e,t,n){let r={keys:[...Rf],vals:[st(s.Word,e),st(s.Word,t),j(n),k,k,k],parent:null};return{t:s.Error,ctx:r}}function Qn(e,t){let n=te(e.ctx,A(t));return n>=0?e.ctx.vals[n]:k}function $n(e,t,n){let r=te(e.ctx,A(t));r>=0&&e.ctx.vals[r].t===s.None&&(e.ctx.vals[r]=n)}function er(e){let t=Qn(e,"type"),n=Qn(e,"message"),r=t.t===s.Word?M(t.sym):"user",o=n.t===s.String?B(n):"";return`${r.charAt(0).toUpperCase()}${r.slice(1)} error: ${o}`}function Z(e,t={}){let n=new os(t.all??!1);return t.only&&(e.t===s.Block||e.t===s.Paren)?n.contents(e.s,e.i,-1):n.value(e,0),n.out}function D(e){switch(e.t){case s.Unset:return"";case s.String:case s.File:case s.Email:case s.Url:return qe(e.s.data,e.i);case s.Char:return String.fromCodePoint(e.v);case s.Word:case s.SetWord:case s.GetWord:case s.LitWord:case s.Refinement:case s.Issue:return M(e.sym);case s.Block:case s.Paren:return e.s.data.slice(e.i).map(D).join(" ");case s.Object:return e.ctx.keys.map((t,n)=>`${M(t)}: ${D(e.ctx.vals[n])}`).join(`
11
+ `);case s.Error:return Ff(e);default:return Z(e)}}function Ff(e){let t=[`** ${er(e)}`],n=Qn(e,"where"),r=Qn(e,"near"),o=Qn(e,"at");return n.t!==s.None&&t.push(`** Where: ${D(n)}`),r.t!==s.None&&t.push(`** Near: ${Z(r)}`),o.t!==s.None&&t.push(`** At: ${D(o)}`),t.join(`
12
+ `)}var Hf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Vl(e,t=!0){if(Number.isNaN(e))return"1.#NaN";if(!Number.isFinite(e))return e>0?"1.#INF":"-1.#INF";let n=String(t?e:Number(e.toPrecision(15)));if(n.includes("e")){n=n.replace("e+","e");let[r,o]=n.split("e");n=(r.includes(".")?r:r+".0")+"e"+o}else n.includes(".")||(n+=".0");return n}function Uf(e,t){t||(e=Number(e.toPrecision(15)));for(let n=1;n<=17;n++){let r=String(Number((e*100).toPrecision(n))).replace("e+","e"),[o,a]=r.split("e");if(+`${o}e${Number(a??0)-2}`===e)return r+"%"}return String(e*100).replace("e+","e")+"%"}function Gl(e){return Number.isInteger(e)?String(e):String(e).replace("e+","e")}function Hr(e){let t=Math.floor(e/1e9),n=e-t*1e9,r=Math.floor(t/3600),o=Math.floor(t/60)%60,a=t%60,i=`${r}:${String(o).padStart(2,"0")}`;return(a!==0||n!==0)&&(i+=":"+String(a).padStart(2,"0"),n!==0&&(i+="."+String(n).padStart(9,"0").replace(/0+$/,""))),i}function zf(e){let t=e<0?"-":"+",n=Math.abs(e);return`${t}${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`}function Yl(e){let t=`${e.d}-${Hf[e.m-1]}-${e.y}`;return e.time!==null&&(t+="/"+Hr(e.time),e.zone!==null&&(t+=zf(e.zone))),t}function _f(e,t){let n=!1,r=0,o=!0;for(let i=t;i<e.length;i++){let l=e[i];(l===10||l===34)&&(n=!0),l===123&&r++,l===125&&--r<0&&(o=!1)}r!==0&&(o=!1);let a=n?"{":'"';for(let i=t;i<e.length;i++){let l=e[i];n&&!o&&(l===123||l===125)?a+="^"+String.fromCodePoint(l):a+=es(l,n?"}":'"',n)}return a+(n?"}":'"')}var qf=/[A-Za-z0-9._~/:+\-!*',=@&$?#\u0080-\u{10FFFF}]/u;function Kf(e,t){if(e.length===t)return'%""';let n="%";for(let r=t;r<e.length;r++){let o=String.fromCodePoint(e[r]);n+=qf.test(o)?o:[...new TextEncoder().encode(o)].map(a=>"%"+a.toString(16).toUpperCase().padStart(2,"0")).join("")}return n}function rs(e,t=0){let n="";for(let r=t;r<e.length;r++)n+=e[r].toString(16).toUpperCase().padStart(2,"0");return n}var Ro=" ",os=class{out="";all;active=new Set;constructor(t){this.all=t}value(t,n){let r=this.all;switch(t.t){case s.Unset:this.out+=r?"#[unset]":"";return;case s.None:this.out+=r?"#[none]":"none";return;case s.Logic:this.out+=r?`#[${t.v}]`:String(t.v);return;case s.Integer:this.out+=Pr(t.v);return;case s.Decimal:this.out+=Vl(t.v,r);return;case s.Percent:this.out+=Uf(t.v,r);return;case s.Money:{let o=t.v.d<0n,a=o?{d:-t.v.d,e:t.v.e}:t.v;this.out+=(o?"-":"")+t.cur+"$"+zt(a,2);return}case s.Char:this.out+='#"'+es(t.v,'"')+'"';return;case s.Pair:this.out+=Gl(t.x)+"x"+Gl(t.y);return;case s.Tuple:this.out+=t.v.join(".");return;case s.Date:this.out+=Yl(t.v);return;case s.Time:this.out+=(t.v<0?"-":"")+Hr(Math.abs(t.v));return;case s.String:this.indexed(t,()=>_f(t.s.data,r?0:t.i));return;case s.File:this.indexed(t,()=>Kf(t.s.data,r?0:t.i));return;case s.Email:case s.Url:this.indexed(t,()=>qe(t.s.data,r?0:t.i));return;case s.Tag:this.indexed(t,()=>"<"+qe(t.s.data,r?0:t.i)+">");return;case s.Binary:this.indexed(t,()=>"#{"+rs(t.s.data,r?0:t.i)+"}");return;case s.Bitset:{let o=(t.neg?"not ":"")+"#{"+rs(t.s.data)+"}";this.out+=r?`#[bitset! ${o}]`:`make bitset! ${t.neg?"[not bits ":""}#{${rs(t.s.data)}}${t.neg?"]":""}`;return}case s.Word:this.out+=M(t.sym);return;case s.SetWord:this.out+=M(t.sym)+":";return;case s.GetWord:this.out+=":"+M(t.sym);return;case s.LitWord:this.out+="'"+M(t.sym);return;case s.Refinement:this.out+="/"+M(t.sym);return;case s.Issue:this.out+="#"+M(t.sym);return;case s.Block:this.blockLike(t,"[","]",n);return;case s.Paren:this.blockLike(t,"(",")",n);return;case s.Path:case s.SetPath:case s.GetPath:case s.LitPath:this.path(t,n);return;case s.Map:this.map(t.s,n);return;case s.Object:this.object(t.ctx,n,r?null:"make object!");return;case s.Error:this.object(t.ctx,n,"make error!");return;case s.Datatype:this.out+=r?`#[datatype! ${ie(t.k)}]`:ie(t.k);return;case s.Typeset:{let o=[];for(let a=0;a<64;a++)t.bits>>BigInt(a)&1n&&o.push(ie(a));this.out+=r?`#[typeset! [${o.join(" ")}]]`:`make typeset! [${o.join(" ")}]`;return}case s.Function:{if(r)break;let o=t.p;this.out+="func ",this.blockLike(o.specBlock,"[","]",n),this.out+=" ",this.blockLike({t:s.Block,s:o.body,i:0},"[","]",n);return}}this.out+=`#[${ie(t.t)}]`}indexed(t,n){this.all&&t.i>0?this.out+=`#[${ie(t.t)} ${n()} ${t.i+1}]`:this.out+=n()}blockLike(t,n,r,o){if(this.all&&t.i>0){this.out+=`#[${ie(t.t)} `,this.blockLike({...t,i:0},n,r,o),this.out+=` ${t.i+1}]`;return}if(this.active.has(t.s)){this.out+=n+"..."+r;return}this.out+=n,this.contents(t.s,t.i,o)&&(this.out+=`
13
+ `+Ro.repeat(o)),this.out+=r}contents(t,n,r){this.active.add(t);let o=!1,a=Ro.repeat(r+1);for(let i=n;i<t.data.length;i++)t.nl?.[i]&&(i>n||r>=0)?(this.out+=`
14
+ `+a,o=!0):i>n&&(this.out+=" "),this.value(t.data[i],r+1);return this.active.delete(t),o}path(t,n){t.t===s.GetPath&&(this.out+=":"),t.t===s.LitPath&&(this.out+="'"),t.s.data.slice(t.i).forEach((r,o)=>{o>0&&(this.out+="/"),this.value(r,n)}),t.t===s.SetPath&&(this.out+=":")}map(t,n){if(this.active.has(t)){this.out+="#(...)";return}this.active.add(t),this.out+="#(";for(let r=0;r<t.data.length;r+=2){r>0&&(this.out+=" ");let o=t.data[r];o.t===s.Word?this.out+=M(o.sym)+":":this.value(o,n+1),this.out+=" ",this.value(t.data[r+1],n+1)}this.out+=")",this.active.delete(t)}object(t,n,r){if(this.active.has(t)){this.out+=r===null?"#[object! [...]]":r+" [...]";return}this.active.add(t),this.out+=r===null?"#[object! [":r+" [";let o=Ro.repeat(n+1);t.keys.forEach((a,i)=>{let l=t.vals[i];this.out+=`
15
+ `+o+M(a)+": ",r!==null&&(l.t===s.Word||l.t===s.Path)&&(this.out+="'"),this.value(l,n+1)}),t.keys.length>0&&(this.out+=`
16
+ `+Ro.repeat(n)),this.out+=r===null?"]]":"]",this.active.delete(t)}};function Ur(e,t){let n=e.pos?.[t];if(n===void 0||n<0)return null;let{line:r,col:o}=Wl(n);return`${e.file?e.file+":":""}${r}:${o}`}var Ne={Arg:0,Lit:1,Get:2,Ref:3,Local:4},Gf=jr["any-value!"],Zl=Ee(s.Logic)|Ee(s.None),Vf=A("local"),Yf=A("return");function nr(e){let t=[],n=[],r=null,o=-1,a=!1,i=e.s.data;for(let l=e.i;l<i.length;l++){let c=i[l];switch(c.t){case s.String:continue;case s.Word:case s.LitWord:case s.GetWord:{if(t.some(p=>I(p.sym)===I(c.sym)))return`duplicate parameter ${M(c.sym)}`;let u=a?Ne.Local:c.t===s.Word?Ne.Arg:c.t===s.LitWord?Ne.Lit:Ne.Get;if(a&&c.t!==s.Word)return`bad local ${M(c.sym)}`;let d=Gf,f=i[l+1];if(!a&&f!==void 0&&f.t===s.Block){let p=tr(f);if(typeof p=="string")return p;d=p,l++}u!==Ne.Local&&o<0&&n.push(t.length),t.push({sym:c.sym,kind:u,types:d,allows:Mo(d),ref:a?-1:o});continue}case s.Refinement:{if(I(c.sym)===I(Vf)){a=!0;continue}if(a)return`refinement /${M(c.sym)} after /local`;if(t.some(u=>I(u.sym)===I(c.sym)))return`duplicate parameter ${M(c.sym)}`;o=t.length,t.push({sym:c.sym,kind:Ne.Ref,types:Zl,allows:Mo(Zl),ref:-1});continue}case s.SetWord:{let u=i[l+1];if(I(c.sym)!==I(Yf)||u===void 0||u.t!==s.Block)return`bad spec item ${M(c.sym)}:`;let d=tr(u);if(typeof d=="string")return d;r=d,l++;continue}default:return"bad spec item"}}return{params:t,base:n,ret:r,retAllows:r===null?null:Mo(r),blank:t.map(()=>k)}}function tr(e){let t=0n;for(let n of e.s.data.slice(e.i)){let r=n.t===s.Word?kl(M(n.sym)):n.t===s.Datatype?Ee(n.k):n.t===s.Typeset?n.bits:void 0;if(r===void 0)return"bad type in spec";t|=r}return t}function Jl(e,t){let n=nr(e);if(typeof n=="string")return n;let r=Le(n.params.map(a=>a.sym)),o=Me(t.s,t.i);return be(o,r),{spec:n,specBlock:{t:s.Block,s:Me(e.s,e.i),i:0},body:o,tmpl:r}}var Fo=e=>e.t===s.Integer||e.t===s.Decimal||e.t===s.Percent||e.t===s.Money;function _t(e){switch(e.t){case s.Integer:return typeof e.v=="bigint"?$l(e.v):Qt(e.v);case s.Decimal:case s.Percent:return Qt(e.v);case s.Money:return e.v}return null}function tc(e,t){if(e.t===s.Integer&&t.t===s.Integer)return An(e.v,t.v);if(e.t===s.Money&&t.t===s.Money&&e.cur!==""&&t.cur!==""&&e.cur.toUpperCase()!==t.cur.toUpperCase())return null;let n=_t(e),r=_t(t);if(n===null||r===null){let o=e.t===s.Decimal||e.t===s.Percent?e.v:NaN,a=t.t===s.Decimal||t.t===s.Percent?t.v:NaN;return Number.isNaN(o)||Number.isNaN(a)?null:o<a?-1:o>a?1:0}return Il(n,r)}function nc(e,t){let n=e.s.data,r=t.s.data,o=Math.min(n.length-e.i,r.length-t.i);for(let l=0;l<o;l++){let c=Ke(n[e.i+l]),u=Ke(r[t.i+l]);if(c!==u)return c<u?-1:1}let a=n.length-e.i,i=r.length-t.i;return a<i?-1:a>i?1:0}function Ke(e){if(e>=65&&e<=90)return e+32;if(e<128)return e;let t=String.fromCodePoint(e).toLowerCase();return t.length===1||t.codePointAt(0)>65535?t.codePointAt(0):e}var Zf=10n,rc=new Float64Array(1),Jf=new BigInt64Array(rc.buffer);function Xl(e){rc[0]=e;let t=Jf[0];return t<0n?-(t&0x7fffffffffffffffn):t}function Xf(e,t){if(e===t)return!0;if(!Number.isFinite(e)||!Number.isFinite(t))return!1;let n=Xl(e)-Xl(t);return(n<0n?-n:n)<=Zf}var Ql=e=>e.t===s.Decimal||e.t===s.Percent;function Ct(e,t){if(e===t)return!0;if(Fo(e)&&Fo(t)){if((Ql(e)||Ql(t))&&e.t!==s.Money&&t.t!==s.Money){let n=r=>r.t===s.Integer?q(r.v):r.v;return Xf(n(e),n(t))}return tc(e,t)===0}if(X(e.t)&&X(t.t))return nc(e,t)===0;if(e.t===s.Char&&t.t===s.Char)return Ke(e.v)===Ke(t.v);if(le(e.t)&&le(t.t))return I(e.sym)===I(t.sym);if(_(e.t)&&e.t===t.t){let n=e,r=t,o=n.s.data.length-n.i;if(o!==r.s.data.length-r.i)return!1;for(let a=0;a<o;a++)if(!Ct(n.s.data[n.i+a],r.s.data[r.i+a]))return!1;return!0}return bt(e,t)}function Bn(e,t){if(Fo(e)&&Fo(t))return tc(e,t);if(X(e.t)&&X(t.t))return nc(e,t);if(e.t===s.Char&&t.t===s.Char){let n=Ke(e.v),r=Ke(t.v);return n<r?-1:n>r?1:0}if(e.t===s.Time&&t.t===s.Time)return e.v<t.v?-1:e.v>t.v?1:0;if(e.t===s.Date&&t.t===s.Date){let n=ec(e.v),r=ec(t.v);return n<r?-1:n>r?1:0}if(e.t===s.Pair&&t.t===s.Pair)return e.y!==t.y?e.y<t.y?-1:1:e.x<t.x?-1:e.x>t.x?1:0;if(e.t===s.Tuple&&t.t===s.Tuple){let n=Math.max(e.v.length,t.v.length);for(let r=0;r<n;r++){let o=e.v[r]??0,a=t.v[r]??0;if(o!==a)return o<a?-1:1}return 0}if(e.t===s.Logic&&t.t===s.Logic)return e.v===t.v?0:e.v?1:-1;if(le(e.t)&&le(t.t)){let n=M(I(e.sym)),r=M(I(t.sym));return n<r?-1:n>r?1:0}return null}function ec(e){return Date.UTC(e.y,e.m-1,e.d)+(e.time??0)/1e6-(e.zone??0)*6e4}function lc(e,t){return le(e.t)&&le(t.t)?I(e.sym)===I(t.sym):bt(e,t)}function cc(e,t){for(let n=0;n<e.data.length;n+=2)if(lc(e.data[n],t))return n+1;return-1}function Uo(e,t,n){for(let r=t;r<e.data.length;r++)if(lc(e.data[r],n))return r;return-1}function hn(e){return e.t!==s.Integer?null:q(e.v)-1}var Qf=["year","month","day","time","zone","date","weekday","yearday","hour","minute","second"],oc=["hour","minute","second"],ac=36e11,as=6e10,sc=864e5;function Ho(e){return le(e.t)?M(I(e.sym)):null}function St(e,t){switch(e.t){case s.Url:case s.File:if(le(t.t)||X(t.t)||t.t===s.Integer){let n=e.s.data.slice(e.i),r=he(le(t.t)?M(t.sym):X(t.t)?qe(t.s.data,t.i):Z(t)),o=n[n.length-1]===47?[]:[47],a=r[0]===47?r.slice(1):r;return{t:e.t,s:{data:[...n,...o,...a]},i:0}}break;case s.Email:{let n=Ho(t);if(n==="user"||n==="host"){let r=e.s.data.slice(e.i),o=r.indexOf(64),a=n==="user"?o<0?r:r.slice(0,o):o<0?[]:r.slice(o+1);return{t:s.String,s:{data:a},i:0}}break}case s.Object:case s.Error:{if(!le(t.t))return`cannot pick ${Z(t)} in an object`;let n=te(e.ctx,t.sym);return n<0?`${Z(t)} is not a field of the object`:e.ctx.vals[n]}case s.Map:{let n=cc(e.s,t);return n<0?k:e.s.data[n]}case s.Pair:{let n=Ho(t),r=hn(t);return n==="x"||r===0?ic(e.x):n==="y"||r===1?ic(e.y):`cannot pick ${Z(t)} in a pair`}case s.Tuple:{let n=hn(t);if(n===null)return`cannot pick ${Z(t)} in a tuple`;let r=e.v[n];return r===void 0?k:H(r)}case s.Date:{let n=Ho(t)??Qf[hn(t)??-1]??null,r=e.v;switch(n){case"year":return H(r.y);case"month":return H(r.m);case"day":return H(r.d);case"time":return r.time===null?k:Ie(r.time);case"zone":return r.zone===null?k:Ie(r.zone*as);case"date":return fn({y:r.y,m:r.m,d:r.d,time:null,zone:null});case"weekday":return H((Date.UTC(r.y,r.m-1,r.d)/sc%7+10)%7+1);case"yearday":return H((Date.UTC(r.y,r.m-1,r.d)-Date.UTC(r.y,0,1))/sc+1);case"hour":case"minute":case"second":return r.time===null?k:St(Ie(r.time),t.t===s.Integer?H(oc.indexOf(n)+1):t)}return`cannot pick ${Z(t)} in a date`}case s.Time:{let n=Ho(t)??oc[hn(t)??-1]??null,r=Math.abs(e.v),o=e.v<0?-1:1;switch(n){case"hour":return H(o*Math.floor(r/ac));case"minute":return H(o*Math.floor(r%ac/as));case"second":{let a=r%as/1e9;return Number.isInteger(a)?H(o*a):ke(o*a)}}return`cannot pick ${Z(t)} in a time`}}if(_(e.t)){let n=e,r=hn(t);if(r!==null)return(r>=0?n.s.data[n.i+r]:void 0)??k;let o=Uo(n.s,n.i,t);return o<0?k:n.s.data[o+1]??k}if(X(e.t)||e.t===s.Binary){let n=e,r=hn(t);if(r===null)return`cannot pick ${Z(t)} in ${Eo(e.t)}`;let o=r>=0?n.s.data[n.i+r]:void 0;return o===void 0?k:e.t===s.Binary?H(o):pt(o)}return`cannot pick ${Z(t)} in ${Eo(e.t)}`}function ic(e){return Number.isInteger(e)?H(e):ke(e)}function rr(e,t,n){switch(e.t){case s.Object:case s.Error:{if(!le(t.t))return`cannot set ${Z(t)} in an object`;let r=te(e.ctx,t.sym);return r<0?`${Z(t)} is not a field of the object`:(ns(e.ctx,r,n),null)}case s.Map:{let r=cc(e.s,t);if(r>=0)e.s.data[r]=n;else{let o=le(t.t)?{t:s.Word,sym:t.sym,bind:null}:t;e.s.data.push(o,n)}return null}}if(_(e.t)){let r=e,o=hn(t);if(o!==null)return o<0||r.i+o>=r.s.data.length?`index ${o+1} is out of range`:(r.s.data[r.i+o]=n,null);let a=Uo(r.s,r.i,t);return a<0||a+1>=r.s.data.length?`${Z(t)} not found in the block`:(r.s.data[a+1]=n,null)}if(e.t===s.String){let r=e,o=hn(t);return o===null||n.t!==s.Char?`cannot set ${Z(t)} in a string`:o<0||r.i+o>=r.s.data.length?`index ${o+1} is out of range`:(r.s.data[r.i+o]=n.v,null)}return`cannot set ${Z(t)} in ${Eo(e.t)}`}function uc(e){return Math.max(0,e.s.data.length-e.i)}function ar(e,t){return Math.max(0,Math.min(e.s.data.length,t))}function Ze(e,t){return{...e,i:ar(e,t)}}function Je(e,t,n,r,o){It(e),e.data.splice(t,n,...r),e.nl!==void 0&&e.nl.splice(t,n,...r.map((a,i)=>o?.[i]??!1)),e.pos!==void 0&&e.pos.splice(t,n,...r.map(()=>-1))}function On(e){return[...new TextEncoder().encode(e)]}function sr(e,t,n){if(_(e)){if(!n&&t.t===s.Block){let r=t;return{add:r.s.data.slice(r.i),nl:r.s.nl?.slice(r.i)}}return{add:[t]}}if(e===s.Binary)return t.t===s.Binary?{add:t.s.data.slice(t.i)}:t.t===s.Integer?{add:[Number(t.v)&255]}:t.t===s.Char?{add:On(String.fromCodePoint(t.v))}:{add:On(or(t))};if(t.t===s.Char)return{add:[t.v]};if(X(t.t)&&(t.t!==s.Tag||e===s.Tag)){let r=t;return{add:r.s.data.slice(r.i)}}return{add:he(or(t))}}function or(e){return e.t===s.Block?e.s.data.slice(e.i).map(or).join(""):D(e)}var U={Error:0,Break:1,Continue:2,Return:3,Throw:4},_o=new Set(["mezzanines"]),fc=e=>e.file!==void 0&&_o.has(e.file);function zo(e){for(let t=e.stack.length-2;t>=0;t--){let n=e.stack[t];if(n.k===oe.Expr||n.k===oe.Do||n.k===oe.Set)return fc(n.feed.s)}return!1}var oe={Do:0,Expr:1,Set:2,Args:3,Native:4,Call:5,Path:6},ir={Call:0,Get:1,Set:2},qt={Start:0,Walk:1,WaitKey:2,WaitValue:3},jn=[];function zr(e,t){let n={...e,id:jn.length};return jn.push({def:n,fn:t}),{t:s.Native,p:n}}function pc(){return jn.map(e=>e.def)}function dr(e,t,n=0){let r={rt:e,stack:[],v:null,thrown:null,waiting:null};return cr(r,t,n),r}function cs(e,t){e.waiting=null,e.v=t}function us(e,t){e.waiting=null,e.thrown={kind:U.Error,v:t,name:null}}function _r(e,t=1/0){if(e.waiting!==null)return{k:"await",p:e.waiting};for(let n=0;n<t;n++){if(e.thrown!==null){let o=ep(e);if(o!==null)return o;continue}let r=e.stack[e.stack.length-1];if(r===void 0)return{k:"done",v:e.v??re};switch(r.k){case oe.Do:r.state===0?tp(e,r):ss(e,r);break;case oe.Expr:r.state===0?ls(e,r):ss(e,r);break;case oe.Set:r.state===0?ls(e,r):ss(e,r);break;case oe.Args:bc(e,r);break;case oe.Native:{let o=e.v;e.v=null,Ko(e,r,jn[r.def.id].fn(e,r,o));break}case oe.Call:{let o=e.v??re;e.v=null,e.stack.pop(),hc(e,r,o);break}case oe.Path:sp(e,r);break}if(e.waiting!==null)return{k:"await",p:e.waiting}}return{k:"yield"}}function ds(e){for(let t=e.stack.length-1;t>=0;t--){let n=e.stack[t];if((n.k===oe.Do||n.k===oe.Expr)&&n.feed.s.file!==void 0)return n.feed.s.file}return null}function Q(e,t,n){return{k:"throw",e:{kind:U.Error,v:Y(e,t,n),name:null}}}function We(e,t,n,r){e.v=null,e.thrown={kind:U.Error,v:Y(t,n,r),name:null}}var lr=e=>e===null?"function":M(e);function ep(e){let t=e.thrown,n=e.stack[e.stack.length-1];if(n===void 0)return e.thrown=null,{k:"error",e:dc(t)};let r=t.kind===U.Error?t.v:null;switch(n.k){case oe.Native:if(n.trap&1<<t.kind)return n.thrown=t,e.thrown=null,e.v=null,Ko(e,n,jn[n.def.id].fn(e,n,null)),null;r!==null&&n.name!==null&&!zo(e)&&$n(r,"where",{t:s.Word,sym:n.name,bind:null});break;case oe.Call:if(t.kind===U.Return)return e.stack.pop(),e.thrown=null,hc(e,n,t.v),null;if(t.kind===U.Break||t.kind===U.Continue)return e.thrown={kind:U.Error,v:dc(t),name:null},null;r!==null&&n.name!==null&&!zo(e)&&$n(r,"where",{t:s.Word,sym:n.name,bind:null});break;case oe.Args:r!==null&&n.name!==null&&!zo(e)&&$n(r,"where",{t:s.Word,sym:n.name,bind:null});break;case oe.Do:case oe.Expr:case oe.Set:if(r!==null&&(n.k!==oe.Do||n.state===1)&&!fc(n.feed.s)){let o=n.feed.s,a=Math.max(n.feed.i,n.start+1);$n(r,"near",Ye(s.Block,o.data.slice(n.start,Math.min(a,n.start+4))));let i=Ur(o,n.start);i!==null&&$n(r,"at",j(i))}break}return e.stack.pop(),null}function dc(e){switch(e.kind){case U.Error:return e.v;case U.Break:return Y("script","no-loop","break used outside of a loop");case U.Continue:return Y("script","no-loop","continue used outside of a loop");case U.Return:return Y("script","no-function","return used outside of a function");default:return Y("script","no-catch","throw has no catch")}}function cr(e,t,n){e.stack.push({k:oe.Do,feed:{s:t,i:n},out:re,infix:!0,start:n,state:0})}function fs(e,t,n){e.stack.push({k:oe.Expr,feed:t,infix:n,start:t.i,state:0})}function tp(e,t){if(e.v!==null&&(t.out=e.v,e.v=null),t.feed.i>=t.feed.s.data.length){e.stack.pop(),e.v=t.out;return}ls(e,t)}function ls(e,t){let n=t.feed,r=n.s.data;t.start=n.i,t.state=1;let o=r[n.i++];switch(o.t){case s.Word:{let a=xe(o);if(a===null)return Nn(e,o);switch(a.t){case s.Function:case s.Native:return ur(e,n,a,o.sym,null,null);case s.Op:return We(e,"script","no-op-arg",`${M(o.sym)} operator is missing its left argument`);case s.Unset:return We(e,"script","no-value",`${M(o.sym)} has no value`)}e.v=a;return}case s.SetWord:{if(n.i>=r.length)return We(e,"script","need-value",`${M(o.sym)}: needs a value`);let a=qo(r[n.i]);if(a!==null&&a.t!==s.Unset&&!ps(r[n.i+1])){if(n.i++,!$e(o,a))return Nn(e,o);e.v=a;return}e.stack.push({k:oe.Set,w:o,feed:n,infix:!0,start:n.i,state:0});return}case s.GetWord:{let a=xe(o);if(a===null)return Nn(e,o);e.v=a;return}case s.LitWord:e.v={t:s.Word,sym:o.sym,bind:o.bind};return;case s.Paren:cr(e,o.s,o.i);return;case s.Path:case s.GetPath:e.stack.push({k:oe.Path,feed:n,path:o,mode:o.t===s.Path?ir.Call:ir.Get,state:qt.Start,j:0,cur:k,setv:k});return;case s.SetPath:if(n.i>=r.length)return We(e,"script","need-value","set-path needs a value");e.stack.push({k:oe.Path,feed:n,path:o,mode:ir.Set,state:qt.WaitValue,j:0,cur:k,setv:k}),fs(e,n,!0);return;case s.LitPath:e.v={t:s.Path,s:o.s,i:o.i};return;case s.Function:case s.Native:return ur(e,n,o,null,null,null)}e.v=o}function ss(e,t){if(t.infix){let n=t.feed.s.data[t.feed.i];if(n!==void 0&&n.t===s.Word){let r=xe(n);if(r!==null&&r.t===s.Op){t.feed.i++;let o=e.v;e.v=null;let a=r.p.fn;np(e,t.feed,a,n.sym,o)||ur(e,t.feed,a,n.sym,null,o);return}}}t.k===oe.Do?t.state=0:t.k===oe.Set?rp(e,t):e.stack.pop()}function np(e,t,n,r,o){if(n.t!==s.Native)return!1;let a=n.p,i=a.spec.params;if(i.length!==2||i[0].kind!==Ne.Arg||i[1].kind!==Ne.Arg)return!1;let l=t.s.data[t.i],c=l===void 0?null:qo(l);if(c===null||!i[0].allows[o.t]||!i[1].allows[c.t])return!1;t.i++;let u={k:oe.Native,def:a,args:[o,c],phase:0,data:null,trap:0,thrown:null,name:r};return e.stack.push(u),Ko(e,u,jn[a.id].fn(e,u,null)),!0}function rp(e,t){let n=e.v;if(e.stack.pop(),n.t===s.Unset)return We(e,"script","need-value",`${M(t.w.sym)}: needs a value`);if(!$e(t.w,n))return Nn(e,t.w)}function Nn(e,t){t.bind===null?We(e,"script","not-bound",`${M(t.sym)} is not bound to a context`):We(e,"script","no-value",`${M(t.sym)} has no value`)}function op(e){return e.t===s.Native,e.p.spec}function ur(e,t,n,r,o,a){if(n.t!==s.Function&&n.t!==s.Native)return We(e,"script","not-function",`${lr(r)} is not a function`);let i=op(n),l=i.blank.slice(),c=i.base;if(o!==null&&o.length>0){c=c.slice();for(let f of o){let p=f.t===s.Word?i.params.findIndex(h=>h.kind===Ne.Ref&&I(h.sym)===I(f.sym)):-1;if(p<0){let h=f.t===s.Word?M(f.sym):"that";return We(e,"script","bad-refine",`${lr(r)} has no refinement called ${h}`)}l[p]=P,i.params.forEach((h,v)=>{h.ref===p&&c.push(v)})}}let u=0;if(a!==null){if(c.length<2)return We(e,"script","bad-op",`${lr(r)} needs two arguments to be an operator`);l[c[0]]=a,u=1}let d={k:oe.Args,feed:t,fn:n,spec:i,vals:l,plan:c,n:u,name:r,op:a!==null};if(e.stack.push(d),t!==null&&a===null){let f=t.s.data;for(;d.n<c.length;){let p=i.params[c[d.n]],h=f[t.i];if(h===void 0||p.kind!==Ne.Arg)break;let v=qo(h);if(v===null||ps(f[t.i+1]))break;t.i++,l[c[d.n++]]=v}d.n===c.length&&bc(e,d)}}function qo(e){switch(e.t){case s.Word:case s.GetWord:{let t=xe(e);return t===null||e.t===s.Word&&(t.t===s.Function||t.t===s.Native||t.t===s.Op||t.t===s.Unset)?null:t}case s.SetWord:case s.LitWord:case s.Paren:case s.Path:case s.GetPath:case s.SetPath:case s.LitPath:case s.Function:case s.Native:return null}return e}function ps(e){if(e===void 0||e.t!==s.Word)return!1;let t=xe(e);return t!==null&&t.t===s.Op}function bc(e,t){e.v!==null&&(t.vals[t.plan[t.n++]]=e.v,e.v=null);let n=t.spec.params;if(t.n<t.plan.length){let i=n[t.plan[t.n]],l=t.feed;if(l===null||l.i>=l.s.data.length)return We(e,"script","no-arg",`${lr(t.name)} is missing its ${M(i.sym)} argument`);if(i.kind===Ne.Arg){let u=qo(l.s.data[l.i]);if(u!==null&&(t.op||!ps(l.s.data[l.i+1]))){l.i++,e.v=u;return}return fs(e,l,!t.op)}let c=l.s.data[l.i++];if(i.kind===Ne.Lit&&c.t===s.Paren)return cr(e,c.s,c.i);if(i.kind===Ne.Lit&&c.t===s.GetWord){let u=xe(c);if(u===null)return Nn(e,c);e.v=u;return}e.v=c;return}for(let i of t.plan){let l=n[i],c=t.vals[i];if(!l.allows[c.t])return We(e,"script","expect-arg",`${lr(t.name)} does not allow ${ie(c.t)} for its ${M(l.sym)} argument`)}if(e.stack.pop(),t.fn.t===s.Native){let i=t.fn.p,l={k:oe.Native,def:i,args:t.vals,phase:0,data:null,trap:0,thrown:null,name:t.name};e.stack.push(l),Ko(e,l,jn[i.id].fn(e,l,null));return}let r=t.fn.p,o={keys:r.tmpl.keys,vals:t.vals,parent:null},a=ql(r.body,r.tmpl,o);e.stack.push({k:oe.Call,def:r,name:t.name}),cr(e,a,0)}function hc(e,t,n){if(t.def.spec.ret!==null&&!t.def.spec.retAllows[n.t])return We(e,"script","bad-return",`${lr(t.name)} does not allow ${ie(n.t)} as its result`);e.v=n}function Ko(e,t,n){switch(n.k){case"value":e.stack.pop(),e.v=n.v;return;case"do":cr(e,n.s,n.i);return;case"expr":fs(e,n.feed,!0);return;case"call":{let r=e.stack.length;ur(e,null,n.fn,t.name,null,null);let o=e.stack[e.stack.length-1];if(e.stack.length>r&&o!==void 0&&o.k===oe.Args){if(n.full){ap(o,n.args);return}let a=Math.min(n.args.length,o.plan.length);for(let i=0;i<a;i++)o.vals[o.plan[i]]=n.args[i];o.n=a}return}case"await":e.waiting=n.p;return;case"throw":{let r=n.e;r.kind===U.Error&&t.name!==null&&!zo(e)&&$n(r.v,"where",{t:s.Word,sym:t.name,bind:null}),e.stack.pop(),e.thrown=r;return}}}function ap(e,t){let n=e.spec.params;e.plan=[];let r=0,o=!0;for(let a=0;a<n.length;a++){let i=n[a];if(i.kind===Ne.Local)continue;let l=t[r++]??k;i.kind===Ne.Ref?(o=l.t!==s.None&&!(l.t===s.Logic&&!l.v),e.vals[a]=o?P:k):(i.ref<0||o)&&(e.vals[a]=l,e.plan.push(a))}e.n=e.plan.length}function sp(e,t){let n=t.path.s.data;switch(t.state){case qt.WaitValue:if(t.setv=e.v,e.v=null,t.setv.t===s.Unset)return We(e,"script","need-value","set-path needs a value");t.state=qt.Start;return;case qt.Start:{let r=n[t.path.i];if(r===void 0||r.t!==s.Word)return We(e,"script","bad-path","a path must start with a word");let o=xe(r);return o===null?Nn(e,r):o.t===s.Unset?We(e,"script","no-value",`${M(r.sym)} has no value`):(t.cur=o,t.j=t.path.i+1,t.state=qt.Walk,t.mode===ir.Call&&(o.t===s.Function||o.t===s.Native)?(e.stack.pop(),ur(e,t.feed,o,r.sym,n.slice(t.j),null)):void 0)}case qt.WaitKey:{let r=e.v;return e.v=null,t.state=qt.Walk,is(e,t,r)}case qt.Walk:{if(t.j>=n.length){e.stack.pop(),e.v=t.cur;return}let r=n[t.j];if(r.t===s.Paren){t.state=qt.WaitKey,cr(e,r.s,r.i);return}if(r.t===s.GetWord){let o=xe(r);return o===null?Nn(e,r):is(e,t,o)}return is(e,t,r)}}}function is(e,t,n){let r=t.path.s.data,o=r[t.j];if(t.j++,t.mode===ir.Set&&t.j>=r.length){let i=rr(t.cur,n,t.setv);if(i!==null)return We(e,"script","bad-path-set",i);e.stack.pop(),e.v=t.setv;return}let a=St(t.cur,n);if(typeof a=="string")return We(e,"script","bad-path",a);t.cur=a,t.mode===ir.Call&&(a.t===s.Function||a.t===s.Native)&&(e.stack.pop(),ur(e,t.feed,a,o.t===s.Word?o.sym:null,r.slice(t.j),null))}function g(e,t,n){let r=me(t).s.data[0],o=nr(r);if(typeof o=="string")throw new Error(`bad spec for native ${e}: ${o}`);zr({name:e,spec:o,specBlock:r},n)}var bs=[];function Te(e,t){bs.push([e,t])}var b=e=>({k:"value",v:e}),N=Q;function Be(e){return!(e.t===s.None||e.t===s.Logic&&!e.v)}function ge(e){return{k:"do",s:e.s,i:e.i}}function Pn(e,t,n,r){let o=te(e.rt.lib,A(t)),a=o<0?void 0:e.rt.lib.vals[o];return a===void 0||a.t!==s.Native&&a.t!==s.Function?Q("access","no-host",`this host cannot ${r}`):{k:"call",fn:a,args:n}}var ip=I(A("trebol"));function Ot(e){let t=e.s.data,n=t[e.i],r=t[e.i+1];return n?.t===s.Word&&I(n.sym)===ip&&r?.t===s.Block?{header:r,start:e.i+2}:{header:null,start:e.i}}function lp(e){let{start:t}=Ot(e);t!==e.i&&(Je(e.s,e.i,t-e.i,[]),e.s.nl!==void 0&&e.s.nl.length>e.i&&(e.s.nl[e.i]=!1))}function Go(e,t){let n;try{n=me(B(t))}catch(r){if(r instanceof rt)return N("syntax","load",r.message);throw r}return lp(n),be(n.s,e.user,!0),b(n)}g("load",'["Reads Trebol source text, or a file of it, into values: the value itself, or a block when there are several." source [string! binary! file! url!] /all "Gives a block even for one value"]',(e,t,n)=>{let r=t.args[0];if(r.t===s.Binary&&(r=j(new TextDecoder().decode(new Uint8Array(r.s.data.slice(r.i))))),t.phase===0&&r.t!==s.String)return t.phase=1,Pn(e,"read",[r],"read files");let o=Go(e.rt,t.phase===1?n:r);if(o.k!=="value"||t.args[1]===P)return o;let a=o.v;return a.s.data.length===1?b(a.s.data[0]):o});g("mold",'["The value as Trebol source text, the way you would type it." value [any-type!] /only /all]',(e,t)=>b(j(Z(t.args[0],{only:t.args[1]===P,all:t.args[2]===P}))));g("form",'["The value as text for people to read." value [any-type!]]',(e,t)=>b(j(D(t.args[0]))));function cp(e,t,n){let r=Le();if(e!==null){r.keys.push(...e.keys);for(let a of e.vals)r.vals.push(up(a,e,r))}Wo(t.s,t.i,r);let o=Me(t.s,t.i);return be(o,r),n===s.Object&&(r.self=!0,Fr(o,r)),{obj:{t:n,ctx:r},body:o}}function up(e,t,n){if(_(e.t)){let r=e;return{t:r.t,s:Me(r.s,0,t,n),i:r.i}}if(e.t===s.Function){let r=e.p;return{t:s.Function,p:{...r,body:Me(r.body,0,t,n)}}}if(X(e.t)||e.t===s.Binary){let r=e;return{t:r.t,s:{data:r.s.data.slice()},i:r.i}}return e}function dp(e,t){switch(e){case s.Function:{if(t.t!==s.Block)break;let[n,r]=t.s.data.slice(t.i);if(n?.t!==s.Block||r?.t!==s.Block)return"make function! needs [spec body]";let o=Jl(n,r);return typeof o=="string"?`bad function spec: ${o}`:{t:s.Function,p:o}}case s.Op:{if(t.t!==s.Function&&t.t!==s.Native)break;return{t:s.Op,p:{fn:t}}}case s.Map:{if(t.t!==s.Block)break;let n=t.s.data.slice(t.i);return n.length%2!==0?"make map! needs key value pairs":{t:s.Map,s:{data:n.map((r,o)=>o%2===0&&le(r.t)?{t:s.Word,sym:r.sym,bind:null}:r)}}}case s.Block:case s.Paren:if(t.t===s.Integer)return{t:e,s:{data:[]},i:0};if(_(t.t))return{t:e,s:{data:t.s.data.slice(t.i)},i:0};break;case s.String:case s.File:case s.Email:case s.Url:case s.Tag:return t.t===s.Integer?{t:e,s:{data:[]},i:0}:{t:e,s:{data:he(D(t))},i:0};case s.Pair:{if(t.t!==s.Block)break;let[n,r]=t.s.data.slice(t.i),o=l=>l?.t===s.Integer?q(l.v):l?.t===s.Decimal?l.v:null,a=o(n),i=o(r);return a===null||i===null?"make pair! needs two numbers":Bt(a,i)}case s.Typeset:{if(t.t!==s.Block)break;let n=tr(t);return typeof n=="string"?n:en(n)}case s.Error:if(t.t===s.String)return Y("user","message",B(t));break}return`cannot make ${ie(e)} from ${ie(t.t)}`}g("make",'["Makes a new value of a type, or from a prototype object." type [any-value!] spec [any-value!]]',(e,t)=>{if(t.phase===1)return b(t.data);let n=t.args[0],r=t.args[1],o=null,a=s.Object;if(n.t===s.Datatype&&(n.k===s.Object||n.k===s.Error&&r.t===s.Block))n.k===s.Error&&(o=Y("user","message","").ctx,a=s.Error);else if(n.t===s.Object||n.t===s.Error)o=n.ctx,a=n.t;else if(n.t===s.Datatype){let c=dp(n.k,r);return typeof c=="string"?N("script","bad-make",c):b(c)}else return N("script","bad-make",`cannot make from ${ie(n.t)}`);if(r.t!==s.Block)return N("script","bad-make",`make ${ie(a)} needs a block`);let{obj:i,body:l}=cp(o,r,a);return t.phase=1,t.data=i,{k:"do",s:l,i:0}});g("get",'["The value a word refers to." word [any-word!] /any]',(e,t)=>{let n=t.args[0],r=xe(n);return r===null?N("script","not-bound",`${M(n.sym)} is not bound to a context`):r.t===s.Unset&&t.args[1]!==P?N("script","no-value",`${M(n.sym)} has no value`):b(r)});g("set",'["Sets a word, or each word of a block, to a value." word [any-word! block!] value [any-type!]]',(e,t)=>{let n=t.args[0],r=t.args[1],o=n.t===s.Block?n.s.data.slice(n.i):[n];for(let a=0;a<o.length;a++){let i=o[a];if(!le(i.t))return N("script","bad-set",`cannot set ${Z(i)}`);let l=n.t===s.Block&&r.t===s.Block?r.s.data[r.i+a]??k:r;if(!$e(i,l))return N("script","not-bound",`${M(i.sym)} is not bound to a context`)}return b(r)});g("value?",'["True if the word has a value." word [any-word!]]',(e,t)=>{let n=xe(t.args[0]);return b(n!==null&&n.t!==s.Unset?P:we)});g("type?",'["The datatype of a value." value [any-type!]]',(e,t)=>b(pn(t.args[0].t)));var hs=e=>e.t===s.Op?e.p.fn:e;g("spec-of",`["A copy of a function's spec block." value [any-function!]]`,(e,t)=>{let n=hs(t.args[0]),r=n.p,o=(n.t===s.Function,r.specBlock);return b({t:s.Block,s:Me(o.s,o.i),i:0})});g("body-of",`["A copy of a function's body block, or none for a native." value [any-function!]]`,(e,t)=>{let n=hs(t.args[0]);return b(n.t===s.Function?{t:s.Block,s:Me(n.p.body),i:0}:k)});g("words-of",'["The words of an object or map, or the arguments, refinements and local words of a function." value [any-object! map! any-function!]]',(e,t)=>{let n=hs(t.args[0]);if(n.t===s.Object||n.t===s.Error)return b(Ye(s.Block,n.ctx.keys.map(l=>st(s.Word,l))));if(n.t===s.Map)return b(Ye(s.Block,n.s.data.filter((l,c)=>c%2===0)));let r=n.p,o=(n.t===s.Function,r.spec),a=[],i=!1;for(let l of o.params)l.kind===Ne.Local&&!i&&(a.push(st(s.Refinement,A("local"))),i=!0),a.push(st(l.kind===Ne.Ref?s.Refinement:s.Word,l.sym));return b(Ye(s.Block,a))});g("values-of",'["The values of an object or map." value [any-object! map!]]',(e,t)=>{let n=t.args[0];return n.t===s.Map?b(Ye(s.Block,n.s.data.filter((r,o)=>o%2===1))):b(Ye(s.Block,n.ctx.vals.slice()))});g("bind",'["Binds the words of a block to a context." words [block! any-word!] context [any-word! any-object!] /new /copy "Binds a deep copy and leaves the block as it was"]',(e,t)=>{let n=t.args[0],r=t.args[1],o=r.t===s.Object||r.t===s.Error?r.ctx:r.bind;if(o===null)return N("script","not-bound",`${Z(r)} is not bound to a context`);let a=t.args[2]===P;if(n.t!==s.Block){let i=n;return!a&&te(o,i.sym)<0?b(i):b({t:i.t,sym:i.sym,bind:o})}return t.args[3]===P&&(n={t:n.t,s:Me(n.s,n.i),i:0}),be(n.s,o,a),b(n)});g("context?",'["The context a word is bound to, or none." word [any-word!]]',(e,t)=>{let n=t.args[0].bind;return b(n===null?k:Oo(n))});g("unset",'["Takes the value away from a word, or from each word of a block." word [any-word! block!]]',(e,t)=>{let n=t.args[0],r=n.t===s.Block?n.s.data.slice(n.i):[n];for(let o of r){if(!le(o.t))return N("script","bad-set",`cannot unset ${Z(o)}`);if(!$e(o,re))return N("script","not-bound",`${M(o.sym)} is not bound to a context`)}return b(re)});g("in",'["The word of an object, bound to it, or none if the object has no such word." object [any-object!] word [any-word!]]',(e,t)=>{let n=t.args[0],r=t.args[1];return b(te(n.ctx,r.sym)>=0?{t:s.Word,sym:r.sym,bind:n.ctx}:k)});g("use",'["Evaluates a block with words of its own, which exist only inside it." words [block! word!] body [block!]]',(e,t,n)=>{if(t.phase===1)return b(n);let r=t.args[0],o=r.t===s.Block?r.s.data.slice(r.i):[r];if(o.some(c=>!le(c.t)))return N("script","bad-words","use needs a block of words");let a=Le(o.map(c=>c.sym),o.map(()=>k)),i=t.args[1],l=Me(i.s,i.i);return be(l,a),t.phase=1,ge({t:s.Block,s:l,i:0})});g("length?",`["The number of values from the series' position to its tail." series [series! map! object!]]`,(e,t)=>{let n=t.args[0];if(n.t===s.Map)return b({t:s.Integer,v:n.s.data.length/2});if(n.t===s.Object||n.t===s.Error)return b({t:s.Integer,v:n.ctx.keys.length});let r=n;return b({t:s.Integer,v:Math.max(0,r.s.data.length-r.i)})});g("pick",'["The value at a position or key." series [any-value!] index [any-value!]]',(e,t)=>{let n=St(t.args[0],t.args[1]);return typeof n=="string"?N("script","bad-pick",n):b(n)});g("poke",'["Sets the value at a position or key; gives the value." series [any-value!] index [any-value!] value [any-value!]]',(e,t)=>{let n=rr(t.args[0],t.args[1],t.args[2]);return n!==null?N("script","bad-poke",n):b(t.args[2])});g("put",'["Sets the value of a key; gives the value." series [map! object! block!] key [any-value!] value [any-value!]]',(e,t)=>{let[n,r,o]=t.args;if(n.t===s.Block){let i=Uo(n.s,n.i,r);if(i<0||i+1>=n.s.data.length){let l=i<0?[r,o]:[o];It(n.s),n.s.data.push(...l),n.s.nl&&n.s.nl.push(...l.map(()=>!1)),n.s.pos&&n.s.pos.push(...l.map(()=>-1))}else n.s.data[i+1]=o;return b(o)}let a=rr(n,r,o);return a!==null?N("script","bad-poke",a):b(o)});var qr=1<<U.Break|1<<U.Continue;function fr(e){let t=e.thrown;return e.thrown=null,t}g("do",'["Evaluates a block, source text or a script file; gives the last value." value [any-type!] /next "Evaluates only the first expression of a block" position [word!] "Set to the block after it"]',(e,t,n)=>{if(t.phase===1)return b(n);let r=t.args[0];if(t.args[1]===P){if(r.t===s.String&&t.phase===0){let a=Go(e.rt,r);if(a.k!=="value")return a;r=t.args[0]=a.v}if(r.t!==s.Block&&r.t!==s.Paren)return $e(t.args[2],k),r.t===s.Error?{k:"throw",e:{kind:U.Error,v:r,name:null}}:b(r);let o=r;if(t.phase===2){let a=t.data;return $e(t.args[2],Ze(o,a.i)),b(n)}return o.i>=o.s.data.length?($e(t.args[2],o),b(re)):(t.phase=2,t.data={s:o.s,i:o.i},{k:"expr",feed:t.data})}switch(r.t){case s.Block:case s.Paren:return t.phase=1,{k:"do",s:r.s,i:r.i};case s.String:{let o=Go(e.rt,r);return o.k!=="value"?o:(t.phase=1,ge(o.v))}case s.File:case s.Url:return t.phase=1,Pn(e,"do-file",[r],"read files");case s.Error:return{k:"throw",e:{kind:U.Error,v:r,name:null}}}return b(r)});g("reduce",'["Evaluates each expression of a block; gives a block of the values." value [any-value!]]',(e,t,n)=>{let r=t.args[0];if(r.t!==s.Block)return b(r);t.phase===0&&(t.phase=1,t.data={feed:{s:r.s,i:r.i},out:[]});let o=t.data;return n!==null&&o.out.push(n),o.feed.i>=o.feed.s.data.length?b(it(o.out)):{k:"expr",feed:o.feed}});g("quote",'["The value as it is, not evaluated." :value [any-type!]]',(e,t)=>b(t.args[0]));g("if",'["Evaluates the block if the condition is true; gives its value, or none." condition [any-value!] body [block!]]',(e,t,n)=>t.phase===1?b(n):Be(t.args[0])?(t.phase=1,ge(t.args[1])):b(k));g("unless",'["Evaluates the block if the condition is not true; gives its value, or none." condition [any-value!] body [block!]]',(e,t,n)=>t.phase===1?b(n):Be(t.args[0])?b(k):(t.phase=1,ge(t.args[1])));g("either",'["Evaluates the first block if the condition is true, the second if not." condition [any-value!] true-body [block!] false-body [block!]]',(e,t,n)=>t.phase===1?b(n):(t.phase=1,ge(t.args[Be(t.args[0])?1:2])));g("not",'["True if the value is false or none, false otherwise." value [any-value!]]',(e,t)=>b({t:s.Logic,v:!Be(t.args[0])}));function mc(e,t,n){let r=e.args[0];e.phase===0&&(e.phase=1,e.data={s:r.s,i:r.i});let o=e.data;if(t!==null){if(Be(t)===n)return b(n?t:k);if(o.i>=o.s.data.length)return b(n?k:t)}else if(o.i>=o.s.data.length)return b(n?k:{t:s.Logic,v:!0});return{k:"expr",feed:o}}g("all",'["Evaluates expressions while they are true; gives the last value, or none at the first false one." block [block!]]',(e,t,n)=>mc(t,n,!1));g("any",'["Evaluates expressions until one is true; gives it, or none." block [block!]]',(e,t,n)=>mc(t,n,!0));g("case",'["Evaluates the block after the first true condition." cases [block!] /all]',(e,t,n)=>{let r=t.args[0],o=t.args[1].t===s.Logic;t.phase===0&&(t.data={feed:{s:r.s,i:r.i},out:k});let a=t.data,i=a.feed.s.data;if(t.phase===1){let l=i[a.feed.i];if(l===void 0)return N("script","case-body","case condition has no block after it");if(a.feed.i++,Be(n))return l.t!==s.Block?b(l):(t.phase=2,ge(l))}else if(t.phase===2){if(!o)return b(n);a.out=n}return a.feed.i>=i.length?b(a.out):(t.phase=1,{k:"expr",feed:a.feed})});g("switch",'["Evaluates the block after the value that is equal to the one given." value [any-value!] cases [block!] /default case [block!]]',(e,t,n)=>{if(t.phase===1)return b(n);let r=t.args[0],o=t.args[1],a=o.s.data;for(let i=o.i;i<a.length;i++){let l=a[i];if(l.t!==s.Block&&Ct(l,r)){let c=i+1;for(;c<a.length&&a[c].t!==s.Block;)c++;let u=a[c];return u===void 0?b(k):(t.phase=1,ge(u))}}return t.args[2].t===s.Logic?(t.phase=1,ge(t.args[3])):b(k)});function ms(e,t,n){let r=fr(e);if(r!==null){if(r.kind===U.Break)return b(r.v)}else n!==null&&(t.out=n);return null}g("loop",'["Evaluates a block a number of times." count [integer!] body [block!]]',(e,t,n)=>{t.phase===0&&(t.phase=1,t.trap=qr,t.data={left:q(t.args[0].v),out:k});let r=t.data,o=ms(t,r,n);return o!==null?o:r.left<=0?b(r.out):(r.left--,ge(t.args[1]))});function gc(e,t){let n=e.t===s.Block?e.s.data.slice(e.i):[e],r=Le(n.map(a=>a.sym),n.map(()=>k)),o=Me(t.s,t.i);return be(o,r),{ctx:r,body:{t:s.Block,s:o,i:0}}}g("repeat",`["Evaluates a block a number of times, with a word counting from 1." 'word [word!] count [integer!] body [block!]]`,(e,t,n)=>{if(t.phase===0){t.phase=1,t.trap=qr;let a=q(t.args[1].v);t.data={...gc(t.args[0],t.args[2]),n:a,i:0,out:k}}let r=t.data,o=ms(t,r,n);return o!==null?o:r.i>=r.n?b(r.out):(r.i++,r.ctx.vals[0]={t:s.Integer,v:r.i},ge(r.body))});g("foreach",`["Evaluates a block for each value of a series, with a word set to it; for a map, each key, or each key and value." 'word [word! block!] data [series! map!] body [block!]]`,(e,t,n)=>{let r=t.args[1];if(t.phase===0){t.phase=1,t.trap=qr;let l=t.args[0];if(l.t===s.Block&&(l.s.data.length===l.i||l.s.data.slice(l.i).some(u=>u.t!==s.Word)))return N("script","bad-words","foreach needs one or more words");let c=gc(l,t.args[2]);if(r.t===s.Map&&c.ctx.keys.length>2)return N("script","bad-words","foreach over a map takes a key, or a key and a value");t.data={...c,at:r.t===s.Map?0:r.i,pairs:r.t===s.Map?r.s.data.slice():null,out:k}}let o=t.data,a=ms(t,o,n);if(a!==null)return a;if(o.pairs!==null)return o.at>=o.pairs.length?b(o.out):(o.ctx.vals[0]=o.pairs[o.at],o.ctx.vals.length===2&&(o.ctx.vals[1]=o.pairs[o.at+1]),o.at+=2,ge(o.body));let i=r.s.data;if(o.at>=i.length)return b(o.out);for(let l=0;l<o.ctx.vals.length;l++)o.ctx.vals[l]=fp(r,o.at+l);return o.at+=o.ctx.vals.length,ge(o.body)});function fp(e,t){if(e.t===s.Binary){let n=e.s.data[t];return n===void 0?k:{t:s.Integer,v:n}}if(e.t>=s.String&&e.t<=s.Tag){let n=e.s.data[t];return n===void 0?k:{t:s.Char,v:n}}return e.s.data[t]??k}g("while",'["Evaluates the body as long as the condition block is true." condition [block!] body [block!]]',(e,t,n)=>{t.phase===0&&(t.trap=qr,t.data={out:k});let r=t.data,o=fr(t);return o!==null&&o.kind===U.Break?b(o.v):t.phase===1&&o===null?Be(n)?(t.phase=2,ge(t.args[1])):b(r.out):(t.phase===2&&o===null&&(r.out=n),t.phase=1,ge(t.args[0]))});g("until",'["Evaluates the block until it gives true." body [block!]]',(e,t,n)=>{let r=fr(t);return r!==null&&r.kind===U.Break?b(r.v):t.phase===1&&r===null&&Be(n)?b(n):(t.phase=1,t.trap=qr,ge(t.args[0]))});g("break",'["Leaves the loop it is in." /return value [any-value!]]',(e,t)=>({k:"throw",e:{kind:U.Break,v:t.args[0].t===s.Logic?t.args[1]:re,name:null}}));g("continue",'["Goes on with the next turn of the loop it is in." ]',()=>({k:"throw",e:{kind:U.Continue,v:re,name:null}}));g("return",'["Leaves the function it is in, giving a value." value [any-type!]]',(e,t)=>({k:"throw",e:{kind:U.Return,v:t.args[0],name:null}}));g("exit",'["Leaves the function it is in, giving no value." ]',()=>({k:"throw",e:{kind:U.Return,v:re,name:null}}));g("try",'["Evaluates a block; gives an error as a value instead of raising it." body [block!]]',(e,t,n)=>{let r=fr(t);return r!==null?b(r.v):t.phase===1?b(n):(t.phase=1,t.trap=1<<U.Error,ge(t.args[0]))});g("attempt",'["Evaluates a block; gives none if it raises an error." body [block!]]',(e,t,n)=>fr(t)!==null?b(k):t.phase===1?b(n):(t.phase=1,t.trap=1<<U.Error,ge(t.args[0])));g("catch",'["Evaluates a block; gives the value a throw inside it threw." body [block!] /name word [word! block!]]',(e,t,n)=>{let r=fr(t);if(r!==null){let o=t.args[1].t===s.Logic,a=t.args[2],i=a.t===s.Block?a.s.data.slice(a.i):[a];return(o?r.name!==null&&i.some(c=>Ct(c,r.name)):r.name===null)?b(r.v):{k:"throw",e:r}}return t.phase===1?b(n):(t.phase=1,t.trap=1<<U.Throw,ge(t.args[0]))});g("throw",'["Throws a value to the catch around it." value [any-value!] /name word [word!]]',(e,t)=>({k:"throw",e:{kind:U.Throw,v:t.args[0],name:t.args[1].t===s.Logic?t.args[2]:null}}));g("cause-error",'["Raises an error of a type and an id." type [word!] id [word!] args [any-value!]]',(e,t)=>{let[n,r,o]=t.args,a=Y(M(n.sym),M(r.sym),D(o));return{k:"throw",e:{kind:U.Error,v:a,name:null}}});var G={Add:0,Sub:1,Mul:2,Div:3,Rem:4},pp=["add","subtract","multiply","divide","take the remainder of"],Nt=()=>N("math","zero-divide","attempt to divide by zero"),gn=()=>N("math","overflow","math or number overflow");function ys(e){switch(e.t){case s.Integer:return q(e.v);case s.Decimal:case s.Percent:return e.v}return null}function gs(e,t,n){switch(e){case G.Add:return t+n;case G.Sub:return t-n;case G.Mul:return t*n;case G.Div:return n===0?null:t/n;case G.Rem:return n===0?null:t%n}}function bp(e,t,n){let r;switch(e){case G.Add:r=qa(t,n);break;case G.Sub:r=Ka(t,n);break;case G.Mul:r=Ga(t,n);break;case G.Rem:if(dn(n))return Nt();r=Yn(t,n);break;case G.Div:{if(dn(n))return Nt();let o=Yn(t,n);if(o!==null&&dn(o)){r=Va(t,n);break}return b(ke(q(t)/q(n)))}}return r===null?gn():b(H(r))}function hp(e,t,n){let r=_t(t),o=_t(n);if(r===null||o===null)return null;let a=t.t===s.Money?t.cur:"",i=n.t===s.Money?n.cur:"";if(a!==""&&i!==""&&a.toUpperCase()!==i.toUpperCase())return N("math","currency",`cannot mix ${a} and ${i}`);let l=a||i,c=t.t===s.Money&&n.t===s.Money,u;switch(e){case G.Add:u=Ml(r,o);break;case G.Sub:u=Tl(r,o);break;case G.Mul:if(c)return null;u=Ll(r,o);break;case G.Div:return u=Al(r,o),u===null?Nt():b(c?ke(xt(u)):ft(u,l));case G.Rem:u=Bl(r,o);break}return u===null?Nt():b(ft(u,l))}function Kr(e,t,n){if(t.t===s.Integer&&n.t===s.Integer)return bp(e,t.v,n.v);let r=ys(t),o=ys(n);if(t.t===s.Money||n.t===s.Money){let a=hp(e,t,n);if(a!==null)return a}else if(t.t===s.Pair||n.t===s.Pair){let a=t.t===s.Pair?t.x:r,i=t.t===s.Pair?t.y:r,l=n.t===s.Pair?n.x:o,c=n.t===s.Pair?n.y:o;if(a!==null&&i!==null&&l!==null&&c!==null){let u=gs(e,a,l),d=gs(e,i,c);return u===null||d===null?Nt():b(Bt(u,d))}}else if(t.t===s.Date){let a=gp(e,t,n);if(a!==null)return a}else if(t.t===s.Time||n.t===s.Time){let a=mp(e,t,n,r,o);if(a!==null)return a}else if(r!==null&&o!==null){let a=gs(e,r,o);if(a===null)return Nt();if(!Number.isFinite(a))return gn();let i=t.t===s.Percent&&(n.t===s.Percent?e!==G.Div:e===G.Mul||e===G.Div);return b(i?$t(a):ke(a))}return N("script","bad-math",`cannot ${pp[e]} ${ie(t.t)} and ${ie(n.t)}`)}function mp(e,t,n,r,o){if(t.t===s.Time&&n.t===s.Time){switch(e){case G.Add:return b(Ie(t.v+n.v));case G.Sub:return b(Ie(t.v-n.v));case G.Div:return n.v===0?Nt():b(ke(t.v/n.v));case G.Rem:return n.v===0?Nt():b(Ie(t.v%n.v))}return null}if(t.t===s.Time&&o!==null){if(e===G.Mul)return b(Ie(Math.round(t.v*o)));if(e===G.Div)return o===0?Nt():b(Ie(Math.round(t.v/o)))}return n.t===s.Time&&r!==null&&e===G.Mul?b(Ie(Math.round(n.v*r))):null}var Vo=864e11;function Yo(e){return Date.UTC(e.y,e.m-1,e.d)/864e5}function vc(e,t,n){let r=new Date(e*864e5);return fn({y:r.getUTCFullYear(),m:r.getUTCMonth()+1,d:r.getUTCDate(),time:t,zone:n})}function gp(e,t,n){let r=t.v;if(n.t===s.Integer&&(e===G.Add||e===G.Sub)){let o=q(n.v);return b(vc(Yo(r)+(e===G.Add?o:-o),r.time,r.zone))}if(n.t===s.Time&&(e===G.Add||e===G.Sub)){let o=(r.time??0)+(e===G.Add?n.v:-n.v),a=Math.floor(o/Vo);return b(vc(Yo(r)+a,o-a*Vo,r.zone))}if(n.t===s.Date&&e===G.Sub){let o=ws(r,n.v);return b(r.time===null&&n.v.time===null?H(Math.round(o/Vo)):Ie(o))}return null}function ws(e,t){return(Yo(e)-Yo(t))*Vo+((e.time??0)-(e.zone??0)*6e10)-((t.time??0)-(t.zone??0)*6e10)}var ht="[number! money! time! pair! date!]";g("add",`["The sum of two values." a ${ht} b ${ht}]`,(e,t)=>Kr(G.Add,t.args[0],t.args[1]));g("subtract",`["The difference of two values." a ${ht} b ${ht}]`,(e,t)=>Kr(G.Sub,t.args[0],t.args[1]));g("multiply",`["The product of two values." a ${ht} b ${ht}]`,(e,t)=>Kr(G.Mul,t.args[0],t.args[1]));g("divide",`["The first value divided by the second." a ${ht} b ${ht}]`,(e,t)=>Kr(G.Div,t.args[0],t.args[1]));g("remainder",`["What is left after dividing the first value by the second." a ${ht} b ${ht}]`,(e,t)=>Kr(G.Rem,t.args[0],t.args[1]));g("negate",`["The value with its sign changed." value ${ht}]`,(e,t)=>{let n=t.args[0];switch(n.t){case s.Integer:{let r=Lo(n.v);return r===null?gn():b(H(r))}case s.Decimal:return b(ke(-n.v));case s.Percent:return b($t(-n.v));case s.Money:return b(ft({d:-n.v.d,e:n.v.e},n.cur));case s.Time:return b(Ie(-n.v));case s.Pair:return b(Bt(-n.x,-n.y))}return N("script","bad-math",`cannot negate ${ie(n.t)}`)});var vp=["even","down","half-down","floor","ceiling","half-ceiling"];g("round",'["The value rounded to the nearest whole number, or to a multiple of a scale." value [number! money! time!] /to scale [number! money! time!] /even /down /half-down /floor /ceiling /half-ceiling]',(e,t)=>{let n=t.args[0],r=t.args[1]===P,o=vp.find((l,c)=>t.args[3+c]===P)??"half-away";if(n.t===s.Time){let l=r?t.args[2]:H(1),c=l.t===s.Time?l.v:(ys(l)??xt(_t(l)))*1e9,u=Za(Qt(n.v),Qt(c),o);return u===null?Nt():b(Ie(xt(u)))}let a=r?t.args[2]:n.t===s.Percent?$t(.01):H(1);if(a.t===s.Time)return N("script","bad-math","cannot round a number to a time!");let i=Za(_t(n),_t(a),o);if(i===null)return Nt();if(n.t===s.Money||a.t===s.Money)return b(ft(i,n.t===s.Money?n.cur:a.cur));if(a.t===s.Integer&&(r||n.t===s.Integer)){let l=i.e===0?Ve(i.d):null;return l===null?gn():b(H(l))}return b(n.t===s.Percent?$t(xt(i)):ke(xt(i)))});g("abs",`["The value without its sign." value ${ht}]`,(e,t)=>{let n=t.args[0];switch(n.t){case s.Integer:{if(An(n.v,0)>=0)return b(n);let r=Lo(n.v);return r===null?gn():b(H(r))}case s.Decimal:return b(ke(Math.abs(n.v)));case s.Percent:return b($t(Math.abs(n.v)));case s.Money:return b(ft({d:n.v.d<0n?-n.v.d:n.v.d,e:n.v.e},n.cur));case s.Time:return b(Ie(Math.abs(n.v)));case s.Pair:return b(Bt(Math.abs(n.x),Math.abs(n.y)))}return N("script","bad-math",`cannot take abs of ${ie(n.t)}`)});g("zero?",`["True if the value is zero." value ${ht}]`,(e,t)=>{let n=t.args[0];switch(n.t){case s.Integer:return b(ee(dn(n.v)));case s.Money:return b(ee(Ao(n.v,{d:0n,e:0})));case s.Pair:return b(ee(n.x===0&&n.y===0));case s.Decimal:case s.Percent:case s.Time:return b(ee(n.v===0))}return b(ee(!1))});g("even?",'["True if the integer is even." value [integer!]]',(e,t)=>b(ee(dn(Yn(t.args[0].v,2)))));g("odd?",'["True if the integer is odd." value [integer!]]',(e,t)=>b(ee(!dn(Yn(t.args[0].v,2)))));g("sign?",'["Gives -1, 0 or 1 by the sign of the value." value [number! money! time!]]',(e,t)=>b(H(ks(t.args[0]))));g("negative?",'["True if the value is less than zero." value [number! money! time!]]',(e,t)=>b(ee(ks(t.args[0])<0)));g("positive?",'["True if the value is more than zero." value [number! money! time!]]',(e,t)=>b(ee(ks(t.args[0])>0)));function ks(e){return e.t===s.Integer?An(e.v,0):e.t===s.Money?Math.sign(Number(e.v.d)):Math.sign(e.v)}var jt="[number!]";function tn(e){return e.t===s.Integer?q(e.v):e.v}function vn(e){return b(ke(e))}g("power",`["The number raised to the exponent." number ${jt} exponent ${jt}]`,(e,t)=>{let[n,r]=t.args;if(n.t===s.Integer&&r.t===s.Integer&&An(r.v,0)>=0){let o=BigInt(n.v),a=BigInt(r.v);if(a>64n&&o!==0n&&o!==1n&&o!==-1n)return gn();let i=Ve(o**(a>64n?a%2n+2n:a));return i===null?gn():b(H(i))}return vn(Math.pow(tn(n),tn(r)))});g("square-root",`["The square root of the number." value ${jt}]`,(e,t)=>vn(Math.sqrt(tn(t.args[0]))));g("exp",`["e raised to the power of the number." power ${jt}]`,(e,t)=>vn(Math.exp(tn(t.args[0]))));function xs(e,t){return vn(t(tn(e.args[0])))}g("log-e",`["The natural logarithm of the number." value ${jt}]`,(e,t)=>xs(t,Math.log));g("log-10",`["The base-10 logarithm of the number." value ${jt}]`,(e,t)=>xs(t,Math.log10));g("log-2",`["The base-2 logarithm of the number." value ${jt}]`,(e,t)=>xs(t,Math.log2));var Cs=Math.PI/180;function Ss(e){return Math.abs(e)<1e-15?0:e}function Es(e,t,n){g(e,`["${t}" angle ${jt} /radians "The angle is in radians"]`,(r,o)=>{let a=tn(o.args[0])*(o.args[1]===P?1:Cs);if(e==="tangent"&&Math.abs(Math.cos(a))<1e-15)return vn(Math.sin(a)>0?1/0:-1/0);let i=n(a);return vn(o.args[1]===P?i:Ss(i))})}Es("sine","The sine of an angle, in degrees.",Math.sin);Es("cosine","The cosine of an angle, in degrees.",Math.cos);Es("tangent","The tangent of an angle, in degrees.",Math.tan);function Ms(e,t,n,r){g(e,`["${t}" value ${jt} /radians "Give the angle in radians"]`,(o,a)=>{let i=tn(a.args[0]);return vn(a.args[1]===P?n(i):Ss(n(i)/Cs))})}Ms("arcsine","The angle whose sine is the value, in degrees.",Math.asin,!0);Ms("arccosine","The angle whose cosine is the value, in degrees.",Math.acos,!0);Ms("arctangent","The angle whose tangent is the value, in degrees.",Math.atan,!1);g("arctangent2",`["The angle of the point x, y, in degrees." y ${jt} x ${jt} /radians "Give the angle in radians"]`,(e,t)=>{let n=Math.atan2(tn(t.args[0]),tn(t.args[1]));return vn(t.args[2]===P?n:Ss(n/Cs))});var Dn={a:BigInt(Date.now())|1n,b:0x9e3779b97f4a7c15n};function mn(){let e=Dn.a,t=Dn.b;return Dn.a=t,e^=e<<23n&0xffffffffffffffffn,Dn.b=e^t^e>>17n^t>>26n,Number(Dn.b+t&0x1fffffffffffffn)/2**53}function vs(e){return Math.floor(mn()*e)+1}g("random",'["A random value: an integer from 1 to it, a decimal up to it, a shuffled series." value [any-value!] /seed "Start the sequence from this value; gives nothing" /only "Pick one element of a series"]',(e,t)=>{let n=t.args[0];if(t.args[1]===P){let r=0x811c9dc5n;for(let o of Z(n))r=(r^BigInt(o.codePointAt(0)))*0x100000001b3n&0xffffffffffffffffn;Dn.a=r|1n,Dn.b=r*0x9e3779b97f4a7c15n&0xffffffffffffffffn|1n;for(let o=0;o<8;o++)mn();return b(re)}switch(n.t){case s.Integer:{let r=q(n.v);return r===0?b(H(0)):b(H(Math.sign(r)*vs(Math.abs(r))))}case s.Decimal:return b(ke(mn()*n.v));case s.Percent:return b($t(mn()*n.v));case s.Money:return b(ft(Qt(Math.floor(mn()*xt(n.v)*100)/100),n.cur));case s.Logic:return b(ee(mn()<.5));case s.Time:return b(Ie(Math.floor(mn()*n.v)));case s.Char:return b({t:s.Char,v:vs(n.v)})}if(wl(n.t)){let r=n,o=r.s.data.length-r.i;if(t.args[2]===P)return o<=0?b(k):b(St(n,H(vs(o))));It(r.s);let a=[r.s.data,r.s.nl,r.s.pos].filter(i=>i!==void 0);for(let i=o-1;i>0;i--){let l=Math.floor(mn()*(i+1));for(let c of a)[c[r.i+i],c[r.i+l]]=[c[r.i+l],c[r.i+i]]}return b(n)}return N("script","bad-random",`cannot make a random ${ie(n.t)}`)});function Zo(e,t,n,r){let o=BigInt(e),a=BigInt(Math.max(0,Math.min(64,t))),i;return n?i=BigInt.asIntN(64,o<<a):r?i=BigInt.asIntN(64,BigInt.asUintN(64,o)>>a):i=o>>a,H(Ve(i))}var Jo='data [integer!] bits [integer!] "How many bits"';g("shift",`["Shifts the bits of an integer right, or left with /left." ${Jo} /left "Shift to the left" /logical "Shift zeros in, not the sign"]`,(e,t)=>b(Zo(t.args[0].v,q(t.args[1].v),t.args[2]===P,t.args[3]===P)));g("shift-left",`["Shifts the bits of an integer left." ${Jo}]`,(e,t)=>b(Zo(t.args[0].v,q(t.args[1].v),!0,!1)));g("shift-right",`["Shifts the bits of an integer right, keeping its sign." ${Jo}]`,(e,t)=>b(Zo(t.args[0].v,q(t.args[1].v),!1,!1)));g("shift-logical",`["Shifts the bits of an integer right, shifting zeros in." ${Jo}]`,(e,t)=>b(Zo(t.args[0].v,q(t.args[1].v),!1,!0)));g("equal?",'["True if the values are equal." a [any-type!] b [any-type!]]',(e,t)=>b(ee(Ct(t.args[0],t.args[1]))));g("not-equal?",'["True if the values are not equal." a [any-type!] b [any-type!]]',(e,t)=>b(ee(!Ct(t.args[0],t.args[1]))));g("strict-equal?",'["True if the values are equal and of the same type and case." a [any-type!] b [any-type!]]',(e,t)=>b(ee(bt(t.args[0],t.args[1]))));g("same?",'["True if the values are the very same: the same series at the same position, the same object." a [any-type!] b [any-type!]]',(e,t)=>b(ee(No(t.args[0],t.args[1]))));g("strict-not-equal?",'["True if the values are not strictly equal." a [any-type!] b [any-type!]]',(e,t)=>b(ee(!bt(t.args[0],t.args[1]))));function Xo(e,t,n){let r=Bn(e,t);return r===null?N("script","bad-compare",`cannot compare ${ie(e.t)} with ${ie(t.t)}`):b(ee(n(r)))}g("lesser?",'["True if the first value is less than the second." a [any-value!] b [any-value!]]',(e,t)=>Xo(t.args[0],t.args[1],n=>n<0));g("greater?",'["True if the first value is more than the second." a [any-value!] b [any-value!]]',(e,t)=>Xo(t.args[0],t.args[1],n=>n>0));g("lesser-or-equal?",'["True if the first value is less than or equal to the second." a [any-value!] b [any-value!]]',(e,t)=>Xo(t.args[0],t.args[1],n=>n<=0));g("greater-or-equal?",'["True if the first value is more than or equal to the second." a [any-value!] b [any-value!]]',(e,t)=>Xo(t.args[0],t.args[1],n=>n>=0));function yc(e,t,n){let r=Bn(e,t);return r===null?N("script","bad-compare",`cannot compare ${ie(e.t)} with ${ie(t.t)}`):b(r>=0===n?e:t)}g("max",'["The greater of two values." a [any-value!] b [any-value!]]',(e,t)=>yc(t.args[0],t.args[1],!0));g("min",'["The lesser of two values." a [any-value!] b [any-value!]]',(e,t)=>yc(t.args[0],t.args[1],!1));function Ts(e,t,n,r){if(e.t===s.Integer&&t.t===s.Integer){let o=Ve(BigInt.asIntN(64,n(BigInt(e.v),BigInt(t.v))));return o===null?gn():b(H(o))}if(e.t===s.Binary&&t.t===s.Binary){let o=e.s.data.slice(e.i),a=t.s.data.slice(t.i),i=[],l=Math.max(o.length,a.length);for(let c=0;c<l&&o.length>0&&a.length>0;c++)i.push(Number(n(BigInt(o[c%o.length]),BigInt(a[c%a.length]))&255n));return b({t:s.Binary,s:{data:i},i:0})}return b(ee(r(Be(e),Be(t))))}g("and~",'["Both values: bitwise for integers and binaries, logical for anything else." a [any-value!] b [any-value!]]',(e,t)=>Ts(t.args[0],t.args[1],(n,r)=>n&r,(n,r)=>n&&r));g("or~",'["Either value: bitwise for integers and binaries, logical for anything else." a [any-value!] b [any-value!]]',(e,t)=>Ts(t.args[0],t.args[1],(n,r)=>n|r,(n,r)=>n||r));g("xor~",'["One value or the other but not both: bitwise for integers and binaries, logical for anything else." a [any-value!] b [any-value!]]',(e,t)=>Ts(t.args[0],t.args[1],(n,r)=>n^r,(n,r)=>n!==r));Te("+","add");Te("-","subtract");Te("*","multiply");Te("/","divide");Te("//","remainder");Te("**","power");Te("<<","shift-left");Te(">>","shift-right");Te(">>>","shift-logical");Te("=","equal?");Te("<>","not-equal?");Te("==","strict-equal?");Te("!==","strict-not-equal?");Te("<","lesser?");Te(">","greater?");Te("<=","lesser-or-equal?");Te(">=","greater-or-equal?");Te("and","and~");Te("or","or~");Te("xor","xor~");var Pt=e=>q(e.v),ce=e=>e===P;function Ls(e,t){let n=e.s.data[t];return n===void 0?k:_(e.t)?n:e.t===s.Binary?H(n):pt(n)}function As(e,t){return t===null||t.t===s.None?e.s.data.length:t.t===s.Integer?ar(e,e.i+Pt(t)):ar(e,t.i)}function wc(e,t){let n=t.t===s.Integer?ar(e,e.i+Pt(t)):ar(e,t.i);return n<e.i?[n,e.i]:[e.i,n]}function kc(e,t,n,r,o){let{add:a,nl:i}=sr(e.t,t,n);if(r!==null){let l=r.t===s.Integer?Math.max(0,Pt(r)):Math.max(0,r.i-t.i);a=a.slice(0,l),i=i?.slice(0,l)}if(o!==null){let l=Math.max(0,Pt(o)),c=a,u=i;a=[],i=u===void 0?void 0:[];for(let d=0;d<l;d++)a.push(...c),i!==void 0&&i.push(...u)}return i===void 0?{add:a}:{add:a,nl:i}}g("next",'["The series one position on." series [series!]]',(e,t)=>b(Ze(t.args[0],t.args[0].i+1)));g("back",'["The series one position back." series [series!]]',(e,t)=>b(Ze(t.args[0],t.args[0].i-1)));g("head",'["The series at its first position." series [series!]]',(e,t)=>b(Ze(t.args[0],0)));g("tail",'["The series just past its last value." series [series!]]',(e,t)=>b(Ze(t.args[0],1/0)));g("skip",'["The series moved on, or back, by an offset." series [series!] offset [integer!]]',(e,t)=>{let n=t.args[0];return b(Ze(n,n.i+Pt(t.args[1])))});g("at",'["The series at a position, counted from where it is." series [series!] index [integer!]]',(e,t)=>{let n=t.args[0],r=Pt(t.args[1]);return b(Ze(n,n.i+(r>0?r-1:r)))});g("index?",'["The position of the series, from 1." series [series!]]',(e,t)=>b(H(t.args[0].i+1)));g("head?",'["True if the series is at its head." series [series!]]',(e,t)=>b(ee(t.args[0].i===0)));g("tail?",'["True if the series is at its tail." series [series!]]',(e,t)=>b(ee(uc(t.args[0])===0)));g("loaded-at",'["Where the value at the position of a block was loaded from, as file:line:col; none if it was made at run time." block [any-block!]]',(e,t)=>{let n=t.args[0],r=Ur(n.s,n.i);return b(r===null?k:j(r))});var xc='series [series!] value [any-value!] /part "Put in only part of the value" range [integer! series!] /only "A block goes in as one value" /dup "Put it in several times" count [integer!]',Cc=e=>kc(e.args[0],e.args[1],ce(e.args[4]),ce(e.args[2])?e.args[3]:null,ce(e.args[5])?e.args[6]:null);g("append",`["Puts a value at the tail of a series; gives the series at its head." ${xc}]`,(e,t)=>{let n=t.args[0],{add:r,nl:o}=Cc(t);return Je(n.s,n.s.data.length,0,r,o),b(Ze(n,0))});g("insert",`["Puts a value where the series is; gives the series just after it." ${xc}]`,(e,t)=>{let n=t.args[0],{add:r,nl:o}=Cc(t);return Je(n.s,n.i,0,r,o),b(Ze(n,n.i+r.length))});g("change",'["Puts a value over what the series holds where it is; gives the series just after it." series [series!] value [any-value!] /part "Change this much of the series" range [integer! series!] /only "A block goes in as one value" /dup "Put the value in several times" count [integer!]]',(e,t)=>{let n=t.args[0],{add:r,nl:o}=kc(n,t.args[1],ce(t.args[4]),null,ce(t.args[5])?t.args[6]:null),a=ce(t.args[2])?As(n,t.args[3]):Math.min(n.s.data.length,n.i+r.length);return Je(n.s,n.i,Math.max(0,a-n.i),r,o),b(Ze(n,n.i+r.length))});g("remove",'["Removes what the series holds where it is; gives the series." series [series!] /part "Remove this much" range [integer! series!]]',(e,t)=>{let n=t.args[0],[r,o]=ce(t.args[1])?wc(n,t.args[2]):[n.i,Math.min(n.s.data.length,n.i+1)];return Je(n.s,r,Math.max(0,o-r),[]),b(Ze(n,r))});g("clear",`["Removes everything from the series' position to its tail." series [series! map!]]`,(e,t)=>{let n=t.args[0];if(n.t===s.Map)return n.s.data.length=0,b(n);let r=n;return Je(r.s,r.i,r.s.data.length-r.i,[]),b(r)});g("copy",'["A copy of the series, map, object or bitset." value [series! map! object! bitset!] /part length [integer! series!] /deep]',(e,t)=>{let n=t.args[0],r=ce(t.args[3]);if(n.t===s.Map)return b({t:s.Map,s:r?Me(n.s):{data:n.s.data.slice()}});if(n.t===s.Object||n.t===s.Error){let l=Le(n.ctx.keys.slice(),n.ctx.vals.slice());return n.ctx.self&&(l.self=!0),b({t:n.t,ctx:l})}if(n.t===s.Bitset)return b({t:s.Bitset,s:{data:n.s.data.slice()},neg:n.neg});let o=n,[a,i]=ce(t.args[1])?wc(o,t.args[2]):[o.i,o.s.data.length];if(_(o.t)){let l=o,c={data:l.s.data.slice(a,i)};return l.s.nl&&(c.nl=l.s.nl.slice(a,i)),l.s.pos&&(c.pos=l.s.pos.slice(a,i)),l.s.file!==void 0&&(c.file=l.s.file),b({t:l.t,s:r?Me(c):c,i:0})}return b({t:o.t,s:{data:o.s.data.slice(a,i)},i:0})});g("reverse",`["Reverses the order of the values from the series' position." series [series!] /part length [integer! series!]]`,(e,t)=>{let n=t.args[0],r=ce(t.args[1])?As(n,t.args[2]):n.s.data.length,o=n.s.data;It(n.s);let a=n.s.nl;for(let i=n.i,l=r-1;i<l;i++,l--)[o[i],o[l]]=[o[l],o[i]],a&&([a[i],a[l]]=[a[l],a[i]]);return b(n)});function yp(e,t,n){return t.t===s.Datatype&&e.t!==s.Datatype?e.t===t.k:t.t===s.Typeset&&e.t!==s.Typeset?(t.bits&Ee(e.t))!==0n:n?bt(e,t):Ct(e,t)}function wp(e,t,n,r,o=!1){if(_(e.t))return{run:!n&&_(t.t)?t.s.data.slice(t.i):[t],eq:o?(c,u)=>No(c,u):(c,u)=>yp(c,u,r)};let a=sr(e.t,t,!1).add,i=r||e.t===s.Binary?(l,c)=>l===c:(l,c)=>Ke(l)===Ke(c);return{run:a,eq:i}}var kp=42,xp=63;function Cp(e,t,n,r,o){let a=[],i=0,l=t;for(;;){if(i===r.length)return l-t;let c=r[i];if(c===kp){a.push([i+1,l]),i++;continue}if(l<n&&(c===xp||o(e[l],c))){i++,l++;continue}let u=a.pop();if(u===void 0||u[1]>=n)return-1;i=u[0],l=u[1]+1,a.push([i,l])}}function Sc(e,t,n){let r=e.s.data,{run:o,eq:a}=wp(e,t,n.only,n.cased,n.same),i=n.wild===!0&&!_(e.t),l=o.length,c=u=>{if(i)return l=Cp(r,u,n.end,o,a),l>=0;if(u+o.length>n.end)return!1;for(let d=0;d<o.length;d++)if(!a(r[u+d],o[d]))return!1;return!0};if(n.match)return{at:c(e.i)?e.i:-1,len:l};if(n.reverse){for(let u=e.i-n.skip;u>=0;u-=n.skip)if(c(u))return{at:u,len:l}}else if(n.last){for(let u=n.end-(i?0:o.length);u>=e.i;u--)if((u-e.i)%n.skip===0&&c(u))return{at:u,len:l}}else for(let u=e.i;u+(i?0:o.length)<=n.end;u+=n.skip)if(c(u))return{at:u,len:l};return{at:-1,len:l}}g("find",'["Finds a value in a series; gives the series where it is, or none." series [series! none! typeset!] value [any-type!] /part "Look only this far" length [integer! series!] /only "A block is one value" /case "Capitals matter" /skip "Look only at every so many" size [integer!] /last "Find the last one" /tail "Give the series just after it" /match "Only where the series is" /reverse "Look back from where the series is" /any "In a string, * is any run of characters and ? any one" /same "In a block, the very same value (same?), not an equal one"]',(e,t)=>{let n=t.args[0];if(n.t===s.None)return b(k);if(n.t===s.Typeset){let l=t.args[1];return b(ee(l.t===s.Datatype&&(n.bits&Ee(l.k))!==0n))}let r=n,o=t.args,a={only:ce(o[4]),cased:ce(o[5]),skip:ce(o[6])?Math.max(1,Pt(o[7])):1,last:ce(o[8]),match:ce(o[10]),end:ce(o[2])?As(r,o[3]):r.s.data.length,reverse:ce(o[11]),wild:ce(o[12]),same:ce(o[13])},i=Sc(r,o[1],a);return i.at<0?b(k):b(Ze(r,ce(o[9])||a.match?i.at+i.len:i.at))});g("select",'["The value after the one found, or none." series [series! map! object! none!] value [any-type!] /only /case /skip size [integer!] /last]',(e,t)=>{let n=t.args[0],r=t.args;if(n.t===s.None)return b(k);if(n.t===s.Map||n.t===s.Object||n.t===s.Error){let l=St(n,r[1]);return b(typeof l=="string"?k:l)}let o=n,a=ce(r[4])?Math.max(1,Pt(r[5])):1,i=Sc(o,r[1],{only:ce(r[2]),cased:ce(r[3]),skip:a,last:ce(r[6]),match:!1,end:o.s.data.length});return i.at<0?b(k):b(Ls(o,i.at+i.len))});function Sp(e,t,n){let r=e.src.length;for(;;){if(e.width>=r)return null;if(!e.merging){if(e.lo>=r){[e.src,e.dst]=[e.dst,e.src],e.width*=2,e.lo=0;continue}e.mid=Math.min(e.lo+e.width,r),e.hi=Math.min(e.lo+2*e.width,r),e.i=e.lo,e.j=e.mid,e.k=e.lo,e.merging=!0}for(;e.k<e.hi;)if(e.i<e.mid&&e.j<e.hi){let o=n;if(n=null,o===null&&(o=t(e.src[e.j],e.src[e.i])),o===null)return[e.src[e.j],e.src[e.i]];e.dst[e.k++]=o?e.src[e.j++]:e.src[e.i++]}else e.i<e.mid?e.dst[e.k++]=e.src[e.i++]:e.dst[e.k++]=e.src[e.j++];e.merging=!1,e.lo+=2*e.width}}g("sort",'["Sorts the series in place." series [series!] /case /skip size [integer!] /compare comparator [any-function! integer!] /reverse]',(e,t,n)=>{let r=t.args[0],o=t.args,a=ce(o[1]),i=ce(o[2])?Math.max(1,Pt(o[3])):1,l=ce(o[4])&&o[5].t===s.Integer?Pt(o[5]):null;if(l!==null&&(l<1||l>i))return N("script","out-of-range",`sort cannot compare field ${l} of records of ${i}`);let c=ce(o[4])&&l===null?o[5]:null,u=ce(o[6]);if(t.phase===0){let w=r.s.data,E=[];for(let S=r.i;S<w.length;S+=i)E.push(w.slice(S,S+i));t.data={src:E,dst:E.slice(),width:1,lo:0,mid:0,hi:0,i:0,j:0,k:0,merging:!1},t.phase=1}let d=t.data,f=null;n!==null&&(f=n.t===s.Integer?Pt(n)<0:Be(n),u&&(f=!f));let p=(w,E=0)=>Ls({...r,s:{data:w},i:0},E),h=!1,y=Sp(d,(w,E)=>{if(c!==null)return null;let S=l===null?0:l-1,T=Ep(p(w,S),p(E,S),a);return T===null&&(h=!0),u?(T??0)>0:(T??0)<0},f);if(h)return N("script","bad-compare","sort cannot compare those values");if(y!==null)return{k:"call",fn:c,args:[p(y[0]),p(y[1])]};let C=d.src.flat(),x=r.s.data;for(let w=0;w<C.length;w++)x[r.i+w]=C[w];return It(r.s),r.s.nl&&r.s.nl.fill(!1,r.i),b(r)});function Ep(e,t,n){if(n&&e.t===s.String&&t.t===s.String){let o=e.s.data.slice(e.i),a=t.s.data.slice(t.i);for(let i=0;i<Math.min(o.length,a.length);i++)if(o[i]!==a[i])return o[i]<a[i]?-1:1;return o.length<a.length?-1:o.length>a.length?1:0}if(n&&e.t===s.Char&&t.t===s.Char)return e.v<t.v?-1:e.v>t.v?1:0;let r=Bn(e,t);return r!==null?r:e.t!==t.t?e.t<t.t?-1:1:e.t===s.None?0:null}function Ec(e){let t=e.args[0],n=t.t===s.Block?t.s.data.slice(t.i):[t],r=Le(n.map(i=>i.sym),n.map(()=>k)),o=e.args[2],a=Me(o.s,o.i);return be(a,r),{ctx:r,body:{t:s.Block,s:a,i:0}}}function Mc(e,t,n){let r=n.s.data;if(t.pos>=r.length)return null;for(let o=0;o<t.ctx.vals.length;o++)t.ctx.vals[o]=Ls(n,t.pos+o);return t.pos+=t.ctx.vals.length,e.trap=1<<U.Break|1<<U.Continue,ge(t.body)}g("remove-each",`["Removes the values of a series for which the block gives true." 'word [word! block!] data [series!] body [block!]]`,(e,t,n)=>{let r=t.args[1];t.phase===0&&(t.phase=1,t.data={...Ec(t),pos:r.i,out:[],keep:r.s.data.slice(0,r.i)});let o=t.data,a=o.ctx.vals.length,i=t.thrown;t.thrown=null;let l=i!==null&&i.kind===U.Break;if(n!==null||i!==null){let u=o.pos-a,d=r.s.data.slice(u,Math.min(u+a,r.s.data.length));(l||n===null||!Be(n))&&o.keep.push(...d)}let c=l?null:Mc(t,o,r);return c!==null?c:(l&&o.keep.push(...r.s.data.slice(o.pos)),Je(r.s,0,r.s.data.length,o.keep),b(r))});g("map-each",`["A block of what the block gives for each value of a series." 'word [word! block!] data [series!] body [block!]]`,(e,t,n)=>{let r=t.args[1];t.phase===0&&(t.phase=1,t.data={...Ec(t),pos:r.i,out:[],keep:[]});let o=t.data,a=t.thrown;return t.thrown=null,a!==null&&a.kind===U.Break?b({t:s.Block,s:{data:o.out},i:0}):(n!==null&&n.t!==s.Unset&&(n.t===s.Block?o.out.push(...n.s.data.slice(n.i)):o.out.push(n)),Mc(t,o,r)??b({t:s.Block,s:{data:o.out},i:0}))});function Mp(e,t){return _(e)?(n,r)=>t?bt(n,r):Ct(n,r):t||e===s.Binary?(n,r)=>n===r:(n,r)=>Ke(n)===Ke(r)}function Gr(e,t){let n=[];for(let r of e)n.some(o=>t(r,o))||n.push(r);return n}function Tp(e,t){return{t:e.t,s:{data:t},i:0}}function Vr(e,t,n){let r=e.args[0],o=t?e.args[1]:null;if(o!==null&&_(r.t)!==_(o.t))return N("script","bad-set","both series must be of the same kind");let a=Mp(r.t,ce(e.args[t?2:1])),i=r.s.data.slice(r.i),l=o===null?[]:o.s.data.slice(o.i);return b(Tp(r,n(i,l,a)))}g("unique",'["The values of the series, each once." set [series!] /case]',(e,t)=>Vr(t,!1,(n,r,o)=>Gr(n,o)));g("union",'["The values that are in either series, each once." a [series!] b [series!] /case]',(e,t)=>Vr(t,!0,(n,r,o)=>Gr([...n,...r],o)));g("intersect",'["The values that are in both series." a [series!] b [series!] /case]',(e,t)=>Vr(t,!0,(n,r,o)=>Gr(n.filter(a=>r.some(i=>o(a,i))),o)));g("difference",'["The values that are in one series but not the other; of two dates, the time between them." a [series! date!] b [series! date!] /case]',(e,t)=>{let[n,r]=t.args;return n.t===s.Date||r.t===s.Date?n.t!==s.Date||r.t!==s.Date?N("script","bad-set","difference takes two dates or two series"):b(Ie(ws(n.v,r.v))):Vr(t,!0,(o,a,i)=>Gr([...o.filter(l=>!a.some(c=>i(l,c))),...a.filter(l=>!o.some(c=>i(c,l)))],i))});g("exclude",'["The values of the first series that are not in the second." a [series!] b [series!] /case]',(e,t)=>Vr(t,!0,(n,r,o)=>Gr(n.filter(a=>!r.some(i=>o(a,i))),o)));var Dt=e=>e===P,nn=e=>q(e.v),Qo=e=>e===32||e===9||e===10||e===13||e===160;function Tc(e){return(t,n)=>{let r=n.args[0],o=l=>{let c=String.fromCodePoint(l),u=e?c.toUpperCase():c.toLowerCase();return u.length===c.length?u.codePointAt(0):l};if(r.t===s.Char)return b(pt(o(r.v)));let a=r,i=Dt(n.args[1])?Math.min(a.s.data.length,a.i+nn(n.args[2])):a.s.data.length;for(let l=a.i;l<i;l++)a.s.data[l]=o(a.s.data[l]);return b(a)}}g("uppercase",'["Changes the text to capitals." string [any-string! char!] /part length [integer!]]',Tc(!0));g("lowercase",'["Changes the text to small letters." string [any-string! char!] /part length [integer!]]',Tc(!1));g("trim",'["Removes spaces at both ends, or with refinements other spaces too." series [any-string! block!] /head /tail /lines /all]',(e,t)=>{let n=t.args[0];if(n.t===s.Block){let u=n.s.data.filter((d,f)=>f<n.i||d.t!==s.None);return n.s.data.splice(0,n.s.data.length,...u),It(n.s),n.s.nl&&(n.s.nl.length=0),n.s.pos&&(n.s.pos.length=0),b(n)}let r=n,o=r.s.data.slice(r.i),[a,i,l,c]=[Dt(t.args[1]),Dt(t.args[2]),Dt(t.args[3]),Dt(t.args[4])];if(c)o=o.filter(u=>!Qo(u));else if(l){let u=[];for(let d of o)Qo(d)?u.length>0&&u[u.length-1]!==32&&u.push(32):u.push(d);u[u.length-1]===32&&u.pop(),o=u}else{let u=0,d=o.length;if(a||!i)for(;u<d&&Qo(o[u]);)u++;if(i||!a)for(;d>u&&Qo(o[d-1]);)d--;o=o.slice(u,d)}return r.s.data.splice(r.i,r.s.data.length-r.i,...o),b(r)});g("split",'["Splits a series at a delimiter, or into pieces of a size." series [any-string! block!] dlm [any-string! char! integer!]]',(e,t)=>{let n=t.args[0],r=t.args[1],o=n.s.data.slice(n.i),a=(u,d)=>({t:n.t,s:{data:o.slice(u,d)},i:0}),i=[];if(r.t===s.Integer){let u=Math.max(1,nn(r));for(let d=0;d<o.length;d+=u)i.push(a(d,d+u));return b({t:s.Block,s:{data:i},i:0})}if(_(n.t))return N("script","bad-split","a block splits only into pieces of a size");let l=r.t===s.Char?[r.v]:r.s.data.slice(r.i);if(l.length===0)return N("script","bad-split","the delimiter is empty");let c=0;for(let u=0;u+l.length<=o.length;)l.every((d,f)=>Ke(o[u+f])===Ke(d))?(i.push(a(c,u)),u+=l.length,c=u):u++;return i.push(a(c,o.length)),b({t:s.Block,s:{data:i},i:0})});function Yr(e,t){try{let n=me(e),r=n.s.data[0];return n.s.data.length===1&&r!==void 0&&t.includes(r.t)?r:null}catch(n){if(n instanceof rt)return null;throw n}}var Lp=[s.Integer,s.Decimal,s.Percent,s.Money];function Is(e){return e.t===s.Integer||e.t===s.Decimal||e.t===s.Percent||e.t===s.Money?e:e.t===s.Char?H(e.v):e.t===s.Logic?H(e.v?1:0):X(e.t)?Yr(B(e).trim(),Lp):null}function Ap(e,t){let n=()=>`cannot convert ${ie(t.t)} to ${ie(e)}`;switch(e){case s.String:case s.File:case s.Email:case s.Url:case s.Tag:return t.t===s.Binary?{t:e,s:{data:he(new TextDecoder().decode(new Uint8Array(t.s.data.slice(t.i))))},i:0}:le(t.t)?{t:e,s:{data:he(M(t.sym))},i:0}:t.t===s.Char?{t:e,s:{data:[t.v]},i:0}:X(t.t)?{t:e,s:{data:t.s.data.slice(t.i)},i:0}:{t:e,s:{data:he(or(t))},i:0};case s.Binary:return t.t===s.Binary?{t:s.Binary,s:{data:t.s.data.slice(t.i)},i:0}:t.t===s.Block?{t:s.Binary,s:{data:t.s.data.slice(t.i).map(r=>r.t===s.Integer?nn(r)&255:0)},i:0}:{t:s.Binary,s:{data:On(or(t))},i:0};case s.Word:case s.SetWord:case s.GetWord:case s.LitWord:case s.Refinement:case s.Issue:{if(le(t.t))return{t:e,sym:t.sym,bind:t.bind};if(X(t.t)||t.t===s.Char){let r=t.t===s.Char?String.fromCodePoint(t.v):B(t);return Yr(r,[s.Word])===null&&e!==s.Issue&&e!==s.Refinement?`${JSON.stringify(r)} is not a valid word`:{t:e,sym:A(r),bind:null}}return t.t===s.Datatype?{t:e,sym:A(ie(t.k)),bind:null}:n()}case s.Integer:{let r=t.t===s.Time?ke(t.v/1e9):Is(t);if(r===null)return n();if(r.t===s.Integer)return r;let o=r.t===s.Money?xt(r.v):r.v,a=Ya(Math.trunc(o));return a===null?"number is too big for integer!":H(a)}case s.Decimal:case s.Percent:{let r=t.t===s.Time&&e===s.Decimal?ke(t.v/1e9):Is(t);if(r===null)return n();let o=r.t===s.Money?xt(r.v):r.t===s.Integer?q(r.v):r.v;return e===s.Decimal?ke(o):$t(o)}case s.Money:{let r=Is(t),o=r===null?null:_t(r);return o===null?n():ft(o,r.t===s.Money?r.cur:"")}case s.Char:return t.t===s.Char?t:t.t===s.Integer?pt(nn(t)):X(t.t)&&t.s.data.length>t.i?pt(t.s.data[t.i]):n();case s.Logic:return ee(Be(t));case s.None:return k;case s.Block:case s.Paren:case s.Path:case s.SetPath:case s.GetPath:case s.LitPath:{if(_(t.t))return{t:e,s:{data:t.s.data.slice(t.i)},i:0};if(X(t.t))try{let r=me(B(t));return{t:e,s:r.s,i:0}}catch(r){if(r instanceof rt)return r.message;throw r}if(t.t===s.Map)return{t:e,s:{data:t.s.data.slice()},i:0};if(t.t===s.Object||t.t===s.Error){let r=[];return t.ctx.keys.forEach((o,a)=>r.push({t:s.SetWord,sym:o,bind:null},t.ctx.vals[a])),{t:e,s:{data:r},i:0}}return{t:e,s:{data:[t]},i:0}}case s.Map:{if(t.t===s.Map)return{t:s.Map,s:{data:t.s.data.slice()}};if(t.t===s.Block){let r=t.s.data.slice(t.i);return r.length%2!==0?"a map needs key value pairs":{t:s.Map,s:{data:r.map((o,a)=>a%2===0&&le(o.t)?{t:s.Word,sym:o.sym,bind:null}:o)}}}if(t.t===s.Object){let r=[];return t.ctx.keys.forEach((o,a)=>r.push({t:s.Word,sym:o,bind:null},t.ctx.vals[a])),{t:s.Map,s:{data:r}}}return n()}case s.Pair:{if(t.t===s.Pair)return t;if(t.t===s.Integer||t.t===s.Decimal){let r=t.t===s.Integer?nn(t):t.v;return Bt(r,r)}if(t.t===s.Block){let[r,o]=t.s.data.slice(t.i),a=c=>c?.t===s.Integer?nn(c):c?.t===s.Decimal?c.v:null,i=a(r),l=a(o);return i===null||l===null?n():Bt(i,l)}return X(t.t)?Yr(B(t),[s.Pair])??n():n()}case s.Tuple:return t.t===s.Tuple?t:t.t===s.Block&&t.s.data.slice(t.i).every(r=>r.t===s.Integer)?$o(t.s.data.slice(t.i).map(nn)):X(t.t)?Yr(B(t),[s.Tuple])??n():n();case s.Date:case s.Time:return t.t===e?t:e===s.Time&&(t.t===s.Integer||t.t===s.Decimal)?{t:s.Time,v:Math.round((t.t===s.Integer?nn(t):t.v)*1e9)}:X(t.t)?Yr(B(t),[e])??n():n();case s.Datatype:if(t.t===s.Datatype)return t;if(le(t.t)){let r=M(I(t.sym)),o=Vn(r);return o===void 0?n():pn(o)}return n();case s.Typeset:{if(t.t===s.Typeset)return t;if(t.t===s.Datatype)return en(Ee(t.k));if(t.t!==s.Block)return n();let r=tr(t);return typeof r=="string"?r:en(r)}}return n()}g("to",'["Converts a value to another type." type [datatype! any-value!] value [any-type!]]',(e,t)=>{let n=t.args[0],r=n.t===s.Datatype?n.k:n.t,o=Ap(r,t.args[1]);return typeof o=="string"?N("script","bad-to",o):b(o)});g("construct",'["Makes an object from a block without evaluating its values." block [block!]]',(e,t)=>{let n=t.args[0],r=[],o=[],a={none:k,true:P,false:we,on:P,off:we,yes:P,no:we},i=n.s.data;for(let l=n.i;l<i.length;l++){if(i[l].t!==s.SetWord)continue;let u=l+1;for(;u<i.length&&i[u].t===s.SetWord;)u++;let d=i[u]??k;d.t===s.Word?d=a[M(I(d.sym))]??d:d.t===s.LitWord&&(d={t:s.Word,sym:d.sym,bind:null});for(let f=l;f<u;f++)r.push(i[f].sym),o.push(d);l=u}return b({t:s.Object,ctx:{keys:r,vals:o,parent:null}})});g("compose",'["Evaluates the parens in a block and puts their values in a copy of it." value [any-value!] /deep /only]',(e,t,n)=>{let r=t.args[0];if(r.t!==s.Block)return b(r);let o=Dt(t.args[1]),a=Dt(t.args[2]);t.phase===0&&(t.phase=1,t.data=[{src:r,i:r.i,out:[],nl:[]}]);let i=t.data;if(n!==null){let l=i[i.length-1],c=l.src.s.nl?.[l.i-1]??!1;n.t===s.Block&&!a?n.s.data.slice(n.i).forEach((u,d)=>{l.out.push(u),l.nl.push(d===0?c:n.s.nl?.[n.i+d]??!1)}):n.t!==s.Unset&&(l.out.push(n),l.nl.push(c))}for(;;){let l=i[i.length-1],c=l.src.s.data;if(l.i>=c.length){i.pop();let d={t:l.src.t,s:{data:l.out,nl:l.nl},i:0};if(i.length===0)return b(d);let f=i[i.length-1];f.out.push(d),f.nl.push(f.src.s.nl?.[f.i-1]??!1);continue}let u=c[l.i++];if(u.t===s.Paren)return{k:"do",s:u.s,i:u.i};if(o&&_(u.t)){i.push({src:u,i:u.i,out:[],nl:[]});continue}l.out.push(u),l.nl.push(l.src.s.nl?.[l.i-1]??!1)}});g("collect-words",'["The words used in a block, each once." block [block!] /deep /set /ignore words [block!]]',(e,t)=>{let n=Dt(t.args[1]),r=Dt(t.args[2]),o=Dt(t.args[3])?t.args[4].s.data.filter(d=>le(d.t)).map(d=>I(d.sym)):[],a=new Set(o),i=[],l=[],c=(d,f)=>{if(!l.includes(d)){l.push(d);for(let p=f;p<d.data.length;p++){let h=d.data[p];(r?h.t===s.SetWord:h.t>=s.Word&&h.t<=s.LitWord)&&!a.has(I(h.sym))?(a.add(I(h.sym)),i.push({t:s.Word,sym:h.sym,bind:null})):n&&_(h.t)&&c(h.s,h.i)}l.pop()}},u=t.args[0];return c(u.s,u.i),b({t:s.Block,s:{data:i},i:0})});function Lc(e,t){return(n,r,o)=>{let a=r.args[0],i=e(r.args);if(r.phase===0){let d=xe(a);if(d===null||!(_(d.t)||X(d.t)))return N("script","bad-walk",`${M(a.sym)} must refer to a series`);r.phase=1,r.trap=1<<U.Break|1<<U.Continue,r.data={start:d,cur:d,out:k,first:!0}}let l=r.data,c=r.thrown;r.thrown=null;let u=d=>($e(a,l.start),b(d));return c!==null&&c.kind===U.Break?u(c.v):(o!==null&&(l.out=o),l.first||(l.cur=Ze(l.cur,l.cur.i+i)),l.first=!1,l.cur.i>=l.cur.s.data.length?u(l.out):($e(a,l.cur),ge(r.args[t])))}}g("forall",`["Evaluates a block for each position of the series a word refers to." 'word [word!] body [block!]]`,Lc(()=>1,1));g("forskip",`["Evaluates a block at every so many positions of the series a word refers to." 'word [word!] size [integer!] body [block!]]`,Lc(e=>Math.max(1,nn(e[1])),2));g("apply",'["Calls a function with the arguments in a block." func [any-function!] block [block!] /only]',(e,t,n)=>{let r=t.args[0],o=t.args[1];if(t.phase===2)return b(n);if(t.phase===0){if(Dt(t.args[2]))return t.phase=2,{k:"call",fn:r,args:o.s.data.slice(o.i),full:!0};t.phase=1,t.data={feed:{s:o.s,i:o.i},out:[]}}let a=t.data;return n!==null&&a.out.push(n),a.feed.i<a.feed.s.data.length?{k:"expr",feed:a.feed}:(t.phase=2,{k:"call",fn:r,args:a.out,full:!0})});function Ac(e){let t=4294967295;for(let n of e){t^=n;for(let r=0;r<8;r++)t=t&1?t>>>1^3988292384:t>>>1}return(t^4294967295)>>>0}function Ic(e){let t=1,n=0;for(let r of e)t=(t+r)%65521,n=(n+t)%65521;return(n<<16|t)>>>0}function $s(e,t){let n=e.slice(),r=e.length*8;for(n.push(128);n.length%64!==56;)n.push(0);let o=[];for(let a=0;a<8;a++)o.push(Math.floor(r/2**(8*a))&255);return n.push(...t?o.reverse():o),n}function Bs(e,t,n){let r=[];for(let o=0;o<16;o++){let a=t+o*4;r.push(n?(e[a]<<24|e[a+1]<<16|e[a+2]<<8|e[a+3])>>>0:(e[a]|e[a+1]<<8|e[a+2]<<16|e[a+3]<<24)>>>0)}return r}function Os(e,t){let n=[];for(let r of e){let o=[r>>>24&255,r>>>16&255,r>>>8&255,r&255];n.push(...t?o:o.reverse())}return n}var ea=(e,t)=>(e<<t|e>>>32-t)>>>0,Kt=(e,t)=>(e>>>t|e<<32-t)>>>0,Ip=[7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21],$p=Array.from({length:64},(e,t)=>Math.floor(Math.abs(Math.sin(t+1))*2**32)>>>0);function $c(e){let t=$s(e,!1),n=[1732584193,4023233417,2562383102,271733878];for(let r=0;r<t.length;r+=64){let o=Bs(t,r,!1),[a,i,l,c]=n;for(let u=0;u<64;u++){let d,f;u<16?(d=i&l|~i&c,f=u):u<32?(d=c&i|~c&l,f=(5*u+1)%16):u<48?(d=i^l^c,f=(3*u+5)%16):(d=l^(i|~c),f=7*u%16);let p=c;c=l,l=i,i=i+ea(a+d+$p[u]+o[f]>>>0,Ip[(u>>4)*4+u%4])>>>0,a=p}n[0]=n[0]+a>>>0,n[1]=n[1]+i>>>0,n[2]=n[2]+l>>>0,n[3]=n[3]+c>>>0}return Os(n,!1)}function Bc(e){let t=$s(e,!0),n=[1732584193,4023233417,2562383102,271733878,3285377520];for(let r=0;r<t.length;r+=64){let o=Bs(t,r,!0);for(let d=16;d<80;d++)o.push(ea(o[d-3]^o[d-8]^o[d-14]^o[d-16],1));let[a,i,l,c,u]=n;for(let d=0;d<80;d++){let[f,p]=d<20?[i&l|~i&c,1518500249]:d<40?[i^l^c,1859775393]:d<60?[i&l|i&c|l&c,2400959708]:[i^l^c,3395469782],h=ea(a,5)+f+u+p+o[d]>>>0;u=c,c=l,l=ea(i,30),i=a,a=h}[a,i,l,c,u].forEach((d,f)=>{n[f]=n[f]+d>>>0})}return Os(n,!0)}var Bp=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298];function Oc(e){let t=$s(e,!0),n=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];for(let r=0;r<t.length;r+=64){let o=Bs(t,r,!0);for(let h=16;h<64;h++){let v=Kt(o[h-15],7)^Kt(o[h-15],18)^o[h-15]>>>3,y=Kt(o[h-2],17)^Kt(o[h-2],19)^o[h-2]>>>10;o.push(o[h-16]+v+o[h-7]+y>>>0)}let[a,i,l,c,u,d,f,p]=n;for(let h=0;h<64;h++){let v=p+(Kt(u,6)^Kt(u,11)^Kt(u,25))+(u&d^~u&f)+Bp[h]+o[h]>>>0,y=(Kt(a,2)^Kt(a,13)^Kt(a,22))+(a&i^a&l^i&l)>>>0;p=f,f=d,d=u,u=c+v>>>0,c=l,l=i,i=a,a=v+y>>>0}[a,i,l,c,u,d,f,p].forEach((h,v)=>{n[v]=n[v]+h>>>0})}return Os(n,!0)}var Op=/^[A-Za-z_][A-Za-z0-9_-]*$/;function Np(e){return Op.test(e)?{t:s.Word,sym:A(e),bind:null}:j(e)}function Gt(e){let t=0,n=[],r=null,o=()=>{for(;t<e.length&&`
17
+ \r`.includes(e[t]);)t++},a=c=>`invalid JSON at ${t+1}: ${c}`,i=()=>{let c="";for(t++;t<e.length;){let u=e[t++];if(u==='"')return c;if(u!=="\\"){c+=u;continue}let d=e[t++];switch(d){case'"':case"\\":case"/":c+=d;break;case"b":c+="\b";break;case"f":c+="\f";break;case"n":c+=`
18
+ `;break;case"r":c+="\r";break;case"t":c+=" ";break;case"u":{let f=e.slice(t,t+4);if(!/^[0-9a-fA-F]{4}$/.test(f))return null;c+=String.fromCharCode(parseInt(f,16)),t+=4;break}default:return null}}return null},l=c=>{let u=n[n.length-1];return u===void 0?(r=c,null):(u.kind==="array"?u.out.push(c):(u.out.push(u.key,c),u.key=null),null)};for(;;){o();let c=n[n.length-1];if(c!==void 0&&c.kind==="object"&&c.key===null)if(e[t]==="}"&&c.out.length===0)t++,n.pop(),l({t:s.Map,s:{data:c.out}});else{if(e[t]!=='"')return a("expected a key");let u=i();if(u===null)return a("bad string");if(o(),e[t]!==":")return a("expected :");t++,c.key=Np(u);continue}else if(r===null||c!==void 0)if(c!==void 0&&c.kind==="array"&&e[t]==="]"&&c.out.length===0)t++,n.pop(),l({t:s.Block,s:{data:c.out},i:0});else{let u=e[t];if(u===void 0)return a("unexpected end");if(u==="{"){t++,n.push({kind:"object",out:[],key:null});continue}if(u==="["){t++,n.push({kind:"array",out:[],key:null});continue}let d;if(u==='"'){let f=i();if(f===null)return a("bad string");d=j(f)}else if(e.startsWith("true",t))t+=4,d=P;else if(e.startsWith("false",t))t+=5,d=we;else if(e.startsWith("null",t))t+=4,d=k;else{let f=/^-?(?:0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/.exec(e.slice(t,t+400));if(f===null)return a("unexpected character");t+=f[0].length;let p=f[1]===void 0&&f[2]===void 0?Zn(f[0]):null;d=p!==null?H(p):ke(Number(f[0]))}l(d)}for(;;){o();let u=n[n.length-1];if(u===void 0)return t<e.length?a("extra text after the value"):r;let d=e[t];if(d===","){t++;break}if(u.kind==="array"&&d==="]"||u.kind==="object"&&d==="}"){t++,n.pop(),l(u.kind==="array"?{t:s.Block,s:{data:u.out},i:0}:{t:s.Map,s:{data:u.out}});continue}return a(d===void 0?"unexpected end":`expected , or ${u.kind==="array"?"]":"}"}`)}}}function Wn(e){return JSON.stringify(e)}var Nc=e=>e.t===s.Function||e.t===s.Native||e.t===s.Op;function Re(e,t=new Set){switch(e.t){case s.None:case s.Unset:return"null";case s.Logic:return e.v?"true":"false";case s.Integer:return Pr(e.v);case s.Decimal:case s.Percent:return Number.isFinite(e.v)?String(e.v):"null";case s.Money:return zt(e.v);case s.Char:return Wn(String.fromCodePoint(e.v));case s.Date:{let n=e.v,r=(a,i=2)=>String(a).padStart(i,"0"),o=`${r(n.y,4)}-${r(n.m)}-${r(n.d)}`;if(n.time!==null){let a=n.time/1e9,i=Math.floor(a%60),l=a%1===0?"":String(Number((a%1).toFixed(9))).slice(1);if(o+=`T${r(Math.floor(a/3600))}:${r(Math.floor(a%3600/60))}:${r(i)}${l}`,n.zone!==null){let c=Math.abs(n.zone);o+=n.zone===0?"Z":`${n.zone<0?"-":"+"}${r(Math.floor(c/60))}:${r(c%60)}`}}return Wn(o)}case s.Time:return Wn(Hr(e.v));case s.Pair:return`[${e.x},${e.y}]`;case s.Tuple:return`[${e.v.join(",")}]`;case s.Map:{if(t.has(e.s))return"null";t.add(e.s);let n=[];for(let r=0;r+1<e.s.data.length;r+=2){let o=e.s.data[r];if(Nc(e.s.data[r+1]))continue;let a=le(o.t)?M(o.sym):X(o.t)?B(o):Re(o);n.push(`${Wn(a)}:${Re(e.s.data[r+1],t)}`)}return t.delete(e.s),`{${n.join(",")}}`}case s.Object:case s.Error:{if(t.has(e.ctx))return"null";t.add(e.ctx);let n=e.ctx.keys.flatMap((r,o)=>Nc(e.ctx.vals[o])?[]:[`${Wn(M(r))}:${Re(e.ctx.vals[o],t)}`]);return t.delete(e.ctx),`{${n.join(",")}}`}case s.Block:case s.Paren:{if(t.has(e.s))return"null";t.add(e.s);let n=`[${e.s.data.slice(e.i).map(r=>Re(r,t)).join(",")}]`;return t.delete(e.s),n}}return X(e.t)?Wn(B(e)):le(e.t)?Wn(M(e.sym)):"null"}g("load-json",'["Reads JSON text into Trebol values: objects as maps, lists as blocks." source [string! binary!]]',(e,t)=>{let n=t.args[0],r=n.t===s.Binary?new TextDecoder().decode(new Uint8Array(n.s.data.slice(n.i))):B(n),o=Gt(r);return typeof o=="string"?N("syntax","json",o):b(o)});g("to-json",'["Writes a value as JSON text." value [any-type!]]',(e,t)=>b(j(Re(t.args[0]))));var Wt=e=>e===P,ta=13,Zr=10,jp=34,Pp=65279;function Dc(e){if(e.t===s.Char)return[e.v];if(e.t===s.String){let t=e.s.data.slice(e.i);return t.length===0?null:t}return[44]}var Ns=e=>e===32||e===9;function Dp(e,t){let n=[],r=e.length,o=t.delim,a=d=>{for(let f=0;f<o.length;f++)if(e[d+f]!==o[f])return!1;return!0},i=d=>e[d]===ta||e[d]===Zr,l=e[0]===Pp?1:0,c=1,u=[];for(;l<r;){if(u.length===0&&i(l)){l+=e[l]===ta&&e[l+1]===Zr?2:1,c++;continue}let d=[];if(t.trim)for(;Ns(e[l]);)l++;let f=e[l]===t.quote;if(f){let p=c;for(l++;;){if(l>=r)return`a quoted field on line ${p} has no closing quote`;let h=e[l];if(h===t.quote){if(e[l+1]===t.quote){d.push(h),l+=2;continue}l++;break}(h===Zr||h===ta&&e[l+1]!==Zr)&&c++,d.push(h),l++}if(t.trim)for(;Ns(e[l]);)l++}for(;l<r&&!i(l)&&!a(l);)d.push(e[l++]);if(t.trim&&!f)for(;Ns(d[d.length-1]);)d.pop();if(u.push(qe(d)),l<r&&a(l))if(l+=o.length,l>=r||i(l))u.push("");else continue;n.push(u),u=[],l<r&&(l+=e[l]===ta&&e[l+1]===Zr?2:1,c++)}return n}function Wp(e){let t="";for(let n=e+1;n>0;n=Math.floor((n-1)/26))t=String.fromCharCode(65+(n-1)%26)+t;return t}function Rp(e,t){let n=[],r=new Set;for(let o=0;o<t;o++){let a=e!==null&&o<e.length?e[o]:Wp(o),i=a;for(let l=2;r.has(I(A(i)));l++)i=`${a} ${l}`;r.add(I(A(i))),n.push(i)}return n}var jc=(e,t)=>t<e.length?j(e[t]):k;g("load-csv",'["Reads CSV text into a block of rows, each a block of strings." data [string! binary!] /with "Another delimiter than a comma" delimiter [char! string!] /header "The first line names the columns; gives columns unless /as-records" /as-columns "A map of columns: name and block of values" /as-records "A block of maps, one per row; implies /header" /flat "One block with every field" /trim "Leave out spaces around fields" /quote "Another quote character than a double quote" qt-char [char!]]',(e,t)=>{let n=t.args,r=n[0],o=r.t===s.Binary?he(new TextDecoder().decode(new Uint8Array(r.s.data.slice(r.i)))):r.s.data.slice(r.i),a=Wt(n[1])?Dc(n[2]):[44];if(a===null)return N("script","bad-delimiter","load-csv needs a delimiter that is not empty");let i=Wt(n[3]),l=Wt(n[4]),c=Wt(n[5]),u=Wt(n[6]);if(u&&(i||l||c))return N("script","bad-refines","load-csv/flat cannot have a header, columns or records");if(l&&c)return N("script","bad-refines","load-csv gives columns or records, not both");let d=Dp(o,{delim:a,quote:Wt(n[8])?n[9].v:jp,trim:Wt(n[7])});if(typeof d=="string")return N("syntax","csv",d);if(u)return b(it(d.flat().map(y=>j(y))));if(!i&&!l&&!c)return b(it(d.map(y=>it(y.map(C=>j(C))))));let f=i||c,p=f?d[0]??[]:null,h=f?d.slice(1):d,v=Rp(p,h.reduce((y,C)=>Math.max(y,C.length),p?.length??0));return c?b(it(h.map(y=>In(v.flatMap((C,x)=>[j(C),jc(y,x)]))))):b(In(v.flatMap((y,C)=>[j(y),it(h.map(x=>jc(x,C)))])))});function Vt(e){return e.t===s.None||e.t===s.Unset?"":e.t===s.Date?JSON.parse(Re(e)).replace("T"," "):e.t===s.Money?zt(e.v,2):X(e.t)&&e.t!==s.Binary?qe(e.s.data,e.i):le(e.t)?M(e.sym):D(e)}function Fp(e,t,n){return e.includes(t)||e.includes(n)||e.includes(`
19
+ `)||e.includes("\r")||e.length>0&&(e[0]===" "||e[e.length-1]===" ")?n+e.split(n).join(n+n)+n:e}function Wc(e){return e.t===s.Map?e.s.data.filter((t,n)=>n%2===0):e.t===s.Object?e.ctx.keys.map(t=>({t:s.Word,sym:t,bind:null})):[]}var na=e=>I(A(Vt(e)));function Rc(e,t){if(e.t===s.Map){let n=e.s.data;for(let r=0;r+1<n.length;r+=2)if(na(n[r])===t)return n[r+1];return k}if(e.t===s.Object){let n=e.ctx.keys.findIndex(r=>I(r)===t);return n<0?k:e.ctx.vals[n]}return k}function Hp(e){let t=[],n=new Set;for(let r of e)for(let o of Wc(r)){let a=na(o);n.has(a)||(n.add(a),t.push(o))}return[t,...e.map(r=>t.map(o=>Rc(r,na(o))))]}var js=e=>e.t===s.Map||e.t===s.Object,Up=e=>e.t===s.Block?e.s.data.slice(e.i):[e],zp=new Set([s.Decimal,s.Percent,s.Money,s.Date,s.Time]);function Pc(e,t,n){return e.map(r=>r.map(o=>Fp(o,t,n)).join(t)+`
20
+ `).join("")}function _p(e){let t=e[0];if(js(t)){let r=Wc(t),o=r.map(l=>Up(Rc(t,na(l)))),a=o.reduce((l,c)=>Math.max(l,c.length),0),i=[r];for(let l=0;l<a;l++)i.push(o.map(c=>c[l]??k));return i}let n=t.s.data.slice(t.i);if(Wt(e[3])){let r=q(e[4].v);if(r<1)return N("script","bad-skip","to-csv/skip needs a size of 1 or more");let o=[];for(let a=0;a<n.length;a+=r)o.push(n.slice(a,a+r));return o}return n.length>0&&n.every(js)?Hp(n):n.length>0&&n[0].t===s.Block?n.every(r=>r.t===s.Block)?n.map(r=>r.s.data.slice(r.i)):N("script","bad-rows","to-csv needs every row to be a block"):n.some(r=>r.t===s.Block||js(r))?N("script","bad-rows","to-csv needs rows all of one kind: blocks, maps or objects"):n.length===0?[]:[n]}g("to-csv",'["Writes CSV text from rows: a block of blocks, of maps or objects (a header from their keys), a flat block with /skip, or a map of columns." data [block! map! object!] /with "Another delimiter than a comma" delimiter [char! string!] /skip "A flat block, so many fields to a row" size [integer!] /quote "Another quote character than a double quote" qt-char [char!] /language "Dates and amounts as a language writes them, and a semicolon where its decimals have a comma" lang [word! string!]]',(e,t,n)=>{let r=t.args,o=Wt(r[5])?String.fromCodePoint(r[6].v):'"',a=null;if(Wt(r[1])){let c=Dc(r[2]);if(c===null)return N("script","bad-delimiter","to-csv needs a delimiter that is not empty");a=qe(c)}let i=r[8];if(t.phase===0){let c=_p(r);if(!Array.isArray(c))return c;let u=c.map(f=>f.map(Vt));if(!Wt(r[7]))return b(j(Pc(u,a??",",o)));let d=[];return c.forEach((f,p)=>f.forEach((h,v)=>{zp.has(h.t)&&d.push([p,v])})),t.data={rows:c,texts:u,todo:d,at:0,delim:a},t.phase=1,Pn(e,"format-local",[ke(1.5),i],"write values in a language")}let l=t.data;if(t.phase===1)l.delim===null&&(l.delim=B(n).includes(",")?";":","),t.phase=2;else{let[c,u]=l.todo[l.at++],d=B(n);l.texts[c][u]=l.rows[c][u].t===s.Date?d.replace(", "," "):d}if(l.at<l.todo.length){let[c,u]=l.todo[l.at];return Pn(e,"format-local",[l.rows[c][u],i],"write values in a language")}return b(j(Pc(l.texts,l.delim,o)))});function Fc(e){return e.t===s.Binary?e.s.data.slice(e.i):On(B(e))}function Hc(e,t){if(e.args[t]!==P)return 64;let n=q(e.args[t+1].v);return n===2||n===16||n===64?n:null}g("enbase",'["Writes bytes as text in base 64, or another base." value [binary! any-string!] /base "2, 16 or 64" base-value [integer!]]',(e,t)=>{let n=Hc(t,1);return n===null?N("script","bad-base","the base must be 2, 16 or 64"):b({t:s.String,s:{data:he(Rl(Fc(t.args[0]),n))},i:0})});g("debase",'["Reads bytes written as text in base 64, or another base." value [any-string! binary!] /base "2, 16 or 64" base-value [integer!]]',(e,t)=>{let n=Hc(t,1);if(n===null)return N("script","bad-base","the base must be 2, 16 or 64");let r=t.args[0],o=r.t===s.Binary?new TextDecoder().decode(new Uint8Array(r.s.data.slice(r.i))):B(r),a=jo(o,n);return a===null?N("script","bad-base",`the text is not valid base ${n}`):b({t:s.Binary,s:{data:a},i:0})});g("to-hex",'["The value in hexadecimal, as an issue." value [integer! tuple!] /size "Use this many digits" len [integer!]]',(e,t)=>{let n=t.args[0],r;if(n.t===s.Tuple?r=n.v.map(o=>o.toString(16).toUpperCase().padStart(2,"0")).join(""):r=BigInt.asUintN(64,BigInt(n.v)).toString(16).toUpperCase().padStart(16,"0"),t.args[1]===P){let o=Math.max(1,q(t.args[2].v));r=r.length>o?r.slice(r.length-o):r.padStart(o,"0")}return b({t:s.Issue,sym:A(r),bind:null})});function Uc(e){let t=[],n=[],r=()=>{n.length>0&&t.push(...he(new TextDecoder().decode(new Uint8Array(n)))),n=[]};for(let o=0;o<e.length;o++){let a=o+2<e.length?String.fromCodePoint(e[o+1],e[o+2]):"";e[o]===37&&/^[0-9A-Fa-f]{2}$/.test(a)?(n.push(parseInt(a,16)),o+=2):(r(),t.push(e[o]))}return r(),t}g("dehex",'["Turns %xx escapes in a string or URL back into characters." value [any-string!]]',(e,t)=>{let n=t.args[0];return b({t:n.t,s:{data:Uc(n.s.data.slice(n.i))},i:0})});var Ps=/^[A-Za-z0-9\-_.!~*'()]$/,qp=/^[A-Za-z0-9\-_.!~*'();/?:@&=+$,#]$/;function Ds(e,t,n){let r="";for(let o of e){let a=String.fromCodePoint(o);if(n&&o===32)r+="+";else if(t.test(a))r+=a;else for(let i of On(a))r+="%"+i.toString(16).toUpperCase().padStart(2,"0")}return r}g("enhex",'["Writes the characters a URL cannot hold as %xx escapes." value [any-string!] /uri "Write spaces as +, as forms send them"]',(e,t)=>{let n=t.args[0],r=n.t===s.Url||n.t===s.File?qp:Ps;return b({t:n.t,s:{data:he(Ds(n.s.data.slice(n.i),r,t.args[1]===P))},i:0})});function ra(e){let t=[];e.t===s.Map?t.push(...e.s.data):e.t===s.Block?t.push(...e.s.data.slice(e.i)):e.t===s.Object&&e.ctx.keys.forEach((o,a)=>t.push({t:s.Word,sym:o,bind:null},e.ctx.vals[a]));let n=[],r=(o,a)=>{a.t!==s.None&&n.push(Ds(he(o),Ps,!1)+"="+Ds(he(Vt(a)),Ps,!1))};for(let o=0;o+1<t.length;o+=2){let a=t[o];if(!(a.t>=s.Word&&a.t<=s.Issue)&&a.t!==s.String)return null;let i=Vt(a),l=t[o+1];if(l.t===s.Block)for(let c of l.s.data.slice(l.i))r(i,c);else r(i,l)}return n.join("&")}g("to-query",'["Writes names and values as the query of a URL: q=caf%C3%A9&page=2." values [map! object! block!]]',(e,t)=>{let n=ra(t.args[0]);return n===null?N("script","bad-query","a query takes words or strings as names"):b(j(n))});var Kp=/^[A-Za-z_][A-Za-z0-9_-]*$/;g("load-query",'["Reads the query of a URL as a map of strings; a name given twice holds a block." source [any-string!]]',(e,t)=>{let n=t.args[0],r=qe(n.s.data,n.i);n.t===s.Url&&(r=r.includes("?")?r.slice(r.indexOf("?")+1):""),r.includes("#")&&(r=r.slice(0,r.indexOf("#"))),r.startsWith("?")&&(r=r.slice(1));let o=[],a=[];for(let l of r.split("&")){if(l==="")continue;let c=l.indexOf("="),u=h=>qe(Uc(he(h.replace(/\+/g," ")))),d=u(c<0?l:l.slice(0,c)),f=j(c<0?"":u(l.slice(c+1))),p=o.indexOf(d);p<0?(o.push(d),a.push([f])):a[p].push(f)}let i=[];return o.forEach((l,c)=>{i.push(Kp.test(l)?{t:s.Word,sym:A(l),bind:null}:j(l)),i.push(a[c].length===1?a[c][0]:it(a[c]))}),b(In(i))});var Gp={md5:$c,sha1:Bc,sha256:Oc};g("checksum",'["A checksum or hash of the bytes: md5 sha1 sha256 give a binary, crc32 adler32 an integer." data [binary! any-string!] method [word!]]',(e,t)=>{let n=Fc(t.args[0]),r=M(I(t.args[1].sym)).toLowerCase();if(r==="crc32")return b(H(Ac(n)));if(r==="adler32")return b(H(Ic(n)));let o=Gp[r];return o===void 0?N("script","bad-method",`checksum has no method ${r}: use md5 sha1 sha256 crc32 adler32`):b({t:s.Binary,s:{data:o(n)},i:0})});var Vp=e=>e===P,Yp=/^[A-Za-z_][A-Za-z0-9_-]*$/;function Ws(e){return Yp.test(e)?{t:s.Word,sym:A(e),bind:null}:j(e)}var Zp={lt:"<",gt:">",amp:"&",quot:'"',apos:"'"};function Rs(e){return e.replace(/&(#x[0-9A-Fa-f]+|#[0-9]+|[A-Za-z]+);/g,(t,n)=>{if(n[0]==="#"){let r=n[1]==="x"?parseInt(n.slice(2),16):parseInt(n.slice(1),10);return r>0&&r<=1114111?String.fromCodePoint(r):t}return Zp[n]??t})}function Jp(e){let t=e.charCodeAt(0)===65279?1:0,n=e.length,r=[],o=[],a="",i=f=>{let p=1;for(let h=0;h<f;h++)e.charCodeAt(h)===10&&p++;return p},l=()=>r.length>0?r[r.length-1].out:o,c=()=>{a!==""&&/\S/.test(a)&&l().push(k,j(a),k),a=""},u=(f,p)=>{let h=e.indexOf(f,t);return h<0?`${p} on line ${i(t)} never ends`:h+f.length};for(;t<n;){let f=e.indexOf("<",t);if(f<0){a+=Rs(e.slice(t));break}a+=Rs(e.slice(t,f)),t=f;let p;if(e.startsWith("<!--",t))p=u("-->","a comment");else if(e.startsWith("<![CDATA[",t))p=u("]]>","a CDATA section"),typeof p=="number"&&(a+=e.slice(t+9,p-3));else if(e.startsWith("<?",t))p=u("?>","a processing instruction");else if(e.startsWith("<!",t)){let h=e.indexOf("[",t),v=e.indexOf(">",t);h>=0&&v>=0&&h<v?(t=h,p=u("]","a DOCTYPE"),typeof p=="number"&&(t=p,p=u(">","a DOCTYPE"))):p=u(">","a DOCTYPE")}else if(e[t+1]==="/"){let h=/^<\/([^\s>]+)\s*>/.exec(e.slice(t,t+512));if(h===null)return`a closing tag on line ${i(t)} is not written right`;c();let v=r.pop();if(v===void 0)return`</${h[1]}> on line ${i(t)} closes no tag`;if(v.name!==h[1])return`</${h[1]}> on line ${i(t)} closes <${v.name}> of line ${i(v.at)}`;l().push(Ws(v.name),it(v.out),v.atts),p=t+h[0].length}else{let h=/^<([^\s/>=]+)/.exec(e.slice(t,t+512));if(h===null)return`a < on line ${i(t)} starts no tag; write it &lt;`;c();let v=h[1],y=t+h[0].length,C=[];for(;;){for(;y<n&&/\s/.test(e[y]);)y++;if(y>=n)return`<${v}> on line ${i(t)} never ends`;if(e[y]===">"||e.startsWith("/>",y))break;let w=/^([^\s/>=]+)\s*=\s*("[^"]*"|'[^']*')/.exec(e.slice(y,y+4096));if(w===null)return`an attribute of <${v}> on line ${i(y)} is not written right`;C.push(Ws(w[1]),j(Rs(w[2].slice(1,-1)))),y+=w[0].length}let x=C.length===0?k:In(C);e[y]==="/"?(l().push(Ws(v),it([]),x),p=y+2):(r.push({name:v,atts:x,out:[],at:t}),p=y+1)}if(typeof p=="string")return p;t=p}let d=r.pop();return d!==void 0?`<${d.name}> on line ${i(d.at)} is never closed`:(c(),o)}g("load-xml",'["Reads XML text into a block of nodes, each its name, content and attributes; a text is none, the text and none." source [string! binary!]]',(e,t)=>{let n=t.args[0],r=n.t===s.Binary?new TextDecoder().decode(new Uint8Array(n.s.data.slice(n.i))):qe(n.s.data,n.i),o=Jp(r);return typeof o=="string"?N("syntax","xml",o):b(it(o))});var Fs=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Xp=e=>Fs(e).replace(/"/g,"&quot;");function zc(e){return e.t===s.Word||e.t===s.SetWord||e.t===s.LitWord?M(e.sym):e.t===s.String?qe(e.s.data,e.i):null}var oa=e=>e.t===s.None||e.t===s.Word&&M(e.sym).toLowerCase()==="none";function Qp(e){let t=[];if(oa(e))return"";if(e.t===s.Map)t.push(...e.s.data);else if(e.t===s.Block)t.push(...e.s.data.slice(e.i));else if(e.t===s.Object)e.ctx.keys.forEach((r,o)=>t.push({t:s.Word,sym:r,bind:null},e.ctx.vals[o]));else return null;let n="";for(let r=0;r+1<t.length;r+=2){let o=zc(t[r]);if(o===null)return null;oa(t[r+1])||(n+=` ${o}="${Xp(Vt(t[r+1]))}"`)}return n}function eb(e){let t="",n=[{nodes:e,at:0}];for(;n.length>0;){let r=n[n.length-1];if(typeof r=="string"||r.at>=r.nodes.length){n.pop(),typeof r=="string"&&(t+=r);continue}if(r.at+3>r.nodes.length)return{error:"every node is three values: name, content and attributes"};let[o,a,i]=[r.nodes[r.at],r.nodes[r.at+1],r.nodes[r.at+2]];if(r.at+=3,oa(o)){t+=Fs(Vt(a));continue}let l=zc(o);if(l===null)return{error:`a node's name is a word or a string, not ${Vt(o)}`};let c=Qp(i);if(c===null)return{error:`the attributes of <${l}> are a map, an object or a block`};let u=a.t===s.Block?a.s.data.slice(a.i):oa(a)?[]:null;u===null?t+=`<${l}${c}>${Fs(Vt(a))}</${l}>`:u.length===0?t+=`<${l}${c}/>`:(t+=`<${l}${c}>`,n.push(`</${l}>`,{nodes:u,at:0}))}return{xml:t}}g("to-xml",'["Writes XML text from a block of nodes, each its name, content and attributes, as load-xml gives them." nodes [block!] /declaration "Start with the <?xml ...?> line a whole document needs"]',(e,t)=>{let n=t.args[0],r=eb(n.s.data.slice(n.i));return"error"in r?N("script","bad-xml",r.error):b(j((Vp(t.args[1])?`<?xml version="1.0" encoding="UTF-8"?>
21
+ `:"")+r.xml))});function qc(e,t){let n=e.s.data[t>>3];return(n!==void 0&&(n&128>>(t&7))!==0)!==e.neg}function aa(e,t){let n=t>>3;for(;e.length<=n;)e.push(0);e[n]|=128>>(t&7)}function Hs(e,t){switch(e.t){case s.Char:return aa(t,e.v),null;case s.Integer:return aa(t,q(e.v)),null;case s.String:case s.File:case s.Email:case s.Url:case s.Tag:for(let n of e.s.data.slice(e.i))aa(t,n);return null;case s.Binary:return e.s.data.slice(e.i).forEach((n,r)=>{t[r]=(t[r]??0)|n}),null;case s.Block:{let n=e.s.data.slice(e.i);for(let r=0;r<n.length;r++){let o=n[r],a=n[r+1];if(a!==void 0&&a.t===s.Word&&n[r+2]!==void 0&&tb(a)){let l=_c(o),c=_c(n[r+2]);if(l===null||c===null||c<l)return"bad range in bitset spec";for(let u=l;u<=c;u++)aa(t,u);r+=2;continue}let i=Hs(o,t);if(i!==null)return i}return null}}return"bad bitset spec"}function tb(e){return e.t===s.Word&&M(e.sym)==="-"}function _c(e){return e.t===s.Char?e.v:e.t===s.Integer?q(e.v):null}var L={Some:0,Any:1,Opt:2,While:3,Not:4,Ahead:5,To:6,Thru:7,Set:8,Copy:9,Into:10,If:11,Collect:12,Keep:13,End:14,Skip:15,None:16,Fail:17,Break:18,Quote:19,Bar:20,Remove:21,Insert:22,Change:23,Only:24,Accept:25,Reject:26,Return:27},nb=new Map([["some",L.Some],["any",L.Any],["opt",L.Opt],["while",L.While],["not",L.Not],["ahead",L.Ahead],["to",L.To],["thru",L.Thru],["set",L.Set],["copy",L.Copy],["into",L.Into],["if",L.If],["collect",L.Collect],["keep",L.Keep],["end",L.End],["skip",L.Skip],["none",L.None],["fail",L.Fail],["break",L.Break],["quote",L.Quote],["remove",L.Remove],["insert",L.Insert],["change",L.Change],["only",L.Only],["accept",L.Accept],["reject",L.Reject],["return",L.Return],["|",L.Bar]].map(([e,t])=>[I(A(e)),t]));function Xe(e){return e!==void 0&&e.t===s.Word?nb.get(I(e.sym))??-1:-1}function qs(e,t){for(;;){let n=e[t];if(n===void 0)return-1;if(n.t===s.Integer){t+=e[t+1]?.t===s.Integer?2:1;continue}switch(Xe(n)){case L.Some:case L.Any:case L.Opt:case L.While:case L.Not:case L.Ahead:case L.To:case L.Thru:case L.Into:case L.Keep:case L.Remove:case L.Return:t+=1;continue;case L.Insert:{let r=t+(Xe(e[t+1])===L.Only?2:1);return r<e.length?r+1:-1}case L.Change:{let r=qs(e,t+(Xe(e[t+1])===L.Only?2:1));return r>=0&&r<e.length?r+1:-1}case L.Set:case L.Copy:t+=2;continue;case L.Collect:t+=Xe(e[t+1])===L.Set?3:1;continue;case L.If:return e[t+1]?.t===s.Paren?t+2:-1;case L.Quote:return t+1<e.length?t+2:-1}return t+1}}var ae={Block:0,Rep:1,Look:2,Scan:3,Cap:4,Into:5,Coll:6,Act:7,Edit:8};function ot(e,t){return e.err=t,null}var Jr=e=>e.input.s.data.length;function Us(e,t){let n=e.input.s.data.slice(t,e.pos);return{t:e.input.t,s:{data:n},i:0}}function Kc(e,t){let n=e.input.s.data[t];return n===void 0?k:_(e.input.t)?n:e.input.t===s.Binary?{t:s.Integer,v:n}:{t:s.Char,v:n}}function zs(e,t){let n=e.input.s.data,r=e.pos;if(_(e.input.t)){let i=n[r];if(i===void 0)return-1;switch(t.t){case s.Datatype:return i.t===t.k?r+1:-1;case s.Typeset:return(t.bits&Ee(i.t))!==0n?r+1:-1;case s.LitWord:return i.t===s.Word&&I(i.sym)===I(t.sym)?r+1:-1}return(e.cased?bt(i,t):Ct(i,t))?r+1:-1}let o=e.input.t===s.Binary,a=(i,l)=>e.cased||o?i===l:Ke(i)===Ke(l);if(t.t===s.Bitset){let i=n[r];return i!==void 0&&qc(t,i)?r+1:-1}if(t.t===s.Char||X(t.t)||t.t===s.Binary||o&&t.t===s.Integer){let i=sr(e.input.t,t,!1).add;if(r+i.length>n.length)return-1;for(let l=0;l<i.length;l++)if(!a(n[r+l],i[l]))return-1;return r+i.length}return ot(e,`cannot match ${t.t===s.Integer?"an integer":"that value"} in a string`),-1}function _s(e,t,n,r,o){let{add:a,nl:i}=sr(e.input.t,r,o);return Je(e.input.s,t,n-t,a,i),e.pos=t+a.length,e.edits++,Ae(e,!0)}function Gc(e,t,n,r,o,a){let i=t.data[n];if(i.t===s.Paren)return e.stack.push({k:ae.Act,how:"put",from:r,to:o,only:a}),{k:"do",s:i.s,i:i.i};if(i.t===s.Word){let l=xe(i);return l===null||l.t===s.Unset?ot(e,"the value to put in has no value"):_s(e,r,o,l,a)}return _s(e,r,o,i,a)}function Vc(e,t){return e.ret=t,e.stack.length=0,null}var rb=e=>M(e.sym);function Ae(e,t){return e.res=t,null}function ob(e,t,n){let r=t.data[n];if(r!==void 0&&r.t===s.Block)return r;if(r!==void 0&&r.t===s.Word){let o=xe(r);if(o!==null&&o.t===s.Block)return o}return ot(e,"into needs a rule block")}function sa(e,t){return e.stack.push({k:ae.Block,rules:t.s,ip:t.i,next:0,alt:0,mark:null,markLen:0,started:!1}),null}function yn(e,t,n){let r=t.data,o=r[n];switch(o.t){case s.Integer:{let c=q(o.v),u=r[n+1],d=u?.t===s.Integer;return e.stack.push({k:ae.Rep,rules:t,sub:n+(d?2:1),min:c,max:d?q(u.v):c,n:0,from:e.pos,edits:e.edits,stall:!1}),null}case s.SetWord:return $e(o,{...e.input,i:e.pos}),Ae(e,!0);case s.GetWord:{let c=xe(o);return c===null||!(_(c.t)||X(c.t))||c.s!==e.input.s?ot(e,"a get-word in parse must refer to a position in the input"):(e.pos=c.i,Ae(e,!0))}case s.Paren:return e.stack.push({k:ae.Act,how:"action"}),{k:"do",s:o.s,i:o.i};case s.Block:return sa(e,o);case s.Word:break;default:{let c=zs(e,o);return c<0?Ae(e,!1):(e.pos=c,Ae(e,!0))}}let a=o;switch(Xe(a)){case L.Some:return e.stack.push({k:ae.Rep,rules:t,sub:n+1,min:1,max:1/0,n:0,from:e.pos,edits:e.edits,stall:!1}),null;case L.Any:case L.While:return e.stack.push({k:ae.Rep,rules:t,sub:n+1,min:0,max:1/0,n:0,from:e.pos,edits:e.edits,stall:Xe(a)===L.While}),null;case L.Opt:return e.stack.push({k:ae.Rep,rules:t,sub:n+1,min:0,max:1,n:0,from:e.pos,edits:e.edits,stall:!1}),null;case L.Not:case L.Ahead:return e.stack.push({k:ae.Look,rules:t,sub:n+1,not:Xe(a)===L.Not,from:e.pos}),null;case L.To:case L.Thru:return e.stack.push({k:ae.Scan,rules:t,sub:n+1,thru:Xe(a)===L.Thru,start:e.pos,at:e.pos}),null;case L.Set:case L.Copy:{let c=r[n+1];return c===void 0||c.t!==s.Word?ot(e,`${Xe(a)===L.Set?"set":"copy"} needs a word`):(e.stack.push({k:ae.Cap,rules:t,sub:n+2,how:Xe(a)===L.Set?"set":"copy",word:c,from:e.pos}),null)}case L.Keep:{let c=r[n+1];return c!==void 0&&c.t===s.Paren?(e.stack.push({k:ae.Act,how:"keep"}),{k:"do",s:c.s,i:c.i}):(e.stack.push({k:ae.Cap,rules:t,sub:n+1,how:"keep",word:null,from:e.pos}),null)}case L.Collect:{let c=Xe(r[n+1])===L.Set,u=c?r[n+2]:void 0;return c&&(u===void 0||u.t!==s.Word)?ot(e,"collect set needs a word"):(e.stack.push({k:ae.Coll,rules:t,sub:n+(c?3:1),word:u??null}),null)}case L.Into:{let c=e.input.s.data[e.pos],u=ob(e,t,n+1);return u===null?null:!_(e.input.t)||c===void 0||!(_(c.t)||X(c.t))?Ae(e,!1):(e.stack.push({k:ae.Into,outer:e.input,outerPos:e.pos}),e.input=c,e.pos=c.i,sa(e,u))}case L.If:{let c=r[n+1];return e.stack.push({k:ae.Act,how:"if"}),{k:"do",s:c.s,i:c.i}}case L.End:return Ae(e,e.pos>=Jr(e));case L.Skip:return e.pos>=Jr(e)?Ae(e,!1):(e.pos++,Ae(e,!0));case L.None:return Ae(e,!0);case L.Fail:return Ae(e,!1);case L.Break:case L.Accept:case L.Reject:{let c=Xe(a)===L.Reject,u=null;for(;e.stack.length>0&&u===null;){let f=e.stack.pop();f.k===ae.Block?u=f:f.k===ae.Into&&(e.input=f.outer,e.pos=f.outerPos)}if(u===null)return ot(e,`${rb(a)} outside of a rule block`);let d=e.stack[e.stack.length-1];return d!==void 0&&d.k===ae.Rep?(e.stack.pop(),c?(e.pos=d.from,Ae(e,d.n>=d.min)):Ae(e,!0)):c?(e.pos=u.alt,u.mark!==null&&(u.mark.length=u.markLen),Ae(e,!1)):Ae(e,!0)}case L.Return:{let c=r[n+1];return c!==void 0&&c.t===s.Paren?(e.stack.push({k:ae.Act,how:"return"}),{k:"do",s:c.s,i:c.i}):(e.stack.push({k:ae.Cap,rules:t,sub:n+1,how:"return",word:null,from:e.pos}),null)}case L.Quote:{let c=zs(e,r[n+1]);return c<0?Ae(e,!1):(e.pos=c,Ae(e,!0))}case L.Remove:return e.stack.push({k:ae.Edit,rules:t,sub:n+1,val:-1,only:!1,from:e.pos}),null;case L.Insert:{let c=Xe(r[n+1])===L.Only;return Gc(e,t,n+(c?2:1),e.pos,e.pos,c)}case L.Change:{let c=Xe(r[n+1])===L.Only,u=n+(c?2:1);return e.stack.push({k:ae.Edit,rules:t,sub:u,val:qs(r,u),only:c,from:e.pos}),null}case L.Only:return ot(e,"only goes after insert or change");case L.Bar:return ot(e,"misplaced |")}let i=xe(a);if(i===null||i.t===s.Unset||i.t===s.None)return ot(e,"rule word has no value");if(i.t===s.Block)return sa(e,i);let l=zs(e,i);return l<0?Ae(e,!1):(e.pos=l,Ae(e,!0))}function ab(e,t){if(t!==null){let n=e.stack.pop();switch(n.how){case"action":e.res=!0;break;case"if":e.res=Be(t);break;case"keep":{let r=e.colls[e.colls.length-1];if(r===void 0)return ot(e,"keep outside of collect");t.t!==s.Unset&&r.push(t),e.res=!0;break}case"put":if(t.t===s.Unset)return ot(e,"the value to put in has no value");_s(e,n.from,n.to,t,n.only);break;case"return":return Vc(e,t)}}for(;;){let n=e.stack[e.stack.length-1];if(n===void 0)return null;let r=e.res;e.res=null;let o=sb(e,n,r);if(o!==null||e.err!==null)return o}}function sb(e,t,n){let r=o=>(e.stack.pop(),Ae(e,o));switch(t.k){case ae.Block:{let o=t.rules.data;if(!t.started)t.started=!0,t.alt=e.pos,t.mark=e.colls[e.colls.length-1]??null,t.markLen=t.mark?.length??0;else if(n===!0)t.ip=t.next;else if(n===!1){let a=t.ip;for(;a<o.length&&Xe(o[a])!==L.Bar;)a++;if(e.pos=t.alt,t.mark!==null&&(t.mark.length=t.markLen),a>=o.length)return r(!1);t.ip=a+1}return t.ip>=o.length||Xe(o[t.ip])===L.Bar?r(!0):(t.next=qs(o,t.ip),t.next<0?ot(e,"rule ends too early"):yn(e,t.rules,t.ip))}case ae.Rep:return n===null?(t.from=e.pos,yn(e,t.rules,t.sub)):n===!1?(e.pos=t.from,r(t.n>=t.min)):(t.n++,!t.stall&&e.pos===t.from&&e.edits===t.edits||t.n>=t.max?r(!0):(t.from=e.pos,t.edits=e.edits,yn(e,t.rules,t.sub)));case ae.Look:return n===null?(t.from=e.pos,yn(e,t.rules,t.sub)):(e.pos=t.from,r(t.not?!n:n));case ae.Scan:return n===!0?(t.thru||(e.pos=t.at),r(!0)):n===!1&&(t.at++,t.at>Jr(e))?(e.pos=t.start,r(!1)):(e.pos=t.at,yn(e,t.rules,t.sub));case ae.Cap:{if(n===null)return t.from=e.pos,yn(e,t.rules,t.sub);if(n===!1)return r(!1);if(t.how==="return")return Vc(e,Us(e,t.from));if(t.how==="set")$e(t.word,e.pos>t.from?Kc(e,t.from):k);else if(t.how==="copy")$e(t.word,Us(e,t.from));else{let o=e.colls[e.colls.length-1];if(o===void 0)return ot(e,"keep outside of collect");e.pos-t.from===1?o.push(Kc(e,t.from)):e.pos>t.from&&o.push(Us(e,t.from))}return r(!0)}case ae.Into:{let o=n===!0&&e.pos>=Jr(e);return e.input=t.outer,e.pos=o?t.outerPos+1:t.outerPos,r(o)}case ae.Coll:{if(n===null)return e.colls.push([]),yn(e,t.rules,t.sub);let o=e.colls.pop();if(n){let a={t:s.Block,s:{data:o},i:0};t.word!==null?$e(t.word,a):e.colls.length>0?e.colls[e.colls.length-1].push(a):e.out=a}return r(n)}case ae.Edit:return n===null?(t.from=e.pos,yn(e,t.rules,t.sub)):n===!1?r(!1):(e.stack.pop(),t.val<0?(Je(e.input.s,t.from,e.pos-t.from,[]),e.pos=t.from,e.edits++,Ae(e,!0)):Gc(e,t.rules,t.val,t.from,e.pos,t.only));case ae.Act:return ot(e,"internal: action frame without a value")}}g("parse",'["Checks the input against a block of rules; true if they match all of it." input [series!] rules [block!] /case]',(e,t,n)=>{if(t.phase===0){t.phase=1;let a=t.args[0],i={input:a,pos:a.i,stack:[],res:null,colls:[],out:null,cased:t.args[2]===P,err:null,edits:0,ret:null};sa(i,t.args[1]),t.data=i}let r=t.data,o=ab(r,n);return r.err!==null?N("script","parse",r.err):o!==null?o:r.ret!==null?b(r.ret):r.out!==null?b(r.out):b(ee(r.res===!0&&r.pos>=Jr(r)))});g("charset",'["Makes a bitset of characters, for parse." spec [char! integer! any-string! binary! block!]]',(e,t)=>{let n=[],r=Hs(t.args[0],n);return r!==null?N("script","bad-bitset",r):b({t:s.Bitset,s:{data:n},neg:!1})});g("complement",'["The opposite: a bitset of everything else, a logic negated, an integer with its bits flipped." value [bitset! logic! integer!]]',(e,t)=>{let n=t.args[0];if(n.t===s.Bitset)return b({t:s.Bitset,s:{data:n.s.data.slice()},neg:!n.neg});if(n.t===s.Logic)return b(ee(!n.v));let r=Ve(~BigInt(n.v));return b(r===null?k:{t:s.Integer,v:r})});var Yc=String.raw`
22
22
  func: make function! [[
23
23
  "Makes a function from a spec and a body."
24
24
  spec [block!] body [block!]
@@ -374,8 +374,8 @@ suffix?: func [
374
374
  ]
375
375
  ]
376
376
  ]
377
- `;function qa(){let e=Ae(),t=(s,i)=>{let l=A(s),c=ee(e,l);c>=0?e.vals[c]=i:_r(e,l,i)};for(let[s,i]of[["none",x],["true",O],["false",xe],["on",O],["off",xe],["yes",O],["no",xe]])t(s,i);Qn.forEach((s,i)=>t(s,Kt(i)));for(let[s,i]of Object.entries(er))t(s,Wt(i));for(let s of Fi())t(s.name,{t:a.Native,p:s});for(let[s,i]of pa){let l=ee(e,A(i));if(l<0)throw new Error(`operator ${s} refers to unknown native ${i}`);t(s,{t:a.Op,p:{fn:e.vals[l]}})}let n={lib:e,user:Ae([],[],e)},r=De(wl,{file:"mezzanines"});ve(r.s,e,!0);let o=Ka(n,r);if(o.k==="error")throw new Error(`mezzanines failed: ${Tn(o.e)}`);return n}function Ka(e,t){let n=lr(ir(e,t.s,t.i));return n.k==="await"||n.k==="yield"?{k:"error",e:X("script","no-await","cannot wait in synchronous evaluation")}:n}function Ga(e,t,n){let r=De(t,n!==void 0?{file:n}:{});return ve(r.s,e.user,!0),Ka(e,{...r,i:jt(r).start})}var ho=new WeakMap,Cl=new WeakMap;function Sl(e,t){ho.set(e,t),Cl.set(e,new Map)}function Ml(){return{base:globalThis.location?.href??"file:///",read:async t=>{let n=await fetch(t);if(!n.ok)throw new Error(`HTTP ${n.status}`);return n.text()}}}function zd(e,t,n){let r=t===null?e:new URL(t,e).href;return new URL(n,r).href}var _d=L(A("exports")),Ud=L(A("export")),qd=L(A("type")),Kd=L(A("module"));function El(e,t){if(e===null)return null;let n=e.s.data;for(let r=e.i;r+1<n.length;r++){let o=n[r];if(o.t===a.SetWord&&L(o.sym)===t)return n[r+1]}return null}function Gd(e){let t=[],n=e.data;for(let r=0;r<n.length;r++){let o=n[r];if(o.t!==a.Word||L(o.sym)!==Ud)continue;let s=n[r+1];if(s?.t===a.SetWord)t.push({t:a.Word,sym:s.sym,bind:null}),ze(e,r,1,[]),r--;else if(s?.t===a.Block){for(let i of s.s.data)i.t===a.Word&&t.push(i);ze(e,r,2,[]),r--}}return t}function Za(e,t,n){return zd(t.base,ua(e),$(n))}var Tl=new Map;function Ya(e,t){Tl.set(e,t)}function Xa(e,t,n){let r=Tl.get(t);return r!==void 0?Promise.resolve(D(r)):e.read(t).then(o=>D(o),o=>{throw X("access","cannot-open",`cannot open ${J(n)}: ${o.message}`)})}g("read",'["The text of a file or a web address." source [file! url!]]',(e,t,n)=>{if(t.phase===1)return b(n);let r=ho.get(e.rt);return r===void 0?te("access","no-loader","this host cannot read files"):(t.phase=1,{k:"await",p:Xa(r,Za(e,r,t.args[0]),t.args[0])})});g("do-file",'["Runs the script in a file, as do does; a module is imported." file [file! url!]]',(e,t,n)=>{if(t.phase===2)return b(n);let r=ho.get(e.rt);if(r===void 0)return te("access","no-loader","this host cannot read files");if(t.phase===0){let u=Za(e,r,t.args[0]);return t.data={href:u},t.phase=1,{k:"await",p:Xa(r,u,t.args[0])}}let{href:o}=t.data,s;try{s=De($(n),{file:o})}catch(u){if(!(u instanceof st))throw u;return te("syntax","load",u.message)}let{header:i,start:l}=jt(s);t.phase=2;let c=El(i,qd);return c!==null&&c.t===a.Word&&L(c.sym)===Kd?{k:"call",fn:ge({t:a.Word,sym:A("import"),bind:e.rt.lib}),args:[t.args[0]]}:(ve(s.s,e.rt.user,!0),{k:"do",s:s.s,i:l})});g("import",'["Runs a module and gives its exports." source [file! url! string!]]',(e,t,n)=>{let r=e.rt,o=ho.get(r),s=Cl.get(r);if(o===void 0||s===void 0)return te("access","no-loader","this host cannot load modules");if(t.phase===0){let u=Za(e,o,t.args[0]),d=s.get(u);if(d!==void 0)return d.obj!==null?b(d.obj):(t.phase=3,{k:"await",p:d.done});let f=()=>{},p=new Promise((y,k)=>{f=(M,w)=>M?y(w):k(w)});p.catch(()=>{});let h={obj:null,done:p,settle:f};return s.set(u,h),t.data={href:u,entry:h,ctx:null,exports:[]},t.phase=1,{k:"await",p:Xa(o,u,t.args[0]).catch(y=>{throw s.delete(u),h.settle(!1,y),y})}}if(t.phase===3)return b(n);let i=t.data,l=u=>{s.delete(i.href),i.entry.settle(!1,u)};if(t.phase===1){let u;try{u=De($(n),{file:i.href})}catch(k){if(!(k instanceof st))throw k;let M=te("syntax","load",k.message);return M.k==="throw"&&l(M.e.v),M}let{header:d,start:f}=jt(u),p=El(d,_d);p!==null&&p.t===a.Block&&(i.exports=p.s.data.filter(k=>k.t===a.Word));let h=we(u.s,f);i.exports.push(...Gd(h));let y=Ae();return y.self=!0,qr(h,0,y),ve(h,r.user,!0),ve(h,y),ar(h,y),i.ctx=y,t.phase=2,t.trap=1<<F.Error,{k:"do",s:h,i:0}}if(t.thrown!==null){let u=t.thrown;return t.thrown=null,l(u.v),{k:"throw",e:u}}let c={t:a.Object,ctx:i.ctx};for(let u of i.exports){let d=i.ctx.keys.findIndex(f=>L(f)===L(u.sym));if(d<0){let f=te("script","bad-export",`${J(u)} is exported but not defined`);return f.k==="throw"&&l(f.e.v),f}Ie({t:a.Word,sym:u.sym,bind:r.user},i.ctx.vals[d])}return i.entry.obj=c,i.entry.settle(!0,c),b(c)});var Va=new Map,Ja=globalThis.localStorage??{getItem:e=>Va.get(e)??null,setItem:(e,t)=>{Va.set(e,t)},removeItem:e=>{Va.delete(e)}},Vd="trebol:",Qa=e=>Vd+(e.t===a.Word||e.t===a.LitWord?J({...e,t:a.Word}):$(e));g("save-local",'["Keeps a value in the browser, under a key." key [string! word!] value [any-value!]]',(e,t)=>(Ja.setItem(Qa(t.args[0]),J(t.args[1],{all:!0})),b(t.args[1])));g("load-local",'["The value kept in the browser under a key, or none." key [string! word!]]',(e,t)=>{let n=Ja.getItem(Qa(t.args[0]));if(n===null)return b(x);try{return b(De(n).s.data[0]??x)}catch(r){if(r instanceof st)return b(x);throw r}});g("remove-local",'["Forgets the value kept in the browser under a key." key [string! word!]]',(e,t)=>(Ja.removeItem(Qa(t.args[0])),b(ae)));var Zd=1e4,Il=1,ts=new Map;function Qt(e,t){let n=Il++;return ts.set(n,t),{t:a.Handle,p:{kind:e,id:n}}}function At(e,t){if(e.t!==a.Handle)return null;let n=e.p;return n.kind===t?ts.get(n.id)??null:null}function Ll(e){e.t===a.Handle&&ts.delete(e.p.id)}var Al=new WeakMap;function Bl(e,t){let n={rt:e,ready:[],byTask:new WeakMap,onError:t,pumping:!1,live:0,afterPump:null};return Al.set(e,n),n}function Ct(e){let t=Al.get(e.rt);if(t===void 0)throw new Error("no scheduler for this runtime");return t}function Ht(e,t,n=0){let r=ir(e.rt,t,n),o={id:Il++,task:r,state:"ready",result:ae,error:null,abort:null,watchers:[]};return e.byTask.set(r,o),e.live++,e.ready.push(o),mo(e),o}function jn(e,t,n){let r=Object.keys(n),o=we(t.s,t.i);if(r.length>0){let s=Ae(r.map(i=>A(i)),r.map(i=>n[i]));ve(o,s)}return Ht(e,o,0)}var Yd=(()=>{let e=globalThis;if(typeof e.setImmediate=="function")return r=>{e.setImmediate(r)};if(typeof MessageChannel>"u")return r=>{setTimeout(r,0)};let t=new MessageChannel,n=[];return t.port1.onmessage=()=>n.shift()?.(),r=>{n.push(r),t.port2.postMessage(null)}})();function mo(e){e.pumping||(e.pumping=!0,Yd(()=>Xd(e)))}function es(e,t,n){t.state=n,t.abort=null,e.live--,n==="failed"&&t.watchers.length===0&&e.onError(t.error,t);for(let r of t.watchers.splice(0))r(t)}function Xd(e){e.pumping=!1;let t=e.ready.splice(0);for(let n of t){if(n.state!=="ready")continue;let r=lr(n.task,Zd);switch(r.k){case"done":n.result=r.v,es(e,n,"done");break;case"error":n.error=r.e,es(e,n,"failed");break;case"yield":e.ready.push(n);break;case"await":n.state="waiting",r.p.then(o=>{n.state==="waiting"&&(n.abort=null,la(n.task,o),n.state="ready",e.ready.push(n),mo(e))},o=>{n.state==="waiting"&&(n.abort=null,ca(n.task,Jd(o)),n.state="ready",e.ready.push(n),mo(e))});break}}e.afterPump?.(),e.ready.length>0&&mo(e)}function Jd(e){if(typeof e=="object"&&e!==null&&e.t===a.Error)return e;let t=e instanceof Error?e.message:String(e);return X("access","host",t)}function $l(e,t){t.state==="done"||t.state==="failed"||t.state==="cancelled"||(t.abort?.(),t.error=X("access","cancelled","the task was cancelled"),es(e,t,"cancelled"))}function Rn(e){return new Promise((t,n)=>{let r=o=>o.state==="done"?t(o.result):n(o.error??X("access","cancelled","the task was cancelled"));e.state==="done"||e.state==="failed"||e.state==="cancelled"?r(e):e.watchers.push(r)})}var ns={line:e=>console.log(e)};g("write-line",'["Writes a value and a new line to the output." value [any-type!]]',(e,t)=>(ns.line(j(t.args[0])),b(ae)));g("probe",'["Prints a value as mold shows it; gives the value." value [any-type!]]',(e,t)=>(ns.line(J(t.args[0])),b(t.args[0])));function rs(e){return e.t===a.Time?e.v/1e6:e.t===a.Integer?he.toNumber(e.v)*1e3:e.v*1e3}var Qd=["year","month","day","time","zone","date","weekday","yearday"];g("now",'["The date and time now." /year /month /day /time /zone /date /weekday /yearday /precise /utc]',(e,t)=>{let n=new Date,r=u=>t.args[u].t===a.Logic,o=r(9)?0:-n.getTimezoneOffset(),s=new Date(n.getTime()+o*6e4),i=((s.getUTCHours()*60+s.getUTCMinutes())*60+s.getUTCSeconds())*1e9+(r(8)?s.getUTCMilliseconds()*1e6:0),l=qt({y:s.getUTCFullYear(),m:s.getUTCMonth()+1,d:s.getUTCDate(),time:i,zone:o}),c=Qd.find((u,d)=>r(d));return b(c===void 0?l:bt(l,ci(c)))});g("wait",'["Waits a number of seconds, or for tasks to finish; other tasks run meanwhile." value [number! time! handle! block!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=t.args[0],s=Ct(e).byTask.get(e);if(r.t===a.Handle||r.t===a.Block){let c=(r.t===a.Block?r.s.data.slice(r.i).map(d=>d.t===a.Word?ge(d)??d:d):[r]).map(d=>At(d,"task"));if(c.some(d=>d===null))return te("script","bad-wait","wait needs tasks or a duration");let u=Promise.all(c.map(d=>Rn(d)));return{k:"await",p:r.t===a.Block?u.then(d=>({t:a.Block,s:{data:d},i:0})):u.then(d=>d[0])}}let i=rs(r);return{k:"await",p:new Promise(l=>{let c=setTimeout(()=>l(x),i);s&&(s.abort=()=>clearTimeout(c))})}});g("spawn",'["Starts a task that evaluates a block on its own; gives a handle at once." body [block!]]',(e,t)=>{let n=t.args[0],r=Ht(Ct(e),n.s,n.i);return b(Qt("task",r))});g("delay",'["Evaluates a block once, after a while; gives a handle." time [number! time!] body [block!]]',(e,t)=>{let n=Ct(e),r=t.args[1],o=setTimeout(()=>jn(n,r,{}),rs(t.args[0]));return b(Qt("timer",{stop:()=>clearTimeout(o)}))});g("every",'["Evaluates a block again and again, every so often; gives a handle." time [number! time!] body [block!]]',(e,t)=>{let n=Ct(e),r=t.args[1],o=setInterval(()=>jn(n,r,{}),Math.max(1,rs(t.args[0])));return b(Qt("timer",{stop:()=>clearInterval(o)}))});var os={timer:e=>e.stop()};g("cancel",'["Stops a task, timer or request." target [handle!]]',(e,t)=>{let n=t.args[0],r=n.p.kind;if(r==="task"){let s=At(n,"task");return s!==null&&$l(Ct(e),s),b(ae)}let o=At(n,r);return o!==null&&os[r]?.(o),Ll(n),b(ae)});function ss(e){return Qt("file",e)}g("read-file",'["The bytes of a file the user chose." file [handle!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=At(t.args[0],"file");return r===null?te("script","bad-handle","read-file needs a file from an upload field"):{k:"await",p:r.arrayBuffer().then(s=>jr([...new Uint8Array(s)]),s=>{throw X("access","read",`cannot read ${r instanceof File?r.name:"the file"}: ${s.message}`)})}});var eb={csv:"text/csv",txt:"text/plain",json:"application/json",xml:"application/xml",html:"text/html",trb:"text/plain",md:"text/markdown",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",pdf:"application/pdf",zip:"application/zip"},tb={save:(e,t)=>{let n=globalThis.document;if(n===void 0)return!1;let r=URL.createObjectURL(t),o=n.createElement("a");return o.href=r,o.download=e,o.style.display="none",n.body.append(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e3),!0}};function nb(e){let t=/filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(e);if(t!==null)try{let r=t[2].trim();return/^utf-8$/i.test(t[1].trim())?decodeURIComponent(r):r.replace(/%([0-9a-f]{2})/gi,(o,s)=>String.fromCharCode(parseInt(s,16)))}catch{}let n=/filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]+))/i.exec(e);return n===null?"":n[1]!==void 0?n[1].replace(/\\(.)/g,"$1"):n[2].trim()}function as(e,t){let n=ee(e.ctx,A(t));return n<0?void 0:e.ctx.vals[n]}function Nl(e,t){if(e===void 0||e.t!==a.Map)return"";let n=e.s.data;for(let r=0;r+1<n.length;r+=2)if(n[r].t===a.String&&$(n[r]).toLowerCase()===t)return j(n[r+1]);return""}g("download",'["Gives the user a file to save: text (as UTF-8), bytes, or the answer of fetch/with [full: true], under the name the server gives." name [file! string!] data [string! binary! object!]]',(e,t)=>{let n=$(t.args[0]).split("/").pop()??"",r=t.args[1],o="",s=!1;if(r.t===a.Object){let d=as(r,"status"),f=as(r,"headers"),p=as(r,"body");if(d===void 0||d.t!==a.Integer||p===void 0)return te("script","bad-answer","download needs an answer of fetch/with [full: true]");let h=he.toNumber(d.v);if(h>=400)return te("access","http",`HTTP ${h}: no file to save`);let y=nb(Nl(f,"content-disposition")).split(/[/\\]/).pop()??"";y!==""&&(n=y,s=!0),o=Nl(f,"content-type"),r=p.t===a.Binary||p.t===a.String?p:D(pt(p))}if(n==="")return te("script","bad-file","download needs a file name");let i=n.includes(".")?n.slice(n.lastIndexOf(".")+1).toLowerCase():"",l=eb[i]??"application/octet-stream",c=r.t===a.Binary?new Uint8Array(r.s.data.slice(r.i)):(i==="csv"?"\uFEFF":"")+$(r),u=new Blob([c],{type:o!==""?o:r.t===a.Binary?l:`${l};charset=utf-8`});return tb.save(n,u)?b(s?Go(t.args[0].t===a.File?a.File:a.String,n):t.args[0]):te("access","no-download","this host cannot give the user files")});function Bt(e,t){if(e===null)return null;let n=ee(e.ctx,A(t)),r=n<0?void 0:e.ctx.vals[n];return r===void 0||r.t===a.None?null:r}var Ol=e=>e!==null&&!(e.t===a.Logic&&!e.v);function Dl(e){let t=[],n=r=>r.t>=a.Word&&r.t<=a.Issue?E(r.sym):j(r);if(e.t===a.Block||e.t===a.Map){let r=e.s.data.slice(e.t===a.Block?e.i:0);for(let o=0;o+1<r.length;o+=2)t.push([n(r[o]),j(r[o+1])])}else e.t===a.Object&&e.ctx.keys.forEach((r,o)=>t.push([E(r),j(e.ctx.vals[o])]));return t}function rb(e,t){if(/json/i.test(e)){let n=fr(new TextDecoder().decode(t));return typeof n=="string"?D(new TextDecoder().decode(t)):n}return/^text\/|xml|javascript|x-www-form-urlencoded/i.test(e)||e===""?D(new TextDecoder().decode(t)):{t:a.Binary,s:{data:[...t]},i:0}}function ob(e){return e.t===a.Time?e.v/1e9:e.t===a.Integer?he.toNumber(e.v):e.v}async function ab(e,t,n){let r=await fetch(e,t),o=[];r.headers.forEach((i,l)=>o.push([l,i]));let s;if(n===null||r.body===null)s=new Uint8Array(await r.arrayBuffer());else{let i=Number(r.headers.get("content-length")??NaN),l=Number.isFinite(i)&&r.headers.get("content-encoding")===null?i:null,c=[],u=0;n(0,l);for(let f=r.body.getReader();;){let{value:p,done:h}=await f.read();if(h)break;c.push(p),u+=p.length,n(u,l)}l===null&&n(u,u),s=new Uint8Array(u);let d=0;for(let f of c)s.set(f,d),d+=f.length}return{status:r.status,statusText:r.statusText,ok:r.ok,headers:o,bytes:s}}function sb(e,t,n){return new Promise((r,o)=>{let s=new XMLHttpRequest;s.open(t.method??"GET",e),t.headers.forEach((l,c)=>s.setRequestHeader(c,l)),s.withCredentials=t.credentials==="include",s.responseType="arraybuffer";let i=l=>n(l.loaded,l.lengthComputable?l.total:null);t.body!==void 0&&(s.upload.onprogress=i),s.onprogress=i,s.onload=()=>{let l=s.getAllResponseHeaders().trim().split(/[\r\n]+/).filter(d=>d.includes(":")).map(d=>[d.slice(0,d.indexOf(":")).trim().toLowerCase(),d.slice(d.indexOf(":")+1).trim()]),c=s.status>=200&&s.status<300,u=s.response.byteLength;n(u,u),r({status:s.status,statusText:s.statusText,ok:c,headers:l,bytes:new Uint8Array(s.response)})},s.onerror=()=>o(new Error("network error")),s.onabort=()=>o(new Error("aborted")),t.signal?.addEventListener("abort",()=>s.abort()),s.send(t.body??null)})}function ib(e,t){let n=Ct(e),r=0,o=(i,l)=>{if(t.t===a.Block){jn(n,t,{done:i,total:l});return}let c=ee(e.rt.user,A("show-progress")),u=c<0?void 0:e.rt.user.vals[c];u!==void 0&&Ht(n,{data:[u,t,i,l]},0)},s=i=>({t:a.Integer,v:i});return{tell:(i,l)=>{let c=Date.now();c-r<100&&i!==l||(r=c,o(s(i),l===null?x:s(l)))},end:()=>{t.t!==a.Block&&o(x,x)}}}g("http-request",'["Sends an HTTP request; used by fetch." url [url! string!] options [object! none!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=t.args[1].t===a.Object?t.args[1]:null,o=$(t.args[0]),s=Bt(r,"query");if(s!==null){let ce=uo(s);if(ce===null)return te("script","bad-query","a query takes words or strings as names");let ye=o.includes("#")?o.slice(o.indexOf("#")):"",je=o.slice(0,o.length-ye.length);ce!==""&&(o=je+(je.includes("?")?"&":"?")+ce+ye)}let i=Bt(r,"method"),l=new Headers,c=Bt(r,"headers");if(c!==null)for(let[ce,ye]of Dl(c))l.set(ce,ye);let u,d=Bt(r,"body"),f=Bt(r,"form"),p=Bt(r,"multipart");if(f!==null)u=new URLSearchParams(Dl(f));else if(p!==null){let ce=new FormData,ye=p.t===a.Block?p.s.data.slice(p.i):[];for(let je=0;je+1<ye.length;je+=2){let Ye=ye[je],W=ye[je+1],ie=Ye.t>=a.Word&&Ye.t<=a.Issue?E(Ye.sym):j(Ye),Re=At(W,"file");W.t===a.Binary?ce.append(ie,new Blob([new Uint8Array(W.s.data.slice(W.i))]),ie):Re!==null?ce.append(ie,Re,Re instanceof File?Re.name:ie):ce.append(ie,j(W))}u=ce}else d!==null&&(d.t===a.String?u=$(d):d.t===a.Binary?u=new Uint8Array(d.s.data.slice(d.i)):(u=pt(d),l.has("content-type")||l.set("content-type","application/json")));l.has("accept")||l.set("accept","application/json, text/*;q=0.9, */*;q=0.8");let h=Bt(r,"timeout"),y=Ol(Bt(r,"full")),k=Bt(r,"cookies"),M=k===null?"same-origin":Ol(k)?"include":"omit",w=new AbortController,v=!1,C=h!==null?setTimeout(()=>{v=!0,w.abort()},ob(h)*1e3):null,S=Ct(e).byTask.get(e);S&&(S.abort=()=>w.abort());let I=i===null?u===void 0?"GET":"POST":j(i).toUpperCase(),H=Bt(r,"progress"),z=H===null?null:ib(e,H);return{k:"await",p:(async()=>{try{let ce={method:I,headers:l,body:u,credentials:M,signal:w.signal},ye=z!==null&&typeof XMLHttpRequest<"u"?await sb(o,ce,z.tell):await ab(o,ce,z===null?null:z.tell),je=ye.headers.find(([W])=>W==="content-type")?.[1]??"",Ye=rb(je,ye.bytes);if(y){let W=[];for(let[ie,Re]of ye.headers)W.push(D(ie),D(Re));return{t:a.Object,ctx:{keys:["status","headers","body"].map(ie=>A(ie)),vals:[{t:a.Integer,v:ye.status},{t:a.Map,s:{data:W}},Ye],parent:null}}}if(!ye.ok)throw X("access","http",`HTTP ${ye.status} ${ye.statusText} for ${o}`);return Ye}catch(ce){throw ce.t===a.Error?ce:v?X("access","timeout",`request to ${o} timed out`):w.signal.aborted?X("access","cancelled",`request to ${o} was cancelled`):X("access","network",`cannot reach ${o}: ${ce.message}`)}finally{C!==null&&clearTimeout(C),z?.end()}})()}});function Pl(e){let t=e.trimStart();if(t.startsWith("{")||t.startsWith("[")){let n=fr(e);if(typeof n!="string")return n}return D(e)}function hn(e,t,n){let r=e.handlers[t];if(r===void 0){e.pending.push([t,n]);return}for(let o of r)jn(e.sch,o,n)}g("open-socket",'["Opens a WebSocket; gives a handle once it is open." url [url! string!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=$(t.args[0]),o=Ct(e);return{k:"await",p:new Promise((i,l)=>{let c;try{c=new WebSocket(r)}catch(f){l(X("access","network",`cannot open ${r}: ${f.message}`));return}c.binaryType="arraybuffer";let u={sch:o,handlers:{},pending:[],close:()=>c.close(),send:f=>c.send(f)},d=!1;c.onopen=()=>{d=!0,i(Qt("stream",u))},c.onmessage=f=>{let p=typeof f.data=="string"?Pl(f.data):{t:a.Binary,s:{data:[...new Uint8Array(f.data)]},i:0};hn(u,"message",{value:p})},c.onerror=()=>{d?hn(u,"error",{value:X("access","network",`socket error on ${r}`)}):l(X("access","network",`cannot open ${r}`))},c.onclose=f=>{d&&hn(u,"close",{value:{t:a.Integer,v:f.code}})}})}});function lb(e,t){let n=e;for(;;){let r=/\r?\n\r?\n/.exec(n);if(r===null)return n;let o=n.slice(0,r.index);n=n.slice(r.index+r[0].length);let s="message",i=[];for(let l of o.split(/\r?\n/)){if(l.startsWith(":"))continue;let c=l.indexOf(":"),u=c<0?l:l.slice(0,c),d=c<0?"":l.slice(c+1).replace(/^ /,"");u==="event"?s=d:u==="data"&&i.push(d)}i.length>0&&t(s,i.join(`
378
- `))}}g("open-events",'["Opens a stream of server-sent events; gives a handle." url [url! string!]]',(e,t)=>{let n=$(t.args[0]),r=Ct(e),o=new AbortController,s={sch:r,handlers:{},pending:[],close:()=>o.abort()},i=Qt("stream",s);return(async()=>{try{let l=await fetch(n,{headers:{accept:"text/event-stream"},signal:o.signal});if(!l.ok||l.body===null)throw new Error(`HTTP ${l.status}`);let c=l.body.getReader(),u=new TextDecoder,d="";for(;;){let{done:f,value:p}=await c.read();if(f)break;d=lb(d+u.decode(p,{stream:!0}),(h,y)=>{hn(s,"message",{value:Pl(y),event:{t:a.Word,sym:A(h),bind:null}})})}hn(s,"close",{value:x})}catch(l){o.signal.aborted||hn(s,"error",{value:X("access","network",`event stream ${n}: ${l.message}`)})}})(),b(i)});function is(e){return(t,n)=>{let r=At(n.args[0],"stream");if(r===null)return te("script","bad-handle",`on-${e} needs a socket or event stream`);(r.handlers[e]??=[]).push(n.args[1]);let o=r.pending.filter(([s])=>s===e);r.pending=r.pending.filter(([s])=>s!==e);for(let[,s]of o)hn(r,e,s);return b(n.args[0])}}g("on-message",'["Runs a block for each message that comes on a stream." stream [handle!] body [block!]]',is("message"));g("on-close",'["Runs a block when a stream closes." stream [handle!] body [block!]]',is("close"));g("on-error",'["Runs a block when a stream fails." stream [handle!] body [block!]]',is("error"));g("send",'["Sends a value on a socket." stream [handle!] data [any-value!]]',(e,t)=>{let n=At(t.args[0],"stream");if(n===null||n.send===void 0)return te("script","bad-handle","send needs an open socket");let r=t.args[1];return n.send(r.t===a.String?$(r):r.t===a.Binary?new Uint8Array(r.s.data.slice(r.i)):pt(r)),b(t.args[0])});os.stream=e=>e.close();var Wl=(e,t)=>(At(t.args[0],"stream")?.close(),b(t.args[0]));g("close",'["Closes a stream, or hides a dialog." stream [handle!]]',Wl);g("close-stream",'["Closes a socket or a stream of events." stream [handle!]]',Wl);var jl=()=>globalThis.navigator,go={open:e=>{let t=globalThis.window;if(t===void 0)return!1;let n=t.open(e,"_blank");return n!==null&&(n.opener=null),!0},writeClipboard:e=>{let t=jl()?.clipboard;return t===void 0?null:t.writeText(e).then(()=>!0,()=>!1)},readClipboard:()=>{let e=jl()?.clipboard;return e===void 0?null:e.readText().then(t=>t,()=>null)}};g("browse",'["Opens a web address in a new tab." url [url! file!]]',(e,t)=>go.open($(t.args[0]))?b(ae):te("access","no-browse","this host cannot open web addresses"));g("write-clipboard",'["Puts text on the clipboard; true when it is there." data [string!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=go.writeClipboard($(t.args[0]));return r===null?te("access","no-clipboard","this host has no clipboard"):{k:"await",p:r.then(Z)}});g("read-clipboard",'["The text on the clipboard, or none; the browser may ask the user first."]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=go.readClipboard();return r===null?te("access","no-clipboard","this host has no clipboard"):{k:"await",p:r.then(o=>o===null||o===""?x:D(o))}});var cb={gzip:"gzip",zlib:"deflate",deflate:"deflate-raw"};function Rl(e){return cb[E(L(e.sym)).toLowerCase()]??null}var Fl=e=>e.t===a.Binary?new Uint8Array(e.s.data.slice(e.i)):new TextEncoder().encode($(e));async function Hl(e,t){let n=await new Response(new Blob([e]).stream().pipeThrough(t)).arrayBuffer();return jr([...new Uint8Array(n)])}g("compress",'["Compresses bytes, or text as UTF-8, into a binary." data [binary! string!] method [word!] "gzip, zlib or deflate"]',(e,t,n)=>{if(t.phase===1)return b(n);let r=Rl(t.args[1]);return r===null?te("script","bad-method","compress takes gzip, zlib or deflate"):(t.phase=1,{k:"await",p:Hl(Fl(t.args[0]),new CompressionStream(r))})});g("decompress",'["The bytes that compress was given." data [binary!] method [word!] "gzip, zlib or deflate"]',(e,t,n)=>{if(t.phase===1)return b(n);let r=Rl(t.args[1]);if(r===null)return te("script","bad-method","decompress takes gzip, zlib or deflate");t.phase=1;let o=E(t.args[1].sym);return{k:"await",p:Hl(Fl(t.args[0]),new DecompressionStream(r)).catch(()=>{throw X("script","bad-compression",`the data is not ${o} compressed`)})}});var cs=new Set([a.Date,a.Time,a.Integer,a.Decimal,a.Percent,a.Money]),zl=1e6,ub=24*3600*1e9;function mn(e){try{return e()}catch{return null}}function Ul(e,t){switch(e.t){case a.Integer:return mn(()=>new Intl.NumberFormat(t).format(e.v));case a.Decimal:return mn(()=>new Intl.NumberFormat(t,{maximumSignificantDigits:15}).format(e.v));case a.Percent:return mn(()=>new Intl.NumberFormat(t,{style:"percent",maximumFractionDigits:2}).format(e.v));case a.Money:{let n=Mt(e.v),r={minimumFractionDigits:2,maximumFractionDigits:Math.max(2,e.v.e)};return mn(()=>new Intl.NumberFormat(t,e.cur!==""?{style:"currency",currency:e.cur,...r}:r).format(n))}case a.Date:{let n=e.v,r=Date.UTC(n.y,n.m-1,n.d)+(n.time??0)/zl,o={year:"numeric",month:"numeric",day:"numeric",timeZone:"UTC"};return n.time!==null&&Object.assign(o,{hour:"numeric",minute:"2-digit"}),n.y<100?null:mn(()=>new Intl.DateTimeFormat(t,o).format(r))}case a.Time:{if(e.v<0||e.v>=ub)return null;let n={hour:"numeric",minute:"2-digit",timeZone:"UTC"};return e.v%6e10!==0&&(n.second="2-digit"),mn(()=>new Intl.DateTimeFormat(t,n).format(e.v/zl))}}return null}function db(e){let t=[];try{t=new Intl.NumberFormat(e).formatToParts(12345.6)}catch{}let n=r=>t.find(o=>o.type===r)?.value;return{decimal:n("decimal")??".",group:n("group")??","}}function us(e,t){if(e.t!==a.Money)return e.t===a.None?"":j(e);let n=Mt(e.v),r={useGrouping:!1,minimumFractionDigits:2,maximumFractionDigits:Math.max(2,e.v.e)};return mn(()=>new Intl.NumberFormat(t,r).format(n))??Mt(e.v)}function ds(e,t){let{decimal:n,group:r}=db(t),o=i=>i===n||i===r||i==="."||i===",",s=[...e].filter(i=>/[0-9+-]/.test(i)||o(i)).join("");if(s.includes(n)){let[i,...l]=s.split(n);if(l.length>1)return null;s=`${_l(i,r)}.${l[0]}`}else/^[+-]?\d{1,3}([.,]\d{3})+$/.test(s)&&[...s].filter(o).every(i=>i===r)?s=_l(s,r):[...s].filter(o).length===1&&(s=s.replace(/[.,]/,"."));return/^[+-]?(\d+\.?\d*|\.\d+)$/.test(s)?s:null}function _l(e,t){return e.split(t).join("")}function bb(e){let t=[];try{t=new Intl.DateTimeFormat(e,{timeZone:"UTC"}).formatToParts(Date.UTC(2026,10,23))}catch{}let n=t.map(r=>r.type[0]).filter(r=>r==="d"||r==="m"||r==="y").join("");return n.length===3?n:"dmy"}function bs(e,t){let n=e.trim().split(/[^0-9]+/).filter(u=>u!=="");if(n.length!==3)return null;let r=n[0].length===4?"ymd":bb(t),o=u=>Number(n[r.indexOf(u)]),s=o("y"),i=o("m"),l=o("d");n[r.indexOf("y")].length<=2&&(s+=2e3);let c=new Date(Date.UTC(s,i-1,l));return s<100||c.getUTCFullYear()!==s||c.getUTCMonth()!==i-1||c.getUTCDate()!==l?null:`${s}-${String(i).padStart(2,"0")}-${String(l).padStart(2,"0")}`}function vo(e){try{let t=new Intl.Locale(e),n=(t.getWeekInfo?.()??t.weekInfo)?.firstDay;return n!==void 0?n:["US","CA","MX","BR","JP","IL","PH"].includes(t.maximize().region??"")?7:1}catch{return 1}}function ft(e){let t=ee(e.user,A("i18n")),n=t<0?null:e.user.vals[t];if(n===null||n.t!==a.Object)return"en";let r=n,o=ee(r.ctx,A("language")),s=o<0?null:r.ctx.vals[o];return s?.t===a.Word||s?.t===a.LitWord?E(s.sym):s?.t===a.String?$(s):"en"}function ls(e,t){let n=ee(e.user,A("i18n")),r=n<0?null:e.user.vals[n];if(r===null||r.t!==a.Object)return null;let o=ee(r.ctx,A(t));return o<0?null:r.ctx.vals[o]}function $t(e,t){let n=e.s.data,r=t.toLowerCase();for(let o=0;o+1<n.length;o+=2){let s=n[o],i=s.t===a.String?$(s):"sym"in s?E(s.sym):null;if(i!==null&&i.toLowerCase()===r)return n[o+1]}return null}function Ue(e,t){if(e.t===a.String)return $(e);if(e.t===a.Map){let n=ls(t,"main"),r=$t(e,ft(t))??(n!==null&&"sym"in n?$t(e,E(n.sym)):null)??e.s.data.find((o,s)=>s%2===1&&o.t===a.String)??null;return r===null?"":Ue(r,t)}if(e.t===a.Word||e.t===a.LitWord){let n=ls(t,"texts"),r=n?.t===a.Map?$t(n,E(e.sym)):null;return r===null?E(e.sym):Ue(r,t)}return j(e)}function ps(e,t,...n){let r=ls(e,"ui"),o=r?.t===a.Map?$t(r,t):null,s=o===null?t:Ue(o,e);return n.forEach((i,l)=>{s=s.replaceAll(`#${l+1}`,i)}),s}function yo(e,t){return Ul(e,t)??j(e)}function fs(e,t){let n=["byte","kilobyte","megabyte","gigabyte"],r=e,o=0;for(;r>=1e3&&o<n.length-1;)r/=1e3,o++;try{let s=o===0?"long":"short";return new Intl.NumberFormat(t,{style:"unit",unit:n[o],unitDisplay:s,maximumFractionDigits:o===0?0:1}).format(r)}catch{return`${e} B`}}g("format-local",'["The value as text in the way of a language: dates, numbers, money." value [any-type!] language [word! string!]]',(e,t)=>{let n=t.args[1],r=n.t===a.String?$(n):E(n.sym);return b(D(yo(t.args[0],r)))});var pb=String.raw`
377
+ `;function Ks(){let e=Le(),t=(a,i)=>{let l=A(a),c=te(e,l);c>=0?e.vals[c]=i:Xn(e,l,i)};for(let[a,i]of[["none",k],["true",P],["false",we],["on",P],["off",we],["yes",P],["no",we]])t(a,i);Nr.forEach((a,i)=>t(a,pn(i)));for(let[a,i]of Object.entries(jr))t(a,en(i));for(let a of pc())a.hidden!==!0&&t(a.name,{t:s.Native,p:a});for(let[a,i]of bs){let l=te(e,A(i));if(l<0)throw new Error(`operator ${a} refers to unknown native ${i}`);t(a,{t:s.Op,p:{fn:e.vals[l]}})}let n={lib:e,user:Le([],[],e)},r=me(Yc,{file:"mezzanines"});be(r.s,e,!0);let o=Gs(n,r);if(o.k==="error")throw new Error(`mezzanines failed: ${er(o.e)}`);return n}function Gs(e,t){let n=_r(dr(e,t.s,t.i));return n.k==="await"||n.k==="yield"?{k:"error",e:Y("script","no-await","cannot wait in synchronous evaluation")}:n}function Vs(e,t,n){let r=me(t,n!==void 0?{file:n}:{});return be(r.s,e.user,!0),Gs(e,{...r,i:Ot(r).start})}var Ys=[],ib=zr({name:"js-function",hidden:!0,spec:nr(me("[]").s.data[0]),specBlock:me("[]").s.data[0]},(e,t,n)=>{if(t.phase===1)return b(n);let r=Ys[t.def.data],o=t.def.name,a;try{a=r(...t.args.map(i=>JSON.parse(Re(i))))}catch(i){return Q("script","js-error",`${o}: ${i?.message??String(i)}`)}return a instanceof Promise?(t.phase=1,{k:"await",p:a.then(i=>{let l=Zc(i,o);if(l.k==="value")return l.v;throw l.e.v},i=>{throw Y("script","js-error",`${o}: ${i?.message??String(i)}`)})}):Zc(a,o)}).p;function Zc(e,t){if(e===void 0)return b(k);let n;try{n=JSON.stringify(e)}catch{n=void 0}if(n===void 0)return Q("script","js-error",`${t} gave a value that is not JSON`);let r=Gt(n);return typeof r=="string"?Q("script","js-error",`${t}: ${r}`):b(r)}function Jc(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/_/g,"-").toLowerCase()}function lb(e){let t=e.toString(),n=/^\s*(?:async\s+)?([\w$]+)\s*=>/.exec(t)??/^[^(=]*\(([^)]*)\)/.exec(t);if(n===null)return null;let r=n[1].split(",").map(o=>o.trim()).filter(o=>o!=="");return r.every(o=>/^[A-Za-z_$][\w$]*$/.test(o))?r.map(Jc):null}function cb(e,t){let n=e.spec,r=typeof n=="string"?n:`[${(lb(e)??Array.from({length:e.length},(i,l)=>`arg${l+1}`)).join(" ")}]`,o;try{o=me(r).s.data[0]}catch(i){return`${t}: bad spec: ${i.message}`}if(o?.t!==s.Block)return`${t}: its spec is not a block`;let a=nr(o);return typeof a=="string"?`${t}: ${a}`:{spec:a,specBlock:o}}function Xc(e){let t=Le();t.self=!0;for(let[n,r]of Object.entries(e)){if(n==="default")continue;let o=Jc(n),a;if(typeof r=="function"){let i=cb(r,o);if(typeof i=="string")return i;Ys.push(r),a={t:s.Native,p:{...ib,...i,name:o,data:Ys.length-1,hidden:!0}}}else{let i;try{i=JSON.stringify(r)}catch{i=void 0}if(i===void 0)continue;let l=Gt(i);if(typeof l=="string")continue;a=l}Xn(t,A(o),a)}return{t:s.Object,ctx:t}}var ia=new WeakMap,Qc=new WeakMap;function eu(e,t){ia.set(e,t),Qc.set(e,new Map)}function tu(){let e=globalThis;return{base:e.location?.href??"file:///",read:async t=>{let n=t.startsWith("file:")?e.process?.getBuiltinModule?.("node:fs/promises"):void 0;if(n!==void 0)return n.readFile(new URL(t),"utf8");let r=await fetch(t);if(!r.ok)throw new Error(`HTTP ${r.status}`);return r.text()}}}function ub(e,t,n){let r=t===null?e:new URL(t,e).href;return new URL(n,r).href}var db=I(A("exports")),fb=I(A("export")),pb=I(A("type")),bb=I(A("module"));function nu(e,t){if(e===null)return null;let n=e.s.data;for(let r=e.i;r+1<n.length;r++){let o=n[r];if(o.t===s.SetWord&&I(o.sym)===t)return n[r+1]}return null}function hb(e){let t=[],n=e.data;for(let r=0;r<n.length;r++){let o=n[r];if(o.t!==s.Word||I(o.sym)!==fb)continue;let a=n[r+1];if(a?.t===s.SetWord)t.push({t:s.Word,sym:a.sym,bind:null}),Je(e,r,1,[]),r--;else if(a?.t===s.Block){for(let i of a.s.data)i.t===s.Word&&t.push(i);Je(e,r,2,[]),r--}}return t}function Js(e,t,n){return ub(t.base,ds(e),B(n))}var Xs=new Map;function pr(e,t){Xs.set(e,t)}function ru(e){return Xs.get(e)}function Qs(e,t,n){let r=Xs.get(t);return r!==void 0?Promise.resolve(j(r)):e.read(t).then(o=>j(o),o=>{throw Y("access","cannot-open",`cannot open ${Z(n)}: ${o.message}`)})}g("read",'["The text of a file or a web address." source [file! url!]]',(e,t,n)=>{if(t.phase===1)return b(n);let r=ia.get(e.rt);return r===void 0?Q("access","no-loader","this host cannot read files"):(t.phase=1,{k:"await",p:Qs(r,Js(e,r,t.args[0]),t.args[0])})});g("do-file",'["Runs the script in a file, as do does; a module is imported." file [file! url!]]',(e,t,n)=>{if(t.phase===2)return b(n);let r=ia.get(e.rt);if(r===void 0)return Q("access","no-loader","this host cannot read files");if(t.phase===0){let u=Js(e,r,t.args[0]);return t.data={href:u},t.phase=1,{k:"await",p:Qs(r,u,t.args[0])}}let{href:o}=t.data,a;try{a=me(B(n),{file:o})}catch(u){if(!(u instanceof rt))throw u;return Q("syntax","load",u.message)}let{header:i,start:l}=Ot(a);t.phase=2;let c=nu(i,pb);return c!==null&&c.t===s.Word&&I(c.sym)===bb?{k:"call",fn:xe({t:s.Word,sym:A("import"),bind:e.rt.lib}),args:[t.args[0]]}:(be(a.s,e.rt.user,!0),{k:"do",s:a.s,i:l})});g("import",'["Runs a module and gives its exports." source [file! url! string!]]',(e,t,n)=>{let r=e.rt,o=ia.get(r),a=Qc.get(r);if(o===void 0||a===void 0)return Q("access","no-loader","this host cannot load modules");if(t.phase===0){let u=Js(e,o,t.args[0]),d=a.get(u);if(d!==void 0)return d.obj!==null?b(d.obj):(t.phase=3,{k:"await",p:d.done});let f=()=>{},p=new Promise((v,y)=>{f=(C,x)=>C?v(x):y(x)});p.catch(()=>{});let h={obj:null,done:p,settle:f};return a.set(u,h),t.data={href:u,entry:h,ctx:null,exports:[]},/\.m?js$/i.test(new URL(u).pathname)?(t.phase=4,{k:"await",p:(o.importJs??(y=>import(y)))(u).then(y=>{let C=Xc(y);if(typeof C=="string")throw Y("script","bad-module",C);return C},y=>{throw Y("access","cannot-open",`cannot open ${Z(t.args[0])}: ${y?.message??String(y)}`)}).then(y=>(h.obj=y,h.settle(!0,y),y),y=>{throw a.delete(u),h.settle(!1,y),y})}):(t.phase=1,{k:"await",p:Qs(o,u,t.args[0]).catch(v=>{throw a.delete(u),h.settle(!1,v),v})})}if(t.phase===3||t.phase===4)return b(n);let i=t.data,l=u=>{a.delete(i.href),i.entry.settle(!1,u)};if(t.phase===1){let u;try{u=me(B(n),{file:i.href})}catch(y){if(!(y instanceof rt))throw y;let C=Q("syntax","load",y.message);return C.k==="throw"&&l(C.e.v),C}let{header:d,start:f}=Ot(u),p=nu(d,db);p!==null&&p.t===s.Block&&(i.exports=p.s.data.filter(y=>y.t===s.Word));let h=Me(u.s,f);i.exports.push(...hb(h));let v=Le();return v.self=!0,Wo(h,0,v),be(h,r.user,!0),be(h,v),Fr(h,v),i.ctx=v,t.phase=2,t.trap=1<<U.Error,{k:"do",s:h,i:0}}if(t.thrown!==null){let u=t.thrown;return t.thrown=null,l(u.v),{k:"throw",e:u}}let c={t:s.Object,ctx:i.ctx};for(let u of i.exports){let d=i.ctx.keys.findIndex(f=>I(f)===I(u.sym));if(d<0){let f=Q("script","bad-export",`${Z(u)} is exported but not defined`);return f.k==="throw"&&l(f.e.v),f}$e({t:s.Word,sym:u.sym,bind:r.user},i.ctx.vals[d])}return i.entry.obj=c,i.entry.settle(!0,c),b(c)});var Zs=new Map,ei=globalThis.localStorage??{getItem:e=>Zs.get(e)??null,setItem:(e,t)=>{Zs.set(e,t)},removeItem:e=>{Zs.delete(e)}},mb="trebol:",ti=e=>mb+(e.t===s.Word||e.t===s.LitWord?Z({...e,t:s.Word}):B(e));g("save-local",'["Keeps a value in the browser, under a key." key [string! word!] value [any-value!]]',(e,t)=>(ei.setItem(ti(t.args[0]),Z(t.args[1],{all:!0})),b(t.args[1])));g("load-local",'["The value kept in the browser under a key, or none." key [string! word!]]',(e,t)=>{let n=ei.getItem(ti(t.args[0]));if(n===null)return b(k);try{return b(me(n).s.data[0]??k)}catch(r){if(r instanceof rt)return b(k);throw r}});g("remove-local",'["Forgets the value kept in the browser under a key." key [string! word!]]',(e,t)=>(ei.removeItem(ti(t.args[0])),b(re)));var gb=1e4,ri=1,oi=new Map;function wn(e,t){let n=ri++;return oi.set(n,t),{t:s.Handle,p:{kind:e,id:n}}}function Et(e,t){if(e.t!==s.Handle)return null;let n=e.p;return n.kind===t?oi.get(n.id)??null:null}function ou(e){e.t===s.Handle&&oi.delete(e.p.id)}var au=new WeakMap;function su(e,t){let n={rt:e,ready:[],byTask:new WeakMap,onError:t,pumping:!1,live:0,afterPump:null};return au.set(e,n),n}function Rt(e){let t=au.get(e.rt);if(t===void 0)throw new Error("no scheduler for this runtime");return t}function Ft(e,t,n=0){let r=dr(e.rt,t,n),o={id:ri++,task:r,state:"ready",result:re,error:null,abort:null,watchers:[]};return e.byTask.set(r,o),e.live++,e.ready.push(o),Xr(e),o}function br(e,t,n){let r=Object.keys(n),o=Me(t.s,t.i);if(r.length>0){let a=Le(r.map(i=>A(i)),r.map(i=>n[i]));be(o,a)}return Ft(e,o,0)}var vb=(()=>{let e=globalThis;if(typeof e.setImmediate=="function")return r=>{e.setImmediate(r)};if(typeof MessageChannel>"u")return r=>{setTimeout(r,0)};let t=new MessageChannel,n=[];return t.port1.onmessage=()=>n.shift()?.(),r=>{n.push(r),t.port2.postMessage(null)}})();function Xr(e){e.pumping||(e.pumping=!0,vb(()=>yb(e)))}function ni(e,t,n){t.state=n,t.abort=null,e.live--,n==="failed"&&t.watchers.length===0&&e.onError(t.error,t);for(let r of t.watchers.splice(0))r(t)}function iu(e,t){let n=_r(t.task,gb);switch(n.k){case"done":t.result=n.v,ni(e,t,"done");break;case"error":t.error=n.e,ni(e,t,"failed");break;case"yield":return!0;case"await":t.state="waiting",n.p.then(r=>{t.state==="waiting"&&(t.abort=null,cs(t.task,r),t.state="ready",e.ready.push(t),Xr(e))},r=>{t.state==="waiting"&&(t.abort=null,us(t.task,kb(r)),t.state="ready",e.ready.push(t),Xr(e))});break}return!1}function yb(e){e.pumping=!1;let t=e.ready.splice(0);for(let n of t)n.state==="ready"&&iu(e,n)&&e.ready.push(n);e.afterPump?.(),e.ready.length>0&&Xr(e)}var wb=10;function lu(e,t,n=0){let r=dr(e.rt,t,n),o={id:ri++,task:r,state:"ready",result:re,error:null,abort:null,watchers:[]};e.byTask.set(r,o),e.live++;let a=!0;for(let i=0;a&&i<wb;i++)a=iu(e,o);return a&&(e.ready.push(o),Xr(e)),o}function kb(e){if(typeof e=="object"&&e!==null&&e.t===s.Error)return e;let t=e instanceof Error?e.message:String(e);return Y("access","host",t)}function cu(e,t){t.state==="done"||t.state==="failed"||t.state==="cancelled"||(t.abort?.(),t.error=Y("access","cancelled","the task was cancelled"),ni(e,t,"cancelled"))}function kn(e){return new Promise((t,n)=>{let r=o=>o.state==="done"?t(o.result):n(o.error??Y("access","cancelled","the task was cancelled"));e.state==="done"||e.state==="failed"||e.state==="cancelled"?r(e):e.watchers.push(r)})}var hr={line:e=>console.log(e)};g("write-line",'["Writes a value and a new line to the output." value [any-type!]]',(e,t)=>(hr.line(D(t.args[0])),b(re)));g("probe",'["Prints a value as mold shows it; gives the value." value [any-type!]]',(e,t)=>(hr.line(Z(t.args[0])),b(t.args[0])));function ai(e){return e.t===s.Time?e.v/1e6:e.t===s.Integer?pe.toNumber(e.v)*1e3:e.v*1e3}var xb=["year","month","day","time","zone","date","weekday","yearday"];g("now",'["The date and time now." /year /month /day /time /zone /date /weekday /yearday /precise /utc]',(e,t)=>{let n=new Date,r=u=>t.args[u].t===s.Logic,o=r(9)?0:-n.getTimezoneOffset(),a=new Date(n.getTime()+o*6e4),i=((a.getUTCHours()*60+a.getUTCMinutes())*60+a.getUTCSeconds())*1e9+(r(8)?a.getUTCMilliseconds()*1e6:0),l=fn({y:a.getUTCFullYear(),m:a.getUTCMonth()+1,d:a.getUTCDate(),time:i,zone:o}),c=xb.find((u,d)=>r(d));return b(c===void 0?l:St(l,Pl(c)))});g("wait",'["Waits a number of seconds, or for tasks to finish; other tasks run meanwhile." value [number! time! handle! block!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=t.args[0],a=Rt(e).byTask.get(e);if(r.t===s.Handle||r.t===s.Block){let c=(r.t===s.Block?r.s.data.slice(r.i).map(d=>d.t===s.Word?xe(d)??d:d):[r]).map(d=>Et(d,"task"));if(c.some(d=>d===null))return Q("script","bad-wait","wait needs tasks or a duration");let u=Promise.all(c.map(d=>kn(d)));return{k:"await",p:r.t===s.Block?u.then(d=>({t:s.Block,s:{data:d},i:0})):u.then(d=>d[0])}}let i=ai(r);return{k:"await",p:new Promise(l=>{let c=setTimeout(()=>l(k),i);a&&(a.abort=()=>clearTimeout(c))})}});g("spawn",'["Starts a task that evaluates a block on its own; gives a handle at once." body [block!]]',(e,t)=>{let n=t.args[0],r=Ft(Rt(e),n.s,n.i);return b(wn("task",r))});g("delay",'["Evaluates a block once, after a while; gives a handle." time [number! time!] body [block!]]',(e,t)=>{let n=Rt(e),r=t.args[1],o=setTimeout(()=>br(n,r,{}),ai(t.args[0]));return b(wn("timer",{stop:()=>clearTimeout(o)}))});g("every",'["Evaluates a block again and again, every so often; gives a handle." time [number! time!] body [block!]]',(e,t)=>{let n=Rt(e),r=t.args[1],o=setInterval(()=>br(n,r,{}),Math.max(1,ai(t.args[0])));return b(wn("timer",{stop:()=>clearInterval(o)}))});var si={timer:e=>e.stop()};g("cancel",'["Stops a task, timer or request." target [handle!]]',(e,t)=>{let n=t.args[0],r=n.p.kind;if(r==="task"){let a=Et(n,"task");return a!==null&&cu(Rt(e),a),b(re)}let o=Et(n,r);return o!==null&&si[r]?.(o),ou(n),b(re)});var mt={event:(e,t,n)=>{},request:(e,t,n,r,o)=>{},note:(e,t)=>{},repainted:()=>{}};function li(e){return wn("file",e)}g("read-file",'["The bytes of a file the user chose." file [handle!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=Et(t.args[0],"file");return r===null?Q("script","bad-handle","read-file needs a file from an upload field"):{k:"await",p:r.arrayBuffer().then(a=>Bo([...new Uint8Array(a)]),a=>{throw Y("access","read",`cannot read ${r instanceof File?r.name:"the file"}: ${a.message}`)})}});var Cb={csv:"text/csv",txt:"text/plain",json:"application/json",xml:"application/xml",html:"text/html",trb:"text/plain",md:"text/markdown",svg:"image/svg+xml",png:"image/png",jpg:"image/jpeg",pdf:"application/pdf",zip:"application/zip"},Sb={save:(e,t)=>{let n=globalThis.document;if(n===void 0)return!1;let r=URL.createObjectURL(t),o=n.createElement("a");return o.href=r,o.download=e,o.style.display="none",n.body.append(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(r),1e3),!0}};function Eb(e){let t=/filename\*\s*=\s*([^']*)'[^']*'([^;]+)/i.exec(e);if(t!==null)try{let r=t[2].trim();return/^utf-8$/i.test(t[1].trim())?decodeURIComponent(r):r.replace(/%([0-9a-f]{2})/gi,(o,a)=>String.fromCharCode(parseInt(a,16)))}catch{}let n=/filename\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^;]+))/i.exec(e);return n===null?"":n[1]!==void 0?n[1].replace(/\\(.)/g,"$1"):n[2].trim()}function ii(e,t){let n=te(e.ctx,A(t));return n<0?void 0:e.ctx.vals[n]}function uu(e,t){if(e===void 0||e.t!==s.Map)return"";let n=e.s.data;for(let r=0;r+1<n.length;r+=2)if(n[r].t===s.String&&B(n[r]).toLowerCase()===t)return D(n[r+1]);return""}g("download",'["Gives the user a file to save: text (as UTF-8), bytes, or the answer of fetch/with [full: true], under the name the server gives." name [file! string!] data [string! binary! object!]]',(e,t)=>{let n=B(t.args[0]).split("/").pop()??"",r=t.args[1],o="",a=!1;if(r.t===s.Object){let d=ii(r,"status"),f=ii(r,"headers"),p=ii(r,"body");if(d===void 0||d.t!==s.Integer||p===void 0)return Q("script","bad-answer","download needs an answer of fetch/with [full: true]");let h=pe.toNumber(d.v);if(h>=400)return Q("access","http",`HTTP ${h}: no file to save`);let v=Eb(uu(f,"content-disposition")).split(/[/\\]/).pop()??"";v!==""&&(n=v,a=!0),o=uu(f,"content-type"),r=p.t===s.Binary||p.t===s.String?p:j(Re(p))}if(n==="")return Q("script","bad-file","download needs a file name");let i=n.includes(".")?n.slice(n.lastIndexOf(".")+1).toLowerCase():"",l=Cb[i]??"application/octet-stream",c=r.t===s.Binary?new Uint8Array(r.s.data.slice(r.i)):(i==="csv"?"\uFEFF":"")+B(r),u=new Blob([c],{type:o!==""?o:r.t===s.Binary?l:`${l};charset=utf-8`});return Sb.save(n,u)?b(a?Ja(t.args[0].t===s.File?s.File:s.String,n):t.args[0]):Q("access","no-download","this host cannot give the user files")});function Yt(e,t){if(e===null)return null;let n=te(e.ctx,A(t)),r=n<0?void 0:e.ctx.vals[n];return r===void 0||r.t===s.None?null:r}var du=e=>e!==null&&!(e.t===s.Logic&&!e.v);function fu(e){let t=[],n=r=>r.t>=s.Word&&r.t<=s.Issue?M(r.sym):D(r);if(e.t===s.Block||e.t===s.Map){let r=e.s.data.slice(e.t===s.Block?e.i:0);for(let o=0;o+1<r.length;o+=2)t.push([n(r[o]),D(r[o+1])])}else e.t===s.Object&&e.ctx.keys.forEach((r,o)=>t.push([M(r),D(e.ctx.vals[o])]));return t}function Mb(e,t){if(/json/i.test(e)){let n=Gt(new TextDecoder().decode(t));return typeof n=="string"?j(new TextDecoder().decode(t)):n}return/^text\/|^[^;]*\/(?:xml|[^;]*\+xml)\s*(?:;|$)|javascript|x-www-form-urlencoded/i.test(e)||e===""?j(new TextDecoder().decode(t)):{t:s.Binary,s:{data:[...t]},i:0}}function Tb(e){return e.t===s.Time?e.v/1e9:e.t===s.Integer?pe.toNumber(e.v):e.v}async function Lb(e,t,n){let r=await fetch(e,t),o=[];r.headers.forEach((i,l)=>o.push([l,i]));let a;if(n===null||r.body===null)a=new Uint8Array(await r.arrayBuffer());else{let i=Number(r.headers.get("content-length")??NaN),l=Number.isFinite(i)&&r.headers.get("content-encoding")===null?i:null,c=[],u=0;n(0,l);for(let f=r.body.getReader();;){let{value:p,done:h}=await f.read();if(h)break;c.push(p),u+=p.length,n(u,l)}l===null&&n(u,u),a=new Uint8Array(u);let d=0;for(let f of c)a.set(f,d),d+=f.length}return{status:r.status,statusText:r.statusText,ok:r.ok,headers:o,bytes:a}}function Ab(e,t,n){return new Promise((r,o)=>{let a=new XMLHttpRequest;a.open(t.method??"GET",e),t.headers.forEach((l,c)=>a.setRequestHeader(c,l)),a.withCredentials=t.credentials==="include",a.responseType="arraybuffer";let i=l=>n(l.loaded,l.lengthComputable?l.total:null);t.body!==void 0&&(a.upload.onprogress=i),a.onprogress=i,a.onload=()=>{let l=a.getAllResponseHeaders().trim().split(/[\r\n]+/).filter(d=>d.includes(":")).map(d=>[d.slice(0,d.indexOf(":")).trim().toLowerCase(),d.slice(d.indexOf(":")+1).trim()]),c=a.status>=200&&a.status<300,u=a.response.byteLength;n(u,u),r({status:a.status,statusText:a.statusText,ok:c,headers:l,bytes:new Uint8Array(a.response)})},a.onerror=()=>o(new Error("network error")),a.onabort=()=>o(new Error("aborted")),t.signal?.addEventListener("abort",()=>a.abort()),a.send(t.body??null)})}function Ib(e,t){let n=Rt(e),r=0,o=(i,l)=>{if(t.t===s.Block){br(n,t,{done:i,total:l});return}let c=te(e.rt.user,A("show-progress")),u=c<0?void 0:e.rt.user.vals[c];u!==void 0&&Ft(n,{data:[u,t,i,l]},0)},a=i=>({t:s.Integer,v:i});return{tell:(i,l)=>{let c=Date.now();c-r<100&&i!==l||(r=c,o(a(i),l===null?k:a(l)))},end:()=>{t.t!==s.Block&&o(k,k)}}}g("http-request",'["Sends an HTTP request; used by fetch." url [url! string!] options [object! none!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=t.args[1].t===s.Object?t.args[1]:null,o=B(t.args[0]),a=Yt(r,"query");if(a!==null){let Fe=ra(a);if(Fe===null)return Q("script","bad-query","a query takes words or strings as names");let He=o.includes("#")?o.slice(o.indexOf("#")):"",Ue=o.slice(0,o.length-He.length);Fe!==""&&(o=Ue+(Ue.includes("?")?"&":"?")+Fe+He)}let i=Yt(r,"method"),l=new Headers,c=Yt(r,"headers");if(c!==null)for(let[Fe,He]of fu(c))l.set(Fe,He);let u,d=Yt(r,"body"),f=Yt(r,"form"),p=Yt(r,"multipart");if(f!==null)u=new URLSearchParams(fu(f));else if(p!==null){let Fe=new FormData,He=p.t===s.Block?p.s.data.slice(p.i):[];for(let Ue=0;Ue+1<He.length;Ue+=2){let Oe=He[Ue],W=He[Ue+1],ue=Oe.t>=s.Word&&Oe.t<=s.Issue?M(Oe.sym):D(Oe),ze=Et(W,"file");W.t===s.Binary?Fe.append(ue,new Blob([new Uint8Array(W.s.data.slice(W.i))]),ue):ze!==null?Fe.append(ue,ze,ze instanceof File?ze.name:ue):Fe.append(ue,D(W))}u=Fe}else d!==null&&(d.t===s.String?u=B(d):d.t===s.Binary?u=new Uint8Array(d.s.data.slice(d.i)):(u=Re(d),l.has("content-type")||l.set("content-type","application/json")));l.has("accept")||l.set("accept","application/json, text/*;q=0.9, */*;q=0.8");let h=Yt(r,"timeout"),v=du(Yt(r,"full")),y=Yt(r,"cookies"),C=y===null?"same-origin":du(y)?"include":"omit",x=new AbortController,w=!1,E=h!==null?setTimeout(()=>{w=!0,x.abort()},Tb(h)*1e3):null,S=Rt(e).byTask.get(e);S&&(S.abort=()=>x.abort());let T=i===null?u===void 0?"GET":"POST":D(i).toUpperCase(),V=Yt(r,"progress"),J=V===null?null:Ib(e,V);return{k:"await",p:(async()=>{let Fe=Date.now(),He=null,Ue=null;try{let Oe={method:T,headers:l,body:u,credentials:C,signal:x.signal},W=J!==null&&typeof XMLHttpRequest<"u"?await Ab(o,Oe,J.tell):await Lb(o,Oe,J===null?null:J.tell);He=W.status;let ue=W.headers.find(([fe])=>fe==="content-type")?.[1]??"",ze=Mb(ue,W.bytes);if(v){let fe=[];for(let[De,_e]of W.headers)fe.push(j(De),j(_e));return{t:s.Object,ctx:{keys:["status","headers","body"].map(De=>A(De)),vals:[{t:s.Integer,v:W.status},{t:s.Map,s:{data:fe}},ze],parent:null}}}if(!W.ok)throw Y("access","http",`HTTP ${W.status} ${W.statusText} for ${o}`);return ze}catch(Oe){throw Oe.t===s.Error?Oe:(Ue=w?"timed out":x.signal.aborted?"cancelled":Oe.message,w?Y("access","timeout",`request to ${o} timed out`):x.signal.aborted?Y("access","cancelled",`request to ${o} was cancelled`):Y("access","network",`cannot reach ${o}: ${Oe.message}`))}finally{E!==null&&clearTimeout(E),J?.end(),mt.request(T,o,He,Date.now()-Fe,Ue)}})()}});function pu(e){let t=e.trimStart();if(t.startsWith("{")||t.startsWith("[")){let n=Gt(e);if(typeof n!="string")return n}return j(e)}function Rn(e,t,n){let r=e.handlers[t];if(r===void 0){e.pending.push([t,n]);return}for(let o of r)br(e.sch,o,n)}g("open-socket",'["Opens a WebSocket; gives a handle once it is open." url [url! string!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=B(t.args[0]),o=Rt(e);return{k:"await",p:new Promise((i,l)=>{let c;try{c=new WebSocket(r)}catch(f){l(Y("access","network",`cannot open ${r}: ${f.message}`));return}c.binaryType="arraybuffer";let u={sch:o,handlers:{},pending:[],close:()=>c.close(),send:f=>c.send(f)},d=!1;c.onopen=()=>{d=!0,i(wn("stream",u))},c.onmessage=f=>{let p=typeof f.data=="string"?pu(f.data):{t:s.Binary,s:{data:[...new Uint8Array(f.data)]},i:0};Rn(u,"message",{value:p})},c.onerror=()=>{d?Rn(u,"error",{value:Y("access","network",`socket error on ${r}`)}):l(Y("access","network",`cannot open ${r}`))},c.onclose=f=>{d&&Rn(u,"close",{value:{t:s.Integer,v:f.code}})}})}});function $b(e,t){let n=e;for(;;){let r=/\r?\n\r?\n/.exec(n);if(r===null)return n;let o=n.slice(0,r.index);n=n.slice(r.index+r[0].length);let a="message",i=[];for(let l of o.split(/\r?\n/)){if(l.startsWith(":"))continue;let c=l.indexOf(":"),u=c<0?l:l.slice(0,c),d=c<0?"":l.slice(c+1).replace(/^ /,"");u==="event"?a=d:u==="data"&&i.push(d)}i.length>0&&t(a,i.join(`
378
+ `))}}g("open-events",'["Opens a stream of server-sent events; gives a handle." url [url! string!]]',(e,t)=>{let n=B(t.args[0]),r=Rt(e),o=new AbortController,a={sch:r,handlers:{},pending:[],close:()=>o.abort()},i=wn("stream",a);return(async()=>{try{let l=await fetch(n,{headers:{accept:"text/event-stream"},signal:o.signal});if(!l.ok||l.body===null)throw new Error(`HTTP ${l.status}`);let c=l.body.getReader(),u=new TextDecoder,d="";for(;;){let{done:f,value:p}=await c.read();if(f)break;d=$b(d+u.decode(p,{stream:!0}),(h,v)=>{Rn(a,"message",{value:pu(v),event:{t:s.Word,sym:A(h),bind:null}})})}Rn(a,"close",{value:k})}catch(l){o.signal.aborted||Rn(a,"error",{value:Y("access","network",`event stream ${n}: ${l.message}`)})}})(),b(i)});function ci(e){return(t,n)=>{let r=Et(n.args[0],"stream");if(r===null)return Q("script","bad-handle",`on-${e} needs a socket or event stream`);(r.handlers[e]??=[]).push(n.args[1]);let o=r.pending.filter(([a])=>a===e);r.pending=r.pending.filter(([a])=>a!==e);for(let[,a]of o)Rn(r,e,a);return b(n.args[0])}}g("on-message",'["Runs a block for each message that comes on a stream." stream [handle!] body [block!]]',ci("message"));g("on-close",'["Runs a block when a stream closes." stream [handle!] body [block!]]',ci("close"));g("on-error",'["Runs a block when a stream fails." stream [handle!] body [block!]]',ci("error"));g("send",'["Sends a value on a socket." stream [handle!] data [any-value!]]',(e,t)=>{let n=Et(t.args[0],"stream");if(n===null||n.send===void 0)return Q("script","bad-handle","send needs an open socket");let r=t.args[1];return n.send(r.t===s.String?B(r):r.t===s.Binary?new Uint8Array(r.s.data.slice(r.i)):Re(r)),b(t.args[0])});si.stream=e=>e.close();var bu=(e,t)=>(Et(t.args[0],"stream")?.close(),b(t.args[0]));g("close",'["Closes a stream, or hides a dialog." stream [handle!]]',bu);g("close-stream",'["Closes a socket or a stream of events." stream [handle!]]',bu);var hu=()=>globalThis.navigator,la={open:e=>{let t=globalThis.window;if(t===void 0)return!1;let n=t.open(e,"_blank");return n!==null&&(n.opener=null),!0},writeClipboard:e=>{let t=hu()?.clipboard;return t===void 0?null:t.writeText(e).then(()=>!0,()=>!1)},readClipboard:()=>{let e=hu()?.clipboard;return e===void 0?null:e.readText().then(t=>t,()=>null)}};g("browse",'["Opens a web address in a new tab." url [url! file!]]',(e,t)=>la.open(B(t.args[0]))?b(re):Q("access","no-browse","this host cannot open web addresses"));g("write-clipboard",'["Puts text on the clipboard; true when it is there." data [string!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=la.writeClipboard(B(t.args[0]));return r===null?Q("access","no-clipboard","this host has no clipboard"):{k:"await",p:r.then(ee)}});g("read-clipboard",'["The text on the clipboard, or none; the browser may ask the user first."]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=la.readClipboard();return r===null?Q("access","no-clipboard","this host has no clipboard"):{k:"await",p:r.then(o=>o===null||o===""?k:j(o))}});var Bb={gzip:"gzip",zlib:"deflate",deflate:"deflate-raw"};function mu(e){return Bb[M(I(e.sym)).toLowerCase()]??null}var gu=e=>e.t===s.Binary?new Uint8Array(e.s.data.slice(e.i)):new TextEncoder().encode(B(e));async function vu(e,t){let n=await new Response(new Blob([e]).stream().pipeThrough(t)).arrayBuffer();return Bo([...new Uint8Array(n)])}g("compress",'["Compresses bytes, or text as UTF-8, into a binary." data [binary! string!] method [word!] "gzip, zlib or deflate"]',(e,t,n)=>{if(t.phase===1)return b(n);let r=mu(t.args[1]);return r===null?Q("script","bad-method","compress takes gzip, zlib or deflate"):(t.phase=1,{k:"await",p:vu(gu(t.args[0]),new CompressionStream(r))})});g("decompress",'["The bytes that compress was given." data [binary!] method [word!] "gzip, zlib or deflate"]',(e,t,n)=>{if(t.phase===1)return b(n);let r=mu(t.args[1]);if(r===null)return Q("script","bad-method","decompress takes gzip, zlib or deflate");t.phase=1;let o=M(t.args[1].sym);return{k:"await",p:vu(gu(t.args[0]),new DecompressionStream(r)).catch(()=>{throw Y("script","bad-compression",`the data is not ${o} compressed`)})}});var di=new Set([s.Date,s.Time,s.Integer,s.Decimal,s.Percent,s.Money]),yu=1e6,Ob=24*3600*1e9;function Fn(e){try{return e()}catch{return null}}function ku(e,t){switch(e.t){case s.Integer:return Fn(()=>new Intl.NumberFormat(t).format(e.v));case s.Decimal:return Fn(()=>new Intl.NumberFormat(t,{maximumSignificantDigits:15}).format(e.v));case s.Percent:return Fn(()=>new Intl.NumberFormat(t,{style:"percent",maximumFractionDigits:2}).format(e.v));case s.Money:{let n=zt(e.v),r={minimumFractionDigits:2,maximumFractionDigits:Math.max(2,e.v.e)};return Fn(()=>new Intl.NumberFormat(t,e.cur!==""?{style:"currency",currency:e.cur,...r}:r).format(n))}case s.Date:{let n=e.v,r=Date.UTC(n.y,n.m-1,n.d)+(n.time??0)/yu,o={year:"numeric",month:"numeric",day:"numeric",timeZone:"UTC"};return n.time!==null&&Object.assign(o,{hour:"numeric",minute:"2-digit"}),n.y<100?null:Fn(()=>new Intl.DateTimeFormat(t,o).format(r))}case s.Time:{if(e.v<0||e.v>=Ob)return null;let n={hour:"numeric",minute:"2-digit",timeZone:"UTC"};return e.v%6e10!==0&&(n.second="2-digit"),Fn(()=>new Intl.DateTimeFormat(t,n).format(e.v/yu))}}return null}function Nb(e){let t=[];try{t=new Intl.NumberFormat(e).formatToParts(12345.6)}catch{}let n=r=>t.find(o=>o.type===r)?.value;return{decimal:n("decimal")??".",group:n("group")??","}}function fi(e,t){if(e.t!==s.Money)return e.t===s.None?"":D(e);let n=zt(e.v),r={useGrouping:!1,minimumFractionDigits:2,maximumFractionDigits:Math.max(2,e.v.e)};return Fn(()=>new Intl.NumberFormat(t,r).format(n))??zt(e.v)}function pi(e,t){let{decimal:n,group:r}=Nb(t),o=i=>i===n||i===r||i==="."||i===",",a=[...e].filter(i=>/[0-9+-]/.test(i)||o(i)).join("");if(a.includes(n)){let[i,...l]=a.split(n);if(l.length>1)return null;a=`${wu(i,r)}.${l[0]}`}else/^[+-]?\d{1,3}([.,]\d{3})+$/.test(a)&&[...a].filter(o).every(i=>i===r)?a=wu(a,r):[...a].filter(o).length===1&&(a=a.replace(/[.,]/,"."));return/^[+-]?(\d+\.?\d*|\.\d+)$/.test(a)?a:null}function wu(e,t){return e.split(t).join("")}function jb(e){let t=[];try{t=new Intl.DateTimeFormat(e,{timeZone:"UTC"}).formatToParts(Date.UTC(2026,10,23))}catch{}let n=t.map(r=>r.type[0]).filter(r=>r==="d"||r==="m"||r==="y").join("");return n.length===3?n:"dmy"}function bi(e,t){let n=e.trim().split(/[^0-9]+/).filter(u=>u!=="");if(n.length!==3)return null;let r=n[0].length===4?"ymd":jb(t),o=u=>Number(n[r.indexOf(u)]),a=o("y"),i=o("m"),l=o("d");n[r.indexOf("y")].length<=2&&(a+=2e3);let c=new Date(Date.UTC(a,i-1,l));return a<100||c.getUTCFullYear()!==a||c.getUTCMonth()!==i-1||c.getUTCDate()!==l?null:`${a}-${String(i).padStart(2,"0")}-${String(l).padStart(2,"0")}`}function ca(e){try{let t=new Intl.Locale(e),n=(t.getWeekInfo?.()??t.weekInfo)?.firstDay;return n!==void 0?n:["US","CA","MX","BR","JP","IL","PH"].includes(t.maximize().region??"")?7:1}catch{return 1}}function lt(e){let t=te(e.user,A("i18n")),n=t<0?null:e.user.vals[t];if(n===null||n.t!==s.Object)return"en";let r=n,o=te(r.ctx,A("language")),a=o<0?null:r.ctx.vals[o];return a?.t===s.Word||a?.t===s.LitWord?M(a.sym):a?.t===s.String?B(a):"en"}function ui(e,t){let n=te(e.user,A("i18n")),r=n<0?null:e.user.vals[n];if(r===null||r.t!==s.Object)return null;let o=te(r.ctx,A(t));return o<0?null:r.ctx.vals[o]}function Zt(e,t){let n=e.s.data,r=t.toLowerCase();for(let o=0;o+1<n.length;o+=2){let a=n[o],i=a.t===s.String?B(a):"sym"in a?M(a.sym):null;if(i!==null&&i.toLowerCase()===r)return n[o+1]}return null}function Ce(e,t){if(e.t===s.String)return B(e);if(e.t===s.Map){let n=ui(t,"main"),r=Zt(e,lt(t))??(n!==null&&"sym"in n?Zt(e,M(n.sym)):null)??e.s.data.find((o,a)=>a%2===1&&o.t===s.String)??null;return r===null?"":Ce(r,t)}if(e.t===s.Word||e.t===s.LitWord){let n=ui(t,"texts"),r=n?.t===s.Map?Zt(n,M(e.sym)):null;return r===null?M(e.sym):Ce(r,t)}return D(e)}function hi(e,t,...n){let r=ui(e,"ui"),o=r?.t===s.Map?Zt(r,t):null,a=o===null?t:Ce(o,e);return n.forEach((i,l)=>{a=a.replaceAll(`#${l+1}`,i)}),a}function ua(e,t){return ku(e,t)??D(e)}function mi(e,t){let n=["byte","kilobyte","megabyte","gigabyte"],r=e,o=0;for(;r>=1e3&&o<n.length-1;)r/=1e3,o++;try{let a=o===0?"long":"short";return new Intl.NumberFormat(t,{style:"unit",unit:n[o],unitDisplay:a,maximumFractionDigits:o===0?0:1}).format(r)}catch{return`${e} B`}}g("format-local",'["The value as text in the way of a language: dates, numbers, money." value [any-type!] language [word! string!]]',(e,t)=>{let n=t.args[1],r=n.t===s.String?B(n):M(n.sym);return b(j(ua(t.args[0],r)))});var Pb=String.raw`
379
379
  print: func ["Prints a value; a block is reduced first." value [any-type!]] [
380
380
  write-line either block? :value [reduce value] [:value]
381
381
  ]
@@ -390,14 +390,14 @@ fetch: func [
390
390
  ]
391
391
 
392
392
  show-progress: func [
393
- "Shows how far a request went on a face: a progress bar's value, or the bar of an upload."
393
+ "Shows how far a request went on a face: a progress bar's value, or the bar of an upload or a photo."
394
394
  face [object!]
395
395
  done [integer! none!] "Bytes done; none once the request is over"
396
396
  total [integer! none!] "Bytes in all, when known"
397
397
  /local part
398
398
  ][
399
399
  part: either all [done total total > 0] [done / to decimal! total] [none]
400
- either 'upload = select face 'style [face/sent: part] [if done [face/value: part]]
400
+ either find [upload photo] select face 'style [face/sent: part] [if done [face/value: part]]
401
401
  ]
402
402
 
403
403
  save: func [
@@ -514,12 +514,12 @@ source: func ["Prints the source of a function." 'word [any-word!] /local value]
514
514
  ]
515
515
  ]
516
516
  ]
517
- `;function ko(e){return j(e)}function ql(e={}){let t=e.onError??(s=>console.error(ko(s))),n=qa();Sl(n,e.loader??Ml());let r=Ga(n,pb,"host");if(r.k==="error")throw new Error(`host mezzanines failed: ${Tn(r.e)}`);let o=Bl(n,s=>t(s));return{rt:n,sch:o}}var xo=new URL("../ui/ui.trb",import.meta.url).href,wo=new URL("../ui/i18n.trb",import.meta.url).href;Xr.add("host").add(xo).add(wo);function Kl(e){return hs(e,`import ${wo} import ${xo}`)}function hs(e,t,n){let r=De(t,n!==void 0?{file:n}:{});return ve(r.s,e.rt.user,!0),Rn(Ht(e.sch,r.s,jt(r).start))}Ya(xo,`Trebol [
517
+ `;function Hn(e){return D(e)}function xu(e={}){let t=e.onError??(a=>console.error(Hn(a))),n=Ks();eu(n,e.loader??tu());let r=Vs(n,Pb,"host");if(r.k==="error")throw new Error(`host mezzanines failed: ${er(r.e)}`);let o=su(n,a=>t(a));return{rt:n,sch:o}}var da=new URL("../ui/ui.trb",import.meta.url).href,fa=new URL("../ui/i18n.trb",import.meta.url).href,gi=new URL("../ui/test.trb",import.meta.url).href;_o.add("host").add(da).add(fa).add(gi);function Cu(e){return vi(e,`import ${fa} import ${da}`)}function vi(e,t,n){let r=me(t,n!==void 0?{file:n}:{});return be(r.s,e.rt.user,!0),kn(Ft(e.sch,r.s,Ot(r).start))}pr(da,`Trebol [
518
518
  title: "UI dialect: faces, styles, layout and validation"
519
519
  exports: [
520
520
  face styles stylize layout view theme looks open close toast confirm print-page
521
- validate-face field-error form-values set-values ui-pane ui-input ui-files ui-remove-file ui-lookup-search ui-lookup-pick ui-lookup-remove ui-blur ui-click ui-select ui-sort ui-close ui-event ui-menu ui-drop ui-reorder ui-crumb ui-expand
522
- go go-back go-forward can-go-back? can-go-forward? ui-route set-language ui-rows
521
+ validate-face field-error form-values set-values insert-text ui-pane ui-input ui-files ui-remove-file ui-lookup-search ui-lookup-pick ui-lookup-remove ui-blur ui-click ui-select ui-sort ui-close ui-event ui-menu ui-drop ui-reorder ui-crumb ui-expand ui-orbit
522
+ go go-back go-forward can-go-back? can-go-forward? unsaved unsaved? ui-route set-language ui-rows ui-check ui-react
523
523
  ]
524
524
  ]
525
525
 
@@ -552,6 +552,14 @@ face: make object! [
552
552
  readonly: false ; shown and sent, but the user cannot change it, and no rule applies
553
553
  inert: false ; shown as it is, but neither it nor its children can be used
554
554
  linked: false ; a tile that stands for something kept elsewhere: marked with an arrow
555
+ round: false ; an image: cut to a circle, as for a person's photo
556
+ tag: none ; a widget: the name of the element it is, as the page's JavaScript defines it
557
+ props: none ; a widget: the element's properties, an object
558
+ poster: none ; a video: the image shown before it plays
559
+ captions: none ; a video: its captions, a .vtt file, or a block of one per language [en %a.vtt es %b.vtt]
560
+ looping: false ; a video or a sound starts again when it ends (loop in the dialect)
561
+ silent: false ; a video or a sound plays without its sound (muted in the dialect)
562
+ autoplay: false ; a video or a sound plays on its own, always silent, as browsers allow
555
563
  drag: false ; can be dragged: carries its value, or the row in a table, list or tree
556
564
  drop: false ; accepts drops (on-drop)
557
565
  reorder: false ; its children or rows can be moved around (on-reorder)
@@ -559,7 +567,7 @@ face: make object! [
559
567
  error: none ; current message, shown once the face is touched
560
568
  touched: false
561
569
  pending: false ; an asynchronous check is running
562
- sent: none ; an upload: how far its files went up, 0-1; none hides the bar
570
+ sent: none ; an upload or photo: how far its files went up, 0-1; none hides the bar
563
571
  async-error: none ; result of the last asynchronous check
564
572
  action: none ; the block after the face: click, change
565
573
  events: none ; [on-change [...] on-select [...]]
@@ -570,18 +578,18 @@ face: make object! [
570
578
  links: none ; a lookup: the screen each value links to when readonly, a map
571
579
  query: none ; a lookup: the text last searched for
572
580
  currency: none ; a money field's currency code: EUR
573
- calc: none ; a formula: the value comes from it and the user cannot change it
581
+ reactions: none ; react, is and calc: a block of reaction objects
574
582
  template: none ; rows: the block of the fields of one row
575
583
  built: none ; rows: what its rows were last made from
576
584
  owner: none ; a row of rows: the rows face it belongs to
577
585
  typed: none ; what the user typed in a number, money or date field when it is not one;
578
- ; in an upload, the names of the files it refused
586
+ ; in an upload or photo, the names of the files it refused
579
587
  multiple: false ; an upload or a lookup takes more than one
580
- accept: none ; the files an upload takes: ["pdf" "image/*"]
588
+ accept: none ; the files an upload takes: ["pdf" "image/*"]; a photo, images unless told
581
589
  pane: none
582
- columns: none ; table, list and tree: [field "Label" ...]
590
+ columns: none ; table, list and tree: [field "Label" ...]; a column of images, [field ["Label" image round]]
583
591
  data: none ; table, list and tree: a block of map! or object! rows (a tree's
584
- ; have their own in \`children\`); breadcrumb: its items
592
+ ; have their own in \`children\`); breadcrumb: its items; orbit: its focus, nodes, edges and trail
585
593
  key: 'id ; the row field that identifies a row
586
594
  selected: none ; the row last chosen
587
595
  sortable: false ; a table the host sorts, from the rows it has, when a header is chosen
@@ -593,6 +601,7 @@ face: make object! [
593
601
  extent: none ; a canvas: the size of its drawing space, a pair
594
602
  form: none ; the enclosing form, if any
595
603
  root: none ; the view this face belongs to
604
+ place: none ; where the face was written, file:line:col; none if made at run time
596
605
  submit: false
597
606
  ]
598
607
 
@@ -600,17 +609,18 @@ face: make object! [
600
609
  styles: make map! []
601
610
 
602
611
  container-styles: [view column row form panel grid dialog scroll split toolbar desktop]
603
- input-styles: [field password number money date area rich check toggle choice radio upload lookup rows]
612
+ input-styles: [field password number money date area rich check toggle choice radio upload photo lookup rows widget]
604
613
  data-styles: [table list tree chart]
605
614
 
606
615
  foreach [name base] [
607
616
  view column column column row row form form panel panel grid grid scroll scroll desktop desktop
608
617
  title title heading heading text text divider divider
609
618
  field field password password number number money money date date area area rich rich check check choice choice
610
- toggle toggle radio radio upload upload lookup lookup progress progress image image icon icon
619
+ toggle toggle radio radio upload upload photo photo lookup lookup progress progress image image backdrop backdrop icon icon
620
+ video video audio audio widget widget
611
621
  button button link link tile tile table table list list tabs tabs tab tab
612
622
  toolbar toolbar breadcrumb breadcrumb tree tree screens screens screen screen rows rows entry entry
613
- canvas canvas chart chart
623
+ canvas canvas chart chart orbit orbit
614
624
  ] [
615
625
  poke styles name make face [style: base]
616
626
  ]
@@ -630,7 +640,7 @@ stylize: function [
630
640
  parse spec [some [
631
641
  set name set-word! set base word! set defaults block! (
632
642
  proto: select styles base
633
- unless proto [do make error! rejoin ["stylize: unknown style " base]]
643
+ unless proto [do make error! rejoin ["stylize: unknown style " base ui-suggest base words-of styles]]
634
644
  poke styles to word! name make proto defaults
635
645
  )
636
646
  ]]
@@ -642,11 +652,13 @@ roles: [primary accent danger success warning muted]
642
652
  sizes: [small medium large]
643
653
  aligns: [left center right spread]
644
654
  valigns: [top middle bottom]
645
- flags: [fill fit hidden disabled readonly inert narrow-only wide-only linked drag drop reorder multiple sortable stacked]
655
+ flags: [fill fit hidden disabled readonly inert narrow-only wide-only linked round drag drop reorder multiple sortable stacked]
646
656
  chart-kinds: [bar line area pie]
647
657
  simple-rules: [required email url integer]
648
658
  letter: charset [#"a" - #"z" #"A" - #"Z"]
649
- rule-words: [min max length pattern match check check-async calc width pad gap menu accept known links sorted]
659
+ rule-words: [min max length pattern match check check-async calc react is width pad gap menu accept known links sorted poster captions]
660
+ media-styles: [video audio]
661
+ media-flags: [loop muted autoplay] ; of a video or a sound
650
662
 
651
663
  ; Words that never name a field. email, url and integer are rules too,
652
664
  ; but also common field names, so the first word after an input style names it.
@@ -666,6 +678,189 @@ event-word?: func [w [word!]] [
666
678
  to logic! find/match form w "on-"
667
679
  ]
668
680
 
681
+ ; --- problems in a layout -------------------------------------------------------
682
+ ;
683
+ ; layout reads the whole block and makes one error of every problem it finds,
684
+ ; each with the place it was loaded from (loaded-at) and a word it may mean.
685
+
686
+ ; [place message ...] while a block is laid out; none otherwise, and then a problem is an error at once.
687
+ ui-problems: none
688
+
689
+ ui-problem: func [place [block!] message [string!]] [
690
+ either ui-problems [append ui-problems reduce [place message]] [ui-fail reduce [place message]]
691
+ ]
692
+
693
+ ; The faces of a block, as build-faces gives them, or an error with every problem in it.
694
+ ui-build: function [spec [block!] labels [block!]] [
695
+ outer: ui-problems
696
+ set 'ui-problems copy []
697
+ out: try [build-faces spec labels]
698
+ found: ui-problems
699
+ set 'ui-problems outer
700
+ if error? out [do out]
701
+ unless empty? found [either ui-checking [append ui-checking found] [ui-fail found]]
702
+ out
703
+ ]
704
+
705
+ ; While ui-check runs: the problems of every block, and no code of the program is run.
706
+ ui-checking: none
707
+
708
+ ; It lays out each block after view or layout (styles of stylize first), and the
709
+ ; faces of each screen and row of rows, which a running app lays out only when shown.
710
+ ui-check: function [
711
+ "Every problem in the layouts of a program, without running it: [place message ...]"
712
+ code [block!]
713
+ /local b p
714
+ ] [
715
+ set 'ui-checking copy []
716
+ blocks: copy []
717
+ ; the blocks after view, layout and stylize, in code and in the blocks inside it
718
+ walk: function [code] [
719
+ parse code [any [
720
+ p: ['view | 'layout | 'stylize | path! if (find [view layout] first first p)]
721
+ ; view compose [...]: its parens stand for values check cannot know
722
+ opt ['compose | path! if ('compose = first first next p)]
723
+ set b block! (
724
+ append/only blocks reduce [first p b]
725
+ walk b
726
+ )
727
+ | set b [block! | paren!] (walk b)
728
+ | skip
729
+ ]]
730
+ ]
731
+ walk code
732
+ attempt-at: func [place body] [
733
+ if error? r: try body [append ui-checking reduce [place form r/message]]
734
+ ]
735
+ foreach p blocks [if 'stylize = first p [attempt-at next p [stylize copy/deep second p]]]
736
+ foreach p blocks [
737
+ unless 'stylize = first p [
738
+ attempt-at next p [
739
+ faces: all-faces layout second p
740
+ ; screens and rows lay these out when shown
741
+ while [not empty? faces] [
742
+ f: take faces
743
+ later: copy []
744
+ if f/style = 'screens [foreach [n t a b] f/data [append/only later b]]
745
+ if all [f/style = 'rows f/template] [append/only later f/template]
746
+ foreach b later [
747
+ spec: copy/deep b
748
+ parse spec [any [set w word! if (event-word? w) block!] body:]
749
+ foreach g ui-build body copy [] [append faces all-faces g]
750
+ ]
751
+ ]
752
+ ]
753
+ ]
754
+ ]
755
+ ; a screen or rows laid out twice (rows with min) gives its problems twice
756
+ found: copy []
757
+ seen: copy []
758
+ foreach [p m] ui-checking [
759
+ k: rejoin [any [loaded-at p ""] " " m]
760
+ unless find seen k [append seen k append found reduce [p m]]
761
+ ]
762
+ set 'ui-checking none
763
+ found
764
+ ]
765
+
766
+ ui-fail: function [found [block!] /local place m] [
767
+ either 2 = length? found [
768
+ message: rejoin ["layout: " second found]
769
+ ] [
770
+ places: collect [foreach [place m] found [keep any [loaded-at place ""]]]
771
+ wide: 0
772
+ foreach p places [wide: max wide length? p]
773
+ message: rejoin ["layout: " (length? found) / 2 " problems"]
774
+ i: 0
775
+ foreach [place m] found [
776
+ p: pick places i: i + 1
777
+ append message rejoin ["^/ " p append/dup copy "" #" " wide + 1 - length? p m]
778
+ ]
779
+ ]
780
+ e: make error! message
781
+ ; the first values from the place, one after another as near shows them
782
+ e/near: copy []
783
+ foreach v copy/part first found 3 [append/only e/near :v]
784
+ e/at: loaded-at first found
785
+ do e
786
+ ]
787
+
788
+ ; What a rule word takes, for a problem when what follows it is something else.
789
+ ui-takes: [
790
+ min "a number, an amount or a date" max "a number, an amount or a date" length "two integers"
791
+ pattern "a block" check "a block" check-async "a block" calc "a block" react "a block, after later or not" is "a block" accept "a block"
792
+ menu "a block" sorted "a block" known "a map" links "a map" match "the name of a field"
793
+ poster "a file or a url" captions "a file, a url or a block" width "small, medium, large or fill"
794
+ pad "a step from 0 to 7, none or wide" gap "a step from 0 to 7, none or wide" key "a text or a word"
795
+ ]
796
+
797
+ ; Every word the dialect knows, for ui-suggest.
798
+ ui-dialect-words: does [
799
+ unique compose [
800
+ (words-of styles) (roles) (sizes) (aligns) (valigns) (flags) (chart-kinds) (simple-rules)
801
+ (rule-words) (media-flags) required global key
802
+ ]
803
+ ]
804
+
805
+ ; The word near enough to w to be what it meant (buton: button), or none.
806
+ ui-nearest: function [w [word!] words [block!]] [
807
+ t: form w
808
+ most: either 4 < length? t [2] [1]
809
+ best: none
810
+ foreach c words [
811
+ d: ui-distance t form c
812
+ if all [d > 0 d <= most] [best: c most: d - 1]
813
+ ]
814
+ best
815
+ ]
816
+
817
+ ; "; did you mean button?" for buton, when one of the words is near enough; "" otherwise.
818
+ ui-suggest: function [w [word!] words [block!]] [
819
+ either best: ui-nearest w words [rejoin ["; did you mean " best "?"]] [""]
820
+ ]
821
+
822
+ ; Optimal string alignment distance: letters put in, taken out, changed, or two neighbours swapped.
823
+ ui-distance: function [a [string!] b [string!]] [
824
+ n: length? b
825
+ before: none
826
+ prev: copy []
827
+ repeat j n + 1 [append prev j - 1]
828
+ repeat i length? a [
829
+ row: reduce [i]
830
+ repeat j n [
831
+ d: min min (pick prev j + 1) + 1 (last row) + 1 (pick prev j) + either (pick a i) = (pick b j) [0] [1]
832
+ if all [i > 1 j > 1 (pick a i) = (pick b j - 1) (pick a i - 1) = (pick b j)] [
833
+ d: min d (pick before j - 1) + 1
834
+ ]
835
+ append row d
836
+ ]
837
+ before: prev
838
+ prev: row
839
+ ]
840
+ last prev
841
+ ]
842
+
843
+ ; A value as a problem shows it: its mold, cut when long.
844
+ ui-shown: function [v] [
845
+ t: mold :v
846
+ either 30 < length? t [append copy/part t 27 "..."] [t]
847
+ ]
848
+
849
+ ; The style a word after a face means when it is a mistyped one (feild: field), or none.
850
+ ui-meant-style: function [v] [
851
+ all [word? :v s: ui-nearest v ui-dialect-words select styles s s]
852
+ ]
853
+
854
+ ; The problem with a value that follows a face and means nothing to it.
855
+ ui-stray: function [f v] [
856
+ case [
857
+ all [word? :v t: select ui-takes v] [rejoin [v " takes " t]]
858
+ s: ui-meant-style :v [rejoin [v " is not a style; did you mean " s "?"]]
859
+ word? :v [rejoin [v " is not a word of " f/style ui-suggest v ui-dialect-words]]
860
+ true [rejoin [f/style " does not take " ui-shown :v]]
861
+ ]
862
+ ]
863
+
669
864
  ; Labels (\`search: field\`, \`table clients\`) are local to the layout, as R3
670
865
  ; planned for its VID: each layout gets an object holding them, and the
671
866
  ; layout's blocks (its handlers too) are bound to it. \`global search: field\`
@@ -681,7 +876,7 @@ layout: function [
681
876
  spec: copy/deep spec
682
877
  labels: copy []
683
878
  either only [
684
- out: build-faces spec labels
879
+ out: ui-build spec labels
685
880
  ] [
686
881
  ; on-xxx handlers and its width before the first face belong to the view itself
687
882
  events: copy []
@@ -690,7 +885,7 @@ layout: function [
690
885
  set ev word! if (event-word? ev) set b block! (append events reduce [ev b])
691
886
  | 'width set w ['small | 'medium | 'large | 'fill] (width: w)
692
887
  ] body:]
693
- out: make select styles 'view [pane: build-faces body labels]
888
+ out: make select styles 'view [pane: ui-build body labels]
694
889
  unless empty? events [out/events: events]
695
890
  out/size: width
696
891
  ]
@@ -721,18 +916,22 @@ text-of: func [t] [either lit-word? :t [to word! t] [t]]
721
916
  ; The faces of a block of the dialect; labels collects [word face ...].
722
917
  build-faces: function [
723
918
  spec [block!] labels [block!]
724
- /local label global? style-word f proto n s b w a i v ev p
919
+ /local label global? style-word f proto n s b w a i v ev p pos later
725
920
  ] [
726
921
  out: copy []
922
+ ; what starts the next face
923
+ face-start: [set-word! | 'global | set w word! if (select styles w)]
727
924
  modifier: [
728
- set s [string! | map!] (either f/text [f/hint: s] [f/text: s])
925
+ ; ui-check reads view compose [...] with its parens in it: menu (looks)
926
+ if (ui-checking) opt [set w word! if (select ui-takes w)] some paren!
927
+ | set s [string! | map!] (either f/text [f/hint: s] [f/text: s])
729
928
  ; a word of the dictionary: button 'save (in a link, a lit-word is the screen)
730
929
  | if (f/style <> 'link) set v lit-word! (v: to word! v either f/text [f/hint: v] [f/text: v])
731
930
  | set ev word! if (event-word? ev) set b block! (
732
931
  unless f/events [f/events: copy []]
733
932
  append f/events reduce [ev b]
734
933
  )
735
- | set b block! (
934
+ | pos: set b block! (
736
935
  case [
737
936
  ; grid [1 4 1] [...]: the weight of each column, then the children
738
937
  all [f/style = 'grid none? f/pane not empty? b parse b [some integer!]] [f/cols: b]
@@ -742,16 +941,20 @@ build-faces: function [
742
941
  ; --- in a toolbar is a separator
743
942
  f/pane: build-faces either f/style = 'toolbar [replace/all copy b '--- 'divider] [b] labels
744
943
  if all [f/style = 'split 2 <> length? f/pane] [
745
- do make error! "layout: split takes two faces, one per pane"
944
+ ui-problem pos "split takes two faces, one per pane"
746
945
  ]
747
946
  ]
748
947
  find data-styles f/style [f/columns: columns-of b]
749
948
  ; the first block holds the items, the second is the action
750
949
  all [f/style = 'breadcrumb none? f/data] [f/data: crumbs-of b]
950
+ ; orbit [focus ... nodes [...]]: what it shows; a second block is the action
951
+ all [f/style = 'orbit none? f/data] [f/data: orbit-of b]
952
+ ; widget <geo-map> [zoom: 12]: its properties; a second block is the action
953
+ all [f/style = 'widget none? f/props] [f/props: either ui-checking [make object! []] [make object! b]]
751
954
  f/style = 'canvas [f/draw: b]
752
955
  f/style = 'tabs [f/pane: tabs-of b labels]
753
956
  f/style = 'screens [f/data: screens-of b]
754
- find [choice radio] f/style [f/options: options-of b]
957
+ all [find [choice radio] f/style none? f/options] [f/options: options-of b]
755
958
  true [f/action: b]
756
959
  ]
757
960
  )
@@ -768,14 +971,22 @@ build-faces: function [
768
971
  | 'length set a integer! set n integer! (add-rule f reduce ['length a n])
769
972
  | 'pattern set b block! (add-rule f reduce ['pattern b])
770
973
  | 'accept set b block! (f/accept: b)
974
+ | 'poster set v [file! | url!] (f/poster: v)
975
+ | 'captions set v [file! | url! | block!] (f/captions: v)
976
+ ; muted names a role elsewhere, and loop a function, so a video keeps them in fields of its own
977
+ | set w word! if (all [find media-flags w find media-styles f/style]) (
978
+ poke f select [muted silent loop looping autoplay autoplay] w true
979
+ )
771
980
  | 'known set v map! (f/known: v)
772
981
  | 'links set v map! (f/links: v)
773
982
  | 'match set w word! (add-rule f reduce ['match w])
774
983
  | 'check set b block! (add-rule f reduce ['check b])
775
984
  | 'check-async set b block! (add-rule f reduce ['check-async b])
776
- | 'calc set b block! (f/calc: b f/readonly: true)
985
+ | 'calc set b block! (add-reaction f 'calc b false f/readonly: true)
986
+ | 'is set b block! (add-reaction f 'is b false)
987
+ | 'react (later: false) opt ['later (later: true)] set b block! (add-reaction f 'react b later)
777
988
  | 'width set w word! (f/size: w)
778
- | set w ['pad | 'gap] [set n integer! | 'none (n: 0) | 'wide (n: 6)] (poke f w spacing n)
989
+ | pos: set w ['pad | 'gap] [set n integer! | 'none (n: 0) | 'wide (n: 6)] (poke f w spacing n pos)
779
990
  | 'menu set b block! (f/menu: menu-of b)
780
991
  | 'key set s string! (f/shortcut: s)
781
992
  | 'key set w word! (f/key: w)
@@ -789,77 +1000,101 @@ build-faces: function [
789
1000
  ; money price "Price" EUR
790
1001
  | set w word! if (all [f/style = 'money parse form w [3 letter]]) (f/currency: to word! uppercase form w)
791
1002
  ]
792
- unless parse spec [
793
- any [
794
- (label: none global?: false)
795
- opt ['global (global?: true)]
796
- opt [set label set-word!]
797
- set style-word word! (
798
- proto: select styles style-word
799
- unless proto [do make error! rejoin ["layout: unknown style " style-word]]
1003
+ parse spec [any [
1004
+ (label: none global?: false)
1005
+ opt ['global (global?: true)]
1006
+ opt [set label set-word!]
1007
+ [
1008
+ ; a face that compose puts in: check takes what follows as words of a face it cannot know
1009
+ if (ui-checking) paren! (f: make face []) any modifier
1010
+ | pos: set style-word word! if (proto: select styles style-word) (
800
1011
  f: make proto []
1012
+ f/place: loaded-at pos
801
1013
  append out f
802
1014
  if label [label-face label labels global? f]
803
1015
  )
1016
+ ; widget <geo-map> place "Place": the element comes before the name
1017
+ opt [if (f/style = 'widget) set v tag! (f/tag: to string! v)]
804
1018
  opt [if (find input-styles f/style) set n word! if (field-name? n) (f/name: n)]
805
1019
  ; chart bar income [...]: the kind comes before the label
806
1020
  opt [if (f/style = 'chart) set n word! if (find chart-kinds n) (f/kind: n)]
807
1021
  ; table clients [...] is the same as clients: table [...]
808
- opt [if (find data-styles f/style) set n word! if (all [field-name? n n <> 'key]) (label-face n labels global? f)]
809
- any modifier
1022
+ opt [if (any [find data-styles f/style f/style = 'orbit]) set n word! if (all [field-name? n n <> 'key]) (label-face n labels global? f)]
1023
+ any [
1024
+ modifier
1025
+ ; a mistyped style starts a face of its own: what follows it is that face's
1026
+ | pos: not face-start skip (ui-problem pos ui-stray f first pos) opt [
1027
+ if (ui-meant-style first pos) any [not face-start skip]
1028
+ ]
1029
+ ]
810
1030
  (if f/style = 'rows [rows-fill f])
1031
+ ; not a style: a problem, then on to the next face
1032
+ | pos: skip (
1033
+ w: first pos
1034
+ ui-problem pos case [
1035
+ not word? :w [rejoin ["a face starts with a style, not " ui-shown :w]]
1036
+ find ui-dialect-words w [rejoin [w " is not a style; it goes after one"]]
1037
+ true [rejoin [w " is not a style" ui-suggest w words-of styles]]
1038
+ ]
1039
+ ) any [not face-start skip]
811
1040
  ]
812
- ] [
813
- do make error! "layout: cannot read the layout"
814
- ]
1041
+ ]]
815
1042
  out
816
1043
  ]
817
1044
 
818
- spacing: func [n [integer!]] [
819
- unless all [n >= 0 n <= 7] [do make error! "layout: pad and gap take a step from 0 to 7"]
820
- n
1045
+ spacing: func [n [integer!] place [block!]] [
1046
+ if all [n >= 0 n <= 7] [return n]
1047
+ ui-problem place rejoin [first place " takes a step from 0 to 7"]
1048
+ 0
821
1049
  ]
822
1050
 
823
1051
  ; [name "Name" email] -> [name "Name" email "email"]
824
- columns-of: function [spec [block!]] [
1052
+ ; A column of images keeps what it is with its label: [photo "" image round] -> [photo ["" image round]]
1053
+ columns-of: function [spec [block!] /local w label kind p] [
825
1054
  out: copy []
826
- unless parse spec [any [set w word! (label: form w) opt [set label text-rule] (append out reduce [w text-of label])]] [
827
- do make error! "layout: table columns are words, each with an optional label"
828
- ]
1055
+ parse spec [any [
1056
+ set w word! (label: form w kind: none) opt [set label text-rule]
1057
+ opt ['image (kind: copy [image]) opt ['round (append kind 'round)]]
1058
+ (
1059
+ label: text-of label
1060
+ append out w
1061
+ append/only out either kind [head insert/only kind label] [label]
1062
+ )
1063
+ | p: skip (ui-problem p "table columns are words, each with an optional label, then image or image round") to end
1064
+ ]]
829
1065
  out
830
1066
  ]
831
1067
 
832
1068
  ; [name desc] -> [name desc], checked
833
1069
  sort-order: function [b [block!]] [
834
- unless parse b [word! ['asc | 'desc]] [
835
- do make error! "layout: sorted takes a column and asc or desc"
836
- ]
1070
+ unless parse b [word! ['asc | 'desc]] [ui-problem b "sorted takes a column and asc or desc"]
837
1071
  copy b
838
1072
  ]
839
1073
 
840
1074
  ; ["General" [...] "Advanced" [...]] -> a tab face per pair
841
- tabs-of: function [spec [block!] labels [block!]] [
1075
+ tabs-of: function [spec [block!] labels [block!] /local p] [
842
1076
  out: copy []
843
- unless parse spec [any [set label text-rule set b block! (
844
- label: text-of label
845
- append out make select styles 'tab [text: label pane: build-faces b labels]
846
- )]] [
847
- do make error! "layout: tabs take a label and a block per tab"
848
- ]
1077
+ parse spec [any [
1078
+ set label text-rule set b block! (
1079
+ label: text-of label
1080
+ append out make select styles 'tab [text: label pane: build-faces b labels]
1081
+ )
1082
+ | p: skip (ui-problem p "tabs take a label and a block per tab") to end
1083
+ ]]
849
1084
  out
850
1085
  ]
851
1086
 
852
1087
  ; [home "Home" [...] client "Client" [id] [...]] -> [name title args body ...]
853
- screens-of: function [spec [block!] /local n t a b] [
1088
+ screens-of: function [spec [block!] /local n t a b p] [
854
1089
  out: copy []
855
- unless parse spec [some [
1090
+ if empty? spec [ui-problem spec "screens take a name, a title, an optional block of arguments and a block per screen"]
1091
+ parse spec [any [
856
1092
  set n word! set t text-rule (a: copy []) opt [ahead [block! block!] set a block!] set b block! (
857
- foreach w a [unless word? w [do make error! "layout: the arguments of a screen are words"]]
858
- append out reduce [n text-of t a b]
1093
+ forall a [unless word? first a [ui-problem a "the arguments of a screen are words"]]
1094
+ append out reduce [n text-of t head a b]
859
1095
  )
860
- ]] [
861
- do make error! "layout: screens take a name, a title, an optional block of arguments and a block per screen"
862
- ]
1096
+ | p: skip (ui-problem p "screens take a name, a title, an optional block of arguments and a block per screen") to end
1097
+ ]]
863
1098
  out
864
1099
  ]
865
1100
 
@@ -872,24 +1107,46 @@ menu-item: make object! [
872
1107
  ]
873
1108
 
874
1109
  ; As in Red: ["Edit" edit #trash "Delete" delete --- "Move to" ["Top" top]] -> menu items
875
- menu-of: function [spec [block!] /local i label w b] [
1110
+ menu-of: function [spec [block!] /local i label w b p] [
876
1111
  out: copy []
877
- unless parse spec [any [
1112
+ parse spec [any [
878
1113
  '--- (append out make menu-item [divider: true])
879
1114
  | (i: none) opt [set i issue!] set label text-rule (label: text-of label) [
880
1115
  set b block! (append out make menu-item [text: label icon: i items: menu-of b])
881
1116
  | set w word! (append out make menu-item [text: label icon: i id: w])
882
1117
  ]
883
- ]] [
884
- do make error! "layout: a menu takes a label and a word per item, a block for a submenu, or ---"
885
- ]
1118
+ | p: skip (ui-problem p "a menu takes a label and a word per item, a block for a submenu, or ---") to end
1119
+ ]]
886
1120
  out
887
1121
  ]
888
1122
 
1123
+ ; [focus id nodes [id "Title" [hints] ...] edges [from to "Label" [dashed] ...] trail [id ...]]
1124
+ ; The host reads the hints (a role or color, many, dashed, count n, steps n at k); this checks the shape.
1125
+ orbit-id: [word! | integer! | string! | issue!]
1126
+ orbit-of: function [spec [block!] /local b p] [
1127
+ parse spec [any [
1128
+ 'focus orbit-id
1129
+ | 'nodes set b block! (parse b [
1130
+ any [orbit-id text-rule opt block!]
1131
+ [end | p: (ui-problem p "nodes takes an id and a title for each, then a block of hints if it has any")]
1132
+ ])
1133
+ | 'edges set b block! (parse b [
1134
+ any [orbit-id orbit-id opt text-rule opt [into ['solid | 'dashed | 'faint]]]
1135
+ [end | p: (ui-problem p "edges takes two ids for each, then a label and [solid], [dashed] or [faint] if it has them")]
1136
+ ])
1137
+ | 'trail set b block! (parse b [
1138
+ any orbit-id [end | p: (ui-problem p "trail takes the ids of nodes, the most recent last")]
1139
+ ])
1140
+ | p: skip (ui-problem p "an orbit takes focus id, nodes [...], edges [...] and trail [...]") to end
1141
+ ]]
1142
+ copy spec
1143
+ ]
1144
+
889
1145
  ; ["Home" home "Clients" clients "Ada"]: a label and a word per item; the last one may have no word
890
- crumbs-of: function [spec [block!] /local label w] [
891
- unless parse spec [any [set label [string! | map!] set w [word! | path!]] opt [string! | map!]] [
892
- do make error! "layout: a breadcrumb takes a label and a word per item; only the last may have no word"
1146
+ crumbs-of: function [spec [block!] /local label w p] [
1147
+ parse spec [
1148
+ any [set label [string! | map!] set w [word! | path!]] opt [string! | map!]
1149
+ [end | p: (ui-problem p "a breadcrumb takes a label and a word per item; only the last may have no word")]
893
1150
  ]
894
1151
  copy spec
895
1152
  ]
@@ -897,6 +1154,7 @@ crumbs-of: function [spec [block!] /local label w] [
897
1154
  ; The options of a choice or radio: each reduced, and so are those of a group,
898
1155
  ; a title followed by a block: ["Bikes" ["Road" "City"] "Other"].
899
1156
  options-of: function [spec [block!]] [
1157
+ if ui-checking [return copy spec]
900
1158
  opts: reduce spec
901
1159
  forall opts [if block? first opts [change/only opts reduce first opts]]
902
1160
  opts
@@ -939,6 +1197,7 @@ view: function [
939
1197
  ; of the screen name and its arguments as strings, as they come in the link.
940
1198
 
941
1199
  router: none ; the screens face of the page
1200
+ marked: false ; the screen on show has changes not saved (unsaved)
942
1201
  page: none ; the root face of the view on show
943
1202
 
944
1203
  ; The [name title args body] of the screen a route names, or none.
@@ -959,13 +1218,16 @@ enter-screen: function [f route [block!] /local ev b] [
959
1218
  ; on-xxx handlers before the first face belong to the screen
960
1219
  events: copy []
961
1220
  parse spec [any [set ev word! if (event-word? ev) set b block! (append events reduce [ev b])] body:]
962
- s: make select styles 'screen [text: def/2 pane: build-faces body labels]
1221
+ s: make select styles 'screen [text: def/2 pane: ui-build body labels]
963
1222
  unless empty? events [s/events: events]
964
1223
  words: copy []
965
1224
  repeat i length? def/3 [append words reduce [to set-word! pick def/3 i pick route i + 1]]
966
1225
  bind-labels spec labels words
967
1226
  f/value: copy route
968
1227
  f/entering: true
1228
+ ; a screen starts with nothing to save
1229
+ set 'marked false
1230
+ set-unsaved false
969
1231
  f/pane: reduce [s]
970
1232
  ui-pane f
971
1233
  s
@@ -985,6 +1247,21 @@ run-enter: function [s] [
985
1247
  if error? :r [do :r]
986
1248
  ]
987
1249
 
1250
+ ; Whether the screen on show lets the page leave it: its on-leave says, false or
1251
+ ; 'continue (as Red's on-close) to stay; with no on-leave, a screen with unsaved
1252
+ ; changes asks the user. Both may wait for a dialog.
1253
+ may-leave?: function [/local s h r] [
1254
+ unless all [router s: first router/pane] [return true]
1255
+ if h: handler-for s 'on-leave [
1256
+ r: run-handler s h
1257
+ return not any [false = :r 'continue = :r]
1258
+ ]
1259
+ any [
1260
+ not marked
1261
+ confirm/with/role select i18n/ui 'leave-unsaved reduce [select i18n/ui 'leave select i18n/ui 'stay] 'danger
1262
+ ]
1263
+ ]
1264
+
988
1265
  ; Shows the screen of a link given as a block of strings; a link that names no
989
1266
  ; screen shows the first one and is replaced by its link.
990
1267
  follow-link: function [f parts [block!]] [
@@ -1006,6 +1283,7 @@ go: function [
1006
1283
  if block? target [foreach a reduce next target [append route form a]]
1007
1284
  if path? target [foreach a next to block! target [append route form a]]
1008
1285
  unless find-screen router route [do make error! rejoin ["go: no screen for " mold route]]
1286
+ unless may-leave? [exit]
1009
1287
  set-route route false
1010
1288
  run-enter enter-screen router route
1011
1289
  ]
@@ -1035,6 +1313,20 @@ can-go-forward?: function [
1035
1313
  0 < second route-steps
1036
1314
  ]
1037
1315
 
1316
+ unsaved: function [
1317
+ "Marks the screen on show as having changes not saved, or not: leaving it asks first, and so does closing the page."
1318
+ on [logic!]
1319
+ ] [
1320
+ set 'marked on
1321
+ set-unsaved on
1322
+ ]
1323
+
1324
+ unsaved?: function [
1325
+ "True if the screen on show has changes not saved (unsaved)."
1326
+ ] [
1327
+ marked
1328
+ ]
1329
+
1038
1330
  ui-route: function [
1039
1331
  "Called by the host when the page's link changes: back, forward or a link."
1040
1332
  f parts [block!]
@@ -1042,6 +1334,8 @@ ui-route: function [
1042
1334
  route: copy parts
1043
1335
  unless empty? route [route/1: attempt [to word! route/1]]
1044
1336
  if route = f/value [exit]
1337
+ ; the link has changed already: staying puts the screen's link back
1338
+ unless may-leave? [route-undo exit]
1045
1339
  run-enter follow-link f parts
1046
1340
  ]
1047
1341
 
@@ -1051,7 +1345,10 @@ ui-pane: function [
1051
1345
  ] [
1052
1346
  inner: either find [form entry] f/style [f] [f/form]
1053
1347
  foreach c any [f/pane []] [attach c f/root inner]
1054
- if f/root [refresh-form any [inner f/root]]
1348
+ unless f/root [exit]
1349
+ refresh-form any [inner f/root]
1350
+ ; and the forms among the new faces, whose submits start disabled until their fields are valid
1351
+ foreach c any [f/pane []] [foreach g all-faces c [if g/style = 'form [refresh-form g]]]
1055
1352
  ]
1056
1353
 
1057
1354
  open: func [
@@ -1194,6 +1491,20 @@ set-values: function [
1194
1491
  refresh-form scope
1195
1492
  ]
1196
1493
 
1494
+ insert-text: function [
1495
+ "Puts text where the cursor of a field, area or rich text was last, in place of what was selected, as if the user typed it."
1496
+ face [object!]
1497
+ text [string!]
1498
+ ] [
1499
+ unless find [field area rich] face/style [
1500
+ do make error! rejoin ["insert-text: a " face/style " has no cursor"]
1501
+ ]
1502
+ if any [face/readonly face/disabled empty? text] [exit]
1503
+ ; the host gives the value with the text in; at its end when the face has had no cursor
1504
+ ui-input face insert-at-caret face text
1505
+ face
1506
+ ]
1507
+
1197
1508
  field-error: function [
1198
1509
  "Shows a message on a named field until the user changes it: what a server refused. False if there is no such field."
1199
1510
  scope name [word! string!] text [string!]
@@ -1235,7 +1546,7 @@ rows-entry: function [f data] [
1235
1546
  labels: copy []
1236
1547
  set 'last-entry last-entry + 1
1237
1548
  e: make select styles 'entry [owner: f value: last-entry]
1238
- e/pane: build-faces spec labels
1549
+ e/pane: ui-build spec labels
1239
1550
  bind-labels spec labels copy []
1240
1551
  foreach g named-faces e [
1241
1552
  if f/readonly [g/readonly: true]
@@ -1325,23 +1636,169 @@ ui-rows: function [
1325
1636
  refresh-form any [f/form f/root]
1326
1637
  ]
1327
1638
 
1328
- ; Gives calculated fields their value, again while one depends on another.
1329
- recalc: function [scope] [
1330
- faces: own-faces scope
1331
- loop 5 [
1332
- again: false
1333
- foreach f faces [
1334
- if f/calc [
1335
- v: attempt [run-handler f f/calc]
1336
- unless :v = f/value [
1337
- f/value: :v
1338
- store-around f
1339
- again: true
1340
- ]
1639
+ ; --- reactions -------------------------------------------------------------------
1640
+ ;
1641
+ ; \`react [...]\` after a face runs the block when the face is shown, and again
1642
+ ; whenever a facet it reads changes: \`total/text\`, \`face/value\`, \`values/qty\`.
1643
+ ; Which facets it reads is found by reading the block, not by running it. The
1644
+ ; host checks them at the end of each round, before it repaints, against what
1645
+ ; they were when the block last ran. \`is [...]\` gives the face's main facet what
1646
+ ; the block gives, and \`calc [...]\` its value, which the user cannot change.
1647
+
1648
+ reaction: make object! [
1649
+ kind: 'react ; react, is or calc
1650
+ body: none
1651
+ later: false ; runs on a change only, not when the face is shown
1652
+ sources: none ; the [face facet ...] it reads, found the first time it is checked
1653
+ targets: none ; the [face facet ...] it sets, so that it runs before what reads them
1654
+ last: none ; what its sources were when it last ran
1655
+ ]
1656
+
1657
+ add-reaction: function [f k b l] [
1658
+ unless f/reactions [f/reactions: copy []]
1659
+ append f/reactions make reaction [kind: k body: b later: l]
1660
+ ]
1661
+
1662
+ value-styles: append copy input-styles [progress image video audio]
1663
+
1664
+ ; The facet \`is\` sets: data for a table, list, tree or chart, a canvas's draw,
1665
+ ; an input's value, and text for the rest.
1666
+ main-facet: func [f] [
1667
+ case [
1668
+ find data-styles f/style ['data]
1669
+ f/style = 'orbit ['data]
1670
+ f/style = 'canvas ['draw]
1671
+ find value-styles f/style ['value]
1672
+ true ['text]
1673
+ ]
1674
+ ]
1675
+
1676
+ face?: func [v] [all [object? :v in v 'style in v 'pane]]
1677
+
1678
+ ; Puts in out the face and facet a path names: name/facet (a label), face/facet
1679
+ ; (the face itself), values/field (the value of the field of that name).
1680
+ react-path: function [f p out [block!]] [
1681
+ w: first p
1682
+ unless all [word? :w word? pick p 2] [exit]
1683
+ facet: second p
1684
+ g: case [
1685
+ w = 'face [f]
1686
+ w = 'values [facet: 'value attempt [find-named f second p]]
1687
+ true [attempt [get w]]
1688
+ ]
1689
+ if all [face? :g in g facet] [append out reduce [g facet]]
1690
+ ]
1691
+
1692
+ react-scan: function [f b [block! paren!] sources [block!] targets [block!] /local v] [
1693
+ foreach v b [
1694
+ case [
1695
+ any [block? :v paren? :v] [react-scan f v sources targets]
1696
+ any [path? :v get-path? :v] [react-path f v sources]
1697
+ set-path? :v [react-path f v targets]
1698
+ ]
1699
+ ]
1700
+ ]
1701
+
1702
+ react-now: function [r /local g facet] [
1703
+ out: copy []
1704
+ foreach [g facet] r/sources [append/only out select g facet]
1705
+ out
1706
+ ]
1707
+
1708
+ ; Faces compare by content, so finding one in a block needs same?.
1709
+ find-same: function [b [block!] v] [
1710
+ foreach x b [if same? x v [return true]]
1711
+ false
1712
+ ]
1713
+
1714
+ react-due?: func [r] [not strict-equal? r/last react-now r]
1715
+
1716
+ ; True if a reaction sets something b reads.
1717
+ feeds?: function [a b /local g m h n] [
1718
+ foreach [g m] a/targets [
1719
+ foreach [h n] b/sources [if all [same? g h m = n] [return true]]
1720
+ ]
1721
+ false
1722
+ ]
1723
+
1724
+ react-run: function [f r] [
1725
+ if r/kind = 'react [
1726
+ run-handler f r/body
1727
+ exit
1728
+ ]
1729
+ m: either r/kind = 'calc ['value] [main-facet f]
1730
+ ; a formula that fails, or lacks a value, leaves the field empty
1731
+ v: either r/kind = 'calc [attempt [run-handler f r/body]] [run-handler f r/body]
1732
+ unless strict-equal? :v select f m [
1733
+ poke f m :v
1734
+ if m = 'value [store-around f]
1735
+ ]
1736
+ ]
1737
+
1738
+ ui-react: function [
1739
+ "Called by the host at the end of each round: runs the reactions of the faces whose facets they read changed. Gives the cycles it cut, as texts."
1740
+ faces [block! object!] "The faces, or a face to take every face in it"
1741
+ /local f r
1742
+ ] [
1743
+ if object? faces [faces: all-faces faces]
1744
+ fs: copy []
1745
+ rs: copy []
1746
+ foreach f faces [
1747
+ foreach r any [select f 'reactions []] [
1748
+ unless r/sources [
1749
+ r/sources: copy []
1750
+ r/targets: copy []
1751
+ react-scan f r/body r/sources r/targets
1752
+ if r/kind <> 'react [append r/targets reduce [f either r/kind = 'calc ['value] [main-facet f]]]
1753
+ ; none is never a list of values: due, so it runs when shown
1754
+ r/last: either r/later [react-now r] [none]
1755
+ ]
1756
+ append fs f
1757
+ append rs r
1758
+ ]
1759
+ ]
1760
+ cut: copy []
1761
+ failed: none
1762
+ ; a second cascade, for what the forms changed after the first (an error, a disabled submit)
1763
+ loop 2 [
1764
+ ran: copy []
1765
+ forever [
1766
+ due: copy []
1767
+ repeat i length? rs [if all [not find ran i react-due? pick rs i] [append due i]]
1768
+ if empty? due [break]
1769
+ ; the first that no other one due feeds; if they all feed each other, the first
1770
+ i: first due
1771
+ foreach j due [
1772
+ ok: true
1773
+ foreach k due [if all [k <> j feeds? pick rs k pick rs j] [ok: false break]]
1774
+ if ok [i: j break]
1775
+ ]
1776
+ r: pick rs i
1777
+ e: try [react-run pick fs i r none]
1778
+ if all [error? :e not failed] [failed: :e]
1779
+ r/last: react-now r
1780
+ append ran i
1781
+ ]
1782
+ if empty? ran [break]
1783
+ ; what reads again what changed after it ran is in a cycle: it waits for the next change
1784
+ foreach i ran [
1785
+ r: pick rs i
1786
+ if react-due? r [
1787
+ where: loaded-at r/body
1788
+ append cut rejoin [either where [rejoin [where " "]] [""] r/kind ": left out, what it reads changed again after it ran (a cycle)"]
1789
+ r/last: react-now r
1341
1790
  ]
1342
1791
  ]
1343
- unless again [break]
1792
+ scopes: copy []
1793
+ foreach i ran [
1794
+ f: pick fs i
1795
+ s: any [f/form f/root]
1796
+ if all [s not find-same scopes s] [append scopes s]
1797
+ ]
1798
+ foreach s scopes [refresh-form s]
1344
1799
  ]
1800
+ if failed [do :failed]
1801
+ cut
1345
1802
  ]
1346
1803
 
1347
1804
  ; --- validation ------------------------------------------------------------------
@@ -1393,6 +1850,7 @@ validate-face: function [
1393
1850
  ]
1394
1851
  if f/typed [
1395
1852
  if f/style = 'upload [return message 'accept reduce [list-of f/accept]]
1853
+ if f/style = 'photo [return either f/accept [message 'accept reduce [list-of f/accept]] [message 'images []]]
1396
1854
  return message select [number number money amount date date] f/style []
1397
1855
  ]
1398
1856
  if blank? :v [
@@ -1455,7 +1913,6 @@ refresh-form: function [scope] [
1455
1913
  ; the fields of a row count for the form its rows are in
1456
1914
  while [all [scope scope/style = 'entry]] [scope: any [scope/form scope/root]]
1457
1915
  unless all [scope find [form view] scope/style] [exit]
1458
- recalc scope
1459
1916
  ok: true
1460
1917
  faces: own-faces scope
1461
1918
  foreach f faces [
@@ -1534,6 +1991,7 @@ changed: function [f] [
1534
1991
 
1535
1992
  ; An upload's value is none or a block of objects [name size type file];
1536
1993
  ; file is a handle the host keeps, read with read-file or sent with multipart.
1994
+ ; A photo's is none, the object of the image chosen, or the address of one kept elsewhere.
1537
1995
  ui-files: function [
1538
1996
  "Called by the host when the user chooses or drops files: name size type file for each, and the names it refused."
1539
1997
  f files [block!] refused [block!]
@@ -1542,7 +2000,11 @@ ui-files: function [
1542
2000
  foreach [n s t h] files [keep make object! [name: n size: s type: t file: h]]
1543
2001
  ]
1544
2002
  unless empty? chosen [
1545
- f/value: either f/multiple [append copy any [f/value []] chosen] [copy/part chosen 1]
2003
+ f/value: case [
2004
+ f/style = 'photo [first chosen]
2005
+ f/multiple [append copy any [f/value []] chosen]
2006
+ true [copy/part chosen 1]
2007
+ ]
1546
2008
  ]
1547
2009
  f/typed: either empty? refused [none] [refused]
1548
2010
  f/touched: true
@@ -1550,12 +2012,15 @@ ui-files: function [
1550
2012
  ]
1551
2013
 
1552
2014
  ui-remove-file: function [
1553
- "Called by the host when the user removes the file at a position of an upload."
2015
+ "Called by the host when the user removes the file at a position of an upload, or a photo's."
1554
2016
  f index [integer!]
1555
2017
  ] [
1556
- files: remove at copy f/value index
1557
- f/value: either empty? head files [none] [head files]
2018
+ f/value: either f/style = 'photo [none] [
2019
+ files: remove at copy f/value index
2020
+ either empty? head files [none] [head files]
2021
+ ]
1558
2022
  f/typed: none
2023
+ f/touched: true
1559
2024
  changed f
1560
2025
  ]
1561
2026
 
@@ -1702,6 +2167,15 @@ ui-reorder: function [
1702
2167
  fire-event f 'on-reorder fields
1703
2168
  ]
1704
2169
 
2170
+ ui-orbit: function [
2171
+ "Called by the host when the user picks a node of an orbit: a neighbour, or one of the trail when back is true."
2172
+ f id back [logic!]
2173
+ ] [
2174
+ f/value: id
2175
+ ; with no on-back, stepping back is one more pick
2176
+ either all [back handler-for f 'on-back] [fire-event f 'on-back []] [if f/action [run-handler f f/action]]
2177
+ ]
2178
+
1705
2179
  ui-expand: function [
1706
2180
  "Called by the host when the user opens a node of a tree."
1707
2181
  f node
@@ -1718,7 +2192,7 @@ move-item: function [items [block!] from [integer!] to [integer!]] [
1718
2192
  insert/only at items to :x
1719
2193
  items
1720
2194
  ]
1721
- `);Ya(wo,`Trebol [
2195
+ `);pr(fa,`Trebol [
1722
2196
  title: "Languages: the active language, texts per language and a dictionary"
1723
2197
  exports: [i18n tr translated localize]
1724
2198
  ]
@@ -1742,6 +2216,7 @@ i18n: make object! [
1742
2216
  amount #(en: "Enter an amount" es: "Introduce un importe")
1743
2217
  date #(en: "Enter a valid date" es: "Introduce una fecha v\xE1lida")
1744
2218
  accept #(en: "Only #1 files" es: "Solo archivos #1")
2219
+ images #(en: "Only images" es: "Solo im\xE1genes")
1745
2220
  min #(en: "Must be at least #1" es: "Debe ser como m\xEDnimo #1")
1746
2221
  max #(en: "Must be at most #1" es: "Debe ser como m\xE1ximo #1")
1747
2222
  length #(en: "Must be between #1 and #2 characters" es: "Debe tener entre #1 y #2 caracteres")
@@ -1762,6 +2237,9 @@ i18n: make object! [
1762
2237
  resize-panes #(en: "Resize panes" es: "Cambiar el tama\xF1o de los paneles")
1763
2238
  breadcrumb #(en: "Breadcrumb" es: "Ruta de navegaci\xF3n")
1764
2239
  more-levels #(en: "Show more levels" es: "Mostrar m\xE1s niveles")
2240
+ orbit-more #(en: "+#1 more" es: "+#1 m\xE1s")
2241
+ orbit-first #(en: "Back to the first" es: "Volver a los primeros")
2242
+ orbit-back-to #(en: "Back to #1" es: "Volver a #1")
1765
2243
  choose-date #(en: "Choose date" es: "Elegir fecha")
1766
2244
  choose-date-of #(en: "#1: choose date" es: "#1: elegir fecha")
1767
2245
  previous-month #(en: "Previous month" es: "Mes anterior")
@@ -1773,8 +2251,14 @@ i18n: make object! [
1773
2251
  drop-file #(en: "or drop it here" es: "o su\xE9ltalo aqu\xED")
1774
2252
  drop-files #(en: "or drop them here" es: "o su\xE9ltalos aqu\xED")
1775
2253
  remove-file #(en: "Remove #1" es: "Quitar #1")
2254
+ choose-photo #(en: "Choose a photo" es: "Elegir una foto")
2255
+ change-photo #(en: "Change" es: "Cambiar")
2256
+ remove-photo #(en: "Remove" es: "Quitar")
1776
2257
  add-row #(en: "Add row" es: "A\xF1adir fila")
1777
2258
  remove-row #(en: "Remove row" es: "Quitar fila")
2259
+ leave-unsaved #(en: "Leave without saving?" es: "\xBFSalir sin guardar?")
2260
+ leave #(en: "Leave" es: "Salir")
2261
+ stay #(en: "Stay" es: "Quedarse")
1778
2262
  bold #(en: "Bold" es: "Negrita")
1779
2263
  italic #(en: "Italic" es: "Cursiva")
1780
2264
  heading #(en: "Heading" es: "T\xEDtulo")
@@ -1825,9 +2309,574 @@ localize: func [
1825
2309
  ] [
1826
2310
  format-local :value i18n/language
1827
2311
  ]
1828
- `);var be=(e,t={},n=[],r)=>{let o={};for(let[s,i]of Object.entries(t))o[s]=typeof i=="number"?Y(i):i;return r===void 0?{tag:e,attrs:o,kids:n}:{tag:e,attrs:o,kids:n,text:r}},Y=e=>String(Math.round(e*100)/100),Vl=["primary","accent","danger","success","warning","muted","text","border","surface","bg"],Co={red:{h:27,c:.2,light:.58,dark:.7},maroon:{h:15,c:.13,light:.38,dark:.58},orange:{h:55,c:.17,light:.68,dark:.76},brown:{h:50,c:.1,light:.45,dark:.62},gold:{h:85,c:.15,light:.76,dark:.8},yellow:{h:100,c:.17,light:.86,dark:.88},olive:{h:115,c:.12,light:.5,dark:.68},green:{h:145,c:.17,light:.6,dark:.74},teal:{h:185,c:.11,light:.58,dark:.72},aqua:{h:195,c:.12,light:.78,dark:.82},cyan:{h:210,c:.12,light:.72,dark:.8},sky:{h:235,c:.1,light:.75,dark:.8},blue:{h:260,c:.19,light:.55,dark:.7},navy:{h:265,c:.14,light:.32,dark:.55},violet:{h:290,c:.15,light:.62,dark:.75},purple:{h:305,c:.18,light:.5,dark:.68},magenta:{h:330,c:.24,light:.6,dark:.72},pink:{h:350,c:.13,light:.75,dark:.8},silver:{h:0,c:0,light:.8,dark:.75},gray:{h:0,c:0,light:.6,dark:.62},black:{h:0,c:0,light:.15,dark:.15},white:{h:0,c:0,light:1,dark:1}},Gl={pen:"pen color","fill-pen":"fill-pen color","line-width":"line-width number","line-cap":"line-cap flat | square | round","line-join":"line-join miter | round | bevel",font:"font [size: number bold italic]",line:"line point point ...",box:"box top-left bottom-right [corner-radius]",triangle:"triangle point point point",polygon:"polygon point point point ...",circle:"circle center radius [radius-y]",ellipse:"ellipse top-left size",arc:"arc center radius begin sweep [closed]",curve:"curve start control end, or curve start control control end",text:"text top-left string",translate:"translate offset",rotate:"rotate angle [center]",scale:"scale x y",push:"push [commands]"},fb={pen:"var(--tb-text)",fill:null,width:1,cap:"butt",join:"miter",size:15,bold:!1,italic:!1};function hb(e){if(e==="off"||e==="none"||e==="transparent")return null;if(Vl.includes(e))return`var(--tb-${e})`;if(Co[e]!==void 0)return`var(--tb-c-${e})`}var Fn=class extends Error{};function Zl(e){let t=[];if(e.t!==a.Block)return{kids:t,error:e.t===a.None?null:"draw takes a block"};try{return Yl(e,{...fb},t),{kids:t,error:null}}catch(n){if(n instanceof Fn)return{kids:t,error:n.message};throw n}}function Yl(e,t,n){let r=e.s.data,o=e.i,s=n,i=M=>M!==void 0&&(M.t===a.Word||M.t===a.LitWord)?E(M.sym).toLowerCase():null,l=M=>M===void 0?null:M.t===a.Integer?he.toNumber(M.v):M.t===a.Decimal?M.v:null,c=M=>{throw new Fn(`draw: ${M} is written ${Gl[M]}`)},u=M=>{let w=r[o];return w===void 0||w.t!==a.Pair?c(M):(o++,[w.x,w.y])},d=()=>{let M=r[o];return M===void 0||M.t!==a.Pair?null:(o++,[M.x,M.y])},f=M=>{let w=l(r[o]);return w===null?c(M):(o++,w)},p=()=>{let M=l(r[o]);return M!==null&&o++,M},h=(M,w)=>{let v=[];for(let C=d();C!==null;C=d())v.push(C);return v.length<w&&c(M),v},y=M=>({fill:M&&t.fill!==null?t.fill:"none",stroke:t.pen??"none","stroke-width":t.width,"stroke-linecap":t.cap,"stroke-linejoin":t.join}),k=M=>M.map(([w,v])=>`${Y(w)},${Y(v)}`).join(" ");for(;o<r.length;){let M=r[o],w=i(M);if(w===null||Gl[w]===void 0)throw new Fn(w===null?`draw: a command was expected, not ${gb(M)}`:`draw: unknown command ${w}`);switch(o++,w){case"pen":case"fill-pen":{let v=i(r[o]),C=v===null?void 0:hb(v);if(C===void 0)throw new Fn(`draw: ${w} takes a role (${Vl.join(" ")}), a color (${Object.keys(Co).join(" ")}) or off`);o++,w==="pen"?t.pen=C:t.fill=C;break}case"line-width":t.width=Math.max(0,f(w));break;case"line-cap":{let v=i(r[o]);v!=="flat"&&v!=="square"&&v!=="round"&&c(w),o++,t.cap=v==="flat"?"butt":v;break}case"line-join":{let v=i(r[o]);v!=="miter"&&v!=="round"&&v!=="bevel"&&c(w),o++,t.join=v;break}case"font":{let v=r[o];(v===void 0||v.t!==a.Block)&&c(w),o++;let C=v.s.data.slice(v.i);for(let S=0;S<C.length;S++){let I=C[S];I.t===a.SetWord&&E(I.sym).toLowerCase()==="size"&&l(C[S+1])!==null?t.size=l(C[++S]):i(I)==="bold"?t.bold=!0:i(I)==="italic"?t.italic=!0:i(I)==="plain"?t.bold=t.italic=!1:c(w)}break}case"line":s.push(be("polyline",{points:k(h(w,2)),...y(!1)}));break;case"triangle":{let v=h(w,3);v.length!==3&&c(w),s.push(be("polygon",{points:k(v),...y(!0)}));break}case"polygon":s.push(be("polygon",{points:k(h(w,3)),...y(!0)}));break;case"box":{let[v,C]=u(w),[S,I]=u(w),H=p(),z={x:Math.min(v,S),y:Math.min(C,I),width:Math.abs(S-v),height:Math.abs(I-C),...y(!0)};H!==null&&(z.rx=H),s.push(be("rect",z));break}case"circle":{let[v,C]=u(w),S=f(w),I=p();s.push(I===null?be("circle",{cx:v,cy:C,r:S,...y(!0)}):be("ellipse",{cx:v,cy:C,rx:S,ry:I,...y(!0)}));break}case"ellipse":{let[v,C]=u(w),[S,I]=u(w);s.push(be("ellipse",{cx:v+S/2,cy:C+I/2,rx:S/2,ry:I/2,...y(!0)}));break}case"arc":{let[v,C]=u(w),[S,I]=u(w),H=f(w),z=f(w),fe=i(r[o])==="closed";fe&&o++,s.push(be("path",{d:mb(v,C,S,I,H,z,fe),...y(fe)}));break}case"curve":{let v=h(w,3);v.length>4&&c(w);let[C,...S]=v,I=`M${Y(C[0])},${Y(C[1])} ${S.length===2?"Q":"C"}${k(S)}`;s.push(be("path",{d:I,...y(!1)}));break}case"text":{let[v,C]=u(w),S=r[o];(S===void 0||S.t!==a.String)&&c(w),o++;let I={x:v,y:C,"dominant-baseline":"hanging",fill:t.pen??"none","font-size":t.size,"font-family":"var(--tb-font)"};t.bold&&(I["font-weight"]="bold"),t.italic&&(I["font-style"]="italic"),s.push(be("text",I,[],$(S)));break}case"translate":case"rotate":case"scale":{let v;if(w==="translate"){let[S,I]=u(w);v=`translate(${Y(S)} ${Y(I)})`}else if(w==="rotate"){let S=f(w),I=d();v=I===null?`rotate(${Y(S)})`:`rotate(${Y(S)} ${Y(I[0])} ${Y(I[1])})`}else{let S=f(w),I=p()??S;v=`scale(${Y(S)} ${Y(I)})`}let C=be("g",{transform:v});s.push(C),s=C.kids;break}case"push":{let v=r[o];(v===void 0||v.t!==a.Block)&&c(w),o++;let C=be("g");s.push(C),Yl(v,{...t},C.kids);break}}}}function mb(e,t,n,r,o,s,i){let l=k=>{let M=k*Math.PI/180;return[e+n*Math.cos(M),t+r*Math.sin(M)]};if(Math.abs(s)>=360){let[k,M]=l(o),[w,v]=l(o+180);return`M${Y(k)},${Y(M)} A${Y(n)},${Y(r)} 0 1 1 ${Y(w)},${Y(v)} A${Y(n)},${Y(r)} 0 1 1 ${Y(k)},${Y(M)}${i?" Z":""}`}let[c,u]=l(o),[d,f]=l(o+s),p=Math.abs(s)>180?1:0,h=s>=0?1:0,y=`A${Y(n)},${Y(r)} 0 ${p} ${h} ${Y(d)},${Y(f)}`;return i?`M${Y(e)},${Y(t)} L${Y(c)},${Y(u)} ${y} Z`:`M${Y(c)},${Y(u)} ${y}`}function gb(e){return e.t===a.String?"a string":e.t===a.Pair?"a pair":e.t===a.Integer||e.t===a.Decimal?"a number":"that"}var ms={base:250,accent:30,neutral:"neutral",density:"normal",radius:"soft",font:"inter",headings:null,mode:"auto",color:1,line:1,depth:"soft",icons:"round",skin:"modern"},Jl={neutral:["cool","neutral","warm"],density:["compact","normal","comfortable"],radius:["sharp","soft","round"],mode:["light","dark","auto"],depth:["flat","soft","lifted"],icons:["fine","round","sharp","bold"],skin:["modern","classic","cupertino","fusion","fluent"]},gs={minimal:{},paper:{base:40,accent:150,neutral:"warm",headings:"serif",radius:"sharp",depth:"flat",icons:"fine"},civic:{base:255,accent:75,neutral:"cool",font:"system",radius:"sharp",line:2,depth:"flat",icons:"sharp"},soft:{base:175,accent:30,density:"comfortable",radius:"round",depth:"lifted",icons:"round"},ink:{color:0,font:"system",headings:"mono",radius:"sharp",line:2,depth:"flat",icons:"bold"},classic:{base:240,accent:45,color:.7,font:"sans",density:"compact",radius:"sharp",depth:"flat",icons:"sharp",skin:"classic"},cupertino:{base:255,accent:330,font:"system",radius:"soft",depth:"soft",icons:"round",skin:"cupertino"},fusion:{base:240,accent:30,color:.8,font:"noto",radius:"sharp",depth:"flat",icons:"sharp",skin:"fusion"},fluent:{base:250,accent:25,font:"segoe",radius:"soft",depth:"soft",icons:"fine",skin:"fluent"}},vb=new Set(["fluent"]),yb={cupertino:{bg:[.945,.23],surface:[1,.29],raised:[.925,.26],border:[.86,.37],"border-strong":[.76,.45],muted:[.48,.74],primary:[.52,.7]},fusion:{bg:[.95,.31],surface:[1,.25],raised:[.95,.31],border:[.84,.24],"border-strong":[.7,.2],muted:[.46,.76],primary:[.5,.72]},fluent:{bg:[.955,.2],surface:[.995,.27],raised:[.985,.24],border:[.9,.33],"border-strong":[.78,.42],muted:[.47,.74],primary:[.48,.78]}},kb=["bg","surface","raised","border","border-strong","text","muted","primary","primary-hover","on-primary","accent","on-accent","danger","on-danger","success","warning","focus"];var xb={cool:255,neutral:0,warm:70},wb={cool:.012,neutral:0,warm:.01};function Cb(e,t){let n=Sb(e,t),r=yb[e.skin];if(r===void 0)return n;let o=t?1:0;for(let s of["bg","surface","raised","border","border-strong","muted"]){let i=r[s][o];n[s]={l:i,c:i>=.99||!vb.has(e.skin)?0:n.bg.c,h:n.bg.h}}return n.primary={...n.primary,l:r.primary[o]},n["primary-hover"]={...n["primary-hover"],l:r.primary[o]+(t?.05:-.05)},n}function Sb(e,t){let n=e.neutral==="neutral"?e.base:xb[e.neutral],r=(e.neutral==="neutral"?.006:wb[e.neutral])*e.color,o=e.color===0,s=(c,u=1)=>({l:c,c:r*u,h:n}),i=(c,u,d)=>({l:c,c:u,h:d}),l=(c,u,d)=>({l:c,c:u*e.color,h:d});return e.skin==="classic"?{bg:s(t?.33:.85,2),surface:s(t?.25:1,t?2:0),raised:s(t?.33:.85,2),border:s(t?.22:.7,2),"border-strong":s(t?.18:.52,2),text:s(t?.95:.18,t?1:3),muted:s(t?.8:.38,3),primary:l(t?.8:.45,.12,e.base),"primary-hover":l(t?.85:.4,.12,e.base),"on-primary":s(t?.18:1,t?2:0),accent:l(t?.8:.48,.13,e.accent),"on-accent":s(t?.18:1,t?2:0),danger:i(t?.75:.5,t?.15:.18,25),"on-danger":s(t?.18:1,t?2:0),success:i(t?.76:.48,.13,150),warning:i(t?.8:.78,.14,75),focus:l(t?.75:.5,.15,e.base)}:t?{bg:s(.16,2),surface:s(.2,2),raised:s(.23,2),border:s(.32,2),"border-strong":s(.42,2),text:s(.94,1),muted:s(.72,2),primary:l(o?.94:.74,.13,e.base),"primary-hover":l(o?.84:.8,.11,e.base),"on-primary":s(.18,2),accent:l(.74,.13,e.accent),"on-accent":s(.18,2),danger:i(.72,.15,25),"on-danger":s(.18,2),success:i(.74,.13,150),warning:i(.8,.13,75),focus:l(.72,.15,e.base)}:{bg:s(.975,1.2),surface:s(1,0),raised:s(1,0),border:s(.9,1.5),"border-strong":s(.8,2),text:s(.24,3),muted:s(.5,3),primary:l(o?.24:.5,.16,e.base),"primary-hover":l(o?.36:.45,.15,e.base),"on-primary":s(1,0),accent:l(.5,.15,e.accent),"on-accent":s(1,0),danger:i(.52,.18,25),"on-danger":s(1,0),success:i(.52,.13,150),warning:i(.78,.14,75),focus:l(.62,.17,e.base)}}var lt=(e,t)=>`oklch(${(e.l*100).toFixed(1)}% ${e.c.toFixed(3)} ${e.h.toFixed(1)}${t===void 0?"":` / ${t}`})`,Mb=[0,4,8,12,16,24,32,48],Eb={classic:34,cupertino:30,fusion:30,fluent:32},Tb={compact:.85,normal:1,comfortable:1.2},Ib={sharp:2,soft:8,round:16},Lb={fine:{stroke:1.5,cap:"round",join:"round"},round:{stroke:2,cap:"round",join:"round"},sharp:{stroke:2,cap:"square",join:"miter"},bold:{stroke:2.75,cap:"butt",join:"miter"}},gr={inter:'Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',sans:'"Helvetica Neue", Helvetica, Arial, sans-serif',noto:'"Noto Sans", "DejaVu Sans", Ubuntu, Cantarell, "Segoe UI", Roboto, sans-serif',segoe:'"Segoe UI Variable Text", "Segoe UI Variable", "Segoe UI", ui-sans-serif, system-ui, sans-serif',system:'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',serif:'ui-serif, Georgia, Cambria, "Times New Roman", serif',mono:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"};function Xl(e,t){let n=Cb(e,t),r=kb.map(l=>` --tb-${l}: ${lt(n[l])};`);r.push(` --tb-focus-ring: ${lt(n.focus,t?.5:.35)};`),r.push(` --tb-danger-soft: ${lt(n.danger,t?.16:.08)};`),r.push(` --tb-primary-soft: ${lt(n.primary,t?.16:.08)};`),r.push(` --tb-overlay: ${lt(vr(n),t?.6:.4)};`);let o=t?"0 0 0 1px oklch(100% 0 0 / 0.06)":`0 1px 2px ${lt(vr(n),.06)}`,s=e.depth==="lifted"?2:1;r.push(` --tb-shadow-1: ${e.depth==="flat"?"none":`${o}, 0 ${s}px ${3*s}px ${lt(vr(n),t?.4:.08)}`};`),r.push(` --tb-shadow-2: ${e.depth==="flat"?"none":`${o}, 0 ${4*s}px ${12*s}px ${lt(vr(n),t?.5:.08)}`};`),r.push(` --tb-shadow-3: ${o}, 0 ${12*s}px ${32*s}px ${lt(vr(n),t?.6:.12)};`);let i=l=>lt({l,c:n.bg.c,h:n.bg.h});e.skin==="classic"&&(r.push(` --tb-bevel-hi: ${i(t?.5:1)};`,` --tb-bevel-lo: ${i(t?.15:.55)};`),r.push(` --tb-face-hi: ${i(t?.47:.97)};`,` --tb-face-lo: ${i(t?.36:.8)};`)),e.skin==="cupertino"&&r.push(` --tb-segment: ${i(t?.47:1)};`),e.skin==="fusion"&&r.push(` --tb-face-hi: ${i(t?.37:.99)};`,` --tb-face-lo: ${i(t?.32:.91)};`),e.skin==="fluent"&&r.push(` --tb-focus-ring: ${lt(n.text)};`,` --tb-subtle: ${lt(n.text,t?.08:.06)};`);for(let[l,c]of Object.entries(Co))r.push(` --tb-c-${l}: ${lt({l:t?c.dark:c.light,c:c.c,h:c.h})};`);return r.push(` color-scheme: ${t?"dark":"light"};`),r.join(`
1829
- `)}var vr=e=>({l:.2,c:e.text.c,h:e.text.h});function Ab(e){let t=Tb[e.density],n=Mb.map((i,l)=>` --tb-space-${l}: ${Math.round(i*t)}px;`),r=Ib[e.radius];n.push(` --tb-radius: ${r}px;`,` --tb-radius-lg: ${Math.round(r*1.5)}px;`);let o=Eb[e.skin];n.push(` --tb-control: ${o!==void 0?Math.round(o*t):Math.max(40,Math.round(44*t))}px;`),n.push(` --tb-font: ${gr[e.font]??`"${e.font}", ${gr.system}`};`),n.push(` --tb-headings: ${e.headings===null?"var(--tb-font)":gr[e.headings]??`"${e.headings}", ${gr.system}`};`),n.push(` --tb-mono: ${gr.mono};`),n.push(` --tb-line: ${e.line}px;`);let s=Lb[e.icons];return n.push(` --tb-icon-stroke: ${s.stroke};`,` --tb-icon-cap: ${s.cap};`,` --tb-icon-join: ${s.join};`),n.push(" --tb-ease: cubic-bezier(0.2, 0, 0, 1);"," --tb-fast: 150ms;"),n.join(`
1830
- `)}function Ql(e){let t=Xl(e,!1),n=Xl(e,!0),r;return e.mode==="light"?r=`:root {
2312
+ `);pr(gi,`Trebol [
2313
+ title: "Screen tests: what a user does, without a browser"
2314
+ exports: [serve reply click type choose attach pick-menu drag press say see test-answer test-route]
2315
+ ]
2316
+
2317
+ ; \`trebol test\` runs every block of an app.test.trb on the app started anew,
2318
+ ; with no browser: the host keeps the view these words act on. Faces are found
2319
+ ; by what the user sees, a label, the text of a button or a hint, or by their
2320
+ ; name; only faces on show count, so a closed dialog or another tab is not there.
2321
+
2322
+ ; --- answers of the server ------------------------------------------------------
2323
+
2324
+ ; [method path handler ...] of every serve
2325
+ test-routes: copy []
2326
+
2327
+ serve: function [
2328
+ "Answers the requests of the app: a method, a path and a block that gives the answer, for each; a later serve comes first."
2329
+ routes [block!] {GET "/api/clients/:id" [...]: the block sees body, query and the :words of the path}
2330
+ /local m p b pos
2331
+ ] [
2332
+ new: copy []
2333
+ parse routes [any [
2334
+ set m ['GET | 'POST | 'PUT | 'PATCH | 'DELETE] set p string! set b block! (append new reduce [m p b])
2335
+ | pos: skip (do make error! rejoin ["serve takes a method, a path and a block, not " mold/flat first pos])
2336
+ ]]
2337
+ ; a later serve, as one in a test, answers before those it follows
2338
+ insert test-routes new
2339
+ true
2340
+ ]
2341
+
2342
+ reply: func [
2343
+ "An answer of serve with its status: reply 422 #(errors: ...)."
2344
+ status [integer!]
2345
+ data [any-type!]
2346
+ ] [
2347
+ make object! [reply-status: status reply-data: :data]
2348
+ ]
2349
+
2350
+ ; The words a path gives: "/api/clients/:id" and "/api/clients/42" -> [id: "42"]; none if they do not match.
2351
+ test-match: function [pattern [string!] path [string!]] [
2352
+ want: split pattern #"/"
2353
+ got: split path #"/"
2354
+ if (length? want) <> length? got [return none]
2355
+ words: copy []
2356
+ repeat i length? want [
2357
+ w: pick want i g: pick got i
2358
+ case [
2359
+ #":" = first w [append words reduce [to set-word! next w dehex g]]
2360
+ w <> g [return none]
2361
+ ]
2362
+ ]
2363
+ words
2364
+ ]
2365
+
2366
+ test-answer: function [
2367
+ "Called by the host for each request of the app: its status and its body as JSON, or none when serve has no answer for it."
2368
+ method [word!] url [string!] body [string! none!]
2369
+ ] [
2370
+ path: url
2371
+ query: make map! []
2372
+ if q: find url #"?" [
2373
+ path: copy/part url q
2374
+ foreach part split next q #"&" [
2375
+ kv: split part #"="
2376
+ poke query to word! dehex first kv either second kv [dehex second kv] [""]
2377
+ ]
2378
+ ]
2379
+ foreach [m pattern b] test-routes [
2380
+ if all [m = method words: test-match pattern path] [
2381
+ data: all [body any [attempt [load-json body] body]]
2382
+ append words compose/only [body: (data) query: (query)]
2383
+ r: do bind copy/deep b make object! words
2384
+ return either all [object? :r in r 'reply-status] [
2385
+ reduce [r/reply-status to-json :r/reply-data]
2386
+ ] [
2387
+ reduce [200 to-json :r]
2388
+ ]
2389
+ ]
2390
+ ]
2391
+ none
2392
+ ]
2393
+
2394
+ ; --- the faces on show ----------------------------------------------------------
2395
+
2396
+ ; [face parent ...] of the faces the user sees, in their order on the page; first
2397
+ ; the reactions run, as the browser runs them at the end of each round
2398
+ test-shown: function [] [
2399
+ out: copy []
2400
+ if v: shown-view [
2401
+ foreach cycle ui-react v [print cycle]
2402
+ test-walk v none out
2403
+ ]
2404
+ out
2405
+ ]
2406
+
2407
+ test-walk: function [f parent out] [
2408
+ ; on a wide screen, as the tests see it
2409
+ if any [f/hidden f/narrow-only] [exit]
2410
+ append out reduce [f parent]
2411
+ unless block? f/pane [exit]
2412
+ either f/style = 'tabs [
2413
+ ; the label of every tab, the faces of the one chosen
2414
+ repeat i length? f/pane [
2415
+ t: pick f/pane i
2416
+ append out reduce [t f]
2417
+ if all [i = f/value block? t/pane] [foreach c t/pane [test-walk c t out]]
2418
+ ]
2419
+ ] [
2420
+ foreach c f/pane [test-walk c f out]
2421
+ ]
2422
+ ]
2423
+
2424
+ test-route: function [
2425
+ "Called by the host when the page goes back or forward: the screens on show follow the link."
2426
+ parts [block!]
2427
+ /local f p
2428
+ ] [
2429
+ foreach [f p] test-shown [if f/style = 'screens [return ui-route f parts]]
2430
+ ]
2431
+
2432
+ ; What a text of the interface shows: a string, a text per language or a word of the dictionary.
2433
+ test-text: func [t] [either any [none? :t logic? :t] [none] [tr t]]
2434
+
2435
+ ; The cells of a row of a table or list, as shown.
2436
+ test-cells: function [f row /local w label] [
2437
+ collect [
2438
+ foreach [w label] any [f/columns []] [
2439
+ v: select row w
2440
+ unless none? :v [keep either string? :v [v] [localize :v]]
2441
+ ]
2442
+ ]
2443
+ ]
2444
+
2445
+ ; Every text on show: of faces, values, errors and rows, and the notices shown.
2446
+ test-texts: function [/local f p t] [
2447
+ out: copy []
2448
+ foreach [f p] test-shown [
2449
+ foreach t reduce [test-text f/text test-text f/hint f/error] [if string? t [append out t]]
2450
+ v: f/value
2451
+ case [
2452
+ string? :v [append out v]
2453
+ find [number money date] f/style [if v [append out localize v]]
2454
+ ]
2455
+ if all [f/style = 'lookup v] [
2456
+ foreach one either block? v [v] [reduce [v]] [
2457
+ append out either t: all [f/known select f/known one] [test-text t] [form one]
2458
+ ]
2459
+ ]
2460
+ ; the names of the files an upload or photo has
2461
+ if all [find [upload photo] f/style v] [
2462
+ foreach one either block? v [v] [reduce [v]] [if object? one [append out one/name]]
2463
+ ]
2464
+ if all [find [choice radio] f/style v] [
2465
+ foreach o any [f/options []] [
2466
+ if all [map? o (form v) = form o/value] [append out test-text o/text]
2467
+ ]
2468
+ ]
2469
+ if all [find [table list] f/style block? f/data] [
2470
+ foreach row f/data [append out test-cells f row]
2471
+ ]
2472
+ ; the title of every node of an orbit, its focus too
2473
+ if all [f/style = 'orbit block? f/data] [
2474
+ parse any [select f/data 'nodes []] [any [skip set t skip (append out test-text t) opt block!]]
2475
+ ]
2476
+ ]
2477
+ append out shown-toasts
2478
+ append out shown-questions
2479
+ out
2480
+ ]
2481
+
2482
+ ; The nodes of an orbit as [id title back ...]: its neighbours, and its trail with back true.
2483
+ test-orbit-nodes: function [f /local id t] [
2484
+ out: copy []
2485
+ unless block? f/data [return out]
2486
+ focus: select f/data 'focus
2487
+ trail: any [select f/data 'trail []]
2488
+ parse any [select f/data 'nodes []] [any [
2489
+ set id skip set t skip opt block! (
2490
+ unless id = focus [append out reduce [id test-text t to logic! find trail id]]
2491
+ )
2492
+ ]]
2493
+ out
2494
+ ]
2495
+
2496
+ ; What a face is called: its label, hint or the text it shows.
2497
+ test-called?: function [f what] [
2498
+ either word? what [f/name = what] [
2499
+ any [what = test-text f/text what = test-text f/hint]
2500
+ ]
2501
+ ]
2502
+
2503
+ ; The one face on show of some styles called what; an error naming the action if there is none or more than one.
2504
+ test-face: function [action [word!] styles [block!] what /local f p] [
2505
+ found: copy []
2506
+ foreach [f p] test-shown [
2507
+ if all [find styles f/style test-called? f what] [append found reduce [f p]]
2508
+ ]
2509
+ if empty? found [do make error! rejoin [action ": nothing on the screen is " mold what]]
2510
+ if 2 < length? found [do make error! rejoin [action ": " (length? found) / 2 " faces on the screen are " mold what]]
2511
+ f: first found
2512
+ if any [f/disabled f/inert f/readonly] [do make error! rejoin [action ": " mold what " cannot be used now"]]
2513
+ found
2514
+ ]
2515
+
2516
+ ; --- what the user does ---------------------------------------------------------
2517
+
2518
+ text-styles: [field password number money date area rich]
2519
+
2520
+ click: function [
2521
+ "Clicks a button, link, tile, check, toggle or tab, the row of a table or list that shows a text, or a node of an orbit."
2522
+ what [string! word!] "What it shows, or a field's name"
2523
+ /local f p row id t back
2524
+ ] [
2525
+ if string? what [
2526
+ ; a neighbour of an orbit, or a node of its trail
2527
+ foreach [f p] test-shown [
2528
+ if f/style = 'orbit [
2529
+ foreach [id t back] test-orbit-nodes f [
2530
+ if t = what [
2531
+ if any [f/disabled f/inert] [do make error! rejoin ["click: " mold what " cannot be used now"]]
2532
+ ui-orbit f id back
2533
+ return true
2534
+ ]
2535
+ ]
2536
+ ]
2537
+ ]
2538
+ ; a row of a table or list
2539
+ foreach [f p] test-shown [
2540
+ if all [find [table list] f/style block? f/data] [
2541
+ foreach row f/data [
2542
+ if find test-cells f row what [
2543
+ if any [f/disabled f/inert] [do make error! rejoin ["click: " mold what " cannot be used now"]]
2544
+ ui-select f row
2545
+ return true
2546
+ ]
2547
+ ]
2548
+ ]
2549
+ ]
2550
+ ]
2551
+ found: test-face 'click [button link tile check toggle tab] what
2552
+ test-activate first found second found
2553
+ ]
2554
+
2555
+ ; Does what a click on a face does; parent is the face it is in.
2556
+ test-activate: function [f parent] [
2557
+ switch/default f/style [
2558
+ check toggle [ui-input f not f/value ui-blur f]
2559
+ tab [ui-input parent index? find parent/pane f]
2560
+ link [
2561
+ case [
2562
+ f/action [ui-click f]
2563
+ any [word? f/value path? f/value] [go f/value]
2564
+ ]
2565
+ ]
2566
+ ] [ui-click f]
2567
+ true
2568
+ ]
2569
+
2570
+ type: function [
2571
+ "Types a text in a field, then leaves it; an empty text clears it."
2572
+ what [string! word!] "Its label or hint, or its name"
2573
+ text [any-type!] "What to type; a number or date is typed as written"
2574
+ ] [
2575
+ f: first test-face 'type text-styles what
2576
+ text: either string? :text [text] [form :text]
2577
+ ui-input f either empty? text [none] [text]
2578
+ ui-blur f
2579
+ true
2580
+ ]
2581
+
2582
+ choose: function [
2583
+ "Chooses an option of a choice, radio or lookup by the text it shows."
2584
+ what [string! word!] "Its label, or its name"
2585
+ option [string!]
2586
+ /local o
2587
+ ] [
2588
+ f: first test-face 'choose [choice radio lookup] what
2589
+ if f/style = 'lookup [
2590
+ ui-lookup-search f option
2591
+ foreach o any [f/options []] [
2592
+ if option = test-text o/text [
2593
+ ui-lookup-pick f o
2594
+ ui-blur f
2595
+ return true
2596
+ ]
2597
+ ]
2598
+ do make error! rejoin ["choose: " mold what " finds no " mold option]
2599
+ ]
2600
+ ; a group of options is a title then a block of them
2601
+ options: collect [
2602
+ opts: any [f/options []]
2603
+ forall opts [
2604
+ case [
2605
+ block? first opts [keep first opts]
2606
+ not block? pick opts 2 [keep/only first opts]
2607
+ ]
2608
+ ]
2609
+ ]
2610
+ foreach o options [
2611
+ if option = either map? o [test-text o/text] [form o] [
2612
+ ui-input f form either map? o [o/value] [o]
2613
+ ui-blur f
2614
+ return true
2615
+ ]
2616
+ ]
2617
+ do make error! rejoin ["choose: " mold what " has no option " mold option]
2618
+ ]
2619
+
2620
+ pick-menu: function [
2621
+ "Chooses an item of the menu a button opens, of the context menu of a face, or of the row of a table or list that shows a text."
2622
+ what [string! word!] "What the face or row shows, or a face's name"
2623
+ item [string! block!] {The item's text; ["Move to" "Top"] for one in a submenu}
2624
+ /local f p row i
2625
+ ] [
2626
+ on: none row: none
2627
+ if string? what [
2628
+ ; foreach keeps its words to itself
2629
+ foreach [f p] test-shown [
2630
+ if all [find [table list] f/style block? f/data f/menu] [
2631
+ foreach r f/data [if find test-cells f r what [on: f row: r break]]
2632
+ if row [break]
2633
+ ]
2634
+ ]
2635
+ ]
2636
+ either on [f: on] [
2637
+ f: first test-face 'pick-menu collect [foreach [f p] test-shown [keep f/style]] what
2638
+ unless block? f/menu [do make error! rejoin ["pick-menu: " mold what " has no menu"]]
2639
+ ]
2640
+ if any [f/disabled f/inert] [do make error! rejoin ["pick-menu: " mold what " cannot be used now"]]
2641
+ items: f/menu
2642
+ texts: either block? item [item] [reduce [item]]
2643
+ forall texts [
2644
+ found: none
2645
+ foreach i items [if all [not i/divider (first texts) = test-text i/text] [found: i break]]
2646
+ unless found [do make error! rejoin ["pick-menu: the menu of " mold what " has no " mold first texts]]
2647
+ either tail? next texts [
2648
+ if found/items [do make error! rejoin ["pick-menu: " mold first texts " opens a submenu"]]
2649
+ ] [
2650
+ unless found/items [do make error! rejoin ["pick-menu: " mold first texts " has no submenu"]]
2651
+ items: found/items
2652
+ ]
2653
+ ]
2654
+ ui-menu f found row
2655
+ true
2656
+ ]
2657
+
2658
+ ; [face row index ...] of the rows of the tables and lists on show that show a text.
2659
+ test-rows: function [what /local f p] [
2660
+ out: copy []
2661
+ if string? what [
2662
+ foreach [f p] test-shown [
2663
+ if all [find [table list] f/style block? f/data] [
2664
+ repeat i length? f/data [
2665
+ if find test-cells f pick f/data i what [append out reduce [f pick f/data i i]]
2666
+ ]
2667
+ ]
2668
+ ]
2669
+ ]
2670
+ out
2671
+ ]
2672
+
2673
+ drag: function [
2674
+ "Drags a face, or the row of a table or list that shows a text, onto another: in a list that can be reordered it takes that place, else it is dropped on it."
2675
+ what [string! word!] "What the face or row shows, or a face's name"
2676
+ onto [string! word!] "The place it goes: a face, or the row it goes before"
2677
+ /local f p row i
2678
+ ] [
2679
+ shown: test-shown
2680
+ styles: collect [foreach [f p] shown [keep f/style]]
2681
+ ; what is dragged: its face, what it carries, where it is, and the face it moves in
2682
+ either not empty? rows: test-rows what [
2683
+ set [from payload index] rows
2684
+ ; rows the user sorted by a header are not in the order of their data
2685
+ sorted: all [from/sortable from/sorted not all [from/events select from/events 'on-sort]]
2686
+ within: all [from/reorder not sorted from]
2687
+ unless any [from/drag within] [do make error! rejoin ["drag: the rows of " mold what " cannot be dragged"]]
2688
+ ] [
2689
+ set [from p] test-face 'drag styles what
2690
+ payload: from/value
2691
+ within: all [p p/reorder not find [table list tree] p/style p]
2692
+ index: all [within index? find/same within/pane from]
2693
+ unless any [from/drag within] [do make error! rejoin ["drag: " mold what " cannot be dragged"]]
2694
+ ]
2695
+ ; moved to another place among its own
2696
+ if within [
2697
+ place: none
2698
+ either find [table list] within/style [
2699
+ foreach [f row i] test-rows onto [if same? f within [place: i break]]
2700
+ ] [
2701
+ foreach c within/pane [if all [not c/hidden test-called? c onto] [place: index? find/same within/pane c break]]
2702
+ ]
2703
+ if place [
2704
+ ui-reorder within index place none
2705
+ return true
2706
+ ]
2707
+ ]
2708
+ ; dropped on a face, or before a row of one
2709
+ zone: none
2710
+ ; foreach keeps its words to itself
2711
+ foreach [f row i] test-rows onto [if f/drop [zone: f at: i break]]
2712
+ either zone [
2713
+ if same? zone from [do make error! rejoin ["drag: " mold what " is already in " mold onto]]
2714
+ ] [
2715
+ zone: first test-face 'drag styles onto
2716
+ unless zone/drop [do make error! rejoin ["drag: " mold onto " takes nothing dropped"]]
2717
+ if test-inside? zone from shown [do make error! rejoin ["drag: " mold what " cannot go into itself"]]
2718
+ at: 1 + length? either find [table list tree] zone/style [any [zone/data []]] [any [zone/pane []]]
2719
+ ]
2720
+ ui-drop zone :payload from at none
2721
+ true
2722
+ ]
2723
+
2724
+ ; Does an upload or photo whose accept is list take a file? As the browser's picker: "pdf" and ".pdf"
2725
+ ; by its name, "image/png" and "image/*" by its type.
2726
+ test-accepts?: function [list [block!] name [string!] type [string!]] [
2727
+ if empty? list [return true]
2728
+ name: lowercase copy name
2729
+ type: lowercase copy type
2730
+ foreach x list [
2731
+ x: lowercase trim form x
2732
+ if either find x #"/" [
2733
+ either #"*" = last x [find/match type copy/part x (length? x) - 1] [type = x]
2734
+ ] [
2735
+ unless #"." = first x [x: join "." x]
2736
+ all [(length? name) >= length? x x = skip tail name negate length? x]
2737
+ ] [return true]
2738
+ ]
2739
+ false
2740
+ ]
2741
+
2742
+ attach: function [
2743
+ "Chooses files for an upload or photo, as the user picks them or drops them on it; the ones its accept refuses are refused, as the browser does."
2744
+ what [string! word!] "Its label, or its name"
2745
+ files [file! block!] "A file next to the test, or a block of them"
2746
+ ] [
2747
+ f: first test-face 'attach [upload photo] what
2748
+ list: either block? f/accept [f/accept] [either f/style = 'photo [["image/*"]] [[]]]
2749
+ taken: copy []
2750
+ refused: copy []
2751
+ foreach file either block? files [files] [reduce [files]] [
2752
+ one: test-file file
2753
+ either test-accepts? list one/1 one/3 [append taken one] [append refused one/1]
2754
+ ]
2755
+ ; one file unless it takes more
2756
+ unless f/multiple [taken: copy/part taken 4]
2757
+ ui-files f taken refused
2758
+ true
2759
+ ]
2760
+
2761
+ ; The face a face is in, among the faces on show.
2762
+ test-parent: function [f shown /local g p] [
2763
+ foreach [g p] shown [if same? g f [return p]]
2764
+ none
2765
+ ]
2766
+
2767
+ ; Is f inside the face outer (or outer itself)?
2768
+ test-inside?: function [f outer shown] [
2769
+ while [f] [
2770
+ if same? f outer [return true]
2771
+ f: test-parent f shown
2772
+ ]
2773
+ false
2774
+ ]
2775
+
2776
+ ; "Ctrl+Shift+K" -> [ctrl shift alt key] as the browser compares them: Ctrl and Cmd are one, names as
2777
+ ; the browser gives them, a letter in lower case
2778
+ test-keys: function [spec [string!] /local k] [
2779
+ parts: split lowercase copy spec #"+"
2780
+ foreach k parts [trim k]
2781
+ k: take/last parts
2782
+ if empty? k [k: "+"]
2783
+ k: any [select ["esc" "escape" "del" "delete" "up" "arrowup" "down" "arrowdown" "left" "arrowleft" "right" "arrowright" "space" " "] k k]
2784
+ any-of: func [names] [not empty? intersect parts names]
2785
+ reduce [any-of ["ctrl" "control" "cmd" "meta"] any-of ["shift"] any-of ["alt" "option"] k]
2786
+ ]
2787
+
2788
+ ; The key of "Ctrl+S" as on-key gets it in event/key: a char (#"s", #"^M" for Enter) or a word ('left, 'F2).
2789
+ test-key: function [spec [string!]] [
2790
+ k: last split spec #"+"
2791
+ if empty? k [k: "+"]
2792
+ shift: find spec "shift+"
2793
+ case [
2794
+ c: select ["enter" #"^M" "escape" #"^[" "esc" #"^[" "tab" #"^-" "backspace" #"^H" "space" #" "] k [c]
2795
+ 1 = length? k [either shift [uppercase first k] [lowercase first k]]
2796
+ w: select [
2797
+ "left" left "arrowleft" left "right" right "arrowright" right "up" up "arrowup" up "down" down "arrowdown" down
2798
+ "home" home "end" end "pageup" page-up "pagedown" page-down "insert" insert "delete" delete "del" delete
2799
+ ] k [w]
2800
+ parse k [#"F" some digit] [to word! uppercase copy k]
2801
+ true [do make error! rejoin ["press: " mold spec " is not a key"]]
2802
+ ]
2803
+ ]
2804
+
2805
+ digit: charset "0123456789"
2806
+
2807
+ press: function [
2808
+ "Presses a key, as Enter or Ctrl+S: the button or link with it as its shortcut, or else the on-key of the face with the cursor, or of the view."
2809
+ key [string!] {"Enter", "Escape", "Ctrl+S", "Shift+Tab", "a"}
2810
+ /on "With the cursor in a face"
2811
+ what [string! word!] "Its label, hint or text, or its name"
2812
+ /local f p
2813
+ ] [
2814
+ shown: test-shown
2815
+ want: test-keys key
2816
+ ; a dialog on show keeps the rest of the page out of reach
2817
+ dialog: none
2818
+ foreach [f p] shown [if f/style = 'dialog [dialog: f]]
2819
+ foreach [f p] shown [
2820
+ if all [
2821
+ f/shortcut
2822
+ find [button link] f/style
2823
+ want = test-keys f/shortcut
2824
+ any [none? dialog test-inside? f dialog shown]
2825
+ ] [
2826
+ if any [f/disabled f/inert] [do make error! rejoin ["press: " mold key " cannot be used now"]]
2827
+ return test-activate f p
2828
+ ]
2829
+ ]
2830
+ at: none
2831
+ if on [at: first test-face 'press collect [foreach [f p] shown [keep f/style]] what]
2832
+ k: test-key key
2833
+ fields: reduce [
2834
+ quote key: either word? k [to lit-word! k] [k]
2835
+ quote ctrl?: to logic! find key "ctrl+" quote shift?: to logic! find key "shift+" quote alt?: to logic! find key "alt+"
2836
+ quote meta?: to logic! any [find key "cmd+" find key "meta+"]
2837
+ ]
2838
+ ; the face with the cursor or the nearest around it that has an on-key, or the view
2839
+ f: any [at shown-view]
2840
+ while [all [f not all [f/events select f/events 'on-key]]] [f: either at [test-parent f shown] [none]]
2841
+ if f [ui-event f 'on-key fields]
2842
+ case [
2843
+ ; Enter in a one-line field of a form clicks its submit, if it can be clicked
2844
+ all [at k = #"^M" find [field password number money date] at/style at/form at/form/style = 'form] [
2845
+ foreach [f p] test-shown [
2846
+ if all [f/submit same? f/form at/form] [
2847
+ unless any [f/disabled f/inert] [ui-click f]
2848
+ break
2849
+ ]
2850
+ ]
2851
+ ]
2852
+ ; Escape closes the dialog on show
2853
+ all [k = #"^[" dialog] [ui-close dialog]
2854
+ ]
2855
+ true
2856
+ ]
2857
+
2858
+ say: func [
2859
+ "Says how the user answers the next question of confirm, which is yes when nothing is said; a test that leaves one unasked fails."
2860
+ yes [logic!] "yes or no"
2861
+ ] [
2862
+ test-say yes
2863
+ ]
2864
+
2865
+ see: function [
2866
+ "True if a text is on the screen, in a face, a field, a row or a notice; an error otherwise."
2867
+ text [string!]
2868
+ /not "True if it is not on the screen"
2869
+ ] [
2870
+ there: false
2871
+ foreach t test-texts [if find t text [there: true break]]
2872
+ if there = to logic! not [
2873
+ do make error! rejoin ["see: " mold text either not [" is on the screen"] [" is not on the screen"]]
2874
+ ]
2875
+ true
2876
+ ]
2877
+ `);var z=(e,t={},n=[],r)=>{let o={};for(let[a,i]of Object.entries(t))o[a]=typeof i=="number"?ne(i):i;return r===void 0?{tag:e,attrs:o,kids:n}:{tag:e,attrs:o,kids:n,text:r}},ne=e=>String(Math.round(e*100)/100),Eu=["primary","accent","danger","success","warning","muted","text","border","surface","bg"],pa={red:{h:27,c:.2,light:.58,dark:.7},maroon:{h:15,c:.13,light:.38,dark:.58},orange:{h:55,c:.17,light:.68,dark:.76},brown:{h:50,c:.1,light:.45,dark:.62},gold:{h:85,c:.15,light:.76,dark:.8},yellow:{h:100,c:.17,light:.86,dark:.88},olive:{h:115,c:.12,light:.5,dark:.68},green:{h:145,c:.17,light:.6,dark:.74},teal:{h:185,c:.11,light:.58,dark:.72},aqua:{h:195,c:.12,light:.78,dark:.82},cyan:{h:210,c:.12,light:.72,dark:.8},sky:{h:235,c:.1,light:.75,dark:.8},blue:{h:260,c:.19,light:.55,dark:.7},navy:{h:265,c:.14,light:.32,dark:.55},violet:{h:290,c:.15,light:.62,dark:.75},purple:{h:305,c:.18,light:.5,dark:.68},magenta:{h:330,c:.24,light:.6,dark:.72},pink:{h:350,c:.13,light:.75,dark:.8},silver:{h:0,c:0,light:.8,dark:.75},gray:{h:0,c:0,light:.6,dark:.62},black:{h:0,c:0,light:.15,dark:.15},white:{h:0,c:0,light:1,dark:1}},Su={pen:"pen color","fill-pen":"fill-pen color","line-width":"line-width number","line-cap":"line-cap flat | square | round","line-join":"line-join miter | round | bevel",font:"font [size: number bold italic]",line:"line point point ...",box:"box top-left bottom-right [corner-radius]",triangle:"triangle point point point",polygon:"polygon point point point ...",circle:"circle center radius [radius-y]",ellipse:"ellipse top-left size",arc:"arc center radius begin sweep [closed]",curve:"curve start control end, or curve start control control end",text:"text top-left string",translate:"translate offset",rotate:"rotate angle [center]",scale:"scale x y",push:"push [commands]"},Db={pen:"var(--tb-text)",fill:null,width:1,cap:"butt",join:"miter",size:15,bold:!1,italic:!1};function yi(e){if(e==="off"||e==="none"||e==="transparent")return null;if(Eu.includes(e))return`var(--tb-${e})`;if(pa[e]!==void 0)return`var(--tb-c-${e})`}var mr=class extends Error{};function Mu(e){let t=[];if(e.t!==s.Block)return{kids:t,error:e.t===s.None?null:"draw takes a block"};try{return Tu(e,{...Db},t),{kids:t,error:null}}catch(n){if(n instanceof mr)return{kids:t,error:n.message};throw n}}function Tu(e,t,n){let r=e.s.data,o=e.i,a=n,i=C=>C!==void 0&&(C.t===s.Word||C.t===s.LitWord)?M(C.sym).toLowerCase():null,l=C=>C===void 0?null:C.t===s.Integer?pe.toNumber(C.v):C.t===s.Decimal?C.v:null,c=C=>{throw new mr(`draw: ${C} is written ${Su[C]}`)},u=C=>{let x=r[o];return x===void 0||x.t!==s.Pair?c(C):(o++,[x.x,x.y])},d=()=>{let C=r[o];return C===void 0||C.t!==s.Pair?null:(o++,[C.x,C.y])},f=C=>{let x=l(r[o]);return x===null?c(C):(o++,x)},p=()=>{let C=l(r[o]);return C!==null&&o++,C},h=(C,x)=>{let w=[];for(let E=d();E!==null;E=d())w.push(E);return w.length<x&&c(C),w},v=C=>({fill:C&&t.fill!==null?t.fill:"none",stroke:t.pen??"none","stroke-width":t.width,"stroke-linecap":t.cap,"stroke-linejoin":t.join}),y=C=>C.map(([x,w])=>`${ne(x)},${ne(w)}`).join(" ");for(;o<r.length;){let C=r[o],x=i(C);if(x===null||Su[x]===void 0)throw new mr(x===null?`draw: a command was expected, not ${Rb(C)}`:`draw: unknown command ${x}`);switch(o++,x){case"pen":case"fill-pen":{let w=i(r[o]),E=w===null?void 0:yi(w);if(E===void 0)throw new mr(`draw: ${x} takes a role (${Eu.join(" ")}), a color (${Object.keys(pa).join(" ")}) or off`);o++,x==="pen"?t.pen=E:t.fill=E;break}case"line-width":t.width=Math.max(0,f(x));break;case"line-cap":{let w=i(r[o]);w!=="flat"&&w!=="square"&&w!=="round"&&c(x),o++,t.cap=w==="flat"?"butt":w;break}case"line-join":{let w=i(r[o]);w!=="miter"&&w!=="round"&&w!=="bevel"&&c(x),o++,t.join=w;break}case"font":{let w=r[o];(w===void 0||w.t!==s.Block)&&c(x),o++;let E=w.s.data.slice(w.i);for(let S=0;S<E.length;S++){let T=E[S];T.t===s.SetWord&&M(T.sym).toLowerCase()==="size"&&l(E[S+1])!==null?t.size=l(E[++S]):i(T)==="bold"?t.bold=!0:i(T)==="italic"?t.italic=!0:i(T)==="plain"?t.bold=t.italic=!1:c(x)}break}case"line":a.push(z("polyline",{points:y(h(x,2)),...v(!1)}));break;case"triangle":{let w=h(x,3);w.length!==3&&c(x),a.push(z("polygon",{points:y(w),...v(!0)}));break}case"polygon":a.push(z("polygon",{points:y(h(x,3)),...v(!0)}));break;case"box":{let[w,E]=u(x),[S,T]=u(x),V=p(),J={x:Math.min(w,S),y:Math.min(E,T),width:Math.abs(S-w),height:Math.abs(T-E),...v(!0)};V!==null&&(J.rx=V),a.push(z("rect",J));break}case"circle":{let[w,E]=u(x),S=f(x),T=p();a.push(T===null?z("circle",{cx:w,cy:E,r:S,...v(!0)}):z("ellipse",{cx:w,cy:E,rx:S,ry:T,...v(!0)}));break}case"ellipse":{let[w,E]=u(x),[S,T]=u(x);a.push(z("ellipse",{cx:w+S/2,cy:E+T/2,rx:S/2,ry:T/2,...v(!0)}));break}case"arc":{let[w,E]=u(x),[S,T]=u(x),V=f(x),J=f(x),Ge=i(r[o])==="closed";Ge&&o++,a.push(z("path",{d:Wb(w,E,S,T,V,J,Ge),...v(Ge)}));break}case"curve":{let w=h(x,3);w.length>4&&c(x);let[E,...S]=w,T=`M${ne(E[0])},${ne(E[1])} ${S.length===2?"Q":"C"}${y(S)}`;a.push(z("path",{d:T,...v(!1)}));break}case"text":{let[w,E]=u(x),S=r[o];(S===void 0||S.t!==s.String)&&c(x),o++;let T={x:w,y:E,"dominant-baseline":"hanging",fill:t.pen??"none","font-size":t.size,"font-family":"var(--tb-font)"};t.bold&&(T["font-weight"]="bold"),t.italic&&(T["font-style"]="italic"),a.push(z("text",T,[],B(S)));break}case"translate":case"rotate":case"scale":{let w;if(x==="translate"){let[S,T]=u(x);w=`translate(${ne(S)} ${ne(T)})`}else if(x==="rotate"){let S=f(x),T=d();w=T===null?`rotate(${ne(S)})`:`rotate(${ne(S)} ${ne(T[0])} ${ne(T[1])})`}else{let S=f(x),T=p()??S;w=`scale(${ne(S)} ${ne(T)})`}let E=z("g",{transform:w});a.push(E),a=E.kids;break}case"push":{let w=r[o];(w===void 0||w.t!==s.Block)&&c(x),o++;let E=z("g");a.push(E),Tu(w,{...t},E.kids);break}}}}function Wb(e,t,n,r,o,a,i){let l=y=>{let C=y*Math.PI/180;return[e+n*Math.cos(C),t+r*Math.sin(C)]};if(Math.abs(a)>=360){let[y,C]=l(o),[x,w]=l(o+180);return`M${ne(y)},${ne(C)} A${ne(n)},${ne(r)} 0 1 1 ${ne(x)},${ne(w)} A${ne(n)},${ne(r)} 0 1 1 ${ne(y)},${ne(C)}${i?" Z":""}`}let[c,u]=l(o),[d,f]=l(o+a),p=Math.abs(a)>180?1:0,h=a>=0?1:0,v=`A${ne(n)},${ne(r)} 0 ${p} ${h} ${ne(d)},${ne(f)}`;return i?`M${ne(e)},${ne(t)} L${ne(c)},${ne(u)} ${v} Z`:`M${ne(c)},${ne(u)} ${v}`}function Rb(e){return e.t===s.String?"a string":e.t===s.Pair?"a pair":e.t===s.Integer||e.t===s.Decimal?"a number":"that"}var wi={base:250,accent:30,neutral:"neutral",density:"normal",radius:"soft",font:"inter",headings:null,mode:"auto",color:1,line:1,depth:"soft",icons:"round",skin:"modern"},Au={neutral:["cool","neutral","warm"],density:["compact","normal","comfortable"],radius:["sharp","soft","round"],mode:["light","dark","auto"],depth:["flat","soft","lifted"],icons:["fine","round","sharp","bold"],skin:["modern","classic","cupertino","fusion","fluent"]},ki={minimal:{},paper:{base:40,accent:150,neutral:"warm",headings:"serif",radius:"sharp",depth:"flat",icons:"fine"},civic:{base:255,accent:75,neutral:"cool",font:"system",radius:"sharp",line:2,depth:"flat",icons:"sharp"},soft:{base:175,accent:30,density:"comfortable",radius:"round",depth:"lifted",icons:"round"},ink:{color:0,font:"system",headings:"mono",radius:"sharp",line:2,depth:"flat",icons:"bold"},classic:{base:240,accent:45,color:.7,font:"sans",density:"compact",radius:"sharp",depth:"flat",icons:"sharp",skin:"classic"},cupertino:{base:255,accent:330,font:"system",radius:"soft",depth:"soft",icons:"round",skin:"cupertino"},fusion:{base:240,accent:30,color:.8,font:"noto",radius:"sharp",depth:"flat",icons:"sharp",skin:"fusion"},fluent:{base:250,accent:25,font:"segoe",radius:"soft",depth:"soft",icons:"fine",skin:"fluent"}},Fb=new Set(["fluent"]),Hb={cupertino:{bg:[.945,.23],surface:[1,.29],raised:[.925,.26],border:[.86,.37],"border-strong":[.76,.45],muted:[.48,.74],primary:[.52,.7]},fusion:{bg:[.95,.31],surface:[1,.25],raised:[.95,.31],border:[.84,.24],"border-strong":[.7,.2],muted:[.46,.76],primary:[.5,.72]},fluent:{bg:[.955,.2],surface:[.995,.27],raised:[.985,.24],border:[.9,.33],"border-strong":[.78,.42],muted:[.47,.74],primary:[.48,.78]}},Ub=["bg","surface","raised","border","border-strong","text","muted","primary","primary-hover","on-primary","accent","on-accent","danger","on-danger","success","warning","focus"];var zb={cool:255,neutral:0,warm:70},_b={cool:.012,neutral:0,warm:.01};function qb(e,t){let n=Kb(e,t),r=Hb[e.skin];if(r===void 0)return n;let o=t?1:0;for(let a of["bg","surface","raised","border","border-strong","muted"]){let i=r[a][o];n[a]={l:i,c:i>=.99||!Fb.has(e.skin)?0:n.bg.c,h:n.bg.h}}return n.primary={...n.primary,l:r.primary[o]},n["primary-hover"]={...n["primary-hover"],l:r.primary[o]+(t?.05:-.05)},n}function Kb(e,t){let n=e.neutral==="neutral"?e.base:zb[e.neutral],r=(e.neutral==="neutral"?.006:_b[e.neutral])*e.color,o=e.color===0,a=(c,u=1)=>({l:c,c:r*u,h:n}),i=(c,u,d)=>({l:c,c:u,h:d}),l=(c,u,d)=>({l:c,c:u*e.color,h:d});return e.skin==="classic"?{bg:a(t?.33:.85,2),surface:a(t?.25:1,t?2:0),raised:a(t?.33:.85,2),border:a(t?.22:.7,2),"border-strong":a(t?.18:.52,2),text:a(t?.95:.18,t?1:3),muted:a(t?.8:.38,3),primary:l(t?.8:.45,.12,e.base),"primary-hover":l(t?.85:.4,.12,e.base),"on-primary":a(t?.18:1,t?2:0),accent:l(t?.8:.48,.13,e.accent),"on-accent":a(t?.18:1,t?2:0),danger:i(t?.75:.5,t?.15:.18,25),"on-danger":a(t?.18:1,t?2:0),success:i(t?.76:.48,.13,150),warning:i(t?.8:.78,.14,75),focus:l(t?.75:.5,.15,e.base)}:t?{bg:a(.16,2),surface:a(.2,2),raised:a(.23,2),border:a(.32,2),"border-strong":a(.42,2),text:a(.94,1),muted:a(.72,2),primary:l(o?.94:.74,.13,e.base),"primary-hover":l(o?.84:.8,.11,e.base),"on-primary":a(.18,2),accent:l(.74,.13,e.accent),"on-accent":a(.18,2),danger:i(.72,.15,25),"on-danger":a(.18,2),success:i(.74,.13,150),warning:i(.8,.13,75),focus:l(.72,.15,e.base)}:{bg:a(.975,1.2),surface:a(1,0),raised:a(1,0),border:a(.9,1.5),"border-strong":a(.8,2),text:a(.24,3),muted:a(.5,3),primary:l(o?.24:.5,.16,e.base),"primary-hover":l(o?.36:.45,.15,e.base),"on-primary":a(1,0),accent:l(.5,.15,e.accent),"on-accent":a(1,0),danger:i(.52,.18,25),"on-danger":a(1,0),success:i(.52,.13,150),warning:i(.78,.14,75),focus:l(.62,.17,e.base)}}function Iu({l:e,c:t,h:n}){let r=t*Math.cos(n*Math.PI/180),o=t*Math.sin(n*Math.PI/180),a=(e+.3963377774*r+.2158037573*o)**3,i=(e-.1055613458*r-.0638541728*o)**3,l=(e-.0894841775*r-1.291485548*o)**3,c=u=>Math.min(1,Math.max(0,u));return[c(4.0767416621*a-3.3077115913*i+.2309699292*l),c(-1.2684380046*a+2.6097574011*i-.3413193965*l),c(-.0041960863*a-.7034186147*i+1.707614701*l)]}function Gb(e){let[t,n,r]=Iu(e);return .2126*t+.7152*n+.0722*r}var Vb=e=>e<=.0031308?12.92*e:1.055*e**(1/2.4)-.055,Yb=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4;function Zb(e,t,n){let[r,o,a]=Iu(e).map(i=>Yb(t*Vb(i)+(1-t)*n));return .2126*r+.7152*o+.0722*a}function Jb(e,t,n){let r=Gb(e);return Math.min(...[0,1].map(o=>{let a=Zb(t,n,o);return(Math.max(r,a)+.05)/(Math.min(r,a)+.05)}))}function Xb(e){let t=.5;for(;t<1&&Jb(e.text,e.bg,t)<4.6;)t=Math.round((t+.01)*100)/100;return t}var ct=(e,t)=>`oklch(${(e.l*100).toFixed(1)}% ${e.c.toFixed(3)} ${e.h.toFixed(1)}${t===void 0?"":` / ${t}`})`,Qb=[0,4,8,12,16,24,32,48],eh={classic:34,cupertino:30,fusion:30,fluent:32},th={compact:.85,normal:1,comfortable:1.2},nh={sharp:2,soft:8,round:16},rh={fine:{stroke:1.5,cap:"round",join:"round"},round:{stroke:2,cap:"round",join:"round"},sharp:{stroke:2,cap:"square",join:"miter"},bold:{stroke:2.75,cap:"butt",join:"miter"}},Qr={inter:'Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',sans:'"Helvetica Neue", Helvetica, Arial, sans-serif',noto:'"Noto Sans", "DejaVu Sans", Ubuntu, Cantarell, "Segoe UI", Roboto, sans-serif',segoe:'"Segoe UI Variable Text", "Segoe UI Variable", "Segoe UI", ui-sans-serif, system-ui, sans-serif',system:'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',serif:'ui-serif, Georgia, Cambria, "Times New Roman", serif',mono:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"};function Lu(e,t){let n=qb(e,t),r=Ub.map(l=>` --tb-${l}: ${ct(n[l])};`);r.push(` --tb-focus-ring: ${ct(n.focus,t?.5:.35)};`),r.push(` --tb-danger-soft: ${ct(n.danger,t?.16:.08)};`),r.push(` --tb-primary-soft: ${ct(n.primary,t?.16:.08)};`),r.push(` --tb-overlay: ${ct(eo(n),t?.6:.4)};`),r.push(` --tb-scrim: ${ct(n.bg,Xb(n))};`);let o=t?"0 0 0 1px oklch(100% 0 0 / 0.06)":`0 1px 2px ${ct(eo(n),.06)}`,a=e.depth==="lifted"?2:1;r.push(` --tb-shadow-1: ${e.depth==="flat"?"none":`${o}, 0 ${a}px ${3*a}px ${ct(eo(n),t?.4:.08)}`};`),r.push(` --tb-shadow-2: ${e.depth==="flat"?"none":`${o}, 0 ${4*a}px ${12*a}px ${ct(eo(n),t?.5:.08)}`};`),r.push(` --tb-shadow-3: ${o}, 0 ${12*a}px ${32*a}px ${ct(eo(n),t?.6:.12)};`);let i=l=>ct({l,c:n.bg.c,h:n.bg.h});e.skin==="classic"&&(r.push(` --tb-bevel-hi: ${i(t?.5:1)};`,` --tb-bevel-lo: ${i(t?.15:.55)};`),r.push(` --tb-face-hi: ${i(t?.47:.97)};`,` --tb-face-lo: ${i(t?.36:.8)};`)),e.skin==="cupertino"&&r.push(` --tb-segment: ${i(t?.47:1)};`),e.skin==="fusion"&&r.push(` --tb-face-hi: ${i(t?.37:.99)};`,` --tb-face-lo: ${i(t?.32:.91)};`),e.skin==="fluent"&&r.push(` --tb-focus-ring: ${ct(n.text)};`,` --tb-subtle: ${ct(n.text,t?.08:.06)};`);for(let[l,c]of Object.entries(pa))r.push(` --tb-c-${l}: ${ct({l:t?c.dark:c.light,c:c.c,h:c.h})};`);return r.push(` color-scheme: ${t?"dark":"light"};`),r.join(`
2878
+ `)}var eo=e=>({l:.2,c:e.text.c,h:e.text.h});function oh(e){let t=th[e.density],n=Qb.map((i,l)=>` --tb-space-${l}: ${Math.round(i*t)}px;`),r=nh[e.radius];n.push(` --tb-radius: ${r}px;`,` --tb-radius-lg: ${Math.round(r*1.5)}px;`);let o=eh[e.skin];n.push(` --tb-control: ${o!==void 0?Math.round(o*t):Math.max(40,Math.round(44*t))}px;`),n.push(` --tb-font: ${Qr[e.font]??`"${e.font}", ${Qr.system}`};`),n.push(` --tb-headings: ${e.headings===null?"var(--tb-font)":Qr[e.headings]??`"${e.headings}", ${Qr.system}`};`),n.push(` --tb-mono: ${Qr.mono};`),n.push(` --tb-line: ${e.line}px;`);let a=rh[e.icons];return n.push(` --tb-icon-stroke: ${a.stroke};`,` --tb-icon-cap: ${a.cap};`,` --tb-icon-join: ${a.join};`),n.push(" --tb-ease: cubic-bezier(0.2, 0, 0, 1);"," --tb-fast: 150ms;"),n.join(`
2879
+ `)}function $u(e){let t=Lu(e,!1),n=Lu(e,!0),r;return e.mode==="light"?r=`:root {
1831
2880
  ${t}
1832
2881
  }`:e.mode==="dark"?r=`:root {
1833
2882
  ${n}
@@ -1842,10 +2891,10 @@ ${n}
1842
2891
  :root[data-tb-scheme="dark"] {
1843
2892
  ${n}
1844
2893
  }`,`:root {
1845
- ${Ab(e)}
2894
+ ${oh(e)}
1846
2895
  }
1847
2896
  ${r}
1848
- ${Bb}${$b[e.skin]}`}var Bb=String.raw`
2897
+ ${ah}${sh[e.skin]}`}var ah=String.raw`
1849
2898
  *, *::before, *::after { box-sizing: border-box; }
1850
2899
  html, body { margin: 0; }
1851
2900
  body {
@@ -1907,6 +2956,12 @@ body {
1907
2956
  background-size: cover;
1908
2957
  background-position: center;
1909
2958
  }
2959
+ /* an image behind what holds it, under a veil that keeps text on it AA; muted text needs the text's color there */
2960
+ :has(> .tb-backdrop) { position: relative; isolation: isolate; --tb-muted: var(--tb-text); }
2961
+ .tb-backdrop { position: absolute; inset: 0; z-index: -1; border-radius: inherit; background-size: cover; background-position: center; pointer-events: none; }
2962
+ .tb-backdrop::after { content: ""; position: absolute; inset: 0; border-radius: inherit; background: var(--tb-scrim); }
2963
+ /* the backdrop of the view or of a screen is the window's */
2964
+ :is(.tb-view, .tb-screen) > .tb-backdrop { position: fixed; border-radius: 0; }
1910
2965
  .tb-tile {
1911
2966
  font: inherit;
1912
2967
  font-size: 13px;
@@ -2236,7 +3291,15 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2236
3291
  .tb-scroll.tb-large { max-height: 640px; }
2237
3292
  .tb-scroll:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-focus-ring); }
2238
3293
 
2239
- .tb-image { display: block; max-width: 100%; height: auto; border-radius: var(--tb-radius); }
3294
+ .tb-image { display: block; max-width: 100%; height: auto; border-radius: var(--tb-radius); object-fit: cover; }
3295
+ .tb-image.tb-round { aspect-ratio: 1; border-radius: 50%; }
3296
+ .tb-video { display: block; width: 100%; max-width: 100%; height: auto; aspect-ratio: auto 16 / 9; border-radius: var(--tb-radius); }
3297
+ .tb-audio { display: block; width: 100%; max-width: 480px; }
3298
+ :is(.tb-video, .tb-audio).tb-small { width: 320px; }
3299
+ :is(.tb-video, .tb-audio).tb-medium { width: 480px; }
3300
+ .tb-video.tb-large { width: 720px; }
3301
+ :is(.tb-video, .tb-audio).tb-fill { max-width: none; }
3302
+ :is(.tb-video, .tb-audio):focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-focus-ring); }
2240
3303
  .tb-canvas { display: block; max-width: 100%; }
2241
3304
  .tb-canvas > svg { display: block; max-width: 100%; height: auto; overflow: visible; }
2242
3305
  .tb-canvas.tb-fill > svg { width: 100%; }
@@ -2249,6 +3312,41 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2249
3312
  .tb-chart-swatch { width: 12px; height: 12px; border-radius: 3px; background: var(--tb-swatch); }
2250
3313
  .tb-chart-empty { margin: 0; color: var(--tb-muted); }
2251
3314
  .tb-chart-caption[hidden], .tb-chart-plot[hidden], .tb-chart-legend[hidden], .tb-chart-empty[hidden] { display: none; }
3315
+ .tb-orbit { position: relative; align-self: stretch; width: 100%; min-width: 0; height: 480px; border-radius: var(--tb-radius);
3316
+ background: radial-gradient(ellipse at 50% 45%, color-mix(in oklch, var(--tb-primary) 7%, transparent) 0%, transparent 70%); }
3317
+ .tb-orbit.tb-small { height: 320px; }
3318
+ .tb-orbit.tb-large { height: 640px; }
3319
+ .tb-orbit.tb-fit { height: auto; min-height: 320px; }
3320
+ .tb-orbit > svg { display: block; position: absolute; inset: 0; width: 100%; height: 100%; cursor: grab; user-select: none; touch-action: none; outline: none; }
3321
+ .tb-orbit > svg.tb-orbit-panning { cursor: grabbing; }
3322
+ .tb-orbit > svg:focus-visible { box-shadow: inset 0 0 0 3px var(--tb-focus-ring); border-radius: var(--tb-radius); }
3323
+ .tb-orbit-node { cursor: pointer; outline: none; }
3324
+ .tb-orbit-focus { cursor: default; }
3325
+ .tb-orbit-body { vector-effect: non-scaling-stroke; transition: stroke-width .2s; }
3326
+ .tb-orbit-node:hover .tb-orbit-body, .tb-orbit-node:focus-visible .tb-orbit-body { stroke-width: 3; }
3327
+ .tb-orbit-node:focus-visible .tb-orbit-body { stroke: var(--tb-focus); }
3328
+ .tb-orbit-halo { opacity: .55; transition: opacity .25s; pointer-events: none; }
3329
+ .tb-orbit-node:hover .tb-orbit-halo, .tb-orbit-node:focus-visible .tb-orbit-halo { opacity: 1; }
3330
+ .tb-orbit-node text { pointer-events: none; fill: var(--tb-text); text-anchor: middle; dominant-baseline: middle; font-family: var(--tb-font); }
3331
+ .tb-orbit-node .tb-orbit-count { fill: var(--tb-muted); }
3332
+ .tb-orbit-line, .tb-orbit-step { fill: none; vector-effect: non-scaling-stroke; pointer-events: none; }
3333
+ .tb-orbit-line { stroke-width: 1; }
3334
+ .tb-orbit-step { stroke-linecap: round; }
3335
+ .tb-orbit-spin { animation: tb-orbit-spin 60s linear infinite; }
3336
+ .tb-orbit-spin.tb-orbit-rev { animation-direction: reverse; animation-duration: 90s; }
3337
+ .tb-orbit-spin.tb-orbit-fast { animation-duration: 24s; }
3338
+ @keyframes tb-orbit-spin { to { transform: rotate(360deg); } }
3339
+ .tb-orbit-now { animation: tb-orbit-pulse 1.8s ease-in-out infinite; }
3340
+ @keyframes tb-orbit-pulse { 50% { opacity: .35; } }
3341
+ .tb-orbit-edge { fill: none; pointer-events: none; }
3342
+ .tb-orbit-edge-solid, .tb-orbit-edge-dashed { stroke: var(--tb-accent); stroke-width: 1.4; stroke-opacity: .7; }
3343
+ .tb-orbit-edge-dashed { stroke-dasharray: 5 5; }
3344
+ .tb-orbit-edge-faint { stroke: var(--tb-muted); stroke-width: 1; stroke-opacity: .35; }
3345
+ .tb-orbit-edge-trail { stroke: var(--tb-muted); stroke-width: 1; stroke-opacity: .5; stroke-dasharray: 2 6; }
3346
+ .tb-orbit-label { font-size: 11px; font-family: var(--tb-font); fill: var(--tb-muted); text-anchor: middle; pointer-events: none;
3347
+ paint-order: stroke; stroke: var(--tb-bg); stroke-width: 3px; letter-spacing: .02em; }
3348
+ .tb-orbit-label.tb-orbit-later { visibility: hidden; }
3349
+ .tb-orbit-label.tb-orbit-later.tb-orbit-shown { visibility: visible; }
2252
3350
  .tb-image.tb-small { width: 96px; }
2253
3351
  .tb-image.tb-medium { width: 240px; }
2254
3352
  .tb-image.tb-large { width: 480px; }
@@ -2259,6 +3357,17 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2259
3357
  .tb-progress-label[hidden] { display: none; }
2260
3358
  .tb-progress { height: 8px; border-radius: 4px; background: var(--tb-border); overflow: hidden; }
2261
3359
  .tb-upload-progress { height: 6px; }
3360
+ .tb-widget { display: block; width: 100%; min-width: 0; }
3361
+ .tb-photo { display: flex; flex-wrap: wrap; align-items: center; gap: var(--tb-space-4); margin: calc(-1 * var(--tb-space-2)); padding: var(--tb-space-2); border: 1px dashed transparent; border-radius: var(--tb-radius-lg); transition: border-color var(--tb-fast) var(--tb-ease), background var(--tb-fast) var(--tb-ease); }
3362
+ .tb-photo.tb-drop-over { border-color: var(--tb-primary); background: var(--tb-primary-soft); }
3363
+ .tb-photo-frame { flex: none; width: 96px; height: 96px; display: grid; place-items: center; overflow: hidden; border: var(--tb-line) solid var(--tb-border); border-radius: var(--tb-radius-lg); background: var(--tb-bg); color: var(--tb-muted); }
3364
+ .tb-photo-frame.tb-photo-pick { cursor: pointer; }
3365
+ .tb-photo-frame.tb-round { border-radius: 50%; }
3366
+ .tb-photo-frame > img { display: block; width: 100%; height: 100%; object-fit: cover; }
3367
+ .tb-photo-frame > .tb-icon { width: 32px; height: 32px; }
3368
+ .tb-invalid .tb-photo-frame { border-color: var(--tb-danger); }
3369
+ .tb-photo-actions { display: flex; flex-wrap: wrap; gap: var(--tb-space-2); }
3370
+ .tb-photo-actions[hidden], .tb-photo-remove[hidden] { display: none; }
2262
3371
  .tb-upload-progress[hidden] { display: none; }
2263
3372
  .tb-progress-bar { height: 100%; width: 0; border-radius: inherit; background: var(--tb-primary); transition: width 300ms var(--tb-ease); }
2264
3373
  .tb-success .tb-progress-bar { background: var(--tb-success); }
@@ -2292,6 +3401,10 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2292
3401
  .tb-table tbody tr:last-child td { border-bottom: 0; }
2293
3402
  .tb-table .tb-num { text-align: right; font-variant-numeric: tabular-nums; }
2294
3403
  .tb-table-wrap:has(tbody:empty) thead { display: none; }
3404
+ /* the room of the rows a long table does not draw */
3405
+ .tb-table .tb-room[hidden] { display: none; }
3406
+ .tb-table.tb-fixed { table-layout: fixed; }
3407
+ .tb-table .tb-room :is(tr, td) { padding: 0; border: 0; margin: 0; background: none; box-shadow: none; }
2295
3408
  .tb-table th:has(> .tb-sort) { padding: 0; }
2296
3409
  .tb-sort {
2297
3410
  display: flex;
@@ -2319,8 +3432,8 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2319
3432
  border-top: var(--tb-line) solid var(--tb-border);
2320
3433
  border-bottom: 0;
2321
3434
  }
2322
- .tb-selectable tbody tr:not(.tb-group-head, .tb-group-foot), .tb-selectable .tb-list > li:not(.tb-group-head, .tb-group-foot) { cursor: pointer; transition: background var(--tb-fast) var(--tb-ease); }
2323
- .tb-selectable tbody tr:not(.tb-group-head, .tb-group-foot):hover, .tb-selectable .tb-list > li:not(.tb-group-head, .tb-group-foot):hover { background: var(--tb-bg); }
3435
+ .tb-selectable tbody:not(.tb-room) tr:not(.tb-group-head, .tb-group-foot), .tb-selectable .tb-list > li:not(.tb-group-head, .tb-group-foot) { cursor: pointer; transition: background var(--tb-fast) var(--tb-ease); }
3436
+ .tb-selectable tbody:not(.tb-room) tr:not(.tb-group-head, .tb-group-foot):hover, .tb-selectable .tb-list > li:not(.tb-group-head, .tb-group-foot):hover { background: var(--tb-bg); }
2324
3437
  .tb-selectable tbody tr:focus-visible, .tb-selectable .tb-list > li:focus-visible { outline: none; box-shadow: inset 0 0 0 2px var(--tb-focus); }
2325
3438
  .tb-table tr.tb-selected, .tb-list > li.tb-selected { background: var(--tb-primary-soft); }
2326
3439
  /* the head and foot of a group in the rows: a title the width of the row, and its subtotals */
@@ -2346,15 +3459,19 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2346
3459
  .tb-list:empty { display: none; }
2347
3460
  .tb-list > li {
2348
3461
  display: flex;
2349
- flex-direction: column;
2350
- justify-content: center;
2351
- gap: 2px;
3462
+ align-items: center;
3463
+ gap: var(--tb-space-3);
2352
3464
  min-height: var(--tb-control);
2353
3465
  padding: var(--tb-space-3) var(--tb-space-4);
2354
3466
  border-bottom: var(--tb-line) solid var(--tb-border);
2355
3467
  }
2356
3468
  .tb-list > li:last-child { border-bottom: 0; }
3469
+ .tb-list-texts { display: flex; flex-direction: column; justify-content: center; gap: 2px; min-width: 0; }
2357
3470
  .tb-list-primary { font-weight: 550; }
3471
+ /* the picture of a row, in a column of images or at the start of a list's item */
3472
+ .tb-thumb { display: block; flex: none; width: 40px; height: 40px; object-fit: cover; border-radius: var(--tb-radius); background: var(--tb-bg); }
3473
+ .tb-thumb.tb-round { border-radius: 50%; }
3474
+ .tb-table td.tb-thumb-cell { width: 1%; padding-top: var(--tb-space-1); padding-bottom: var(--tb-space-1); }
2358
3475
  .tb-list-secondary { color: var(--tb-muted); font-size: 13px; }
2359
3476
  .tb-list-secondary:empty { display: none; }
2360
3477
 
@@ -2619,6 +3736,171 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2619
3736
  .tb-toast.tb-warning::before { background: var(--tb-warning); }
2620
3737
  .tb-toast.tb-danger { background: var(--tb-danger); color: var(--tb-on-danger); }
2621
3738
 
3739
+ /* under trebol dev, the errors the app does not catch */
3740
+ .tb-dev-errors {
3741
+ position: fixed;
3742
+ inset: var(--tb-space-4) var(--tb-space-4) auto;
3743
+ width: auto;
3744
+ max-width: 960px;
3745
+ max-height: calc(100vh - 2 * var(--tb-space-4));
3746
+ margin: 0 auto;
3747
+ overflow: auto;
3748
+ box-sizing: border-box;
3749
+ padding: var(--tb-space-4) var(--tb-space-5);
3750
+ border: 1px solid var(--tb-border);
3751
+ border-left: 4px solid var(--tb-danger);
3752
+ border-radius: var(--tb-radius);
3753
+ background: var(--tb-surface);
3754
+ color: var(--tb-text);
3755
+ box-shadow: var(--tb-shadow-3);
3756
+ font-family: var(--tb-font);
3757
+ }
3758
+ .tb-dev-errors header {
3759
+ display: flex;
3760
+ align-items: center;
3761
+ justify-content: space-between;
3762
+ gap: var(--tb-space-3);
3763
+ margin-bottom: var(--tb-space-3);
3764
+ font-weight: 600;
3765
+ }
3766
+ .tb-dev-errors pre {
3767
+ margin: 0 0 var(--tb-space-3);
3768
+ white-space: pre-wrap;
3769
+ overflow-wrap: anywhere;
3770
+ font: 13px/1.6 ui-monospace, Menlo, Consolas, monospace;
3771
+ }
3772
+
3773
+ /* under trebol dev, the dev tools: Faces, Console, Log */
3774
+ .tb-dev-tools {
3775
+ position: fixed;
3776
+ inset: auto 0 0 0;
3777
+ width: 100%;
3778
+ max-width: none;
3779
+ margin: 0;
3780
+ padding: 0;
3781
+ box-sizing: border-box;
3782
+ flex-direction: column;
3783
+ border: 0;
3784
+ border-top: 1px solid var(--tb-border-strong);
3785
+ background: var(--tb-surface);
3786
+ color: var(--tb-text);
3787
+ box-shadow: var(--tb-shadow-3);
3788
+ font: 13px/1.5 var(--tb-font);
3789
+ }
3790
+ .tb-dev-tools:popover-open { display: flex; }
3791
+ .tb-dev-tools :is(pre, code, .tb-dev-in, .tb-dev-node, .tb-dev-detail dd, .tb-dev-text) {
3792
+ font-family: ui-monospace, Menlo, Consolas, monospace;
3793
+ font-size: 12px;
3794
+ }
3795
+ .tb-dev-grip { height: 6px; margin-top: -3px; cursor: ns-resize; flex: none; touch-action: none; }
3796
+ .tb-dev-tools header {
3797
+ display: flex;
3798
+ align-items: center;
3799
+ gap: var(--tb-space-2);
3800
+ padding: 0 var(--tb-space-3) 0 0;
3801
+ border-bottom: 1px solid var(--tb-border);
3802
+ flex: none;
3803
+ }
3804
+ .tb-dev-tabs { display: flex; }
3805
+ .tb-dev-space { flex: 1; }
3806
+ .tb-dev-tab, .tb-dev-button, .tb-dev-node, .tb-dev-opener {
3807
+ font: inherit;
3808
+ color: inherit;
3809
+ cursor: pointer;
3810
+ }
3811
+ .tb-dev-tab {
3812
+ padding: var(--tb-space-2) var(--tb-space-4);
3813
+ border: 0;
3814
+ border-bottom: 2px solid transparent;
3815
+ background: transparent;
3816
+ color: var(--tb-muted);
3817
+ }
3818
+ .tb-dev-tab[aria-selected="true"] { color: var(--tb-text); border-bottom-color: var(--tb-primary); font-weight: 600; }
3819
+ .tb-dev-button {
3820
+ padding: 2px var(--tb-space-3);
3821
+ border: 1px solid var(--tb-border-strong);
3822
+ border-radius: var(--tb-radius);
3823
+ background: var(--tb-bg);
3824
+ }
3825
+ .tb-dev-button[aria-pressed="true"] { background: var(--tb-primary); color: var(--tb-on-primary); border-color: var(--tb-primary); }
3826
+ .tb-dev-tools :is(button, a, textarea):focus-visible { outline: 2px solid var(--tb-focus); outline-offset: -2px; }
3827
+ .tb-dev-body { flex: 1; min-height: 0; display: flex; }
3828
+ .tb-dev-pane { flex: 1; min-width: 0; min-height: 0; }
3829
+ .tb-dev-pane[hidden] { display: none; }
3830
+ .tb-dev-faces { display: grid; grid-template-columns: minmax(200px, 2fr) 3fr; }
3831
+ .tb-dev-tree { overflow: auto; border-right: 1px solid var(--tb-border); padding: var(--tb-space-1) 0; }
3832
+ .tb-dev-node {
3833
+ display: block;
3834
+ width: 100%;
3835
+ padding: 1px var(--tb-space-2);
3836
+ border: 0;
3837
+ background: transparent;
3838
+ text-align: left;
3839
+ white-space: nowrap;
3840
+ overflow: hidden;
3841
+ text-overflow: ellipsis;
3842
+ }
3843
+ .tb-dev-node:hover { background: var(--tb-primary-soft); }
3844
+ .tb-dev-node[aria-current="true"] { background: var(--tb-primary); color: var(--tb-on-primary); }
3845
+ .tb-dev-unseen { color: var(--tb-muted); }
3846
+ .tb-dev-detail { overflow: auto; padding: var(--tb-space-3) var(--tb-space-4); }
3847
+ .tb-dev-detail h3 { margin: 0 0 var(--tb-space-1); font-size: 14px; }
3848
+ .tb-dev-detail dl { display: grid; grid-template-columns: max-content 1fr; gap: 2px var(--tb-space-4); margin: var(--tb-space-3) 0 0; }
3849
+ .tb-dev-detail dt { color: var(--tb-muted); }
3850
+ .tb-dev-detail dd { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
3851
+ .tb-dev-place { margin: 0; }
3852
+ .tb-dev-place a { color: var(--tb-primary); }
3853
+ .tb-dev-hint { margin: 0; color: var(--tb-muted); }
3854
+ .tb-dev-console { display: flex; flex-direction: column; }
3855
+ .tb-dev-out { flex: 1; overflow: auto; padding: var(--tb-space-2) var(--tb-space-3); }
3856
+ .tb-dev-out pre { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
3857
+ .tb-dev-said-in { color: var(--tb-muted); }
3858
+ .tb-dev-said-error { color: var(--tb-danger); }
3859
+ .tb-dev-face { padding: 2px var(--tb-space-3); color: var(--tb-muted); border-top: 1px solid var(--tb-border); }
3860
+ .tb-dev-prompt { display: flex; align-items: flex-start; gap: var(--tb-space-2); padding: var(--tb-space-1) var(--tb-space-3) var(--tb-space-2); }
3861
+ .tb-dev-sign { font: 12px/20px ui-monospace, Menlo, Consolas, monospace; color: var(--tb-primary); }
3862
+ textarea.tb-dev-in { flex: 1; resize: none; border: 0; padding: 0; background: transparent; color: var(--tb-text); line-height: 20px; outline: none; }
3863
+ .tb-dev-log { display: flex; flex-direction: column; }
3864
+ .tb-dev-bar { display: flex; justify-content: flex-end; padding: var(--tb-space-1) var(--tb-space-3); flex: none; }
3865
+ ol.tb-dev-entries { flex: 1; margin: 0; overflow: auto; list-style: none; padding: 0 var(--tb-space-3) var(--tb-space-2); }
3866
+ ol.tb-dev-entries li { display: grid; grid-template-columns: max-content 5.5em 1fr; gap: var(--tb-space-3); padding: 1px 0; border-bottom: 1px solid var(--tb-border); }
3867
+ ol.tb-dev-entries time { color: var(--tb-muted); font-variant-numeric: tabular-nums; }
3868
+ .tb-dev-kind { color: var(--tb-muted); }
3869
+ ol.tb-dev-entries .tb-dev-text { overflow-wrap: anywhere; }
3870
+ ol.tb-dev-entries :is(.tb-dev-error, .tb-dev-failed) .tb-dev-kind, ol.tb-dev-entries :is(.tb-dev-error, .tb-dev-failed) .tb-dev-text { color: var(--tb-danger); }
3871
+ ol.tb-dev-entries .tb-dev-warning .tb-dev-kind { color: var(--tb-warning); }
3872
+ .tb-dev-opener {
3873
+ position: fixed;
3874
+ inset: auto var(--tb-space-3) var(--tb-space-3) auto;
3875
+ margin: 0;
3876
+ padding: 2px var(--tb-space-3);
3877
+ border: 1px solid var(--tb-border-strong);
3878
+ border-radius: 999px;
3879
+ background: var(--tb-surface);
3880
+ box-shadow: var(--tb-shadow-1);
3881
+ font: 600 12px/1.6 var(--tb-font);
3882
+ opacity: 0.7;
3883
+ }
3884
+ .tb-dev-opener:hover, .tb-dev-opener:focus-visible { opacity: 1; }
3885
+ .tb-dev-outline {
3886
+ position: fixed;
3887
+ margin: 0;
3888
+ padding: 0;
3889
+ box-sizing: border-box;
3890
+ border: 2px solid var(--tb-primary);
3891
+ border-radius: 2px;
3892
+ background: transparent;
3893
+ pointer-events: none;
3894
+ }
3895
+ .tb-dev-outline.tb-dev-pointed { border-style: dashed; background: color-mix(in srgb, var(--tb-primary) 12%, transparent); }
3896
+ .tb-dev-picking, .tb-dev-picking * { cursor: crosshair !important; }
3897
+ @media (max-width: 640px) {
3898
+ .tb-dev-faces { grid-template-columns: 1fr; grid-template-rows: 2fr 3fr; }
3899
+ .tb-dev-tree { border-right: 0; border-bottom: 1px solid var(--tb-border); }
3900
+ ol.tb-dev-entries li { grid-template-columns: max-content 1fr; }
3901
+ ol.tb-dev-entries time { display: none; }
3902
+ }
3903
+
2622
3904
  @media (max-width: 640px) {
2623
3905
  .tb-wide-only { display: none !important; }
2624
3906
  .tb-view:has(.tb-fit) { height: auto; }
@@ -2665,6 +3947,8 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2665
3947
  text-align: right;
2666
3948
  }
2667
3949
  .tb-table td::before { content: attr(data-label); color: var(--tb-muted); font-weight: 500; text-align: left; }
3950
+ .tb-table td.tb-thumb-cell { width: auto; justify-content: flex-start; }
3951
+ .tb-table td.tb-thumb-cell::before { content: none; }
2668
3952
  .tb-table tr.tb-group-head { padding: var(--tb-space-3) 0 0; background: none; border: 0; box-shadow: none; }
2669
3953
  .tb-table .tb-group-head > th, .tb-table .tb-group-head.tb-level-2 > th { display: block; padding: 0; background: none; border: 0; }
2670
3954
  .tb-table .tb-level-2 > :first-child { padding-left: 0; }
@@ -2691,7 +3975,7 @@ button.tb-crumb:focus-visible { outline: none; box-shadow: 0 0 0 3px var(--tb-fo
2691
3975
  * { transition: none !important; animation: none !important; }
2692
3976
  .tb-indeterminate .tb-progress-bar { width: 100%; opacity: 0.35; }
2693
3977
  }
2694
- `,$b={modern:"",classic:String.raw`
3978
+ `,sh={modern:"",classic:String.raw`
2695
3979
  /* classic: controls in relief on a grey window, sunken wells for what is typed, title bars on dialogs */
2696
3980
  :root {
2697
3981
  --tb-raise: inset 1px 1px 0 var(--tb-bevel-hi), inset -1px -1px 0 var(--tb-bevel-lo);
@@ -2984,17 +4268,22 @@ select.tb-input:focus { box-shadow: 0 0 0 1px var(--tb-surface), 0 0 0 3px var(-
2984
4268
  .tb-dialog-title { font-size: 20px; font-weight: 600; letter-spacing: 0; }
2985
4269
  .tb-toast { background: var(--tb-raised); color: var(--tb-text); border: 1px solid var(--tb-border); border-radius: 8px; font-weight: 400; }
2986
4270
  .tb-scroll { border-radius: 8px; }
2987
- `};var tc={search:"M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14zM16.5 16.5L21 21",plus:"M12 5v14M5 12h14",minus:"M5 12h14",close:"M6 6l12 12M18 6L6 18",check:"M5 12.5l4.5 4.5L19 7","chevron-left":"M15 6l-6 6 6 6","chevron-right":"M9 6l6 6-6 6","chevron-up":"M6 15l6-6 6 6","chevron-down":"M6 9l6 6 6-6","chevrons-left":"M11 6l-6 6 6 6M19 6l-6 6 6 6","chevrons-right":"M5 6l6 6-6 6M13 6l6 6-6 6","arrow-left":"M19 12H5M11 6l-6 6 6 6","arrow-right":"M5 12h14M13 6l6 6-6 6","arrow-up":"M12 19V5M6 11l6-6 6 6","arrow-down":"M12 5v14M6 13l6 6 6-6",edit:"M4 20h4L19 9l-4-4L4 16v4zM13.5 6.5l4 4",trash:"M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6",user:"M12 4a4 4 0 1 0 0 8a4 4 0 1 0 0-8zM4 21c0-4 3.5-7 8-7s8 3 8 7",mail:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a1 1 0 0 1-1 1A16 16 0 0 1 4 5a1 1 0 0 1 1-1z",info:"M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18zM12 11v6M12 7.5v.5",warning:"M12 3L2 20h20L12 3zM12 10v4M12 17v.5",menu:"M4 6h16M4 12h16M4 18h16",home:"M3 11l9-7 9 7M5 9.5V20h5v-6h4v6h5V9.5",folder:"M3 6.5A1.5 1.5 0 0 1 4.5 5H9l2 2.5h8.5A1.5 1.5 0 0 1 21 9v9.5a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18.5z",door:"M6 21V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v17M3 21h18M14.5 12v.5",building:"M5 21V4h14v17M3 21h18M9 8h.01M15 8h.01M9 12h.01M15 12h.01M10 21v-5h4v5",landmark:"M3 21h18M5 18h14M12 3l9 5H3zM6 8v10M10 8v10M14 8v10M18 8v10",shield:"M12 3l8 3v6c0 5-3.5 8-8 9c-4.5-1-8-4-8-9V6z",fireworks:"M12 22v-9M12 3v3M5 7l2.5 2M19 7l-2.5 2M3.5 13h3M17.5 13h3M8 3.5l1 2.5M16 3.5l-1 2.5",coins:"M9 4a6 6 0 1 0 0 12a6 6 0 1 0 0-12zM15.5 8.3a6 6 0 1 1-7.2 7.2",book:"M4 5a2 2 0 0 1 2-2h14v15H6a2 2 0 0 0-2 2zM4 20a2 2 0 0 0 2 1h14v-3",scale:"M12 4v17M7 21h10M5 7h14M5 7l-3 7a3.5 3.5 0 0 0 6 0zM19 7l-3 7a3.5 3.5 0 0 0 6 0z",people:"M9 5a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7zM2.5 20c0-3.5 3-6 6.5-6s6.5 2.5 6.5 6M16 5.3a3.5 3.5 0 0 1 0 6.4M18 14.5c2 .8 3.5 2.8 3.5 5.5",tree:"M12 3l6 7h-3l4 5H5l4-5H6zM12 15v6",truck:"M2 6h12v11H2zM14 10h4l4 4v3h-8zM6.5 15a2 2 0 1 0 0 4a2 2 0 1 0 0-4zM17.5 15a2 2 0 1 0 0 4a2 2 0 1 0 0-4z",box:"M12 3l8 4.5v9L12 21l-8-4.5v-9zM4 7.5l8 4.5 8-4.5M12 12v9",file:"M6 3h8l4 4v14H6zM14 3v4h4M9 12h6M9 16h6",image:"M4 5h16v14H4zM4 16l5-5 4 4 2-2 5 5M15 8.5a1.5 1.5 0 1 0 0 3a1.5 1.5 0 1 0 0-3z",settings:"M4 7h10M18 7h2M4 17h4M12 17h8M16 5v4M10 15v4",filter:"M4 5h16l-6 8v6l-4-2v-4L4 5z",refresh:"M20 12a8 8 0 1 1-2.3-5.7M20 4v5h-5",download:"M12 4v11M7 10l5 5 5-5M5 20h14",upload:"M12 16V4M7 9l5-5 5 5M5 20h14",external:"M14 4h6v6M20 4l-9 9M18 14v6H4V6h6",eye:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12zM12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z",lock:"M5 11h14v10H5zM8 11V7a4 4 0 0 1 8 0v4",calendar:"M4 6h16v15H4zM4 10h16M8 3v4M16 3v4",star:"M12 3l2.8 5.8 6.2.9-4.5 4.4 1 6.3L12 17.5l-5.5 2.9 1-6.3L3 9.7l6.2-.9L12 3z",heart:"M12 20s-8-5-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 9c0 6-8 11-8 11z",type:"M5 7V4h14v3M12 4v16M9 20h6",lines:"M4 6h16M4 12h16M4 18h10",rows:"M3 5h18v6H3zM3 13h18v6H3z",bold:"M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z",italic:"M10 5h8M6 19h8M14 5l-4 14",heading:"M6 5v14M18 5v14M6 12h12",list:"M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01","list-ordered":"M10 6h10M10 12h10M10 18h10M4 5l1.5-1v5M4 14.5a1.5 1.5 0 0 1 3 0c0 1.5-3 2-3 4h3",link:"M10 14a4 4 0 0 0 6 0l3-3a4 4 0 0 0-6-6l-1 1M14 10a4 4 0 0 0-6 0l-3 3a4 4 0 0 0 6 6l1-1",hash:"M5 9h14M5 15h14M10 4L8 20M16 4l-2 16",banknote:"M3 7h18v10H3zM12 9.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5zM6.5 10v4M17.5 10v4","check-square":"M4 4h16v16H4zM8 12l3 3 5-6",toggle:"M8 7h8a5 5 0 0 1 0 10H8A5 5 0 0 1 8 7zM16 9.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5z",radio:"M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18zM12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z",dropdown:"M3 7h18v10H3zM14 11l2 2 2-2",panel:"M4 4h16v16H4zM4 9h16",columns:"M3 5h7v14H3zM14 5h7v14h-7z",grid:"M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z",tabs:"M3 9h18v11H3zM3 9V5h7v4M10 5h6v4",pointer:"M6 4l13 6-5.5 2L11 18z"},zv=Object.keys(tc),ec="http://www.w3.org/2000/svg";function vs(e,t=null){let n=tc[e];if(n===void 0)return null;let r=document.createElementNS(ec,"svg");r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("class","tb-icon"),t===null?r.setAttribute("aria-hidden","true"):(r.setAttribute("role","img"),r.setAttribute("aria-label",t));let o=document.createElementNS(ec,"path");return o.setAttribute("d",n),r.append(o),r}var nc=/^(#{1,3}) +(.*)$/,So=/^[-*] +(.*)$/,ys=/^\d+\. +(.*)$/;function oc(e){let t=e.replace(/\r\n?/g,`
4271
+ `};var Ou={search:"M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14zM16.5 16.5L21 21",plus:"M12 5v14M5 12h14",minus:"M5 12h14",close:"M6 6l12 12M18 6L6 18",check:"M5 12.5l4.5 4.5L19 7","chevron-left":"M15 6l-6 6 6 6","chevron-right":"M9 6l6 6-6 6","chevron-up":"M6 15l6-6 6 6","chevron-down":"M6 9l6 6 6-6","chevrons-left":"M11 6l-6 6 6 6M19 6l-6 6 6 6","chevrons-right":"M5 6l6 6-6 6M13 6l6 6-6 6","arrow-left":"M19 12H5M11 6l-6 6 6 6","arrow-right":"M5 12h14M13 6l6 6-6 6","arrow-up":"M12 19V5M6 11l6-6 6 6","arrow-down":"M12 5v14M6 13l6 6 6-6",edit:"M4 20h4L19 9l-4-4L4 16v4zM13.5 6.5l4 4",trash:"M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6",user:"M12 4a4 4 0 1 0 0 8a4 4 0 1 0 0-8zM4 21c0-4 3.5-7 8-7s8 3 8 7",mail:"M3 6h18v12H3zM3 7l9 6 9-6",phone:"M5 4h4l2 5-2.5 1.5a11 11 0 0 0 5 5L15 13l5 2v4a1 1 0 0 1-1 1A16 16 0 0 1 4 5a1 1 0 0 1 1-1z",info:"M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18zM12 11v6M12 7.5v.5",warning:"M12 3L2 20h20L12 3zM12 10v4M12 17v.5",menu:"M4 6h16M4 12h16M4 18h16",home:"M3 11l9-7 9 7M5 9.5V20h5v-6h4v6h5V9.5",folder:"M3 6.5A1.5 1.5 0 0 1 4.5 5H9l2 2.5h8.5A1.5 1.5 0 0 1 21 9v9.5a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 18.5z",door:"M6 21V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v17M3 21h18M14.5 12v.5",building:"M5 21V4h14v17M3 21h18M9 8h.01M15 8h.01M9 12h.01M15 12h.01M10 21v-5h4v5",landmark:"M3 21h18M5 18h14M12 3l9 5H3zM6 8v10M10 8v10M14 8v10M18 8v10",shield:"M12 3l8 3v6c0 5-3.5 8-8 9c-4.5-1-8-4-8-9V6z",fireworks:"M12 22v-9M12 3v3M5 7l2.5 2M19 7l-2.5 2M3.5 13h3M17.5 13h3M8 3.5l1 2.5M16 3.5l-1 2.5",coins:"M9 4a6 6 0 1 0 0 12a6 6 0 1 0 0-12zM15.5 8.3a6 6 0 1 1-7.2 7.2",book:"M4 5a2 2 0 0 1 2-2h14v15H6a2 2 0 0 0-2 2zM4 20a2 2 0 0 0 2 1h14v-3",scale:"M12 4v17M7 21h10M5 7h14M5 7l-3 7a3.5 3.5 0 0 0 6 0zM19 7l-3 7a3.5 3.5 0 0 0 6 0z",people:"M9 5a3.5 3.5 0 1 0 0 7a3.5 3.5 0 1 0 0-7zM2.5 20c0-3.5 3-6 6.5-6s6.5 2.5 6.5 6M16 5.3a3.5 3.5 0 0 1 0 6.4M18 14.5c2 .8 3.5 2.8 3.5 5.5",tree:"M12 3l6 7h-3l4 5H5l4-5H6zM12 15v6",truck:"M2 6h12v11H2zM14 10h4l4 4v3h-8zM6.5 15a2 2 0 1 0 0 4a2 2 0 1 0 0-4zM17.5 15a2 2 0 1 0 0 4a2 2 0 1 0 0-4z",box:"M12 3l8 4.5v9L12 21l-8-4.5v-9zM4 7.5l8 4.5 8-4.5M12 12v9",file:"M6 3h8l4 4v14H6zM14 3v4h4M9 12h6M9 16h6",image:"M4 5h16v14H4zM4 16l5-5 4 4 2-2 5 5M15 8.5a1.5 1.5 0 1 0 0 3a1.5 1.5 0 1 0 0-3z",settings:"M4 7h10M18 7h2M4 17h4M12 17h8M16 5v4M10 15v4",filter:"M4 5h16l-6 8v6l-4-2v-4L4 5z",refresh:"M20 12a8 8 0 1 1-2.3-5.7M20 4v5h-5",download:"M12 4v11M7 10l5 5 5-5M5 20h14",upload:"M12 16V4M7 9l5-5 5 5M5 20h14",external:"M14 4h6v6M20 4l-9 9M18 14v6H4V6h6",eye:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12zM12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z",lock:"M5 11h14v10H5zM8 11V7a4 4 0 0 1 8 0v4",calendar:"M4 6h16v15H4zM4 10h16M8 3v4M16 3v4",star:"M12 3l2.8 5.8 6.2.9-4.5 4.4 1 6.3L12 17.5l-5.5 2.9 1-6.3L3 9.7l6.2-.9L12 3z",heart:"M12 20s-8-5-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 9c0 6-8 11-8 11z",type:"M5 7V4h14v3M12 4v16M9 20h6",lines:"M4 6h16M4 12h16M4 18h10",rows:"M3 5h18v6H3zM3 13h18v6H3z",bold:"M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z",italic:"M10 5h8M6 19h8M14 5l-4 14",heading:"M6 5v14M18 5v14M6 12h12",list:"M9 6h11M9 12h11M9 18h11M4 6h.01M4 12h.01M4 18h.01","list-ordered":"M10 6h10M10 12h10M10 18h10M4 5l1.5-1v5M4 14.5a1.5 1.5 0 0 1 3 0c0 1.5-3 2-3 4h3",link:"M10 14a4 4 0 0 0 6 0l3-3a4 4 0 0 0-6-6l-1 1M14 10a4 4 0 0 0-6 0l-3 3a4 4 0 0 0 6 6l1-1",hash:"M5 9h14M5 15h14M10 4L8 20M16 4l-2 16",banknote:"M3 7h18v10H3zM12 9.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5zM6.5 10v4M17.5 10v4","check-square":"M4 4h16v16H4zM8 12l3 3 5-6",toggle:"M8 7h8a5 5 0 0 1 0 10H8A5 5 0 0 1 8 7zM16 9.5a2.5 2.5 0 1 0 0 5a2.5 2.5 0 1 0 0-5z",radio:"M12 3a9 9 0 1 0 0 18a9 9 0 1 0 0-18zM12 9a3 3 0 1 0 0 6a3 3 0 1 0 0-6z",dropdown:"M3 7h18v10H3zM14 11l2 2 2-2",panel:"M4 4h16v16H4zM4 9h16",columns:"M3 5h7v14H3zM14 5h7v14h-7z",grid:"M4 4h7v7H4zM13 4h7v7h-7zM4 13h7v7H4zM13 13h7v7h-7z",tabs:"M3 9h18v11H3zM3 9V5h7v4M10 5h6v4",pointer:"M6 4l13 6-5.5 2L11 18z"},yk=Object.keys(Ou),Bu="http://www.w3.org/2000/svg";function xi(e,t=null){let n=Ou[e];if(n===void 0)return null;let r=document.createElementNS(Bu,"svg");r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("class","tb-icon"),t===null?r.setAttribute("aria-hidden","true"):(r.setAttribute("role","img"),r.setAttribute("aria-label",t));let o=document.createElementNS(Bu,"path");return o.setAttribute("d",n),r.append(o),r}var ih=[{file:"inter-cyrillic-ext.woff2",range:"U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F"},{file:"inter-cyrillic.woff2",range:"U+0301,U+0400-045F,U+0490-0491,U+04B0-04B1,U+2116"},{file:"inter-greek-ext.woff2",range:"U+1F00-1FFF"},{file:"inter-greek.woff2",range:"U+0370-0377,U+037A-037F,U+0384-038A,U+038C,U+038E-03A1,U+03A3-03FF"},{file:"inter-vietnamese.woff2",range:"U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB"},{file:"inter-latin-ext.woff2",range:"U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF"},{file:"inter-latin.woff2",range:"U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD"}];function Nu(e,t=ih){return t.map(n=>`@font-face { font-family: Inter; font-style: normal; font-weight: 100 900; font-display: swap; src: url(${e(n.file)}) format("woff2"); unicode-range: ${n.range}; }`).join(`
4272
+ `)}var ju=/^(#{1,3}) +(.*)$/,ba=/^[-*] +(.*)$/,Ci=/^\d+\. +(.*)$/;function Si(e){let t=e.replace(/\r\n?/g,`
2988
4273
  `).split(`
2989
- `),n=[],r=0;for(;r<t.length;){let o=t[r];if(o.trim()===""){r++;continue}let s=nc.exec(o);if(s!==null){n.push({k:"h",level:s[1].length,kids:yr(s[2])}),r++;continue}let i=So.test(o)?So:ys.test(o)?ys:null;if(i!==null){let c=[];for(let u=i.exec(t[r]??"");u!==null;u=i.exec(t[r]??""))c.push(yr(u[1])),r++;n.push({k:i===So?"ul":"ol",items:c});continue}let l=[];for(;r<t.length&&t[r].trim()!==""&&!nc.test(t[r])&&!So.test(t[r])&&!ys.test(t[r]);)l.push(t[r++]);n.push({k:"p",kids:yr(l.join(`
2990
- `))})}return n}function rc(e,t,n){for(let r=n;r<e.length;r++){if(e[r]==="\\"){r++;continue}if(e.startsWith(t,r)){if(t==="*"&&e[r+1]==="*"){r++;continue}if(t==="**")for(;e[r+2]==="*";)r++;return r}}return-1}function Nb(e,t){let n=0;for(let r=t;r<e.length&&e[r]!==`
2991
- `;r++)if(e[r]==="(")n++;else if(e[r]===")"&&n--===0)return r;return-1}function yr(e){let t=[],n=o=>{let s=t[t.length-1];s?.k==="text"?s.text+=o:t.push({k:"text",text:o})},r=0;for(;r<e.length;){let o=e[r];if(o==="\\"&&r+1<e.length)n(e[r+1]),r+=2;else if(o===`
2992
- `)t.push({k:"br"}),r++;else if(o==="*"){let s=e.startsWith("**",r)?"**":"*",i=rc(e,s,r+s.length);i<=r+s.length?(n(o),r++):(t.push({k:s==="**"?"b":"i",kids:yr(e.slice(r+s.length,i))}),r=i+s.length)}else if(o==="["){let s=rc(e,"]",r+1),i=s>0&&e[s+1]==="("?Nb(e,s+2):-1;i<0?(n(o),r++):(t.push({k:"a",href:e.slice(s+2,i),kids:yr(e.slice(r+1,s))}),r=i+1)}else n(o),r++}return t}function gn(e){return e.map(t=>{switch(t.k){case"text":return t.text.replace(/[\\*[\]]/g,"\\$&");case"br":return`
2993
- `;case"b":return`**${gn(t.kids)}**`;case"i":return`*${gn(t.kids)}*`;case"a":return`[${gn(t.kids)}](${t.href})`}}).join("")}function Ob(e){return gn(e).split(`
4274
+ `),n=[],r=0;for(;r<t.length;){let o=t[r];if(o.trim()===""){r++;continue}let a=ju.exec(o);if(a!==null){n.push({k:"h",level:a[1].length,kids:to(a[2])}),r++;continue}let i=ba.test(o)?ba:Ci.test(o)?Ci:null;if(i!==null){let c=[];for(let u=i.exec(t[r]??"");u!==null;u=i.exec(t[r]??""))c.push(to(u[1])),r++;n.push({k:i===ba?"ul":"ol",items:c});continue}let l=[];for(;r<t.length&&t[r].trim()!==""&&!ju.test(t[r])&&!ba.test(t[r])&&!Ci.test(t[r]);)l.push(t[r++]);n.push({k:"p",kids:to(l.join(`
4275
+ `))})}return n}function Pu(e,t,n){for(let r=n;r<e.length;r++){if(e[r]==="\\"){r++;continue}if(e.startsWith(t,r)){if(t==="*"&&e[r+1]==="*"){r++;continue}if(t==="**")for(;e[r+2]==="*";)r++;return r}}return-1}function lh(e,t){let n=0;for(let r=t;r<e.length&&e[r]!==`
4276
+ `;r++)if(e[r]==="(")n++;else if(e[r]===")"&&n--===0)return r;return-1}function to(e){let t=[],n=o=>{let a=t[t.length-1];a?.k==="text"?a.text+=o:t.push({k:"text",text:o})},r=0;for(;r<e.length;){let o=e[r];if(o==="\\"&&r+1<e.length)n(e[r+1]),r+=2;else if(o===`
4277
+ `)t.push({k:"br"}),r++;else if(o==="*"){let a=e.startsWith("**",r)?"**":"*",i=Pu(e,a,r+a.length);i<=r+a.length?(n(o),r++):(t.push({k:a==="**"?"b":"i",kids:to(e.slice(r+a.length,i))}),r=i+a.length)}else if(o==="["){let a=Pu(e,"]",r+1),i=a>0&&e[a+1]==="("?lh(e,a+2):-1;i<0?(n(o),r++):(t.push({k:"a",href:e.slice(a+2,i),kids:to(e.slice(r+1,a))}),r=i+1)}else n(o),r++}return t}function Un(e){return e.map(t=>{switch(t.k){case"text":return t.text.replace(/[\\*[\]]/g,"\\$&");case"br":return`
4278
+ `;case"b":return`**${Un(t.kids)}**`;case"i":return`*${Un(t.kids)}*`;case"a":return`[${Un(t.kids)}](${t.href})`}}).join("")}function ch(e){return Un(e).split(`
2994
4279
  `).map(t=>t.replace(/^(#{1,3} |- )/,"\\$1").replace(/^(\d+)\. /,"$1\\. ")).join(`
2995
- `)}function ac(e){return e.map(t=>{switch(t.k){case"p":return Ob(t.kids);case"h":return`${"#".repeat(t.level)} ${gn(t.kids)}`;case"ul":return t.items.map(n=>`- ${gn(n).replace(/\n/g," ")}`).join(`
2996
- `);case"ol":return t.items.map((n,r)=>`${r+1}. ${gn(n).replace(/\n/g," ")}`).join(`
4280
+ `)}function ha(e){return e.map(t=>{switch(t.k){case"p":return ch(t.kids);case"h":return`${"#".repeat(t.level)} ${Un(t.kids)}`;case"ul":return t.items.map(n=>`- ${Un(n).replace(/\n/g," ")}`).join(`
4281
+ `);case"ol":return t.items.map((n,r)=>`${r+1}. ${Un(n).replace(/\n/g," ")}`).join(`
2997
4282
  `)}}).join(`
2998
4283
 
2999
- `)}function ks(e){return/^(https?:|mailto:)/i.test(e.trim())}function et(e,t){if(e.t===a.Object){let n=ee(e.ctx,t);return n<0?x:e.ctx.vals[n]}if(e.t===a.Map){let n=e.s.data,r=L(t);for(let o=0;o+1<n.length;o+=2){let s=n[o];if(s.t===a.Word||s.t===a.SetWord||s.t===a.LitWord){if(L(s.sym)===r)return n[o+1]}else if(s.t===a.String&&L(A($(s)))===r)return n[o+1]}}return x}function xs(e){if(e.t!==a.Block)return null;let[t,n,r]=e.s.data.slice(e.i);if(t===void 0||n===void 0||r===void 0||t.t!==a.Word||n.t!==a.Integer)return null;let o=E(t.sym).toLowerCase();return o!=="head"&&o!=="foot"?null:{kind:o,level:Number(n.v)>=2?2:1,value:r}}function ic(e,t,n,r,o){let s=[],i=[];for(let l of e){if(xs(l)===null){i.push(l);continue}s.push(...sc(i,t,n,r,o),l),i=[]}return s.concat(sc(i,t,n,r,o))}function sc(e,t,n,r,o){let s=new Intl.Collator(r,{numeric:!0}),i=c=>c.t===a.None||c.t===a.String&&$(c)==="",l=(c,u)=>c.t===a.String&&u.t===a.String?s.compare($(c),$(u)):ln(c,u)??s.compare(o(c),o(u));return e.map(c=>({row:c,v:et(c,t)})).sort((c,u)=>{let d=i(c.v),f=i(u.v);return d||f?d===f?0:d?1:-1:n?l(u.v,c.v):l(c.v,u.v)}).map(c=>c.row)}var kr=["var(--tb-primary)","var(--tb-accent)","var(--tb-c-teal)","var(--tb-c-orange)","var(--tb-c-purple)","var(--tb-c-green)","var(--tb-c-pink)","var(--tb-c-gold)"],Hn=12,lc={fill:"var(--tb-muted)","font-size":Hn,"font-family":"var(--tb-font)"};function cc(e){return e.labels.length===0||e.series.length===0?[]:e.kind==="pie"?Wb(e):Pb(e)}function Db(e,t,n=!1,r=5){t===e&&(t=e+1);let o=(t-e)/r,s=10**Math.floor(Math.log10(o)),i=Math.max(n?1:0,[1,2,2.5,5,10].map(c=>c*s).find(c=>c>=o&&(!n||Number.isInteger(c)))),l=[];for(let c=Math.floor(e/i);c*i<=t+i*1e-9;c++)l.push(Number((c*i).toPrecision(12)));return l[l.length-1]<t&&l.push(l[l.length-1]+i),l}function Pb(e){let{labels:t,series:n,width:r,height:o,stacked:s,format:i}=e,l=t.length,c=s&&e.kind!=="line",u=n.map(()=>[]),d=n.map(()=>[]);for(let W=0;W<l;W++){let ie=0,Re=0;n.forEach((Me,Xe)=>{let Ke=Me.values[W]??0,Ar=c?Ke>=0?ie:Re:0;d[Xe][W]=Ar,u[Xe][W]=Ar+Ke,c&&(Ke>=0?ie+=Ke:Re+=Ke)})}let f=u.flat().concat(d.flat(),[0]),p=Db(Math.min(...f),Math.max(...f),f.every(Number.isInteger)),h=p[0],y=p[p.length-1],k=Math.max(...p.map(W=>i(W).length))*Hn*.6+8,M=8,w=Hn,v=Hn*2+4,C=Math.max(1,r-k-M),S=Math.max(1,o-w-v),I=W=>w+S-(W-h)/(y-h)*S,H=[];for(let W of p)H.push(be("line",{x1:k,x2:k+C,y1:I(W),y2:I(W),stroke:"var(--tb-border)","stroke-width":W===0?1.5:1})),H.push(be("text",{...lc,x:k-6,y:I(W),"text-anchor":"end","dominant-baseline":"middle"},[],i(W)));let z=C/l,fe=W=>k+z*(W+.5),ce=Math.max(1,Math.floor(C/(Math.max(...t.map(W=>W.length))*Hn*.6+12))),ye=Math.ceil(l/ce);t.forEach((W,ie)=>{ie%ye===0&&H.push(be("text",{...lc,x:fe(ie),y:w+S+Hn+4,"text-anchor":"middle","dominant-baseline":"middle"},[],W))});let je=(W,ie)=>be("title",{},[],`${t[W]}, ${ie.name}: ${ie.values[W]===null?"":i(ie.values[W])}`);if(e.kind==="bar"){let W=c?1:n.length,ie=z*.7,Re=ie/W;return n.forEach((Me,Xe)=>{for(let Ke=0;Ke<l;Ke++){if(Me.values[Ke]===null)continue;let Ar=k+z*Ke+(z-ie)/2+(c?0:Re*Xe),Us=I(Math.max(d[Xe][Ke],u[Xe][Ke])),nu=I(Math.min(d[Xe][Ke],u[Xe][Ke]));H.push(be("rect",{x:Ar+1,y:Us,width:Math.max(1,Re-2),height:Math.max(0,nu-Us),fill:Me.color,rx:2},[je(Ke,Me)]))}}),H}let Ye=[];return n.forEach((W,ie)=>{let Re=[];for(let Me=0;Me<l;Me++)W.values[Me]!==null&&Re.push(`${fe(Me)},${I(u[ie][Me])}`);if(e.kind==="area"){let Me=[];for(let Xe=l-1;Xe>=0;Xe--)W.values[Xe]!==null&&Me.push(`${fe(Xe)},${I(d[ie][Xe])}`);H.push(be("polygon",{points:[...Re,...Me].join(" "),fill:W.color,"fill-opacity":.18,stroke:"none"}))}Ye.push(be("polyline",{points:Re.join(" "),fill:"none",stroke:W.color,"stroke-width":2,"stroke-linejoin":"round","stroke-linecap":"round"}));for(let Me=0;Me<l;Me++)W.values[Me]!==null&&Ye.push(be("circle",{cx:fe(Me),cy:I(u[ie][Me]),r:3.5,fill:W.color,stroke:"var(--tb-surface)","stroke-width":1.5},[je(Me,W)]))}),H.concat(Ye)}function Wb(e){let n=e.series[0].values.map(u=>u===null||u<0?0:u),r=n.reduce((u,d)=>u+d,0);if(r===0)return[];let o=Math.max(1,Math.min(e.width,e.height)/2-4),s=e.width/2,i=e.height/2,l=[],c=-90;return n.forEach((u,d)=>{if(u===0)return;let f=u/r*360,p=be("title",{},[],`${e.labels[d]}: ${e.format(u)} (${Math.round(u/r*100)}%)`),h={fill:ws(d),stroke:"var(--tb-surface)","stroke-width":2};if(f>=359.999)l.push(be("circle",{cx:s,cy:i,r:o,...h},[p]));else{let y=S=>[s+o*Math.cos(S*Math.PI/180),i+o*Math.sin(S*Math.PI/180)],[k,M]=y(c),[w,v]=y(c+f),C=`M${s},${i} L${k},${M} A${o},${o} 0 ${f>180?1:0} 1 ${w},${v} Z`;l.push(be("path",{d:C,...h},[p]))}c+=f}),l}function ws(e){return kr[e%kr.length]}function N(e,t){let n=ee(e.ctx,A(t));return n<0?x:e.ctx.vals[n]}function K(e,t){let n=N(e,t);return n.t===a.None?null:n.t===a.Map||(t==="text"||t==="hint")&&n.t===a.Word?Ue(n,le.rt):j(n)}function Gn(e){let t=e.t===a.Map?$t(e,"value"):null;return j(t??e)}function Ir(e){let t=e.t===a.Map?$t(e,"text"):null;return t!==null?Ue(t,le.rt):Gn(e)}function Yn(e){let t=N(e,"options");if(t.t!==a.Block)return[];let n=t.s.data.slice(t.i),r=[];for(let o=0;o<n.length;o++){let s=n[o+1];s!==void 0&&s.t===a.Block&&n[o].t!==a.Block?(r.push({title:n[o],options:s.s.data.slice(s.i)}),o++):n[o].t!==a.Block&&r.push(n[o])}return r}function Xn(e){return"options"in e}function yc(e){return Yn(e).flatMap(t=>Xn(t)?t.options:[t])}function kc(e){return Yn(e).map(t=>Xn(t)?`${t.options.map(Gn).join("\0")}`:Gn(t)).join("\0")}function xc(e,t){let n=m("option");n.value="",e.replaceChildren(n);let r=o=>{let s=m("option");return s.value=Gn(o),s.textContent=Ir(o),s};for(let o of Yn(t))if(Xn(o)){let s=m("optgroup");s.label=Ue(o.title,le.rt),s.append(...o.options.map(r)),e.append(s)}else e.append(r(o));e.dataset.options=kc(t)}function Se(e,...t){return ps(le.rt,e,...t)}function Er(e,t,n){e.dataset.tbOwn=n===void 0?t:`${n} ${t}`,wc(e)}function wc(e){let[t,n]=e.dataset.tbOwn.split(" ");n===void 0?e.textContent=Se(t):e.setAttribute(t,Se(n))}function qn(e){return cs.has(e.t)?yo(e,ft(le.rt)):j(e)}function P(e,t){let n=N(e,t);return!(n.t===a.None||n.t===a.Logic&&!n.v)}function We(e,t){let n=N(e,t);return n.t===a.Word||n.t===a.LitWord?E(n.sym).toLowerCase():null}function rn(e){let t=N(e,"pane");return t.t!==a.Block?[]:t.s.data.slice(t.i).filter(n=>n.t===a.Object)}function Lr(e){let t=N(e,"icon");return t.t===a.Issue?E(t.sym).toLowerCase():null}function tt(e,t=null){let n=vs(e,t);return n===null&&console.warn(`Trebol: unknown icon #${e}`),n}function wr(e,t){let n=N(e,"rules");return n.t!==a.Block?!1:n.s.data.some(r=>r.t===a.Block&&r.s.data[0]?.t===a.Word&&E(r.s.data[0].sym)===t)}var le,yn=new WeakMap,zt=new WeakMap,xn=new WeakMap,Ms=[],nt=1,jb=new Set([a.Word,a.SetWord,a.GetWord,a.Paren,a.Path,a.SetPath,a.GetPath,a.Function,a.Native]);function _(e,t,...n){let r={t:a.Word,sym:A("quote"),bind:le.rt.lib},o=[{t:a.Word,sym:A(e),bind:le.rt.user},t,...n.flatMap(i=>jb.has(i.t)?[r,i]:[i])],s=Rn(Ht(le.sch,{data:o},0));return s.catch(i=>console.error(ko(i))),s}function m(e,t){let n=document.createElement(e);return t&&(n.className=t),n}var Cc=new Set(["field","password","number","money","date","area","choice"]);function kn(e){let t=We(e,"style")??"face",n={face:e,el:null,input:null,label:null,error:null,kids:N(e,"pane"),box:null,rows:null,empty:null,button:null,radios:null,open:null,shown:void 0,typing:0,typed:null},r;if(Cc.has(t))r=sp(e,t,n);else if(t==="check"||t==="toggle")r=ip(e,n,t==="toggle");else if(t==="radio")r=lp(e,n);else if(t==="upload")r=cp(e,n);else if(t==="lookup")r=pp(e,n);else if(t==="rich")r=Dp(e,n);else{switch(t){case"view":r=m("main","tb-view");break;case"column":r=m("div","tb-column");break;case"row":r=m("div","tb-row");break;case"toolbar":r=Gp();break;case"breadcrumb":r=Yp(n);break;case"rows":r=Lp(n);break;case"entry":{r=m("div","tb-entry"),r.setAttribute("role","group");break}case"grid":r=m("div","tb-grid");break;case"desktop":r=m("div","tb-desktop");break;case"scroll":{r=m("div","tb-scroll"),r.tabIndex=0,r.setAttribute("role","region");break}case"panel":r=m("section","tb-panel");break;case"form":{let o=m("form","tb-form");o.noValidate=!0,o.addEventListener("submit",s=>s.preventDefault()),r=o;break}case"title":r=m("h1","tb-title");break;case"heading":r=m("h2","tb-heading");break;case"text":r=m("p","tb-text");break;case"divider":r=m("hr","tb-divider");break;case"link":{let o=m("a","tb-link");o.href=Mr(N(e,"value"))??K(e,"value")??"#",Cs(o,e,n),o.addEventListener("click",s=>{N(e,"action").t===a.Block&&(s.preventDefault(),_("ui-click",e))}),r=o;break}case"button":{let o=m("button","tb-button"),s=P(e,"submit");o.type=s?"submit":"button",o.addEventListener("click",i=>{if(!s)return void _("ui-click",e);i.preventDefault(),ap(e,o.closest("form, .tb-view")??document.body)}),Cs(o,e,n),r=o;break}case"tile":{let o=m("button",P(e,"linked")?"tb-tile tb-tile-linked":"tb-tile");o.type="button",o.addEventListener("click",()=>{_("ui-click",e)}),Cs(o,e,n),r=o;break}case"progress":r=vp(n);break;case"image":r=m("img","tb-image");break;case"canvas":r=kp(n);break;case"chart":r=Cp(n);break;case"icon":r=m("span","tb-icon-face");break;case"table":case"list":r=jp(e,t,n);break;case"tree":r=zp(e,n);break;case"dialog":r=Jp(e,n);break;case"tabs":r=Qp(e,n);break;case"split":r=tf(e,n);break;case"screens":{r=m("div","tb-screens"),Tr=e;break}case"screen":{r=m("section","tb-screen");let o=K(e,"text");o!==null&&(r.setAttribute("aria-label",o),document.title=o,Oo=e);break}case"tab":{r=m("div","tb-tab-panel"),r.setAttribute("role","tabpanel");break}default:r=m("div")}t==="screens"?Xc(n,r):rn(e).length>0&&t!=="tabs"&&t!=="split"&&Rs(n.box??r,e,t)}return n.el=r,yn.set(r,n),n.input!==null&&yn.set(n.input,n),xn.set(e.ctx,n),e.ctx.watch=Ms,Rb(n,t),jo(n),r}function vn(e,t,n=[]){let r=n.flatMap(([o,s])=>[Je(a.SetWord,o),s]);_("ui-event",e,Je(a.LitWord,t),Ge(a.Block,r))}var nn=new WeakSet,Io=null,Es=new Set;function Rb(e,t){let n=e.face,r=e.el,o=i=>!r.contains(i.relatedTarget);en(n,"on-focus")&&r.addEventListener("focusin",i=>{o(i)&&vn(n,"on-focus")}),en(n,"on-unfocus")&&r.addEventListener("focusout",i=>{o(i)&&vn(n,"on-unfocus")}),en(n,"on-over")&&(r.addEventListener("pointerenter",()=>vn(n,"on-over",[["away?",xe]])),r.addEventListener("pointerleave",()=>vn(n,"on-over",[["away?",O]]))),en(n,"on-dbl-click")&&r.addEventListener("dblclick",()=>vn(n,"on-dbl-click")),en(n,"on-key")&&(t==="view"?Io=n:r.addEventListener("keydown",i=>{nn.has(i)||js(i)===null||(nn.add(i),vn(n,"on-key",Pc(i)))})),K(n,"shortcut")!==null&&Es.add(e),P(n,"drop")&&Ts.add(e);let s=N(n,"menu");if(s.t===a.Block&&(t==="button"||t==="link")&&N(n,"action").t!==a.Block){r.setAttribute("aria-haspopup","menu"),r.setAttribute("aria-expanded","false"),e.label===null&&(e.label=m("span"),r.prepend(e.label));let i=tt("chevron-down");i!==null&&(i.classList.add("tb-menu-chevron"),r.append(i)),r.addEventListener("click",l=>{l.preventDefault();let c=r.getBoundingClientRect();$o(Is(n,s,x),c.left,c.bottom+4,r)})}else(s.t===a.Block||P(n,"drag"))&&r.addEventListener("contextmenu",i=>{let l=i.target,c=t==="table"||t==="list"||t==="tree",u=c?l.closest(t==="tree"?'[role="treeitem"]':"tr, li"):null;if(u===null&&c&&s.t!==a.Block)return;let d=u!==null?zt.get(u)??x:x,f=s.t===a.Block?Is(n,s,d):[];if(P(n,"drag")){let y=zb(n,u!==null?d:N(n,"value"));y.length>0&&(f.length>0&&f.push({text:"",divider:!0}),f.push({text:Se("move-to"),sub:y}))}if(f.length===0)return;i.preventDefault(),i.stopPropagation();let{clientX:p,clientY:h}=i;if(p===0&&h===0){let y=(u??(document.activeElement&&r.contains(document.activeElement)?document.activeElement:r)).getBoundingClientRect();p=y.left+8,h=y.top+Math.min(y.height,40)}$o(f,p,h,u??l)})}var Ts=new Set,Lo=e=>e.rows!==null;function Jn(e){return Lo(e)?Array.from(e.box.children):rn(e.face).map(t=>xn.get(t.ctx)?.el).filter(t=>t!==void 0&&t.isConnected)}function Ao(e){for(let t=e;t!==null;t=t.parentElement){let n=yn.get(t);if(n!==void 0&&n.el===t)return n}}function Sc(e){if(e.closest("input, textarea, select, [contenteditable], .tb-split-handle, .tb-menu")!==null)return null;for(let t=e;t!==null;t=t.parentElement){let n=zt.get(t);if(n!==void 0){let i=Ao(t),l=P(i.face,"reorder")&&qc(i.face)===null;if(!P(i.face,"drag")&&!l)return null;let c=t.parentElement,u=Array.prototype.indexOf.call(c.children,t);return{face:i.face,el:t,payload:n,within:l?i:null,index:u,group:c}}let r=yn.get(t);if(r===void 0||r.el!==t)continue;let o=Ao(t.parentElement),s=o!==void 0&&!Lo(o)&&P(o.face,"reorder");if(P(r.face,"drag")&&!Lo(r)||s){let i=s?Jn(o).indexOf(t):-1;return{face:r.face,el:t,payload:N(r.face,"value"),within:s?o:null,index:i,group:null}}}return null}function Fb(e,t,n){for(let r=Ao(document.elementFromPoint(t,n));r!==void 0;r=Ao(r.el.parentElement)){if(r.open!==null){let s=qp(r,e,t,n);if(s!==null)return s;continue}let o=r===e.within;if((o||P(r.face,"drop"))&&r.el!==e.el&&!e.el.contains(r.el))return{m:r,index:Ec(r,t,n),reorder:o}}return null}var Mc=e=>We(e.face,"style")==="row";function Ec(e,t,n){let r=Mc(e),o=0;for(let s of Jn(e)){let i=s.getBoundingClientRect();(r?t:n)>(r?i.left+i.width/2:i.top+i.height/2)&&o++}return o}var St=null;function Tc(e){if(document.querySelectorAll(".tb-drop-over").forEach(i=>i.classList.remove("tb-drop-over")),e===null){St?.remove(),St=null;return}if(e.into!==void 0){e.into.querySelector(":scope > .tb-tree-row").classList.add("tb-drop-over"),St?.remove(),St=null;return}e.m.el.classList.add("tb-drop-over"),St===null&&(St=m("div","tb-drop-line"),St.setAttribute("aria-hidden","true"),document.body.append(St));let t=Mc(e.m),n=e.group!==void 0?Array.from(e.group.children):Jn(e.m),r=(e.group??e.m.box??e.m.el).getBoundingClientRect(),o=n[e.index]?.getBoundingClientRect(),s=n[e.index-1]?.getBoundingClientRect();if(St.classList.toggle("tb-across",t),t){let i=o&&s?(s.right+o.left)/2:o?o.left-3:s?s.right+3:r.left+8,l=o??s??r;Object.assign(St.style,{left:`${i-1}px`,top:`${l.top}px`,width:"",height:`${l.height}px`})}else{let i=o&&s?(s.bottom+o.top)/2:o?o.top-3:s?s.bottom+3:r.top+8,l=o??s??r;Object.assign(St.style,{left:`${l.left}px`,top:`${i-1}px`,width:`${l.width}px`,height:""})}}function Hb(e,t){if(t.reorder){let n=t.index>e.index?t.index-1:t.index;n!==e.index&&Ic(t.m,e.index,n,t.group,t.parent)}else _("ui-drop",t.m.face,e.payload,e.face,Nt(t.index+1),t.parent??x)}var Nt=e=>({t:a.Integer,v:e});async function Ic(e,t,n,r,o=x){let s=document.activeElement!==null&&document.activeElement!==document.body&&e.el.contains(document.activeElement);if(await _("ui-reorder",e.face,Nt(t+1),Nt(n+1),o),Qc(),!s)return;let i=(r!==void 0?Array.from(r.children):Jn(e))[n];((i?.matches("[tabindex], button, a, input, textarea, select")?i:i?.querySelector("[tabindex], button, a, input, textarea, select"))??null)?.focus()}function zb(e,t){let n=[];for(let r of Ts){if(!r.el.isConnected){Ts.delete(r);continue}r.face.ctx===e.ctx||r.el.getClientRects().length===0||K(r.face,"text")===null&&r.el.querySelector(".tb-drop-zone")!==null||n.push({text:K(r.face,"text")??We(r.face,"style")??"",run:()=>{_("ui-drop",r.face,t,e,Nt(Jn(r).length+1),x)}})}return n}var tn=null;function Lc(e){e.on=!0,e.ghost=m("div","tb-drag-ghost"),e.ghost.textContent=(e.src.el.innerText||e.src.el.textContent||"").split(`
3000
- `).find(t=>t.trim()!=="")?.trim()??"",e.ghost.setAttribute("aria-hidden","true"),document.body.append(e.ghost),e.src.el.classList.add("tb-dragging"),getSelection()?.removeAllRanges(),document.documentElement.classList.add("tb-drag-active"),Ac(e,e.x,e.y)}function Ac(e,t,n){e.ghost.style.transform=`translate(${t+12}px, ${n+12}px)`,e.target=Fb(e.src,t,n),Tc(e.target)}function Mo(e){let t=tn;t!==null&&(tn=null,clearTimeout(t.timer),t.on&&(t.ghost?.remove(),t.src.el.classList.remove("tb-dragging"),document.documentElement.classList.remove("tb-drag-active"),Tc(null),e&&t.target!==null&&Hb(t.src,t.target),addEventListener("click",uc,!0),setTimeout(()=>removeEventListener("click",uc,!0),0)))}function uc(e){e.stopPropagation(),e.preventDefault()}function _b(e){if(e.button!==0||tn!==null)return;let t=Sc(e.target);if(t===null)return;let n={src:t,x:e.clientX,y:e.clientY,id:e.pointerId,on:!1,ghost:null,target:null,timer:0};tn=n,e.pointerType==="touch"&&(n.timer=setTimeout(()=>{tn===n&&Lc(n)},400))}function Ub(e){let t=tn;if(!(t===null||e.pointerId!==t.id)){if(!t.on){if(!(Math.hypot(e.clientX-t.x,e.clientY-t.y)>5))return;if(e.pointerType==="touch")return Mo(!1);t.x=e.clientX,t.y=e.clientY,Lc(t)}e.preventDefault(),Ac(t,e.clientX,e.clientY)}}function qb(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.key!=="ArrowUp"&&e.key!=="ArrowDown")return;let t=document.activeElement;if(t===null)return;let n=Sc(t);if(n===null||n.within===null)return;let r=n.index+(e.key==="ArrowUp"?-1:1);if(r<0||r>=(n.group!==null?n.group.children.length:Jn(n.within).length))return;e.preventDefault(),nn.add(e);let o=n.group??void 0;Ic(n.within,n.index,r,o,o!==void 0&&n.within.open!==null?Gc(n.within,o):x)}var Bo=[],_n=null;function Un(e=0,t=!0){for(let n of Bo.splice(e))n.hidePopover?.(),n.remove();e===0?(_n?.setAttribute("aria-expanded","false"),_n?.hasAttribute("aria-haspopup")||_n?.removeAttribute("aria-expanded"),t&&_n?.focus(),_n=null,document.removeEventListener("pointerdown",Bc,!0)):Bo[e-1]?.querySelector('[aria-expanded="true"]')?.setAttribute("aria-expanded","false")}function Bc(e){Bo.some(t=>t.contains(e.target))||Un(0,!1)}function dc(e){return Array.from(e.querySelectorAll(':scope > [role="menuitem"]'))}function Is(e,t,n){return t.s.data.slice(t.i).filter(r=>r.t===a.Object).map(r=>{let o=N(r,"items");return{text:K(r,"text")??"",icon:Lr(r),divider:P(r,"divider"),sub:o.t===a.Block?Is(e,o,n):void 0,run:()=>{_("ui-menu",e,r,n)}}})}function $o(e,t,n,r,o=0){Un(o,!1),o===0&&(_n=r,r.hasAttribute("aria-haspopup")&&r.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",Bc,!0));let s=m("div","tb-menu");s.setAttribute("role","menu"),s.setAttribute("popover","manual");let i=r.getAttribute("aria-label")??r.textContent;i&&s.setAttribute("aria-label",i.trim());for(let c of e){if(c.divider){let h=m("div","tb-menu-divider");h.setAttribute("role","separator"),s.append(h);continue}let u=m("button","tb-menu-item");u.type="button",u.tabIndex=-1,u.setAttribute("role","menuitem");let d=c.icon?tt(c.icon):null,f=m("span");f.textContent=c.text,u.append(d??m("span","tb-menu-gap"),f);let p=c.sub;if(p!==void 0){u.setAttribute("aria-haspopup","menu"),u.setAttribute("aria-expanded","false");let h=tt("chevron-right");h!==null&&u.append(h);let y=()=>{let k=u.getBoundingClientRect();$o(p,k.right-4,k.top-5,u,o+1),u.setAttribute("aria-expanded","true")};u.addEventListener("click",y),u.addEventListener("keydown",k=>{k.key==="ArrowRight"&&(k.preventDefault(),y())})}else u.addEventListener("click",()=>{Un(),c.run?.()});u.addEventListener("pointerenter",()=>u.focus()),s.append(u)}s.addEventListener("keydown",c=>{nn.add(c);let u=dc(s),d=u.indexOf(document.activeElement),f=u.length,p=c.key==="ArrowDown"?(d+1)%f:c.key==="ArrowUp"?(d-1+f)%f:c.key==="Home"?0:c.key==="End"?f-1:-1;if(p>=0)c.preventDefault(),u[p]?.focus();else if(c.key==="Escape"||c.key==="ArrowLeft"&&o>0)c.preventDefault(),c.stopPropagation(),o>0?(Un(o),r.focus()):Un();else if(c.key==="Tab")c.preventDefault(),Un();else if(c.key.length===1&&/\S/.test(c.key)){let h=c.key.toLowerCase();[...u.slice(d+1),...u.slice(0,d+1)].find(k=>k.textContent?.trim().toLowerCase().startsWith(h))?.focus()}}),s.querySelector(".tb-menu-item > svg:first-child")===null&&s.querySelectorAll(".tb-menu-gap").forEach(c=>c.remove()),document.body.append(s),s.showPopover?.();let l=s.getBoundingClientRect();s.style.left=`${Math.max(8,Math.min(t,innerWidth-l.width-8))}px`,s.style.top=`${Math.max(8,n+l.height>innerHeight-8?n-l.height:n)}px`,Bo.push(s),dc(s)[0]?.focus()}var qe=null,Ls=864e5;function Ws(e){return e.t===a.Date?new Date(Date.UTC(e.v.y,e.v.m-1,e.v.d)):null}function No(e){return e.toISOString().slice(0,10)}function bc(e,t){let n=N(e,"rules");if(n.t!==a.Block)return null;for(let r of n.s.data)if(!(r.t!==a.Block||r.s.data[0]?.t!==a.Word||E(r.s.data[0].sym)!==t))return Ws(r.s.data[1]??x);return null}function Kb(e,t){Vn(!1);let n=new Date(Date.UTC(new Date().getFullYear(),new Date().getMonth(),new Date().getDate())),r=m("div","tb-calendar");r.setAttribute("role","dialog"),r.setAttribute("aria-label",t.getAttribute("aria-label")??Se("choose-date")),r.setAttribute("popover","manual");let o=m("h2","tb-calendar-month");o.id=`tb-${nt++}`,o.setAttribute("aria-live","polite");let s=(u,d,f)=>{let p=m("button","tb-calendar-step");p.type="button",p.setAttribute("aria-label",d);let h=tt(u);return h!==null&&p.append(h),p.addEventListener("click",()=>{qe!==null&&(qe.at=Nc(qe.at,f),As())}),p},i=m("div","tb-calendar-head");i.append(s("chevron-left",Se("previous-month"),-1),o,s("chevron-right",Se("next-month"),1)),r.append(i),qe={face:e,opener:t,box:r,month:o,at:Ws(N(e,"value"))??n},t.setAttribute("aria-expanded","true"),r.addEventListener("keydown",Gb),r.addEventListener("focusout",u=>{qe?.box===r&&!r.contains(u.relatedTarget)&&u.relatedTarget!==null&&Vn(!1)}),document.addEventListener("pointerdown",$c,!0),document.body.append(r),r.showPopover?.(),As();let l=t.closest(".tb-date").getBoundingClientRect(),c=r.getBoundingClientRect();r.style.left=`${Math.max(8,Math.min(l.right-c.width,innerWidth-c.width-8))}px`,r.style.top=`${l.bottom+4+c.height>innerHeight-8?Math.max(8,l.top-4-c.height):l.bottom+4}px`,Oc()}function Vn(e=!0){if(qe===null)return;let{box:t,opener:n}=qe;qe=null,t.hidePopover?.(),t.remove(),n.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",$c,!0),e&&n.focus()}function $c(e){qe!==null&&!qe.box.contains(e.target)&&!qe.opener.contains(e.target)&&Vn(!1)}function As(){let e=qe,t=ft(le.rt),n=e.at,r=bc(e.face,"min"),o=bc(e.face,"max"),s=Ws(N(e.face,"value")),i=new Date,l=Date.UTC(i.getFullYear(),i.getMonth(),i.getDate()),c=w=>new Intl.DateTimeFormat(t,{timeZone:"UTC",...w});e.month.textContent=c({month:"long",year:"numeric"}).format(n);let u=m("table","tb-calendar-grid");u.setAttribute("role","grid"),u.setAttribute("aria-labelledby",e.month.id);let d=vo(t)%7,f=m("tr");for(let w=0;w<7;w++){let v=new Date(Date.UTC(1970,0,4+(d+w)%7)),C=m("th");C.scope="col",C.abbr=c({weekday:"long"}).format(v),C.textContent=c({weekday:"narrow"}).format(v),f.append(C)}let p=m("thead");p.append(f);let h=m("tbody"),y=Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),1),k=y-(new Date(y).getUTCDay()-d+7)%7*Ls,M=c({dateStyle:"full"});do{let w=m("tr");for(let v=0;v<7;v++,k+=Ls){let C=new Date(k),S=m("td","tb-calendar-day");S.setAttribute("role","gridcell"),S.textContent=String(C.getUTCDate()),S.setAttribute("aria-label",M.format(C)),S.dataset.day=No(C),S.tabIndex=k===n.getTime()?0:-1,C.getUTCMonth()!==n.getUTCMonth()&&S.classList.add("tb-calendar-other"),k===l&&S.setAttribute("aria-current","date"),S.setAttribute("aria-selected",s!==null&&k===s.getTime()?"true":"false"),(r!==null&&C<r||o!==null&&C>o)&&S.setAttribute("aria-disabled","true"),S.addEventListener("click",()=>Dc(C)),w.append(S)}h.append(w)}while(new Date(k).getUTCMonth()===n.getUTCMonth());u.append(p,h),e.box.querySelector("table")?.remove(),e.box.append(u)}function Nc(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,o=new Date(Date.UTC(n,r+1,0)).getUTCDate();return new Date(Date.UTC(n,r,Math.min(e.getUTCDate(),o)))}function Oc(){qe?.box.querySelector('td[tabindex="0"]')?.focus()}function Dc(e){let t=qe;if(t===null||t.box.querySelector(`td[data-day="${No(e)}"]`)?.getAttribute("aria-disabled")==="true")return;let n=t.face;Vn(),_("ui-input",n,D(No(e))).then(()=>_("ui-blur",n))}function Gb(e){let t=qe;if(t===null)return;if(nn.add(e),e.key==="Escape"){e.preventDefault(),e.stopPropagation(),Vn();return}if(!(e.target instanceof HTMLTableCellElement))return;let n=t.at,r=vo(ft(le.rt))%7,o=(n.getUTCDay()-r+7)%7,s={ArrowLeft:-1,ArrowRight:1,ArrowUp:-7,ArrowDown:7,Home:-o,End:6-o},i=null;if(e.key in s)i=new Date(n.getTime()+s[e.key]*Ls);else if(e.key==="PageUp"||e.key==="PageDown")i=Nc(n,(e.key==="PageUp"?-1:1)*(e.shiftKey?12:1));else if(e.key==="Enter"||e.key===" "){e.preventDefault(),Dc(n);return}if(i!==null)if(e.preventDefault(),t.at=i,i.getUTCMonth()===n.getUTCMonth()){t.box.querySelectorAll('td[tabindex="0"]').forEach(c=>{c.tabIndex=-1});let l=t.box.querySelector(`td[data-day="${No(i)}"]`);l.tabIndex=0,l.focus()}else As(),Oc()}var Vb=new Set(["Shift","Control","Alt","Meta","AltGraph","CapsLock","Dead","Unidentified"]),Zb={Enter:13,Escape:27,Tab:9,Backspace:8},Yb={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down",Home:"home",End:"end",PageUp:"page-up",PageDown:"page-down",Insert:"insert",Delete:"delete"};function js(e){if(Vb.has(e.key))return null;let t=Zb[e.key];if(t!==void 0)return ot(t);let n=[...e.key];return n.length===1?ot(n[0].codePointAt(0)):/^F\d+$/.test(e.key)?Je(a.LitWord,e.key):Je(a.LitWord,Yb[e.key]??e.key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase())}function Pc(e){let t=n=>n?O:xe;return[["key",js(e)],["ctrl?",t(e.ctrlKey)],["shift?",t(e.shiftKey)],["alt?",t(e.altKey)],["meta?",t(e.metaKey)]]}var Cr=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),Xb={esc:"escape",space:" ",del:"delete",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright"};function Jb(e){let t=e.toLowerCase().split("+").map(o=>o.trim()),n=t.pop()??"",r=(...o)=>t.some(s=>o.includes(s));return{key:Xb[n]??n,ctrl:r("ctrl","control"),shift:r("shift"),alt:r("alt","option"),meta:r("meta","cmd")}}function Qb(e,t){return(Cr&&e.metaKey||e.ctrlKey)!==(t.ctrl||Cr&&t.meta)||e.shiftKey!==t.shift||e.altKey!==t.alt||!Cr&&e.metaKey!==t.meta?!1:/^[a-z]$/.test(t.key)?e.code===`Key${t.key.toUpperCase()}`:/^[0-9]$/.test(t.key)?e.code===`Digit${t.key}`:e.key.toLowerCase()===t.key}function ep(e){return e.split("+").map(t=>{let n=t.trim().toLowerCase();return n==="ctrl"||n==="control"?Cr?"Meta":"Control":n==="cmd"?"Meta":t.trim().length===1?t.trim().toUpperCase():t.trim()}).join("+")}function tp(e){return Cr?e.replace(/ctrl|control/i,"Cmd"):e}function np(e){let t=Array.from(document.querySelectorAll("dialog[open]")).pop();for(let n of Es){if(!n.el.isConnected){Es.delete(n);continue}let r=K(n.face,"shortcut");if(!(r===null||!Qb(e,Jb(r)))&&!(n.el.getClientRects().length===0||t!==void 0&&!t.contains(n.el))){e.preventDefault(),nn.add(e),n.el.click();return}}}function rp(e){Io===null||nn.has(e)||js(e)===null||vn(Io,"on-key",Pc(e))}function Cs(e,t,n){let r=Lr(t),o=r!==null?tt(r):null;o!==null&&(n.label=m("span"),e.append(o,n.label),e.classList.add("tb-has-icon"))}function op(e){let t=Lr(e);if(t===null||(K(e,"text")??"")!=="")return null;let n=K(e,"hint");if(n!==null)return n;let r=t.replace(/-/g," ");return r.charAt(0).toUpperCase()+r.slice(1)}function Rs(e,t,n){let r=null;for(let o of rn(t)){let s=We(o,"style")==="button";if(n==="form"&&s)r===null&&(r=m("div","tb-actions"),e.append(r)),r.append(kn(o));else{r=null;let i=kn(o);n==="toolbar"&&i.tagName==="HR"&&i.setAttribute("aria-orientation","vertical"),e.append(i)}}}function ap(e,t){_("ui-click",e).then(()=>{for(let n of Array.from(t.querySelectorAll("input, textarea, select"))){let r=yn.get(n);if(r!==void 0&&N(r.face,"error").t===a.String)return n.focus()}})}function sp(e,t,n){let r=`tb-${nt++}`,o=m("div","tb-field"),s=m("label","tb-label");s.htmlFor=r;let i=m("div","tb-control"),l;if(t==="area")l=m("textarea","tb-input");else if(t==="choice"){let p=m("select","tb-input");xc(p,e),l=p}else{let p=m("input","tb-input");p.type=t==="password"?"password":wr(e,"email")?"email":wr(e,"url")?"url":"text",(t==="number"||t==="money"||wr(e,"integer"))&&(p.inputMode=wr(e,"integer")?"numeric":"decimal"),t==="password"&&(p.autocomplete="new-password"),l=p}l.id=r;let c=m("div","tb-error");c.id=`${r}-error`,c.setAttribute("aria-live","polite"),l.setAttribute("aria-describedby",c.id);let u=We(e,"name");u!==null&&(l.name=u),l.addEventListener(t==="choice"?"change":"input",()=>{let p=ft(le.rt),h=t==="money"?ds(l.value,p)??l.value:t==="date"?bs(l.value,p)??l.value:l.value;n.typing++;let y=()=>{n.typing--,n.typed=N(e,"value")};_("ui-input",e,h===""?x:D(h)).then(y,y)}),t==="money"&&l.addEventListener("focus",()=>{P(e,"readonly")||(l.value=us(N(e,"value"),ft(le.rt)))}),l.addEventListener("blur",()=>{_("ui-blur",e)});let d=t==="area"||t==="choice"?null:Lr(e),f=d!==null?tt(d):null;if(t==="date"){let p=m("div","tb-date"),h=m("button","tb-date-button");h.type="button",h.setAttribute("aria-haspopup","dialog"),h.setAttribute("aria-expanded","false");let y=tt("calendar");y!==null&&h.append(y),h.addEventListener("click",()=>qe?.opener===h?Vn():Kb(e,h)),p.append(l,h),i.append(p,c)}else if(f!==null){let p=m("div","tb-input-icon");p.append(f,l),i.append(p,c)}else i.append(l,c);return o.append(s,i),n.input=l,n.label=s,n.error=c,o}function ip(e,t,n){let r=m("div","tb-check-row tb-control"),o=m("label",n?"tb-check tb-switch":"tb-check"),s=m("input");s.type="checkbox",n&&s.setAttribute("role","switch");let i=m("span"),l=m("div","tb-error");return l.id=`tb-${nt++}-error`,l.setAttribute("aria-live","polite"),s.setAttribute("aria-describedby",l.id),s.addEventListener("change",()=>{_("ui-input",e,s.checked?O:xe).then(()=>_("ui-blur",e))}),o.append(s,i),r.append(o,l),t.input=s,t.label=i,t.error=l,r}function lp(e,t){let n=`tb-${nt++}`,r=m("div","tb-field"),o=m("span","tb-label");o.id=n;let s=m("div","tb-control"),i=m("div","tb-radios");i.setAttribute("role","radiogroup"),i.setAttribute("aria-labelledby",n);let l=m("div","tb-error");l.id=`${n}-error`,l.setAttribute("aria-live","polite"),i.setAttribute("aria-describedby",l.id),t.radios=[];let c=u=>{let d=m("label","tb-check"),f=m("input");f.type="radio",f.name=n,f.value=Gn(u),f.addEventListener("change",()=>{f.checked&&_("ui-input",e,D(f.value)).then(()=>_("ui-blur",e))});let p=m("span");return p.textContent=Ir(u),d.append(f,p),t.radios.push(f),d};for(let u of Yn(e))if(Xn(u)){let d=m("div","tb-radio-group");d.setAttribute("role","group");let f=m("span","tb-radio-title");f.id=`tb-${nt++}`,f.textContent=Ue(u.title,le.rt),d.setAttribute("aria-labelledby",f.id);let p=m("div","tb-radios");p.append(...u.options.map(c)),d.append(f,p),i.append(d)}else i.append(c(u));return s.append(i,l),r.append(o,s),t.label=o,t.error=l,r}function cp(e,t){let n=`tb-${nt++}`,r=m("div","tb-field"),o=m("label","tb-label");o.htmlFor=n;let s=m("div","tb-control"),i=m("div","tb-upload"),l=m("input");l.type="file",l.hidden=!0,l.tabIndex=-1;let c=m("button","tb-button");c.type="button",c.id=n;let u=tt("upload");u!==null&&c.append(u),c.append(m("span"));let d=m("span","tb-upload-hint"),f=m("div","tb-error");f.id=`${n}-error`,f.setAttribute("aria-live","polite"),c.setAttribute("aria-describedby",f.id);let p=m("ul","tb-upload-list");o.id=`${n}-label`;let h=m("div","tb-progress tb-upload-progress");h.setAttribute("role","progressbar"),h.setAttribute("aria-valuemin","0"),h.setAttribute("aria-valuemax","100"),h.setAttribute("aria-labelledby",o.id),h.hidden=!0,h.append(m("div","tb-progress-bar")),c.addEventListener("click",()=>l.click()),l.addEventListener("change",()=>{let k=[...l.files??[]];l.value="",k.length>0&&fc(e,k)});let y=k=>k.dataTransfer?.types.includes("Files")===!0;return i.addEventListener("dragover",k=>{!y(k)||c.disabled||(k.preventDefault(),k.dataTransfer.dropEffect="copy",i.classList.add("tb-drop-over"))}),i.addEventListener("dragleave",k=>{i.contains(k.relatedTarget)||i.classList.remove("tb-drop-over")}),i.addEventListener("drop",k=>{i.classList.remove("tb-drop-over"),!(!y(k)||c.disabled)&&(k.preventDefault(),fc(e,[...k.dataTransfer.files]))}),i.append(c,d,l),s.append(i,p,h,f),r.append(o,s),t.label=o,t.error=f,t.button=c,t.box=p,r}function Wc(e){let t=N(e,"accept");return t.t===a.Block?t.s.data.slice(t.i).map(n=>j(n).trim().toLowerCase()).filter(n=>n!==""):[]}function pc(e,t){if(t.length===0)return!0;let n=e.name.toLowerCase(),r=e.type.toLowerCase();return t.some(o=>o.includes("/")?o.endsWith("/*")?r.startsWith(o.slice(0,-1)):r===o:n.endsWith(o.startsWith(".")?o:`.${o}`))}function fc(e,t){let n=Wc(e),r=t.filter(l=>pc(l,n)),o=P(e,"multiple")?r:r.slice(0,1),s=[];for(let l of o)s.push(D(l.name),Nt(l.size),D(l.type),ss(l));let i=t.filter(l=>!pc(l,n)).map(l=>D(l.name));_("ui-files",e,Ge(a.Block,s),Ge(a.Block,i))}function up(e){try{let t=new URL(e,location.href);return t.protocol==="http:"||t.protocol==="https:"?t.href:null}catch{return null}}function dp(e,t){let n=e.face,r=e.label;r.textContent=K(n,"text")??"",r.classList.toggle("tb-required",Ot(n));let o=P(n,"multiple"),s=e.button;s.lastChild.textContent=Se(o?"choose-files":"choose-file");let i=P(n,"readonly");s.disabled=P(n,"disabled")||i,s.setAttribute("aria-invalid",t!==null?"true":"false");let l=s.parentElement;l.hidden=i,l.querySelector(".tb-upload-hint").textContent=Se(o?"drop-files":"drop-file");let c=l.querySelector("input");c.multiple=o,c.accept=Wc(n).map(k=>k.includes("/")||k.startsWith(".")?k:`.${k}`).join(","),e.error.textContent=t??"";let u=N(n,"value"),d=u.t===a.Block?u.s.data.slice(u.i).filter(k=>k.t===a.Object):[],f=ft(le.rt),p=d.map((k,M)=>{let w=m("li"),v=K(k,"url"),C=v!==null?up(v):null,S=m(C!==null?"a":"span","tb-upload-name");if(S.textContent=K(k,"name")??"",S instanceof HTMLAnchorElement&&C!==null&&(S.href=C,S.target="_blank",S.rel="noopener"),C!==null&&(K(k,"type")??"").startsWith("image/")){let ce=m("img","tb-upload-thumb");ce.src=C,ce.alt="",w.append(ce)}let I=m("span","tb-upload-size"),H=N(k,"size");if(I.textContent=H.t===a.Integer?fs(Number(H.v),f):"",i)return w.append(S,I),w;let z=m("button","tb-upload-remove");z.type="button",z.disabled=s.disabled,z.setAttribute("aria-label",Se("remove-file",S.textContent??""));let fe=tt("close");return fe!==null&&z.append(fe),z.addEventListener("click",()=>{s.focus(),_("ui-remove-file",n,Nt(M+1))}),w.append(S,I,z),w});e.box.replaceChildren(...p),e.box.hidden=p.length===0;let h=e.el.querySelector(".tb-upload-progress"),y=Fc(N(n,"sent"));h.hidden=N(n,"sent").t===a.None,h.setAttribute("aria-valuenow",String(Math.round((y??0)*100))),h.firstChild.style.width=`${(y??0)*100}%`}var pe=null,Bs,bp=200;function Do(e){let t=N(e,"value");return t.t===a.None?[]:t.t===a.Block?t.s.data.slice(t.i):[t]}function $s(e,t){let n=N(e,"known"),r=n.t===a.Map?$t(n,j(t)):null;return r!==null?Ue(r,le.rt):j(t)}function hc(e,t){let n=N(e,"links");if(!P(e,"readonly")||n.t!==a.Map)return null;let r=$t(n,j(t));return r===null?null:r.t===a.LitWord?Mr({...r,t:a.Word}):r.t===a.LitPath?Mr({...r,t:a.Path}):Mr(r)??(r.t===a.Url||r.t===a.File||r.t===a.String?j(r):null)}function pp(e,t){let n=`tb-${nt++}`,r=m("div","tb-field"),o=m("label","tb-label");o.htmlFor=n;let s=m("div","tb-control"),i=m("div","tb-lookup"),l=m("ul","tb-lookup-chosen"),c=m("input","tb-input");c.id=n,c.type="text",c.autocomplete="off",c.setAttribute("role","combobox"),c.setAttribute("aria-autocomplete","list"),c.setAttribute("aria-expanded","false");let u=We(e,"name");u!==null&&(c.name=u);let d=m("div","tb-error");return d.id=`${n}-error`,d.setAttribute("aria-live","polite"),c.setAttribute("aria-describedby",d.id),c.addEventListener("click",()=>{pe?.m!==t&&Ns(t,c,"")}),c.addEventListener("input",()=>{pe?.m!==t&&Ns(t,c,null),clearTimeout(Bs),Bs=setTimeout(()=>{_("ui-lookup-search",e,D(c.value))},bp)}),c.addEventListener("keydown",f=>gp(t,c,f)),c.addEventListener("blur",()=>{if(Po(),c.readOnly)return;let f=P(e,"multiple");!f&&c.value===""&&N(e,"value").t!==a.None?_("ui-input",e,x):c.value=f?"":Do(e).map(h=>$s(e,h)).join(""),_("ui-blur",e)}),i.append(l,c),s.append(i,d),r.append(o,s),t.input=c,t.label=o,t.error=d,t.box=l,r}function fp(e,t){let n=e.face,r=e.input,o=e.label;o.textContent=K(n,"text")??"",o.classList.toggle("tb-required",Ot(n));let s=P(n,"multiple"),i=P(n,"readonly"),l=P(n,"disabled"),c=Do(n),u=s||c.some(f=>hc(n,f)!==null);r.readOnly=i,r.disabled=l,r.hidden=u&&i&&c.length>0,r.setAttribute("aria-required",Ot(n)?"true":"false"),r.setAttribute("aria-invalid",t!==null?"true":"false");let d=K(n,"hint");if(d!==null&&(r.placeholder=d),e.error.textContent=t??"",u)e.box.replaceChildren(...c.map((f,p)=>{let h=m("li","tb-lookup-chip"),y=hc(n,f),k=m(y!==null?"a":"span",y!==null?"tb-link":"");if(k instanceof HTMLAnchorElement&&(k.href=y),k.textContent=$s(n,f),h.append(k),!i&&!l){let M=m("button","tb-upload-remove");M.type="button",M.setAttribute("aria-label",Se("remove-value",k.textContent));let w=tt("close");w!==null&&M.append(w),M.addEventListener("click",()=>{r.focus(),_("ui-lookup-remove",n,Nt(p+1))}),h.append(M)}return h}));else{e.box.replaceChildren();let f=c.map(p=>$s(n,p)).join("");document.activeElement!==r&&r.value!==f&&(r.value=f)}pe?.m===e&&hp()}function Ns(e,t,n){if(t.readOnly||t.disabled)return;Po();let r=m("ul","tb-lookup-list");r.id=`tb-${nt++}`,r.setAttribute("role","listbox"),r.setAttribute("popover","manual"),r.addEventListener("pointerdown",o=>o.preventDefault()),pe={m:e,list:r,shown:null,items:[],active:-1},t.setAttribute("aria-expanded","true"),t.setAttribute("aria-controls",r.id),(t.closest("dialog")??document.body).append(r),r.showPopover?.(),jc(),n!==null&&_("ui-lookup-search",e.face,D(n))}function jc(){if(pe===null)return;let{list:e,m:t}=pe,n=t.input.getBoundingClientRect();e.style.width=`${n.width}px`,e.style.left=`${n.left}px`;let r=e.getBoundingClientRect().height;e.style.top=`${n.bottom+4+r>innerHeight-8?Math.max(8,n.top-4-r):n.bottom+4}px`}function Po(){if(clearTimeout(Bs),pe===null)return;let{list:e,m:t}=pe;pe=null,e.hidePopover?.(),e.remove(),t.input.setAttribute("aria-expanded","false"),t.input.removeAttribute("aria-controls"),t.input.removeAttribute("aria-activedescendant")}function hp(){if(pe===null)return;let e=pe,t=N(e.m.face,"options");if(t.t!==a.Block||t===e.shown||e.shown===null&&N(e.m.face,"query").t===a.None)return;e.shown=t;let n=new Set(P(e.m.face,"multiple")?Do(e.m.face).map(r=>j(r)):[]);if(e.items=yc(e.m.face).filter(r=>!n.has(Gn(r))),e.active=-1,e.list.replaceChildren(...e.items.map((r,o)=>{let s=m("li","tb-lookup-option");return s.id=`${e.list.id}-${o}`,s.setAttribute("role","option"),s.setAttribute("aria-selected","false"),s.textContent=Ir(r),s.addEventListener("click",()=>Rc(r)),s})),e.items.length===0){let r=m("li","tb-lookup-none");r.textContent=Se("no-matches"),e.list.append(r)}jc()}function Rc(e){if(pe===null)return;let{m:t}=pe,n=t.input;Po(),n.value=P(t.face,"multiple")?"":Ir(e),_("ui-lookup-pick",t.face,e)}function mp(e){if(pe===null||pe.items.length===0)return;let{list:t,items:n,m:r}=pe,o=pe.active<0&&e<0?n.length-1:(pe.active+e+n.length)%n.length;t.children[pe.active]?.setAttribute("aria-selected","false"),pe.active=o;let s=t.children[o];s.setAttribute("aria-selected","true"),s.scrollIntoView({block:"nearest"}),r.input.setAttribute("aria-activedescendant",s.id)}function gp(e,t,n){let r=pe?.m===e,o=()=>{n.preventDefault(),n.stopPropagation()};switch(n.key){case"ArrowDown":case"ArrowUp":o(),r?mp(n.key==="ArrowDown"?1:-1):Ns(e,t,"");break;case"Enter":if(!r)break;o(),pe.active>=0&&Rc(pe.items[pe.active]);break;case"Escape":r&&(o(),Po());break;case"Backspace":if(P(e.face,"multiple")&&t.value===""&&!t.readOnly){let s=Do(e.face).length;s>0&&_("ui-lookup-remove",e.face,Nt(s))}break}}function vp(e){let t=m("div","tb-progress-wrap"),n=m("span","tb-progress-label");n.id=`tb-${nt++}`;let r=m("div","tb-progress");return r.setAttribute("role","progressbar"),r.setAttribute("aria-valuemin","0"),r.setAttribute("aria-valuemax","100"),r.append(m("div","tb-progress-bar")),t.append(n,r),e.label=n,e.box=r,t}function Fc(e){let t=e.t===a.Percent||e.t===a.Decimal?e.v:e.t===a.Integer?Number(e.v):null;return t===null||Number.isNaN(t)?null:Math.min(1,Math.max(0,t))}function yp(e){let t=K(e.face,"text"),n=e.label;n.textContent=t??"",n.hidden=t===null;let r=e.box;t!==null?r.setAttribute("aria-labelledby",n.id):r.removeAttribute("aria-labelledby");let o=Fc(N(e.face,"value"));r.classList.toggle("tb-indeterminate",o===null);let s=r.firstChild;o===null?(r.removeAttribute("aria-valuenow"),s.style.removeProperty("width")):(r.setAttribute("aria-valuenow",String(Math.round(o*100))),s.style.width=`${o*100}%`)}var Fs="http://www.w3.org/2000/svg";function Hs(e){let t=document.createElementNS(Fs,e.tag);for(let[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);e.text!==void 0&&(t.textContent=e.text);for(let n of e.kids)t.append(Hs(n));return t}function kp(e){let t=m("div","tb-canvas"),n=document.createElementNS(Fs,"svg");return t.append(n),e.kids=n,t}function xp(e){let t=e.kids,n=N(e.face,"extent"),[r,o]=n.t===a.Pair?[n.x,n.y]:[300,150];t.setAttribute("viewBox",`0 0 ${r} ${o}`),t.setAttribute("width",String(r)),t.setAttribute("height",String(o));let s=K(e.face,"text");s!==null?(t.setAttribute("role","img"),t.setAttribute("aria-label",s),t.removeAttribute("aria-hidden")):(t.removeAttribute("role"),t.removeAttribute("aria-label"),t.setAttribute("aria-hidden","true"));let{kids:i,error:l}=Zl(N(e.face,"draw"));l!==null&&console.warn(`Trebol: ${l}`),t.replaceChildren(...i.map(Hs))}var wp={small:160,medium:240,large:360};function Cp(e){let t=m("figure","tb-chart"),n=m("figcaption","tb-chart-caption"),r=m("div","tb-chart-plot"),o=document.createElementNS(Fs,"svg");o.setAttribute("aria-hidden","true"),r.append(o);let s=m("ul","tb-chart-legend"),i=m("table","tb-sr-only"),l=m("p","tb-chart-empty");t.append(n,r,s,l,i);let c={caption:n,plot:r,svg:o,legend:s,table:i,empty:l,width:0};return e.kids=c,typeof ResizeObserver<"u"&&new ResizeObserver(()=>{r.clientWidth!==c.width&&Hc(e)}).observe(r),t}function Sp(e){return e.t===a.Integer?Number(e.v):e.t===a.Decimal||e.t===a.Percent?e.v:e.t===a.Money?ut(e.v):null}function Mp(e){return t=>{if(e!==null&&e.t===a.Money){let n=Pt(Math.round(t*100)/100);if(n!==null)return qn(rt(n,e.cur))}return e!==null&&e.t===a.Percent?qn({t:a.Percent,v:t}):qn(Number.isInteger(t)?{t:a.Integer,v:t}:{t:a.Decimal,v:t})}}function Ep(e){let t=e.kids,n=K(e.face,"text");t.caption.textContent=n??"",t.caption.hidden=n===null,Hc(e)}function Hc(e){let t=e.face,n=e.kids,r=Wo(t),o=N(t,"data"),s=o.t===a.Block?o.s.data.slice(o.i):[],i=We(t,"kind")??"bar",l=s.map(v=>Zn(et(v,r[0]?.sym??A("label")))),c=null,u=r.slice(1).map((v,C)=>({name:v.label,color:kr[C%kr.length],values:s.map(S=>{let I=et(S,v.sym),H=Sp(I);return H!==null&&c===null&&(c=I),H})})),d=Mp(c),f=s.length===0||u.length===0;if(n.empty.hidden=!f,n.plot.hidden=f,f){n.empty.textContent=Se("empty"),n.legend.replaceChildren(),n.table.replaceChildren();return}let p=n.plot.clientWidth||600,h=wp[We(t,"size")??"medium"]??240;n.width=n.plot.clientWidth,n.svg.setAttribute("viewBox",`0 0 ${p} ${h}`),n.svg.replaceChildren(...cc({kind:i,labels:l,series:u,stacked:P(t,"stacked"),width:p,height:h,format:d}).map(Hs));let y=i==="pie"?l.map((v,C)=>[v,ws(C)]):u.length>1?u.map(v=>[v.name,v.color]):[];n.legend.replaceChildren(...y.map(([v,C])=>{let S=m("li","tb-chart-key"),I=m("span","tb-chart-swatch");return I.style.setProperty("--tb-swatch",C),S.append(I,v),S})),n.legend.hidden=y.length===0;let k=m("caption");k.textContent=K(t,"text")??"";let M=m("tr");for(let v of r){let C=m("th");C.textContent=v.label,M.append(C)}let w=s.map(v=>{let C=m("tr");for(let S of r){let I=m("td");I.textContent=Zn(et(v,S.sym)),C.append(I)}return C});n.table.replaceChildren(k,m("thead"),m("tbody")),n.table.tHead.append(M),n.table.tBodies[0].append(...w)}function Tp(e){let t=Lr(e.face)??"",n=K(e.face,"text"),r=`${t} ${n??""}`;if(e.el.dataset.icon===r)return;e.el.dataset.icon=r;let o=t!==""?tt(t,n):null;e.el.replaceChildren(...o!==null?[o]:[])}function Ot(e){return wr(e,"required")&&!P(e,"readonly")}function Ip(e,t){let n=e.face;e.label.textContent=K(n,"text")??"",e.label.classList.toggle("tb-required",Ot(n));let r=N(n,"value"),o=r.t===a.None?null:j(r);for(let i of e.radios)i.checked=i.value===o,i.disabled=P(n,"disabled")||P(n,"readonly");let s=e.radios[0]?.closest('[role="radiogroup"]');s?.querySelectorAll(".tb-radio-title").forEach((i,l)=>{let c=Yn(n).filter(Xn)[l];c&&(i.textContent=Ue(c.title,le.rt))}),s?.setAttribute("aria-invalid",t!==null?"true":"false"),s?.setAttribute("aria-required",Ot(n)?"true":"false"),e.error.textContent=t??""}function Lp(e){let t=`tb-${nt++}`,n=m("div","tb-field"),r=m("div","tb-label");r.id=t;let o=m("div","tb-control"),s=m("div","tb-rows");s.setAttribute("role","group"),s.setAttribute("aria-labelledby",t);let i=m("div","tb-error");return i.setAttribute("aria-live","polite"),o.append(s,i),n.append(r,o),e.label=r,e.error=i,e.box=s,n}function Ap(e,t){let n=e.face;e.label.textContent=K(n,"text")??"",e.label.classList.toggle("tb-required",Ot(n)),e.error.textContent=t??"";let r=N(n,"value"),o=[r.t===a.Block?r.s:null,P(n,"readonly"),P(n,"disabled")],s=e.shown;(s===void 0||o.some((i,l)=>i!==s[l]))&&(e.shown=o,_("ui-rows",n))}function Bp(e){let t=e.box,n=rn(e.face),r=document.activeElement,o=[],s=n.map(c=>{let u=xn.get(c.ctx);if(u!==void 0&&u.el.parentElement===t)return u.el;let d=kn(c);return o.push(d),d}),i=t.firstChild;for(let c of s)c===i?i=i.nextSibling:t.insertBefore(c,i);for(;i!==null;){let c=i.nextSibling;t.removeChild(i),i=c}let l=s[s.length-1];r!==null&&r!==document.body&&!r.isConnected?l?.focus():o.length===1&&(r===l||r===document.body)&&o[0].querySelector('input, textarea, select, [contenteditable="true"]')?.focus()}var $p=[["bold","bold"],["italic","italic"],["heading","heading"],["list","bullet-list"],["list-ordered","number-list"],["link","link"]];function Sr(e){return e.flatMap(t=>{switch(t.k){case"text":return[document.createTextNode(t.text)];case"br":return[m("br")];case"b":case"i":{let n=m(t.k);return n.append(...Sr(t.kids)),[n]}case"a":{if(!ks(t.href))return Sr(t.kids);let n=m("a");return n.href=t.href,n.rel="noopener noreferrer",n.target="_blank",n.append(...Sr(t.kids)),[n]}}})}function Np(e){return e.map(t=>{if(t.k==="p"||t.k==="h"){let r=t.k==="p"?m("p"):m(`h${t.level}`);return r.append(...Sr(t.kids)),r}let n=m(t.k);for(let r of t.items){let o=m("li");o.append(...Sr(r)),n.append(o)}return n})}function Eo(e){let t=[];for(let n of e)if(n.nodeType===Node.TEXT_NODE){let r=(n.textContent??"").replace(/\u00a0/g," ").replace(/[\n\r]+/g," "),o=t[t.length-1];if(r==="")continue;o?.k==="text"?o.text+=r:t.push({k:"text",text:r})}else if(n instanceof HTMLElement){let r=Eo(n.childNodes);switch(n.tagName){case"BR":t.push({k:"br"});break;case"B":case"STRONG":r.length>0&&t.push({k:"b",kids:r});break;case"I":case"EM":r.length>0&&t.push({k:"i",kids:r});break;case"A":r.length>0&&t.push({k:"a",href:n.getAttribute("href")??"",kids:r});break;default:t.push(...r)}}for(;t[t.length-1]?.k==="br";)t.pop();return t}var Op=/^(P|DIV|H[1-6]|UL|OL|BLOCKQUOTE|SECTION)$/;function zc(e){let t=[],n=[],r=()=>{let o=Eo(n);o.length>0&&t.push({k:"p",kids:o}),n=[]};for(let o of e.childNodes){if(!(o instanceof HTMLElement)||!Op.test(o.tagName)){n.push(o);continue}if(r(),o.tagName==="UL"||o.tagName==="OL"){let s=[...o.children].map(i=>Eo(i.childNodes)).filter(i=>i.length>0);s.length>0&&t.push({k:o.tagName==="UL"?"ul":"ol",items:s})}else if(o.tagName==="DIV"||o.tagName==="SECTION"||o.tagName==="BLOCKQUOTE")t.push(...zc(o));else{let s=Eo(o.childNodes);if(s.length===0)continue;o.tagName==="P"?t.push({k:"p",kids:s}):t.push({k:"h",level:Math.min(3,Number(o.tagName[1])),kids:s})}}return r(),t}function Dp(e,t){let n=`tb-${nt++}`,r=m("div","tb-field"),o=m("div","tb-label");o.id=n;let s=m("div","tb-control"),i=m("div","tb-rich"),l=m("div","tb-rich-tools");l.setAttribute("role","toolbar");let c=m("div","tb-input tb-rich-box");c.setAttribute("role","textbox"),c.setAttribute("aria-multiline","true"),c.setAttribute("aria-labelledby",n);let u=m("div","tb-rich-link");u.hidden=!0;let d=m("input","tb-input");d.type="url";let f=m("button","tb-button tb-small");f.type="button",u.append(d,f);let p=m("div","tb-error");p.id=`${n}-error`,p.setAttribute("aria-live","polite"),c.setAttribute("aria-describedby",p.id),o.addEventListener("click",()=>c.focus());let h=()=>{let v=ac(zc(c));v!==t.shown&&(t.shown=v,_("ui-input",e,v===""?x:D(v)))};c.addEventListener("input",h),c.addEventListener("paste",v=>{v.preventDefault(),document.execCommand("insertText",!1,v.clipboardData?.getData("text/plain")??"")}),c.addEventListener("drop",v=>v.preventDefault()),r.addEventListener("focusout",v=>{r.contains(v.relatedTarget)||_("ui-blur",e)});let y=null,k=()=>{let v=getSelection()?.anchorNode??null;return(v instanceof Element?v:v?.parentElement)?.closest("h1, h2, h3")!=null},M=v=>{switch(c.focus(),v){case"bold":case"italic":document.execCommand(v);break;case"heading":document.execCommand("formatBlock",!1,k()?"P":"H2");break;case"bullet-list":document.execCommand("insertUnorderedList");break;case"number-list":document.execCommand("insertOrderedList");break;case"link":{let C=getSelection();y=C!==null&&C.rangeCount>0&&c.contains(C.anchorNode)?C.getRangeAt(0).cloneRange():null,u.hidden=!1,d.value="",d.removeAttribute("aria-invalid"),d.focus();return}}h()};for(let[v,C]of $p){let S=m("button","tb-rich-tool");S.type="button",S.dataset.tool=C;let I=tt(v);I!==null&&S.append(I),S.addEventListener("mousedown",H=>H.preventDefault()),S.addEventListener("click",()=>M(C)),l.append(S)}let w=()=>{let v=d.value.trim(),C=/^[a-z][a-z0-9+.-]*:/i.test(v)?v:`https://${v}`;if(v===""||!ks(C)){d.setAttribute("aria-invalid","true");return}u.hidden=!0,c.focus();let S=getSelection();if(y!==null&&S!==null&&(S.removeAllRanges(),S.addRange(y)),(y===null||y.collapsed)&&document.execCommand("insertText",!1,v),y!==null&&!y.collapsed)document.execCommand("createLink",!1,C);else{let I=getSelection()?.getRangeAt(0);if(I!==void 0){let H=I.startContainer,z=Math.max(0,I.startOffset-v.length),fe=document.createRange();fe.setStart(H,z),fe.setEnd(H,I.startOffset),S?.removeAllRanges(),S?.addRange(fe),document.execCommand("createLink",!1,C)}}h()};return f.addEventListener("click",w),d.addEventListener("keydown",v=>{v.key==="Enter"?(v.preventDefault(),w()):v.key==="Escape"&&(v.stopPropagation(),u.hidden=!0,c.focus())}),i.append(l,u,c),s.append(i,p),r.append(o,s),t.label=o,t.error=p,t.box=c,r}function Pp(e,t){let n=e.face,r=e.box;e.label.textContent=K(n,"text")??"",e.label.classList.toggle("tb-required",Ot(n));let o=r.parentElement,s=P(n,"readonly"),i=P(n,"disabled"),l=s||i;r.contentEditable=l?"false":"true",r.tabIndex=i?-1:0,r.setAttribute("aria-readonly",l?"true":"false"),r.setAttribute("aria-disabled",i?"true":"false"),r.setAttribute("aria-required",Ot(n)?"true":"false"),r.setAttribute("aria-invalid",t!==null?"true":"false");let c=o.querySelector(".tb-rich-tools");c.hidden=l,c.setAttribute("aria-label",K(n,"text")??"");for(let f of c.querySelectorAll("button")){let p=Se(f.dataset.tool);f.setAttribute("aria-label",p),f.title=p}let u=o.querySelector(".tb-rich-link");l&&(u.hidden=!0),u.querySelector("input").placeholder=Se("link-url"),u.querySelector("button").textContent=Se("link-add"),e.error.textContent=t??"";let d=K(n,"value")??"";d!==e.shown&&document.activeElement!==r&&(e.shown=d,r.replaceChildren(...Np(oc(d))))}function Wo(e){let t=N(e,"columns");if(t.t!==a.Block)return[];let n=[],r=t.s.data;for(let o=t.i;o+1<r.length;o+=2){let s=r[o];s.t===a.Word&&n.push({sym:s.sym,word:s,label:Ue(r[o+1],le.rt)})}return n}function _c(e,t){return e.t===a.Map&&t.t===a.Map?e.s===t.s:e.t===a.Object&&t.t===a.Object?e.ctx===t.ctx:!1}function Zn(e){return e.t===a.None?"":e.t===a.Logic?Se(e.v?"yes":"no"):qn(e)}var Wp=new Set([a.Integer,a.Decimal,a.Money,a.Percent]);function jp(e,t,n){let r=m("div",t==="table"?"tb-table-wrap":"tb-list-wrap"),o;if(t==="table"){let l=m("table","tb-table");l.setAttribute("role","table");let c=m("thead"),u=m("tr");u.setAttribute("role","row");let d=Wo(e);for(let h of d){let y=m("th");y.scope="col",y.setAttribute("role","columnheader"),u.append(y)}c.append(u),c.addEventListener("click",h=>{let y=h.target.closest("th"),k=y!==null&&y.querySelector(".tb-sort")!==null?d[y.cellIndex]:void 0;k!==void 0&&_("ui-sort",e,k.word)}),o=m("tbody");let f=m("tfoot"),p=Os(d);p.className="tb-totals",f.append(p),l.append(c,o,f),r.append(l)}else o=m("ul","tb-list"),r.append(o);let s=m("p","tb-empty");r.append(s);let i=l=>{let c=l?.closest(t==="table"?"tr":"li"),u=c?zt.get(c):void 0;u!==void 0&&_("ui-select",e,u)};return o.addEventListener("click",l=>i(l.target)),o.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),i(l.target))}),n.box=o,n.rows=new Map,n.empty=s,r}function Rp(e){let t=e.face,n=e.box,r=n.tagName==="TBODY",o=Wo(t),s=N(t,"data"),i=s.t===a.Block?s.s.data.slice(s.i):[];if(r){Fp(t,n.parentElement,o);let y=qc(t);y!==null&&(i=ic(i,y.sym,y.desc,ft(le.rt),Zn))}let l=N(t,"key"),c=l.t===a.Word||l.t===a.LitWord?l.sym:A("id"),u=N(t,"selected"),d=en(t,"on-select");n.parentElement.classList.toggle("tb-selectable",d);let f=e.rows,p=new Map,h=n.firstChild;i.forEach((y,k)=>{let M=xs(y);if(M!==null){let I=`${M.kind}#${k}`,H=f.get(I);if(H===void 0&&(H=M.kind==="head"?Hp(o,r):r?Os(o):mc()),p.set(I,H),H.className=`tb-group-${M.kind} tb-level-${M.level}`,M.kind==="head"){let z=Ue(M.value,le.rt),fe=H.firstElementChild;fe.textContent!==z&&(fe.textContent=z),r&&(fe.colSpan=Math.max(1,o.length))}else Ds(H,M.value,o,r);H!==h?n.insertBefore(H,h):h=h.nextSibling;return}let w=et(y,c),v=w.t===a.None?`#${k}`:`${w.t}:${j(w)}`;p.has(v)&&(v=`${v}#${k}`);let C=f.get(v);C===void 0&&(C=r?Os(o):mc()),p.set(v,C),zt.set(C,y),Ds(C,y,o,r),d?C.tabIndex=0:C.removeAttribute("tabindex");let S=u.t!==a.None&&_c(u,y);C.classList.toggle("tb-selected",S),d?C.setAttribute("aria-selected",S?"true":"false"):C.removeAttribute("aria-selected"),C!==h?n.insertBefore(C,h):h=h.nextSibling});for(let[y,k]of f)p.get(y)!==k&&k.remove();e.rows=p,e.empty.textContent=K(t,"text")??Se("empty"),e.empty.hidden=i.length>0}function Fp(e,t,n){let r=P(e,"sortable")||en(e,"on-sort"),o=Uc(e),s=t.tHead.rows[0].cells;n.forEach((c,u)=>{let d=s[u];if(d===void 0)return;let f=o!==null&&L(o.sym)===L(c.sym),p=d.querySelector(".tb-sort");r&&p===null?(p=m("button","tb-sort"),p.type="button",p.append(m("span")),d.replaceChildren(p)):!r&&p!==null&&(d.replaceChildren(),p=null);let h=p!==null?p.firstChild:d;if(h.textContent!==c.label&&(h.textContent=c.label),p!==null){let y=f&&o.desc?"arrow-down":"arrow-up",k=p.querySelector("svg");if(k?.dataset.icon!==y){let M=tt(y);M!==null&&(M.dataset.icon=y,k?k.replaceWith(M):p.append(M))}p.querySelector("svg")?.classList.toggle("tb-sort-idle",!f)}f?d.setAttribute("aria-sort",o.desc?"descending":"ascending"):d.removeAttribute("aria-sort")});let i=N(e,"totals"),l=t.tFoot;l.hidden=i.t===a.None,i.t!==a.None&&Ds(l.rows[0],i,n,!0)}function Uc(e){let t=N(e,"sorted");if(t.t!==a.Block||t.s.data.length-t.i<2)return null;let n=t.s.data[t.i],r=t.s.data[t.i+1];return n.t!==a.Word&&n.t!==a.LitWord||r.t!==a.Word&&r.t!==a.LitWord?null:{sym:n.sym,desc:L(r.sym)===L(A("desc"))}}function qc(e){return P(e,"sortable")&&!en(e,"on-sort")?Uc(e):null}function Hp(e,t){if(!t){let o=m("li");return o.append(m("span")),o}let n=m("tr");n.setAttribute("role","row");let r=m("th");return r.scope="rowgroup",r.setAttribute("role","rowheader"),r.colSpan=Math.max(1,e.length),n.append(r),n}function Os(e){let t=m("tr");t.setAttribute("role","row");for(let n of e){let r=m("td");r.setAttribute("role","cell"),r.dataset.label=n.label,t.append(r)}return t}function mc(){let e=m("li");return e.append(m("span","tb-list-primary"),m("span","tb-list-secondary")),e}function Ds(e,t,n,r){let o=(l,c)=>{l.textContent!==c&&(l.textContent=c)};if(r){n.forEach((l,c)=>{let u=et(t,l.sym),d=e.children[c];o(d,Zn(u)),d.classList.toggle("tb-num",Wp.has(u.t))});return}let[s,...i]=n.map(l=>Zn(et(t,l.sym)));o(e.children[0],s??""),o(e.children[1],i.filter(Boolean).join(" \xB7 "))}function en(e,t){let n=N(e,"events");if(n.t!==a.Block)return!1;let r=L(A(t));return n.s.data.some(o=>o.t===a.Word&&L(o.sym)===r)}var Kc=A("children"),gc=A("expanded");function zs(e){return Array.from(e.box.querySelectorAll('[role="treeitem"]'))}function Gc(e,t){if(t===e.box)return x;let n=t.closest('[role="treeitem"]');return n!==null?zt.get(n)??x:x}function zp(e,t){let n=m("div","tb-tree-wrap"),r=m("ul","tb-tree");r.setAttribute("role","tree");let o=m("p","tb-empty");return n.append(r,o),r.addEventListener("click",s=>{let i=s.target,l=i.closest('[role="treeitem"]');if(l!==null){if(i.closest(".tb-tree-toggle")!==null)return Ps(t,l);_s(t,l),Zc(t,l)}}),r.addEventListener("keydown",s=>Up(t,s)),t.box=r,t.rows=new Map,t.empty=o,t.open=new Set,n}function _p(){let e=m("li");e.setAttribute("role","treeitem");let t=m("div","tb-tree-row"),n=m("span","tb-tree-toggle");n.setAttribute("aria-hidden","true");let r=tt("chevron-right");r!==null&&n.append(r),t.append(n,m("span","tb-tree-label"));let o=m("ul");return o.setAttribute("role","group"),e.append(t,o),e}function Vc(e){let t=e.face,n=Wo(t)[0]?.sym??A("name"),r=N(t,"key"),o=r.t===a.Word||r.t===a.LitWord?r.sym:A("id"),s=N(t,"selected"),i=e.rows,l=e.open,c=new Map,u=(h,y,k,M)=>{let w=h.firstChild;for(y.forEach((v,C)=>{let S=et(v,o),I=S.t===a.None?`${M}/${C}`:`${S.t}:${j(S)}`;c.has(I)&&(I=`${M}/${C}#${I}`);let H=i.get(I),z=H??_p();c.set(I,z),zt.set(z,v),z.dataset.key=I,z.setAttribute("aria-level",String(k)),z.style.setProperty("--tb-level",String(k-1));let fe=Zn(et(v,n)),ce=z.firstElementChild.lastElementChild;ce.textContent!==fe&&(ce.textContent=fe);let ye=et(v,Kc),je=ye.t===a.Block;je&&H===void 0&&et(v,gc).t===a.Logic&&et(v,gc).v&&l.add(I);let Ye=je&&l.has(I);je?z.setAttribute("aria-expanded",Ye?"true":"false"):z.removeAttribute("aria-expanded");let W=z.lastElementChild;Ye?u(W,ye.s.data.slice(ye.i),k+1,I):W.replaceChildren(),W.hidden=W.childElementCount===0;let ie=s.t!==a.None&&_c(s,v);z.classList.toggle("tb-selected",ie),z.setAttribute("aria-selected",ie?"true":"false"),z!==w?h.insertBefore(z,w):w=w.nextSibling});w!==null;){let v=w;w=w.nextSibling,v.remove()}},d=N(t,"data");u(e.box,d.t===a.Block?d.s.data.slice(d.i):[],1,""),e.rows=c;let f=zs(e),p=f.find(h=>h.tabIndex===0&&h.hasAttribute("tabindex"))??f.find(h=>h.classList.contains("tb-selected"))??f[0];for(let h of f)h.tabIndex=h===p?0:-1;e.empty.textContent=K(t,"text")??Se("empty"),e.empty.hidden=f.length>0}function _s(e,t){for(let n of zs(e))n.tabIndex=n===t?0:-1;t.focus()}function Zc(e,t){let n=zt.get(t);n!==void 0&&_("ui-select",e.face,n)}function Ps(e,t,n){if(!t.hasAttribute("aria-expanded"))return;let r=t.dataset.key,o=n??!e.open.has(r);if(o===e.open.has(r))return;let s=document.activeElement!==t&&t.contains(document.activeElement);o?e.open.add(r):e.open.delete(r),Vc(e),s&&_s(e,t);let i=zt.get(t);o&&i!==void 0&&_("ui-expand",e.face,i)}function Up(e,t){let n=t.target.closest('[role="treeitem"]');if(n===null||t.altKey||t.ctrlKey||t.metaKey)return;let r=zs(e),o=r.indexOf(n),s=n.getAttribute("aria-expanded"),i=null;switch(t.key){case"ArrowDown":i=r[o+1];break;case"ArrowUp":i=r[o-1];break;case"Home":i=r[0];break;case"End":i=r[r.length-1];break;case"ArrowRight":s==="false"?Ps(e,n,!0):s==="true"&&(i=n.querySelector('[role="treeitem"]'));break;case"ArrowLeft":s==="true"?Ps(e,n,!1):i=n.parentElement.closest('[role="treeitem"]');break;case"Enter":case" ":Zc(e,n);break;default:{if(t.key.length!==1||t.key.trim()==="")return;let l=t.key.toLowerCase(),c=u=>(u.querySelector(".tb-tree-label")?.textContent??"").toLowerCase();i=[...r.slice(o+1),...r.slice(0,o)].find(u=>c(u).startsWith(l))}}t.preventDefault(),i&&_s(e,i)}function qp(e,t,n,r){let o=document.elementFromPoint(n,r)?.closest('[role="treeitem"]'),s=P(e.face,"drop"),i;if(o==null||!e.box.contains(o))i={m:e,index:Ec(e,n,r),reorder:!1,group:e.box,parent:x};else{let l=o.querySelector(":scope > .tb-tree-row").getBoundingClientRect();if(o.hasAttribute("aria-expanded")&&r>l.top+l.height/4&&r<l.bottom-l.height/4){let c=zt.get(o),u=et(c,Kc);i={m:e,index:u.s.data.length-u.i,reorder:!1,group:o.lastElementChild,parent:c,into:o}}else{let c=o.parentElement,u=Array.prototype.indexOf.call(c.children,o)+(r>l.top+l.height/2?1:0);i={m:e,index:u,reorder:!1,group:c,parent:Gc(e,c)}}}return t.el===i.into||t.el.contains(i.group)?null:(i.reorder=t.within===e&&i.group===t.group&&i.into===void 0,i.reorder||s?i:null)}var Kp="button, a[href], input, select, textarea, [tabindex]";function To(e,t=!0){return Array.from(e.querySelectorAll(Kp)).filter(n=>n.closest(".tb-toolbar")===e&&(!t||n.getClientRects().length>0&&!n.disabled))}function Gp(){let e=m("div","tb-toolbar");return e.setAttribute("role","toolbar"),e.addEventListener("keydown",t=>{let n=t.target;if(t.altKey||t.ctrlKey||t.metaKey||n.matches("input, select, textarea"))return;let r=To(e),o=r.indexOf(n);if(o<0)return;let s=t.key==="ArrowRight"?(o+1)%r.length:t.key==="ArrowLeft"?(o-1+r.length)%r.length:t.key==="Home"?0:t.key==="End"?r.length-1:-1;s<0||(t.preventDefault(),r[s].focus())}),e.addEventListener("focusin",t=>{let n=t.target;if(To(e,!1).includes(n))for(let r of To(e,!1))r.tabIndex=r===n?0:-1}),e}function Vp(e){for(let r of Array.from(e.children)){let o=yn.get(r);o!==void 0&&o.el===r&&We(o.face,"style")==="button"&&jo(o)}let t=To(e,!1),n=t.find(r=>r.tabIndex===0&&r.hasAttribute("tabindex"))??t[0];for(let r of t)r.tabIndex=r===n?0:-1}function Zp(e){let t=N(e,"data");if(t.t!==a.Block)return[];let n=[],r=t.s.data.slice(t.i);for(let o=0;o<r.length;o++){let s=r[o];if(s.t!==a.String&&s.t!==a.Map)continue;let i=r[o+1],l=i!==void 0&&(i.t===a.Word||i.t===a.Path)?i:x;l!==x&&o++,n.push({text:Ue(s,le.rt),id:l})}return n}function Yp(e){let t=m("nav","tb-breadcrumb");return Er(t,"breadcrumb","aria-label"),e.box=m("ol"),t.append(e.box),t}function Xp(e){let t=e.face,n=Zp(t),r=n.map(l=>`${l.text}\0${j(l.id)}`).join("");if(e.kids===r)return;e.kids=r;let o=l=>{_("ui-crumb",t,l.id.t===a.Path?{...l.id,t:a.LitPath}:Je(a.LitWord,j(l.id)))},s=n.length>3?n.slice(1,-2):[],i=n.map((l,c)=>{let u=m("li");if(s.includes(l)&&(u.className="tb-crumb-middle"),l.id===x){let d=m("span","tb-crumb");d.textContent=l.text,c===n.length-1&&d.setAttribute("aria-current","page"),u.append(d)}else{let d=m("button","tb-crumb");d.type="button",d.textContent=l.text,d.addEventListener("click",()=>o(l)),u.append(d)}return u});if(s.length>0){let l=m("li","tb-crumb-more"),c=m("button","tb-crumb");c.type="button",c.textContent="\u2026",Er(c,"more-levels","aria-label"),c.setAttribute("aria-haspopup","menu"),c.setAttribute("aria-expanded","false"),c.addEventListener("click",()=>{let u=c.getBoundingClientRect();$o(s.map(d=>({text:d.text,run:()=>o(d)})),u.left,u.bottom+4,c)}),l.append(c),i.splice(1,0,l)}e.box.replaceChildren(...i)}function Jp(e,t){let n=m("dialog","tb-dialog"),r=m("header","tb-dialog-head"),o=m("h2","tb-dialog-title");o.id=`tb-${nt++}`,n.setAttribute("aria-labelledby",o.id);let s=m("button","tb-dialog-close");s.type="button",Er(s,"close","aria-label"),s.textContent="\xD7",s.addEventListener("click",()=>{_("ui-close",e)}),r.append(o,s);let i=m("div","tb-dialog-body");return n.append(r,i),n.addEventListener("cancel",l=>{l.preventDefault(),_("ui-close",e)}),t.label=o,t.box=i,n}function Yc(e){let t=e.el;e.label.textContent=K(e.face,"text")??"";let n=!P(e.face,"hidden");if(n!==t.open){if(!t.isConnected){queueMicrotask(()=>{t.isConnected&&Yc(e)});return}if(!n)return t.close();t.showModal(),queueMicrotask(()=>t.querySelector("input, textarea, select")?.focus())}}function Qp(e,t){let n=m("div","tb-tabs"),r=m("div","tb-tablist");r.setAttribute("role","tablist"),n.append(r);let o=rn(e),s=i=>{_("ui-input",e,{t:a.Integer,v:i+1}),r.children[i]?.focus()};return o.forEach((i,l)=>{let c=kn(i),u=m("button","tb-tab");u.type="button",u.id=`tb-${nt++}`,c.id=`${u.id}-panel`,u.setAttribute("role","tab"),u.setAttribute("aria-controls",c.id),c.setAttribute("aria-labelledby",u.id),u.textContent=K(i,"text")??"",u.addEventListener("click",()=>s(l));let d=xn.get(i.ctx);d.button=u,r.append(u),n.append(c)}),r.addEventListener("keydown",i=>{let l=Array.prototype.indexOf.call(r.children,document.activeElement),c=o.length,u=i.key==="ArrowRight"?(l+1)%c:i.key==="ArrowLeft"?(l-1+c)%c:i.key==="Home"?0:i.key==="End"?c-1:-1;u<0||l<0||(i.preventDefault(),s(u))}),t.box=r,n}function ef(e){let t=N(e.face,"value"),n=rn(e.face),r=t.t===a.Integer?Math.min(Math.max(Number(t.v),1),n.length)-1:0;n.forEach((o,s)=>{let i=xn.get(o.ctx);if(i===void 0||i.button===null)return;let l=s===r;i.button.setAttribute("aria-selected",l?"true":"false"),i.button.tabIndex=l?0:-1,i.el.hidden=!l})}function tf(e,t){let n=m("div","tb-split"),[r,o]=rn(e),s=m("div","tb-split-pane"),i=m("div","tb-split-pane");s.tabIndex=i.tabIndex=-1;let l=m("div","tb-split-handle");l.tabIndex=0,l.setAttribute("role","separator"),l.setAttribute("aria-orientation","vertical"),Er(l,"resize-panes","aria-label"),l.setAttribute("aria-valuemin","20"),l.setAttribute("aria-valuemax","80");let c=p=>{let h=Math.round(Math.min(80,Math.max(20,p)));n.style.setProperty("--tb-split",`${h}%`),l.setAttribute("aria-valuenow",String(h))};c(40),l.addEventListener("pointerdown",p=>{l.setPointerCapture(p.pointerId),p.preventDefault()}),l.addEventListener("pointermove",p=>{if(!l.hasPointerCapture(p.pointerId))return;let h=n.getBoundingClientRect();c((p.clientX-h.left)/h.width*100)}),l.addEventListener("keydown",p=>{let h=Number(l.getAttribute("aria-valuenow")),y=p.key==="ArrowLeft"?h-5:p.key==="ArrowRight"?h+5:p.key==="Home"?20:p.key==="End"?80:null;y!==null&&(p.preventDefault(),c(y))});let u=m("button","tb-button tb-split-back");u.type="button";let d=vs("arrow-left"),f=m("span");return Er(f,"back"),u.append(...d!==null?[d]:[],f),u.addEventListener("click",()=>{_("ui-input",e,{t:a.Integer,v:1})}),r!==void 0&&s.append(kn(r)),i.append(u),o!==void 0&&i.append(kn(o)),n.append(s,l,i),n}function nf(e){let t=N(e.face,"value"),n=t.t===a.Integer&&Number(t.v)===2?"2":"1",r=e.el.dataset.pane;if(r!==n&&(e.el.dataset.pane=n,r!==void 0&&matchMedia("(max-width: 640px)").matches)){let o=e.el.children[n==="2"?2:0];(o.querySelector(".tb-selected")??o).focus()}}var zn=null;g("show-toast",'["Shows a short message at the edge of the screen." message [string!] kind [word! none!]]',(e,t)=>{zn===null&&(zn=m("div","tb-toasts"),zn.popover="manual",zn.setAttribute("aria-live","polite"),document.body.append(zn));let n=t.args[1].t===a.Word?E(t.args[1].sym).toLowerCase():null,r=m("div",n!==null?`tb-toast tb-${n}`:"tb-toast");n==="danger"&&r.setAttribute("role","alert");let o=$(t.args[0]),s=zn,i=()=>{r.remove(),s.childElementCount===0&&s.matches(":popover-open")&&s.hidePopover()};return r.addEventListener("click",i),setTimeout(i,n==="danger"?6e3:4e3),s.matches(":popover-open")&&s.hidePopover(),s.append(r),s.showPopover(),setTimeout(()=>{r.textContent=o},50),b(t.args[0])});g("show-confirm",'["Asks a question in a small dialog; true when the user says yes." question [string!] yes [string! none!] no [string! none!] kind [word! none!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=(p,h)=>t.args[p].t===a.String?$(t.args[p]):Se(h),o=t.args[3].t===a.Word&&E(t.args[3].sym).toLowerCase()==="danger",s=m("dialog","tb-dialog tb-confirm");s.setAttribute("role","alertdialog");let i=m("div","tb-dialog-body"),l=m("p","tb-confirm-question");l.id=`tb-${nt++}`,l.textContent=$(t.args[0]),s.setAttribute("aria-labelledby",l.id);let c=m("div","tb-row tb-right"),u=m("button","tb-button"),d=m("button",o?"tb-button tb-danger":"tb-button tb-primary");u.type=d.type="button",u.textContent=r(2,"no"),d.textContent=r(1,"yes"),c.append(u,d),i.append(l,c),s.append(i);let f=new Promise(p=>{let h=y=>{s.close(),s.remove(),p(y?O:xe)};d.addEventListener("click",()=>h(!0)),u.addEventListener("click",()=>h(!1)),s.addEventListener("cancel",y=>{y.preventDefault(),h(!1)})});return document.body.append(s),s.showModal(),(o?u:d).focus(),{k:"await",p:f}});g("print-faces",'["Opens the print dialog for the page, or for one face only." face [object! none!]]',(e,t)=>{let n=t.args[0].t===a.Object?xn.get(t.args[0].ctx)?.el:void 0;return t.args[0].t===a.Object&&(n===void 0||!n.isConnected)?te("script","not-shown","print-page/only needs a face on the screen"):(n!==void 0&&(n.classList.add("tb-print-target"),document.documentElement.classList.add("tb-print-only"),addEventListener("afterprint",()=>{n.classList.remove("tb-print-target"),document.documentElement.classList.remove("tb-print-only")},{once:!0})),print(),b(ae))});function jo(e){let t=e.face,n=We(t,"style")??"",r=We(t,"role"),o=K(t,"text"),s=P(t,"hidden"),i=K(t,"error"),l=[];s&&n!=="dialog"&&l.push("tb-hidden"),P(t,"fill")&&l.push("tb-fill"),P(t,"narrow-only")&&l.push("tb-narrow-only"),P(t,"wide-only")&&l.push("tb-wide-only"),P(t,"fit")&&l.push("tb-fit"),P(t,"drop")&&l.push("tb-drop-zone"),r!==null&&!Cc.has(n)&&l.push(`tb-${r}`);let c=We(t,"size");c!==null&&l.push(`tb-${c}`);let u=We(t,"align");u!==null&&n==="row"&&l.push(`tb-${u}`);let d=We(t,"valign");if(d!==null&&n==="row"&&l.push(`tb-${d}`),i!==null&&l.push("tb-invalid"),P(t,"pending")&&l.push("tb-pending"),rf(e.el,l),e.el.inert=P(t,"inert"),P(t,"drag")&&!Lo(e)&&e.el.tabIndex<0&&(e.el.tabIndex=0),vc(e.el,"padding",N(t,"pad")),vc(e.el,"gap",N(t,"gap")),n==="radio")return Ip(e,i);if(n==="upload")return dp(e,i);if(n==="lookup")return fp(e,i);if(n==="rich")return Pp(e,i);if(e.input!==null){e.label!==null&&(e.label.textContent=o??"",e.label.classList.toggle("tb-required",Ot(t)&&n!=="check"));let p=N(t,"value");if(e.input instanceof HTMLInputElement&&e.input.type==="checkbox")e.input.checked=p.t===a.Logic&&p.v;else{e.input instanceof HTMLSelectElement&&e.input.dataset.options!==kc(t)&&xc(e.input,t);let k=p.t===a.None?K(t,"typed")??"":n==="money"||n==="date"?qn(p):j(p);!(document.activeElement===e.input&&!P(t,"readonly")&&(e.typing>0||p===e.typed))&&e.input.value!==k&&(e.input.value=k);let w=K(t,"hint");if(e.input instanceof HTMLSelectElement){let v=e.input;v.options[0].textContent=w??Se("choose"),yc(t).forEach((S,I)=>{let H=v.options[I+1];H&&(H.textContent=Ir(S))});let C=v.querySelectorAll("optgroup");Yn(t).filter(Xn).forEach((S,I)=>{C[I]&&(C[I].label=Ue(S.title,le.rt))})}else w!==null&&(e.input.placeholder=w)}let h=P(t,"readonly"),y=e.input instanceof HTMLTextAreaElement||e.input instanceof HTMLInputElement&&e.input.type!=="checkbox";if(y&&(e.input.readOnly=h),e.input.disabled=P(t,"disabled")||h&&!y,n==="date"){let k=e.input.nextElementSibling;k.disabled=e.input.disabled||h,k.setAttribute("aria-label",o!==null?Se("choose-date-of",o):Se("choose-date"))}e.input.setAttribute("aria-required",Ot(t)?"true":"false"),e.input.setAttribute("aria-invalid",i!==null?"true":"false"),e.error!==null&&(e.error.textContent=i??"");return}switch(n){case"title":case"heading":case"text":{let p=N(t,"text");e.el.textContent=p.t===a.None?"":p.t===a.Map||p.t===a.Word?Ue(p,le.rt):qn(p);break}case"tile":(e.label??e.el).textContent=o??"";break;case"button":case"link":{(e.label??e.el).textContent=o??"";let p=op(t);p!==null?e.el.setAttribute("aria-label",p):e.el.removeAttribute("aria-label");let h=K(t,"shortcut");h!==null?e.el.setAttribute("aria-keyshortcuts",ep(h)):e.el.removeAttribute("aria-keyshortcuts");let y=e.label!==null&&e.el.parentElement?.classList.contains("tb-toolbar")===!0,k=p??(h!==null||y?o:null);e.el.title=k===null?"":h===null?k:`${k} (${tp(h)})`;break}case"progress":yp(e);return;case"canvas":xp(e);return;case"chart":Ep(e);return;case"icon":Tp(e);return;case"image":{let p=e.el,h=K(t,"value")??"";p.getAttribute("src")!==h&&(p.src=h),p.alt=o??"";return}case"table":case"list":Rp(e);return;case"rows":Ap(e,i);break;case"tree":Vc(e);return;case"breadcrumb":Xp(e);return;case"toolbar":{o!==null?e.el.setAttribute("aria-label",o):e.el.removeAttribute("aria-label");break}case"desktop":{let p=K(t,"value");e.el.style.backgroundImage=p!==null?`url(${JSON.stringify(p)})`:"";break}case"dialog":Yc(e);break;case"tabs":ef(e);return;case"split":nf(e);return;case"tab":e.button!==null&&(e.button.textContent=o??"");break;case"panel":{let p=e.el.querySelector(":scope > .tb-panel-title");o===null?p?.remove():(p===null&&(p=m("h2","tb-panel-title"),e.el.prepend(p)),p.textContent=o);break}case"scroll":{o!==null?e.el.setAttribute("aria-label",o):e.el.removeAttribute("aria-label");break}case"grid":{let p=N(t,"cols");e.el.style.setProperty("--tb-cols",p.t===a.Integer?String(p.v):"2");let h=p.t===a.Block?p.s.data.slice(p.i).filter(y=>y.t===a.Integer):[];h.length>0?e.el.style.setProperty("--tb-tracks",h.map(y=>`minmax(min-content, ${j(y)}fr)`).join(" ")):e.el.style.removeProperty("--tb-tracks");break}}n==="toolbar"&&Vp(e.el),e.el instanceof HTMLButtonElement&&(P(t,"submit")?e.el.setAttribute("aria-disabled",P(t,"disabled")?"true":"false"):e.el.disabled=P(t,"disabled"));let f=N(t,"pane");if(f.t===a.Block&&e.kids?.s!==f.s){if(e.kids=f,n==="rows"){Bp(e),_("ui-pane",t);return}let p=e.box??e.el;if(n==="screens")Xc(e,p);else{let h=p.querySelector(":scope > .tb-panel-title");p.replaceChildren(...h?[h]:[]),Rs(p,t,n)}_("ui-pane",t)}n==="screens"&&Jc(e.box??e.el,t)}function Xc(e,t){Kn=m("div"),Rs(Kn,e.face,"screens"),Jc(t,e.face)}function Jc(e,t){let n=P(t,"entering");e.toggleAttribute("aria-busy",n),!(n||Kn===null)&&(e.replaceChildren(...Kn.childNodes),Kn=null,lf(e))}function vc(e,t,n){n.t===a.Integer?e.style.setProperty(t,`var(--tb-space-${n.v})`):e.style.removeProperty(t)}function rf(e,t){let n=(e.dataset.tb??"").split(" ").filter(Boolean);for(let r of n)t.includes(r)||e.classList.remove(r);for(let r of t)e.classList.add(r);e.dataset.tb=t.join(" ")}function Qc(){for(let e of Ms){e.dirty=!1;let t=xn.get(e);t!==void 0&&(t.el.isConnected||Kn?.contains(t.el))&&jo(t)}Ms.length=0}var Tr=null,Kn=null,xr=null;function of(){let e=location.hash.replace(/^#\/?/,"");return e===""?[]:e.split("/").map(t=>{try{return decodeURIComponent(t)}catch{return t}})}function eu(){return Ge(a.Block,of().map(e=>D(e)))}function Mr(e){let t=n=>encodeURIComponent(n.t===a.String?$(n):n.t===a.Word?E(n.sym):j(n));return e.t===a.Word?"#/"+t(e):e.t===a.Path?"#/"+e.s.data.slice(e.i).map(t).join("/"):null}g("route",'["The screen and arguments in the address bar." ]',()=>b(eu()));var $e={depth:0,top:0};function af(){let e=history.state;typeof e?.depth=="number"&&($e={depth:e.depth,top:e.top??e.depth}),history.replaceState({...$e},"")}function sf(){let e=history.state;typeof e?.depth=="number"?$e={depth:e.depth,top:$e.top}:$e={depth:$e.depth+1,top:$e.depth+1},history.replaceState({...$e},"")}g("set-route",'["Puts a screen and arguments in the address bar." route [block!] replace [logic!]]',(e,t)=>{let n=Mr({...t.args[0],t:a.Path})??"#/";return t.args[1].t===a.Logic&&t.args[1].v?(history.replaceState({...$e},"",n),b(t.args[0])):($e={depth:$e.depth+1,top:$e.depth+1},history.pushState({...$e},"",n),b(t.args[0]))});g("route-steps",'["How many steps back and forward the history has." ]',()=>b(Ge(a.Block,[Nt($e.depth),Nt($e.top-$e.depth)])));g("route-back",'["Goes one step back in the history." ]',()=>$e.depth===0?b(Z(!1)):(history.back(),b(Z(!0))));g("route-forward",'["Goes one step forward in the history." ]',()=>$e.depth>=$e.top?b(Z(!1)):(history.forward(),b(Z(!0))));function lf(e){let t=e.firstElementChild;if(t===null)return;let r=t.querySelector("h1, h2")??t;r.tabIndex<0&&(r.tabIndex=-1),r.focus({preventScroll:!0}),window.scrollTo(0,0),xr===null&&(xr=m("div","tb-sr-only"),xr.setAttribute("aria-live","polite"),document.body.append(xr));let o=xr;o.textContent="",setTimeout(()=>{o.textContent=t.getAttribute("aria-label")??""},50)}g("repaint",'["Redraws the faces that changed." ]',()=>{document.documentElement.lang=ft(le.rt),Oo!==null&&(document.title=K(Oo,"text")??document.title);for(let e of Array.from(document.querySelectorAll("[data-tb-own]")))wc(e);for(let e of Array.from(document.querySelectorAll("*"))){let t=yn.get(e);t!==void 0&&t.el===e&&jo(t)}return b(x)});var Ss=null,Oo=null;g("show",'["Draws a face and everything in it." face [object!]]',(e,t)=>{let n=t.args[0];Io=null,Tr=null,document.documentElement.lang=ft(le.rt);let r=kn(n);Ss!==null?Ss.replaceWith(r):document.body.append(r),Ss=r;let o=rn(n).find(s=>We(s,"style")==="title");return o!==void 0&&Tr===null&&(document.title=K(o,"text")??document.title,Oo=o),b(n)});function cf(e){let t=We(e,"look"),n={...ms,...t!==null?gs[t]:void 0},r=l=>{let c=N(e,l);return c.t===a.Integer?Number(c.v):c.t===a.Decimal?c.v:null};n.base=r("base")??n.base;let o=r("accent");n.accent=o??(t!==null&&r("base")===null&&t in gs?n.accent:(n.base+180)%360),n.color=Math.min(1,Math.max(0,r("color")??n.color)),(r("line")===2||r("line")===1)&&(n.line=r("line"));for(let[l,c]of Object.entries(Jl)){let u=We(e,l);u!==null&&c.includes(u)&&(n[l]=u)}let s=N(e,"font");s.t===a.Word?n.font=E(s.sym).toLowerCase():s.t===a.String&&(n.font=$(s));let i=N(e,"headings");return i.t===a.Word?n.headings=E(i.sym).toLowerCase():i.t===a.String&&(n.headings=$(i)),n}function tu(e){let t=document.getElementById("tb-theme");t===null&&(t=m("style"),t.id="tb-theme",document.head.append(t)),t.textContent=Ql(e)}g("apply-theme",'["Changes the look of the whole screen." spec [object!]]',(e,t)=>(tu(cf(t.args[0])),b(t.args[0])));async function uf(){tu(ms),le=ql(),le.sch.afterPump=Qc,document.addEventListener("keydown",np,!0),document.addEventListener("keydown",qb),document.addEventListener("pointerdown",_b),document.addEventListener("pointermove",Ub,{passive:!1}),document.addEventListener("pointerup",()=>Mo(!0)),document.addEventListener("pointercancel",()=>Mo(!1)),document.addEventListener("keydown",e=>{e.key==="Escape"&&tn?.on&&(e.preventDefault(),nn.add(e),Mo(!1))},!0),document.addEventListener("touchmove",e=>{tn?.on&&e.preventDefault()},{passive:!1}),document.addEventListener("keydown",rp),af(),window.addEventListener("hashchange",()=>{sf(),Tr!==null&&_("ui-route",Tr,eu())}),await Kl(le);for(let e of Array.from(document.querySelectorAll('script[type="text/trebol"]'))){let t=e.getAttribute("src"),n=t!==null?new URL(t,location.href).href:location.href,r=t!==null?await(await fetch(n)).text():e.textContent??"";try{await hs(le,r,n)}catch(o){console.error(o instanceof Error?o.message:ko(o))}}}uf();
4284
+ `)}function Du(e,t){let n=Si(e),r=n[n.length-1];return r?.k==="p"?r.kids.push({k:"text",text:t}):n.push({k:"p",kids:[{k:"text",text:t}]}),ha(n)}function Ei(e){return/^(https?:|mailto:)/i.test(e.trim())}function at(e,t){if(e.t===s.Object){let n=te(e.ctx,t);return n<0?k:e.ctx.vals[n]}if(e.t===s.Map){let n=e.s.data,r=I(t);for(let o=0;o+1<n.length;o+=2){let a=n[o];if(a.t===s.Word||a.t===s.SetWord||a.t===s.LitWord){if(I(a.sym)===r)return n[o+1]}else if(a.t===s.String&&I(A(B(a)))===r)return n[o+1]}}return k}function ga(e){if(e.t!==s.Block)return null;let[t,n,r]=e.s.data.slice(e.i);if(t===void 0||n===void 0||r===void 0||t.t!==s.Word||n.t!==s.Integer)return null;let o=M(t.sym).toLowerCase();return o!=="head"&&o!=="foot"?null:{kind:o,level:Number(n.v)>=2?2:1,value:r}}function Fu(e,t,n,r,o){let a=[],i=[];for(let l of e){if(ga(l)===null){i.push(l);continue}a.push(...Wu(i,t,n,r,o),l),i=[]}return a.concat(Wu(i,t,n,r,o))}function Wu(e,t,n,r,o){let a=new Intl.Collator(r,{numeric:!0}),i=c=>c.t===s.None||c.t===s.String&&B(c)==="",l=(c,u)=>c.t===s.String&&u.t===s.String?a.compare(B(c),B(u)):Bn(c,u)??a.compare(o(c),o(u));return e.map(c=>({row:c,v:at(c,t)})).sort((c,u)=>{let d=i(c.v),f=i(u.v);return d||f?d===f?0:d?1:-1:n?l(u.v,c.v):l(c.v,u.v)}).map(c=>c.row)}var Mi=200,Ru=30,ma=60;function Hu(e,t,n,r,o){let a=Math.max(1,t),i=f=>Math.min(e,Math.max(0,f)),l=i(Math.floor(n/a)),c=i(Math.ceil((n+r)/a));if(o!==void 0&&o.end<=e&&o.end-o.first>=Math.min(e,ma)&&o.first<=l&&c<=o.end)return o;let u=i(l-Ru),d=i(c+Ru);return d-u<ma&&((u===0||d<e)&&(d=i(u+ma)),u=i(d-ma)),{first:u,end:d}}var no=["var(--tb-primary)","var(--tb-accent)","var(--tb-c-teal)","var(--tb-c-orange)","var(--tb-c-purple)","var(--tb-c-green)","var(--tb-c-pink)","var(--tb-c-gold)"],gr=12,Uu={fill:"var(--tb-muted)","font-size":gr,"font-family":"var(--tb-font)"};function zu(e){return e.labels.length===0||e.series.length===0?[]:e.kind==="pie"?fh(e):dh(e)}function uh(e,t,n=!1,r=5){t===e&&(t=e+1);let o=(t-e)/r,a=10**Math.floor(Math.log10(o)),i=Math.max(n?1:0,[1,2,2.5,5,10].map(c=>c*a).find(c=>c>=o&&(!n||Number.isInteger(c)))),l=[];for(let c=Math.floor(e/i);c*i<=t+i*1e-9;c++)l.push(Number((c*i).toPrecision(12)));return l[l.length-1]<t&&l.push(l[l.length-1]+i),l}function dh(e){let{labels:t,series:n,width:r,height:o,stacked:a,format:i}=e,l=t.length,c=a&&e.kind!=="line",u=n.map(()=>[]),d=n.map(()=>[]);for(let W=0;W<l;W++){let ue=0,ze=0;n.forEach((fe,De)=>{let _e=fe.values[W]??0,So=c?_e>=0?ue:ze:0;d[De][W]=So,u[De][W]=So+_e,c&&(_e>=0?ue+=_e:ze+=_e)})}let f=u.flat().concat(d.flat(),[0]),p=uh(Math.min(...f),Math.max(...f),f.every(Number.isInteger)),h=p[0],v=p[p.length-1],y=Math.max(...p.map(W=>i(W).length))*gr*.6+8,C=8,x=gr,w=gr*2+4,E=Math.max(1,r-y-C),S=Math.max(1,o-x-w),T=W=>x+S-(W-h)/(v-h)*S,V=[];for(let W of p)V.push(z("line",{x1:y,x2:y+E,y1:T(W),y2:T(W),stroke:"var(--tb-border)","stroke-width":W===0?1.5:1})),V.push(z("text",{...Uu,x:y-6,y:T(W),"text-anchor":"end","dominant-baseline":"middle"},[],i(W)));let J=E/l,Ge=W=>y+J*(W+.5),Fe=Math.max(1,Math.floor(E/(Math.max(...t.map(W=>W.length))*gr*.6+12))),He=Math.ceil(l/Fe);t.forEach((W,ue)=>{ue%He===0&&V.push(z("text",{...Uu,x:Ge(ue),y:x+S+gr+4,"text-anchor":"middle","dominant-baseline":"middle"},[],W))});let Ue=(W,ue)=>z("title",{},[],`${t[W]}, ${ue.name}: ${ue.values[W]===null?"":i(ue.values[W])}`);if(e.kind==="bar"){let W=c?1:n.length,ue=J*.7,ze=ue/W;return n.forEach((fe,De)=>{for(let _e=0;_e<l;_e++){if(fe.values[_e]===null)continue;let So=y+J*_e+(J-ue)/2+(c?0:ze*De),gl=T(Math.max(d[De][_e],u[De][_e])),kf=T(Math.min(d[De][_e],u[De][_e]));V.push(z("rect",{x:So+1,y:gl,width:Math.max(1,ze-2),height:Math.max(0,kf-gl),fill:fe.color,rx:2},[Ue(_e,fe)]))}}),V}let Oe=[];return n.forEach((W,ue)=>{let ze=[];for(let fe=0;fe<l;fe++)W.values[fe]!==null&&ze.push(`${Ge(fe)},${T(u[ue][fe])}`);if(e.kind==="area"){let fe=[];for(let De=l-1;De>=0;De--)W.values[De]!==null&&fe.push(`${Ge(De)},${T(d[ue][De])}`);V.push(z("polygon",{points:[...ze,...fe].join(" "),fill:W.color,"fill-opacity":.18,stroke:"none"}))}Oe.push(z("polyline",{points:ze.join(" "),fill:"none",stroke:W.color,"stroke-width":2,"stroke-linejoin":"round","stroke-linecap":"round"}));for(let fe=0;fe<l;fe++)W.values[fe]!==null&&Oe.push(z("circle",{cx:Ge(fe),cy:T(u[ue][fe]),r:3.5,fill:W.color,stroke:"var(--tb-surface)","stroke-width":1.5},[Ue(fe,W)]))}),V.concat(Oe)}function fh(e){let n=e.series[0].values.map(u=>u===null||u<0?0:u),r=n.reduce((u,d)=>u+d,0);if(r===0)return[];let o=Math.max(1,Math.min(e.width,e.height)/2-4),a=e.width/2,i=e.height/2,l=[],c=-90;return n.forEach((u,d)=>{if(u===0)return;let f=u/r*360,p=z("title",{},[],`${e.labels[d]}: ${e.format(u)} (${Math.round(u/r*100)}%)`),h={fill:Ti(d),stroke:"var(--tb-surface)","stroke-width":2};if(f>=359.999)l.push(z("circle",{cx:a,cy:i,r:o,...h},[p]));else{let v=S=>[a+o*Math.cos(S*Math.PI/180),i+o*Math.sin(S*Math.PI/180)],[y,C]=v(c),[x,w]=v(c+f),E=`M${a},${i} L${y},${C} A${o},${o} 0 ${f>180?1:0} 1 ${x},${w} Z`;l.push(z("path",{d:E,...h},[p]))}c+=f}),l}function Ti(e){return no[e%no.length]}var ph=["many","dashed","count","steps","at"],bh=["solid","dashed","faint"];function oo(e){switch(e.t){case s.Word:case s.LitWord:return`w:${M(e.sym)}`;case s.Integer:return`i:${pe.toString(e.v)}`;case s.String:return`s:${B(e)}`;case s.Issue:return`#:${M(e.sym)}`;default:return null}}var _u=e=>e!==void 0&&(e.t===s.String||e.t===s.Map),va=e=>e!==void 0&&e.t===s.Word?M(e.sym):null,Li=e=>e!==void 0&&e.t===s.Integer?pe.toNumber(e.v):null,vr=e=>e.s.data.slice(e.i),Tt=class extends Error{};function Ii(e){let t={focus:null,nodes:new Map,edges:[],trail:[]};if(e.t!==s.Block)return{spec:t,error:e.t===s.None?null:"orbit: an orbit takes a block"};try{let n=vr(e);for(let r=0;r<n.length;r++){let o=va(n[r]),a=n[++r];if(o==="focus"){let i=a===void 0?null:oo(a);if(i===null)throw new Tt("focus takes the id of a node");t.focus=i}else if(o==="nodes"&&a?.t===s.Block)hh(vr(a),t);else if(o==="edges"&&a?.t===s.Block)gh(vr(a),t);else if(o==="trail"&&a?.t===s.Block)for(let i of vr(a)){let l=oo(i);if(l===null)throw new Tt("trail takes the ids of nodes");t.trail.push(l)}else throw new Tt("an orbit takes focus id, nodes [...], edges [...] and trail [...]")}return{spec:t,error:null}}catch(n){if(n instanceof Tt)return{spec:t,error:`orbit: ${n.message}`};throw n}}function hh(e,t){for(let n=0;n<e.length;n++){let r=e[n],o=oo(r);if(o===null||!_u(e[n+1]))throw new Tt("nodes takes an id and a title for each, then a block of hints if it has any");let a={key:o,id:r,title:e[++n],color:"var(--tb-primary)",count:null,many:!1,dashed:!1,steps:0,at:0};e[n+1]?.t===s.Block&&mh(vr(e[++n]),a),t.nodes.set(o,a)}}function mh(e,t){for(let n=0;n<e.length;n++){let r=va(e[n]);if(r==="many")t.many=!0;else if(r==="dashed")t.dashed=!0;else if(r==="count"){let o=Li(e[++n]);if(o===null)throw new Tt("count takes an integer");t.count=o}else if(r==="steps"){let o=Li(e[++n]),a=va(e[n+1])==="at"?Li(e[n+=2]):0;if(o===null||o<1||a===null)throw new Tt("steps takes how many, then at and the current one: steps 5 at 2");t.steps=o,t.at=Math.max(0,Math.min(o,a))}else{let o=r===null||ph.includes(r)?void 0:yi(r);if(o==null)throw new Tt(`a node's hints are a role or color, many, dashed, count n and steps n at k, not ${r??"that"}`);t.color=o}}}function gh(e,t){for(let n=0;n<e.length;n++){let r=oo(e[n]),o=e[n+1]===void 0?null:oo(e[++n]);if(r===null||o===null)throw new Tt("edges takes two ids for each, then a label and a block with solid, dashed or faint if it has them");let a=_u(e[n+1])?e[++n]:null,i="solid";if(e[n+1]?.t===s.Block){let l=vr(e[++n]),c=va(l[0]);if(l.length!==1||c===null||!bh.includes(c))throw new Tt("an edge looks solid, dashed or faint");i=c}t.edges.push({from:r,to:o,label:a,look:i})}}var zn=92,ro=30,qu=18,vh=4,Ai="\0more";function yh(e){let t=new Set(e.trail);return[...e.nodes.keys()].filter(n=>n!==e.focus&&!t.has(n))}function Ku(e,t=0){let n=[];if(e.focus===null)return{placed:n,box:{x0:-zn,y0:-zn,x1:zn,y1:zn},left:0,pages:1};n.push({key:e.focus,role:"focus",x:0,y:0,r:zn,o:1});let r=yh(e),o=Math.max(1,Math.ceil(r.length/ro)),a=0;if(r.length>ro){let y=t%o*ro;a=r.length-Math.min(r.length,y+ro),r=r.slice(y,y+ro)}let i=r.length+(o>1?1:0),l=Math.max(24,Math.min(62,66-i*1.6)),c=[],u=zn+l+120,d=zn;for(let y=0,C=0;y<i;C++){let x=Math.max(6,Math.floor(2*Math.PI*u/(2*l+30))),w=Math.min(x,i-y);for(let E=0;E<w;E++){let S=-Math.PI/2+2*Math.PI*E/w+(C%2===1?Math.PI/w:0);c.push({x:Math.cos(S)*u,y:Math.sin(S)*u})}y+=w,d=u+l,u+=2*l+46}r.forEach((y,C)=>n.push({key:y,role:"near",...c[C],r:l,o:1})),o>1&&n.push({key:Ai,role:"more",...c[r.length],r:l,o:1});let f=e.trail.filter(y=>y!==e.focus&&e.nodes.has(y)).slice(-vh).reverse(),p=-Math.PI*.9,h=d+150;f.forEach((y,C)=>{let x=h+C*120;n.push({key:y,role:"trail",x:Math.cos(p)*x,y:Math.sin(p)*x,r:46-C*7,o:.8-C*.17})});let v={x0:1/0,y0:1/0,x1:-1/0,y1:-1/0};for(let y of n){let C=y.r*1.5+40,x=y.r*1.5+24;v.x0=Math.min(v.x0,y.x-C),v.x1=Math.max(v.x1,y.x+C),v.y0=Math.min(v.y0,y.y-x),v.y1=Math.max(v.y1,y.y+x)}return{placed:n,box:v,left:a,pages:o}}function Gu(e,t){let n=new Map(t.map(i=>[i.key,i.role])),r=[],o=new Set;for(let i of e.edges){let l=n.get(i.from),c=n.get(i.to);if(l!=="focus"&&l!=="near"||c!=="focus"&&c!=="near"||i.from===i.to)continue;let u=[i.from,i.to].sort().join("");o.has(u)||(o.add(u),r.push({...i,curve:l==="near"&&c==="near"?.35:0,trail:!1}))}n.has(Ai)&&r.push({from:e.focus,to:Ai,label:null,look:"faint",curve:0,trail:!1});let a=e.focus;for(let i of t)i.role==="trail"&&(r.push({from:a,to:i.key,label:null,look:"faint",curve:0,trail:!0}),a=i.key);return r}function Vu(e,t){for(let n of e.edges)if(n.label!==null&&(n.from===e.focus&&n.to===t||n.to===e.focus&&n.from===t))return n.label;return null}function wh(e,t){let n=[],r="";for(let o of e.split(/\s+/).filter(a=>a!==""))r!==""&&[...`${r} ${o}`].length>t?(n.push(r),r=o):r=r===""?o:`${r} ${o}`;return r!==""&&n.push(r),n.length>3&&(n.length=3,n[2]=`${[...n[2]].slice(0,Math.max(1,t-1)).join("")}\u2026`),n}function kh(e,t,n){let r=o=>`${Mt(Math.cos(o)*e)},${Mt(Math.sin(o)*e)}`;return`M${r(t)} A${e},${e} 0 ${n-t>Math.PI?1:0} 1 ${r(n)}`}var Mt=e=>String(Math.round(e*1e3)/1e3);function Yu(e){let t=e.node,n=e.color,r=e.role==="focus",o=[z("circle",{class:"tb-orbit-halo",r:1.45,fill:`url(#${e.halo})`}),z("circle",{class:"tb-orbit-body",r:1,fill:`url(#${e.body})`,stroke:n,"stroke-width":r?2:1.4,...t?.dashed===!0?{"stroke-dasharray":"4 4"}:{},...e.role==="trail"?{"stroke-opacity":.6}:{}})];if(t?.many===!0&&o.push(z("circle",{class:"tb-orbit-line",r:1.09,stroke:n,"stroke-opacity":.55})),t!==null&&t.steps>0){let f=t.steps>1?.09:0;for(let p=0;p<t.steps;p++){let h=-Math.PI/2+2*Math.PI*p/t.steps+f/2,v=h+2*Math.PI/t.steps-f,y=p+1===t.at;o.push(z("path",{class:y?"tb-orbit-step tb-orbit-now":"tb-orbit-step",d:kh(1.16,h,t.steps>1?v:h+2*Math.PI-.001),stroke:n,"stroke-opacity":p+1<t.at?.9:y?1:.18,"stroke-width":y?4:3}))}}let a=t?.count??0;if(a>0&&!r&&e.role!=="more"){let f=Math.min(a,14),p=[];for(let h=0;h<f;h++){let v=2*Math.PI*h/f;p.push(z("circle",{cx:Math.cos(v)*1.24,cy:Math.sin(v)*1.24,r:.05,fill:n,"fill-opacity":.8}))}o.push(z("g",{class:"tb-orbit-spin tb-orbit-fast"},p))}let i=1/(e.r*e.scale),l=r||e.r>=44&&12*i<=.26,c=r?Math.max(.2,14*i):l?Math.max(.24,12*i):12.5*i,u=wh(e.title,r?Math.max(8,Math.floor(3.2/c)):l?13:18),d=l?-((u.length-1)*c*1.15)/2:e.above?-1.34-c*.6-(u.length-1)*c*1.15:1.34+c*.6;if(o.push(z("text",{class:"tb-orbit-title","font-size":c,"font-weight":r?600:500},u.map((f,p)=>z("tspan",{x:0,y:d+p*c*1.15},[],f)))),a>0&&l){let f=r?d-c*1.2:d+(u.length-1)*c*1.15+.3;o.push(z("text",{class:"tb-orbit-count","font-size":Math.max(r?.12:.16,10*i),y:f},[],String(a)))}return r&&(o.push(z("g",{class:"tb-orbit-spin"},[z("circle",{class:"tb-orbit-line",r:1.24,stroke:n,"stroke-opacity":.35,"stroke-dasharray":"2 10"})])),o.push(z("g",{class:"tb-orbit-spin tb-orbit-rev"},[z("circle",{class:"tb-orbit-line",r:1.42,stroke:n,"stroke-opacity":.18,"stroke-dasharray":"40 14 4 14"})]))),o}function Zu(e,t,n){let r=(o,a)=>z("stop",{offset:o,"stop-color":e,"stop-opacity":a});return[z("radialGradient",{id:t,cx:"50%",cy:"40%",r:"60%"},[r("0%",.05),r("75%",.16),r("100%",.38)]),z("radialGradient",{id:n},[r("55%",0),r("72%",.22),r("100%",0)])]}function Ju(e,t,n){let r=t.x-e.x,o=t.y-e.y,a=Math.hypot(r,o)||1,i=r/a,l=o/a,c=e.x+i*e.r*1.04,u=e.y+l*e.r*1.04,d=t.x-i*t.r*1.04,f=t.y-l*t.r*1.04,p=(c+d)/2,h=(u+f)/2,v=`M${Mt(c)},${Mt(u)} L${Mt(d)},${Mt(f)}`;if(n!==0){let C=Math.hypot(d-c,f-u)||1,x=-(f-u)/C,w=(d-c)/C;x*p+w*h<0&&(x=-x,w=-w);let E=p+x*C*n,S=h+w*C*n;v=`M${Mt(c)},${Mt(u)} Q${Mt(E)},${Mt(S)} ${Mt(d)},${Mt(f)}`,p=(c+2*E+d)/4,h=(u+2*S+f)/4}let y=Math.atan2(f-u,d-c)*180/Math.PI;return y>90&&(y-=180),y<-90&&(y+=180),{d:v,x:p,y:h,angle:y}}var Xu=e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;function ya(e,t,n){let r=Math.max(.15,Math.min(1.25,e/(n.x1-n.x0),t/(n.y1-n.y0)));return{x:-((n.x0+n.x1)/2)*r,y:-((n.y0+n.y1)/2)*r,s:r}}var xa="trebol-dev",nd="trebol-dev-history",xh=100,rd=500,Ch=2e3,yt,ve={open:!1,tab:"faces",height:320},vt,Jt,gt,ao,Sn,Cn,ut,je,Ni,dt,so=new Map,on=null,ji=null,kr=!1,Lt=[],xn=0,_n=null,$i=0,Qu=Promise.resolve();function se(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n!==void 0&&(r.textContent=n),r}function wr(e,t,n){let r=se("button",e,t);return r.type="button",r.addEventListener("click",n),r}function ed(e,t,n){try{let r=e().getItem(t);return r===null?n:{...n,...JSON.parse(r)}}catch{return n}}function Ca(e,t,n){try{e().setItem(t,JSON.stringify(n))}catch{}}function rn(e,t){let n=te(e.ctx,A(t));return n<0?k:e.ctx.vals[n]}function Pi(e){return e.t===s.Word||e.t===s.LitWord?M(e.sym):null}function od(e,t=80){let n=e.replace(/\s+/g," ");return n.length>t?n.slice(0,t-1)+"\u2026":n}function xr(e,t){let n=Pi(rn(e,"style"))??"face",r=Pi(rn(e,"name")),o=rn(e,"text"),a=o.t===s.None?null:o.t===s.String||o.t===s.Map||o.t===s.Word?Ce(o,t):D(o);return[n,r,a!==null&&a!==""?`"${od(a,40)}"`:null].filter(i=>i!==null).join(" ")}function Sh(e,t){let n=rn(e,t);return!(n.t===s.None||n.t===s.Logic&&!n.v)}function ad(e,t=Ch){let n=Z(e);return n.length>t?n.slice(0,t-1)+"\u2026":n}function Eh(e){let t=rn(e,"place");if(t.t!==s.String)return null;let n=D(t),r=/^(.*):(\d+):(\d+)$/.exec(n);if(r===null)return{text:n,href:null};let o;try{o=new URL(r[1])}catch{return{text:n,href:null}}let a=decodeURIComponent(o.pathname),i=`${a.slice(1)}:${r[2]}:${r[3]}`,l=o.origin===location.origin&&!a.startsWith("/@trebol/")&&yt.root!==null;return{text:i,href:l?`vscode://file${yt.root.replace(/\/$/,"")}${a}:${r[2]}:${r[3]}`:null}}function sd(e){if(window!==window.top)return;yt=e,ve=ed(()=>sessionStorage,xa,ve),Lt=ed(()=>localStorage,nd,{lines:[]}).lines,vt=se("section","tb-dev-tools"),vt.popover="manual",vt.setAttribute("aria-label","Trebol dev tools");let t=se("div","tb-dev-grip");t.addEventListener("pointerdown",Mh);let n=se("header"),r=se("div","tb-dev-tabs");r.setAttribute("role","tablist"),n.append(r);let o=se("div","tb-dev-body");for(let[i,l]of[["faces","Faces"],["console","Console"],["log","Log"]]){let c=wr("tb-dev-tab",l,()=>Di(i));c.setAttribute("role","tab"),c.id=`tb-dev-tab-${i}`;let u=se("div",`tb-dev-pane tb-dev-${i}`);u.setAttribute("role","tabpanel"),u.setAttribute("aria-labelledby",c.id),r.append(c),o.append(u),so.set(i,{button:c,pane:u})}ao=wr("tb-dev-button","Pick",()=>ka(!kr)),ao.title="Click a face on the page to see it here",ao.setAttribute("aria-pressed","false");let a=wr("tb-dev-button","Close",()=>wa(!1));a.title="Close (Ctrl+`)",n.append(se("span","tb-dev-space"),ao,a),vt.append(t,n,o),vt.addEventListener("keydown",i=>{i.stopPropagation(),i.key==="Escape"&&i.preventDefault()}),Ih(so.get("faces").pane),Wh(so.get("console").pane),Uh(so.get("log").pane),Jt=wr("tb-dev-opener","Trebol",()=>wa(!0)),Jt.popover="manual",Jt.title="Dev tools (Ctrl+`)",gt=se("div","tb-dev-outline"),gt.popover="manual",gt.setAttribute("aria-hidden","true"),document.body.append(vt,Jt,gt),addEventListener("keydown",i=>{i.ctrlKey&&!i.altKey&&!i.metaKey&&i.code==="Backquote"?(i.preventDefault(),i.stopImmediatePropagation(),wa(!ve.open)):kr&&i.key==="Escape"&&(i.preventDefault(),i.stopImmediatePropagation(),ka(!1))},!0),addEventListener("pointermove",Nh,!0),addEventListener("pointerdown",jh,!0),addEventListener("click",Ph,!0),addEventListener("scroll",()=>io(),{capture:!0,passive:!0}),addEventListener("resize",()=>{Wi(ve.height),io()}),Th(),Di(ve.tab),wa(ve.open)}function qn(e){return e instanceof Element&&e.closest(".tb-dev-tools")!==null}function id(){let e=document.querySelectorAll("dialog:modal"),t=e.length>0?e[e.length-1]:document.body;if(vt.parentElement!==t)for(let n of[vt,Jt,gt]){let r=n.matches(":popover-open");t.append(n),r&&n.showPopover()}}function wa(e){if(ve.open=e,Ca(()=>sessionStorage,xa,ve),id(),e)Jt.hidePopover(),vt.showPopover(),Wi(ve.height),Sa(),ve.tab==="console"&&je.focus();else{ka(!1),Cr(null);let t=vt.contains(document.activeElement);vt.hidePopover(),Jt.showPopover(),t&&Jt.focus(),document.body.style.paddingBottom=""}}function Wi(e){ve.height=Math.round(Math.max(140,Math.min(e,innerHeight-60))),vt.style.height=`${ve.height}px`,ve.open&&(document.body.style.paddingBottom=`${ve.height}px`)}function Mh(e){e.preventDefault();let t=e.currentTarget;t.setPointerCapture(e.pointerId);let n=o=>Wi(innerHeight-o.clientY),r=()=>{t.removeEventListener("pointermove",n),t.removeEventListener("pointerup",r),Ca(()=>sessionStorage,xa,ve)};t.addEventListener("pointermove",n),t.addEventListener("pointerup",r)}function Di(e){ve.tab=e,Ca(()=>sessionStorage,xa,ve);for(let[t,{button:n,pane:r}]of so)n.setAttribute("aria-selected",String(t===e)),n.tabIndex=t===e?0:-1,r.hidden=t!==e;Sa(),io(),e==="console"&&ve.open&&je.focus(),e==="log"&&(dt.scrollTop=dt.scrollHeight)}function Th(){mt.event=(t,n,r)=>{if(t==="ui-blur")return;let o=t.replace(/^ui-/,""),a=r;t==="ui-event"&&r[0]!==void 0&&(o=Pi(r[0])??o,a=[]);let i=a.length>0&&a[0].t!==s.Object?" "+od(Z(a[0]),60):"";Oi("event",`${o} \xB7 ${xr(n,yt.host.rt)}${i}`,`${t} ${Ah(n)}`)},mt.request=(t,n,r,o,a)=>{let i=n;try{let c=new URL(n,location.href);c.origin===location.origin&&(i=c.pathname+c.search)}catch{}let l=r!==null?String(r):`failed (${a??"network"})`;Oi(r!==null&&r<400?"request":"failed",`${t} ${i} ${l} \xB7 ${o} ms`)},mt.note=(t,n)=>Oi(t,n),mt.repainted=()=>{id(),ve.open&&(io(),ve.tab==="faces"&&$i===0&&($i=requestAnimationFrame(()=>{$i=0,Sa()})))};let e=hr.line;hr.line=t=>{e(t),yr("out",t)}}function Sa(){ve.open&&(ve.tab==="faces"&&(Bh(),Oh()),Ni.textContent=on!==null?`face: ${xr(on,yt.host.rt)}`:"face: none (pick one in Faces)")}var td=new WeakMap,Lh=1;function Ah(e){let t=td.get(e.ctx);return t===void 0&&td.set(e.ctx,t=Lh++),t}function Ih(e){Sn=se("div","tb-dev-tree"),Sn.setAttribute("aria-label","Faces on the page"),Sn.addEventListener("pointerleave",()=>Cr(null)),Cn=se("div","tb-dev-detail"),e.append(Sn,Cn)}function $h(){let e=[],t=(n,r)=>{for(let o of Array.from(n.children)){if(o===vt||o===Jt||o===gt)continue;let a=yt.faceOf(o);a!==null&&e.push({face:a,el:o,depth:r}),t(o,a!==null?r+1:r)}};return t(document.body,0),e}function Bh(){let e=Sn.scrollTop;Sn.replaceChildren();for(let{face:t,el:n,depth:r}of $h()){let o=wr("tb-dev-node",xr(t,yt.host.rt),()=>ld(t));o.style.paddingLeft=`${8+r*14}px`,t.ctx===on?.ctx&&o.setAttribute("aria-current","true"),n.offsetParent===null&&getComputedStyle(n).position!=="fixed"&&o.classList.add("tb-dev-unseen"),o.addEventListener("pointerenter",()=>Cr(t)),Sn.append(o)}Sn.scrollTop=e}function Oh(){if(Cn.replaceChildren(),on===null){Cn.append(se("p","tb-dev-hint","Pick a face on the page, or choose one in the tree."));return}let e=on,t=se("h3",void 0,xr(e,yt.host.rt));Cn.append(t);let n=Eh(e);if(n!==null){let u=se("p","tb-dev-place");if(n.href!==null){let d=se("a",void 0,n.text);d.href=n.href,d.title="Open in VS Code",u.append(d)}else u.textContent=n.text;Cn.append(u)}yt.nodeOf(e)===null&&Cn.append(se("p","tb-dev-hint","Not on the page any more."));let r=se("dl"),o=(u,d)=>{r.append(se("dt",void 0,u),se("dd",void 0,d))};for(let u of["style","name","text","value","error","rules","hint","role"]){let d=rn(e,u);d.t!==s.None&&o(u,ad(d,400))}let a=[];rn(e,"action").t===s.Block&&a.push("action");let i=rn(e,"events");if(i.t===s.Block)for(let u of i.s.data.slice(i.i))u.t!==s.Block&&a.push(D(u));a.length>0&&o("events",a.join(" "));let l=["required","disabled","hidden","readonly"].filter(u=>Sh(e,u));l.length>0&&o("flags",l.join(" "));let c=rn(e,"data");c.t===s.Block&&o("rows",String(c.s.data.length-c.i)),Cn.append(r)}function ld(e){on=e,Cr(null),Sa()}function Cr(e){ji=e,io()}function io(){let e=ji??(ve.open&&ve.tab==="faces"?on:null),n=(e!==null?yt.nodeOf(e):null)?.getBoundingClientRect();if(n===void 0||n.width===0&&n.height===0){gt.matches(":popover-open")&&gt.hidePopover();return}Object.assign(gt.style,{left:`${n.left}px`,top:`${n.top}px`,width:`${n.width}px`,height:`${n.height}px`}),gt.classList.toggle("tb-dev-pointed",ji!==null),gt.matches(":popover-open")&&gt.hidePopover(),gt.showPopover()}function ka(e){kr=e,ao.setAttribute("aria-pressed",String(e)),document.documentElement.classList.toggle("tb-dev-picking",e),e?Di("faces"):Cr(null)}function Ri(e){let t=e.target;return!(t instanceof Element)||qn(t)||t===Jt?null:yt.faceAt(t)}function Nh(e){if(!kr)return;let t=Ri(e);t!==null&&Cr(t.face)}function jh(e){!kr||Ri(e)===null||(e.preventDefault(),e.stopImmediatePropagation())}function Ph(e){if(!kr)return;let t=Ri(e);t!==null&&(e.preventDefault(),e.stopImmediatePropagation(),ka(!1),ld(t.face))}var Dh=/: missing ([\])]|} to close (string|binary))$/;function Wh(e){ut=se("div","tb-dev-out"),ut.setAttribute("role","log"),ut.setAttribute("aria-label","Console output"),Ni=se("div","tb-dev-face");let t=se("div","tb-dev-prompt");je=se("textarea","tb-dev-in"),je.rows=1,je.spellcheck=!1,je.setAttribute("aria-label","Trebol code to run"),je.placeholder='face/text: "Hello"',je.addEventListener("keydown",Rh),je.addEventListener("input",cd),t.append(se("span","tb-dev-sign",">>"),je),t.addEventListener("click",()=>je.focus()),e.append(ut,Ni,t)}function cd(){je.style.height="auto",je.style.height=`${Math.min(je.scrollHeight,160)}px`}function Bi(e){je.value=e,cd(),je.setSelectionRange(e.length,e.length)}function Rh(e){let t=je.value;if(e.key==="Enter"&&!e.shiftKey){if(t.trim()===""||Fh(t))return;e.preventDefault(),Bi(""),Qu=Qu.then(()=>Hh(t))}else e.key==="ArrowUp"&&!t.slice(0,je.selectionStart).includes(`
4285
+ `)&&xn<Lt.length?(e.preventDefault(),xn++,Bi(Lt[Lt.length-xn])):e.key==="ArrowDown"&&!t.slice(je.selectionEnd).includes(`
4286
+ `)&&xn>0&&(e.preventDefault(),xn--,Bi(xn===0?"":Lt[Lt.length-xn]))}function Fh(e){try{return me(e),!1}catch(t){return t instanceof rt&&Dh.test(t.message)}}function yr(e,t){let n=se("pre",`tb-dev-said-${e}`,t),r=ut.scrollTop+ut.clientHeight>=ut.scrollHeight-4;for(ut.append(n);ut.childElementCount>rd;)ut.firstElementChild.remove();r&&(ut.scrollTop=ut.scrollHeight)}async function Hh(e){xn=0,Lt[Lt.length-1]!==e&&Lt.push(e),Lt=Lt.slice(-xh),Ca(()=>localStorage,nd,{lines:Lt}),yr("in",e.split(`
4287
+ `).map((r,o)=>(o===0?">> ":" ")+r).join(`
4288
+ `)),ut.scrollTop=ut.scrollHeight;let t;try{t=me(e)}catch(r){yr("error",`** Syntax error: ${r.message}`);return}let n=yt.host.rt;be(t.s,n.user,!0),on!==null&&be(t.s,{keys:[A("face")],vals:[on],parent:null});try{let r=await kn(Ft(yt.host.sch,t.s,Ot(t).start));r.t===s.Error?yr("error",D(r)):r.t!==s.Unset&&yr("value",`== ${ad(r)}`)}catch(r){yr("error",Hn(r))}}function Uh(e){let t=se("div","tb-dev-bar");t.append(wr("tb-dev-button","Clear",()=>{dt.replaceChildren(),_n=null})),dt=se("ol","tb-dev-entries"),dt.setAttribute("aria-label","What the app did"),e.append(t,dt)}function Oi(e,t,n){if(n!==void 0&&_n?.key===n&&_n.li.isConnected){_n.count++,_n.text.textContent=`${t} (\xD7${_n.count})`;return}let r=se("li",`tb-dev-${e}`),o=new Date,a=`${String(o.getHours()).padStart(2,"0")}:${String(o.getMinutes()).padStart(2,"0")}:${String(o.getSeconds()).padStart(2,"0")}`,i=se("span","tb-dev-text",t);r.append(se("time",void 0,a),se("span","tb-dev-kind",e),i);let l=dt.scrollTop+dt.clientHeight>=dt.scrollHeight-4;for(dt.append(r);dt.childElementCount>rd;)dt.firstElementChild.remove();l&&(dt.scrollTop=dt.scrollHeight),_n=n!==void 0?{key:n,li:r,text:i,count:1}:null}function $(e,t){let n=te(e.ctx,A(t));return n<0?k:e.ctx.vals[n]}function R(e,t){let n=$(e,t);return n.t===s.None?null:n.t===s.Map||(t==="text"||t==="hint")&&n.t===s.Word?Ce(n,K.rt):D(n)}function Ar(e){let t=e.t===s.Map?Zt(e,"value"):null;return D(t??e)}function yo(e){let t=e.t===s.Map?Zt(e,"text"):null;return t!==null?Ce(t,K.rt):Ar(e)}function Br(e){let t=$(e,"options");if(t.t!==s.Block)return[];let n=t.s.data.slice(t.i),r=[];for(let o=0;o<n.length;o++){let a=n[o+1];a!==void 0&&a.t===s.Block&&n[o].t!==s.Block?(r.push({title:n[o],options:a.s.data.slice(a.i)}),o++):n[o].t!==s.Block&&r.push(n[o])}return r}function Or(e){return"options"in e}function Md(e){return Br(e).flatMap(t=>Or(t)?t.options:[t])}function Td(e){return Br(e).map(t=>Or(t)?`${t.options.map(Ar).join("\0")}`:Ar(t)).join("\0")}function Ld(e,t){let n=m("option");n.value="",e.replaceChildren(n);let r=o=>{let a=m("option");return a.value=Ar(o),a.textContent=yo(o),a};for(let o of Br(t))if(Or(o)){let a=m("optgroup");a.label=Ce(o.title,K.rt),a.append(...o.options.map(r)),e.append(a)}else e.append(r(o));e.dataset.options=Td(t)}function de(e,...t){return hi(K.rt,e,...t)}function ho(e,t,n){e.dataset.tbOwn=n===void 0?t:`${n} ${t}`,Ad(e)}function Ad(e){let[t,n]=e.dataset.tbOwn.split(" ");n===void 0?e.textContent=de(t):e.setAttribute(t,de(n))}function Tr(e){return di.has(e.t)?ua(e,lt(K.rt)):D(e)}function O(e,t){let n=$(e,t);return!(n.t===s.None||n.t===s.Logic&&!n.v)}function Pe(e,t){let n=$(e,t);return n.t===s.Word||n.t===s.LitWord?M(n.sym).toLowerCase():null}function Ln(e){let t=$(e,"pane");return t.t!==s.Block?[]:t.s.data.slice(t.i).filter(n=>n.t===s.Object)}function wo(e){let t=$(e,"icon");return t.t===s.Issue?M(t.sym).toLowerCase():null}function et(e,t=null){let n=xi(e,t);return n===null&&console.warn(`Trebol: unknown icon #${e}`),n}function co(e,t){let n=$(e,"rules");return n.t!==s.Block?!1:n.s.data.some(r=>r.t===s.Block&&r.s.data[0]?.t===s.Word&&M(r.s.data[0].sym)===t)}var K,Mn=new WeakMap,ln=new WeakMap,cn=new WeakMap,Ba=[],uo=new Set,Ta=!1,Fi=null,tt=1,zh=new Set([s.Word,s.SetWord,s.GetWord,s.Paren,s.Path,s.SetPath,s.GetPath,s.Function,s.Native]),_h={"ui-click":"action","ui-input":"on-change","ui-files":"on-change","ui-remove-file":"on-change","ui-lookup-pick":"on-change","ui-lookup-remove":"on-change","ui-lookup-search":"on-search","ui-select":"on-select","ui-sort":"on-sort","ui-drop":"on-drop","ui-menu":"on-menu","ui-reorder":"on-reorder","ui-expand":"on-expand","ui-close":"on-close"};function qh(e,t,n,r){let o=te(e.ctx,A("where")),a=o<0?null:e.ctx.vals[o];if(a===null||a.t!==s.Word||M(a.sym)!==t)return;let i=t==="ui-event"&&r[0]!==void 0&&r[0].t===s.LitWord?M(r[0].sym):null;e.ctx.vals[o]=j(`${i??_h[t]??t.replace(/^ui-/,"")} of ${xr(n,K.rt)}`)}function F(e,t,...n){let r={t:s.Word,sym:A("quote"),bind:K.rt.lib},o=[{t:s.Word,sym:A(e),bind:K.rt.user},t,...n.flatMap(a=>zh.has(a.t)?[r,a]:[a])];return mt.event(e,t,n),kn(Ft(K.sch,{data:o},0)).catch(a=>(a.t===s.Error&&qh(a,e,t,n),qi(Hn(a)),k))}var Ea=null;function qi(e){if(console.error(e),mt.note("error",e),document.querySelector('meta[name="trebol-dev"]')===null)return;if(Ea===null||!Ea.isConnected){let n=m("section","tb-dev-errors");n.popover="manual",n.setAttribute("role","alert"),n.setAttribute("aria-label","Trebol error");let r=m("header"),o=m("span");o.textContent="Trebol error";let a=m("button","tb-button");a.type="button",a.textContent="Close",a.addEventListener("click",()=>n.remove()),n.addEventListener("keydown",i=>{i.key==="Escape"&&n.remove()}),r.append(o,a),n.append(r),document.body.append(n),n.showPopover(),Ea=n}let t=m("pre");t.textContent=e,Ea.append(t)}function m(e,t){let n=document.createElement(e);return t&&(n.className=t),n}var Id=new Set(["field","password","number","money","date","area","choice"]);function Gn(e){let t=Pe(e,"style")??"face",n={face:e,el:null,input:null,label:null,error:null,kids:$(e,"pane"),box:null,rows:null,empty:null,button:null,radios:null,open:null,shown:void 0,typing:0,typed:null,items:[],first:0,end:0,rowHeight:0},r;if(Id.has(t))r=pm(e,t,n);else if(t==="check"||t==="toggle")r=bm(e,n,t==="toggle");else if(t==="radio")r=hm(e,n);else if(t==="upload")r=mm(e,n);else if(t==="photo")r=ym(e,n);else if(t==="widget")r=Cm(e,n);else if(t==="lookup")r=Lm(e,n);else if(t==="rich")r=ag(e,n);else{switch(t){case"view":r=m("main","tb-view");break;case"column":r=m("div","tb-column");break;case"row":r=m("div","tb-row");break;case"toolbar":r=vg();break;case"breadcrumb":r=kg(n);break;case"rows":r=Qm(n);break;case"entry":{r=m("div","tb-entry"),r.setAttribute("role","group");break}case"grid":r=m("div","tb-grid");break;case"desktop":r=m("div","tb-desktop");break;case"scroll":{r=m("div","tb-scroll"),r.tabIndex=0,r.setAttribute("role","region");break}case"panel":r=m("section","tb-panel");break;case"form":{let o=m("form","tb-form");o.noValidate=!0,o.addEventListener("submit",a=>a.preventDefault()),r=o;break}case"title":r=m("h1","tb-title");break;case"heading":r=m("h2","tb-heading");break;case"text":r=m("p","tb-text");break;case"divider":r=m("hr","tb-divider");break;case"link":{let o=m("a","tb-link");o.href=bo($(e,"value"))??R(e,"value")??"#",Hi(o,e,n),o.addEventListener("click",a=>{$(e,"action").t===s.Block&&(a.preventDefault(),F("ui-click",e))}),r=o;break}case"button":{let o=m("button","tb-button"),a=O(e,"submit");o.type=a?"submit":"button",o.addEventListener("click",i=>{if(!a)return void F("ui-click",e);i.preventDefault(),fm(e,o.closest("form, .tb-view")??document.body)}),Hi(o,e,n),r=o;break}case"tile":{let o=m("button",O(e,"linked")?"tb-tile tb-tile-linked":"tb-tile");o.type="button",o.addEventListener("click",()=>{F("ui-click",e)}),Hi(o,e,n),r=o;break}case"progress":r=Om(n);break;case"image":r=m("img","tb-image");break;case"video":case"audio":{let o=m(t,`tb-${t}`);o.controls=!0,o.preload="metadata",o instanceof HTMLVideoElement&&(o.playsInline=!0),r=o;break}case"backdrop":{r=m("div","tb-backdrop"),r.setAttribute("aria-hidden","true");break}case"canvas":r=jm(n);break;case"chart":r=Wm(n);break;case"orbit":r=Um(n);break;case"icon":r=m("span","tb-icon-face");break;case"table":case"list":r=cg(e,t,n);break;case"tree":r=pg(e,n);break;case"dialog":r=Cg(e,n);break;case"tabs":r=Sg(e,n);break;case"split":r=Mg(e,n);break;case"screens":{r=m("div","tb-screens"),vo=e;break}case"screen":{r=m("section","tb-screen");let o=R(e,"text");o!==null&&(r.setAttribute("aria-label",o),document.title=o,Wa=e);break}case"tab":{r=m("div","tb-tab-panel"),r.setAttribute("role","tabpanel");break}default:r=m("div")}t==="screens"?hf(n,r):Ln(e).length>0&&t!=="tabs"&&t!=="split"&&ul(n.box??r,e,t)}return n.el=r,Mn.set(r,n),n.input!==null&&Mn.set(n.input,n),cn.set(e.ctx,n),e.ctx.watch=Ba,$(e,"reactions").t===s.Block&&(uo.add(n),Ta=!0),Kh(n,t),Ua(n),r}function an(e,t,n=[]){let r=n.flatMap(([o,a])=>[st(s.SetWord,o),a]);F("ui-event",e,st(s.LitWord,t),Ye(s.Block,r))}var Tn=new WeakSet,Oa=null,Ki=new Set;function Kh(e,t){let n=e.face,r=e.el,o=i=>!r.contains(i.relatedTarget);sn(n,"on-focus")&&r.addEventListener("focusin",i=>{o(i)&&an(n,"on-focus")}),sn(n,"on-unfocus")&&r.addEventListener("focusout",i=>{o(i)&&an(n,"on-unfocus")}),sn(n,"on-over")&&(r.addEventListener("pointerenter",()=>an(n,"on-over",[["away?",we]])),r.addEventListener("pointerleave",()=>an(n,"on-over",[["away?",P]]))),sn(n,"on-dbl-click")&&r.addEventListener("dblclick",()=>an(n,"on-dbl-click")),sn(n,"on-end")&&r.addEventListener("ended",()=>an(n,"on-end")),sn(n,"on-key")&&(t==="view"?Oa=n:r.addEventListener("keydown",i=>{Tn.has(i)||cl(i)===null||(Tn.add(i),an(n,"on-key",_d(i)))})),R(n,"shortcut")!==null&&Ki.add(e),O(n,"drop")&&Gi.add(e);let a=$(n,"menu");if(a.t===s.Block&&(t==="button"||t==="link")&&$(n,"action").t!==s.Block){r.setAttribute("aria-haspopup","menu"),r.setAttribute("aria-expanded","false"),e.label===null&&(e.label=m("span"),r.prepend(e.label));let i=et("chevron-down");i!==null&&(i.classList.add("tb-menu-chevron"),r.append(i)),r.addEventListener("click",l=>{l.preventDefault();let c=r.getBoundingClientRect();ja(Vi(n,a,k),c.left,c.bottom+4,r)})}else(a.t===s.Block||O(n,"drag"))&&r.addEventListener("contextmenu",i=>{let l=i.target,c=t==="table"||t==="list"||t==="tree",u=c?l.closest(t==="tree"?'[role="treeitem"]':"tr, li"):null;if(u===null&&c&&a.t!==s.Block)return;let d=u!==null?ln.get(u)??k:k,f=a.t===s.Block?Vi(n,a,d):[];if(O(n,"drag")){let v=Yh(n,u!==null?d:$(n,"value"));v.length>0&&(f.length>0&&f.push({text:"",divider:!0}),f.push({text:de("move-to"),sub:v}))}if(f.length===0)return;i.preventDefault(),i.stopPropagation();let{clientX:p,clientY:h}=i;if(p===0&&h===0){let v=(u??(document.activeElement&&r.contains(document.activeElement)?document.activeElement:r)).getBoundingClientRect();p=v.left+8,h=v.top+Math.min(v.height,40)}ja(f,p,h,u??l)})}var Gi=new Set,mo=e=>e.rows!==null;function ko(e){return mo(e)?Array.from(e.box.children):Ln(e.face).map(t=>cn.get(t.ctx)?.el).filter(t=>t!==void 0&&t.isConnected)}function go(e){for(let t=e;t!==null;t=t.parentElement){let n=Mn.get(t);if(n!==void 0&&n.el===t)return n}}function $d(e){if(e.closest("input, textarea, select, [contenteditable], .tb-split-handle, .tb-menu")!==null)return null;for(let t=e;t!==null;t=t.parentElement){let n=ln.get(t);if(n!==void 0){let i=go(t),l=O(i.face,"reorder")&&cf(i.face)===null;if(!O(i.face,"drag")&&!l)return null;let c=t.parentElement;if(i.open===null){let d=i.first+Array.prototype.indexOf.call(c.children,t);return{face:i.face,el:t,payload:n,within:l?i:null,index:d,group:null}}let u=Array.prototype.indexOf.call(c.children,t);return{face:i.face,el:t,payload:n,within:l?i:null,index:u,group:c}}let r=Mn.get(t);if(r===void 0||r.el!==t)continue;let o=go(t.parentElement),a=o!==void 0&&!mo(o)&&O(o.face,"reorder");if(O(r.face,"drag")&&!mo(r)||a){let i=a?ko(o).indexOf(t):-1;return{face:r.face,el:t,payload:$(r.face,"value"),within:a?o:null,index:i,group:null}}}return null}function Gh(e,t,n){for(let r=go(document.elementFromPoint(t,n));r!==void 0;r=go(r.el.parentElement)){if(r.open!==null){let a=mg(r,e,t,n);if(a!==null)return a;continue}let o=r===e.within;if((o||O(r.face,"drop"))&&r.el!==e.el&&!e.el.contains(r.el))return{m:r,index:Od(r,t,n),reorder:o}}return null}var Bd=e=>Pe(e.face,"style")==="row";function Od(e,t,n){let r=Bd(e),o=0;for(let a of ko(e)){let i=a.getBoundingClientRect();(r?t:n)>(r?i.left+i.width/2:i.top+i.height/2)&&o++}return e.first+o}function Nd(e){return mo(e)&&e.open===null?e.items.length:ko(e).length}var Ht=null;function jd(e){if(document.querySelectorAll(".tb-drop-over").forEach(l=>l.classList.remove("tb-drop-over")),e===null){Ht?.remove(),Ht=null;return}if(e.into!==void 0){e.into.querySelector(":scope > .tb-tree-row").classList.add("tb-drop-over"),Ht?.remove(),Ht=null;return}e.m.el.classList.add("tb-drop-over"),Ht===null&&(Ht=m("div","tb-drop-line"),Ht.setAttribute("aria-hidden","true"),document.body.append(Ht));let t=Bd(e.m),n=e.group!==void 0?Array.from(e.group.children):ko(e.m),r=(e.group??e.m.box??e.m.el).getBoundingClientRect(),o=e.group!==void 0?e.index:e.index-e.m.first,a=n[o]?.getBoundingClientRect(),i=n[o-1]?.getBoundingClientRect();if(Ht.classList.toggle("tb-across",t),t){let l=a&&i?(i.right+a.left)/2:a?a.left-3:i?i.right+3:r.left+8,c=a??i??r;Object.assign(Ht.style,{left:`${l-1}px`,top:`${c.top}px`,width:"",height:`${c.height}px`})}else{let l=a&&i?(i.bottom+a.top)/2:a?a.top-3:i?i.bottom+3:r.top+8,c=a??i??r;Object.assign(Ht.style,{left:`${c.left}px`,top:`${l-1}px`,width:`${c.width}px`,height:""})}}function Vh(e,t){if(t.reorder){let n=t.index>e.index?t.index-1:t.index;n!==e.index&&Pd(t.m,e.index,n,t.group,t.parent)}else F("ui-drop",t.m.face,e.payload,e.face,Ut(t.index+1),t.parent??k)}var Ut=e=>({t:s.Integer,v:e});async function Pd(e,t,n,r,o=k){let a=document.activeElement!==null&&document.activeElement!==document.body&&e.el.contains(document.activeElement);if(await F("ui-reorder",e.face,Ut(t+1),Ut(n+1),o),gf(),!a)return;let i=r!==void 0?r.children[n]:ko(e)[n-e.first];((i?.matches("[tabindex], button, a, input, textarea, select")?i:i?.querySelector("[tabindex], button, a, input, textarea, select"))??null)?.focus()}function Yh(e,t){let n=[];for(let r of Gi){if(!r.el.isConnected){Gi.delete(r);continue}r.face.ctx===e.ctx||r.el.getClientRects().length===0||R(r.face,"text")===null&&r.el.querySelector(".tb-drop-zone")!==null||n.push({text:R(r.face,"text")??Pe(r.face,"style")??"",run:()=>{F("ui-drop",r.face,t,e,Ut(Nd(r)+1),k)}})}return n}var En=null;function Dd(e){e.on=!0,e.ghost=m("div","tb-drag-ghost"),e.ghost.textContent=(e.src.el.innerText||e.src.el.textContent||"").split(`
4289
+ `).find(t=>t.trim()!=="")?.trim()??"",e.ghost.setAttribute("aria-hidden","true"),document.body.append(e.ghost),e.src.el.classList.add("tb-dragging"),getSelection()?.removeAllRanges(),document.documentElement.classList.add("tb-drag-active"),Wd(e,e.x,e.y)}function Wd(e,t,n){e.ghost.style.transform=`translate(${t+12}px, ${n+12}px)`,e.target=Gh(e.src,t,n),jd(e.target)}function La(e){let t=En;t!==null&&(En=null,clearTimeout(t.timer),t.on&&(t.ghost?.remove(),t.src.el.classList.remove("tb-dragging"),document.documentElement.classList.remove("tb-drag-active"),jd(null),e&&t.target!==null&&Vh(t.src,t.target),addEventListener("click",ud,!0),setTimeout(()=>removeEventListener("click",ud,!0),0)))}function ud(e){e.stopPropagation(),e.preventDefault()}function Zh(e){if(e.button!==0||En!==null)return;let t=$d(e.target);if(t===null)return;let n={src:t,x:e.clientX,y:e.clientY,id:e.pointerId,on:!1,ghost:null,target:null,timer:0};En=n,e.pointerType==="touch"&&(n.timer=setTimeout(()=>{En===n&&Dd(n)},400))}function Jh(e){let t=En;if(!(t===null||e.pointerId!==t.id)){if(!t.on){if(!(Math.hypot(e.clientX-t.x,e.clientY-t.y)>5))return;if(e.pointerType==="touch")return La(!1);t.x=e.clientX,t.y=e.clientY,Dd(t)}e.preventDefault(),Wd(t,e.clientX,e.clientY)}}function Xh(e){if(qn(e.target)||!e.altKey||e.ctrlKey||e.metaKey||e.key!=="ArrowUp"&&e.key!=="ArrowDown")return;let t=document.activeElement;if(t===null)return;let n=$d(t);if(n===null||n.within===null)return;let r=n.index+(e.key==="ArrowUp"?-1:1);if(r<0||r>=(n.group!==null?n.group.children.length:Nd(n.within)))return;e.preventDefault(),Tn.add(e);let o=n.group??void 0;Pd(n.within,n.index,r,o,o!==void 0&&n.within.open!==null?df(n.within,o):k)}var Na=[],Er=null;function Mr(e=0,t=!0){for(let n of Na.splice(e))n.hidePopover?.(),n.remove();e===0?(Er?.setAttribute("aria-expanded","false"),Er?.hasAttribute("aria-haspopup")||Er?.removeAttribute("aria-expanded"),t&&Er?.focus(),Er=null,document.removeEventListener("pointerdown",Rd,!0)):Na[e-1]?.querySelector('[aria-expanded="true"]')?.setAttribute("aria-expanded","false")}function Rd(e){Na.some(t=>t.contains(e.target))||Mr(0,!1)}function dd(e){return Array.from(e.querySelectorAll(':scope > [role="menuitem"]'))}function Vi(e,t,n){return t.s.data.slice(t.i).filter(r=>r.t===s.Object).map(r=>{let o=$(r,"items");return{text:R(r,"text")??"",icon:wo(r),divider:O(r,"divider"),sub:o.t===s.Block?Vi(e,o,n):void 0,run:()=>{F("ui-menu",e,r,n)}}})}function ja(e,t,n,r,o=0){Mr(o,!1),o===0&&(Er=r,r.hasAttribute("aria-haspopup")&&r.setAttribute("aria-expanded","true"),document.addEventListener("pointerdown",Rd,!0));let a=m("div","tb-menu");a.setAttribute("role","menu"),a.setAttribute("popover","manual");let i=r.getAttribute("aria-label")??r.textContent;i&&a.setAttribute("aria-label",i.trim());for(let c of e){if(c.divider){let h=m("div","tb-menu-divider");h.setAttribute("role","separator"),a.append(h);continue}let u=m("button","tb-menu-item");u.type="button",u.tabIndex=-1,u.setAttribute("role","menuitem");let d=c.icon?et(c.icon):null,f=m("span");f.textContent=c.text,u.append(d??m("span","tb-menu-gap"),f);let p=c.sub;if(p!==void 0){u.setAttribute("aria-haspopup","menu"),u.setAttribute("aria-expanded","false");let h=et("chevron-right");h!==null&&u.append(h);let v=()=>{let y=u.getBoundingClientRect();ja(p,y.right-4,y.top-5,u,o+1),u.setAttribute("aria-expanded","true")};u.addEventListener("click",v),u.addEventListener("keydown",y=>{y.key==="ArrowRight"&&(y.preventDefault(),v())})}else u.addEventListener("click",()=>{Mr(),c.run?.()});u.addEventListener("pointerenter",()=>u.focus()),a.append(u)}a.addEventListener("keydown",c=>{Tn.add(c);let u=dd(a),d=u.indexOf(document.activeElement),f=u.length,p=c.key==="ArrowDown"?(d+1)%f:c.key==="ArrowUp"?(d-1+f)%f:c.key==="Home"?0:c.key==="End"?f-1:-1;if(p>=0)c.preventDefault(),u[p]?.focus();else if(c.key==="Escape"||c.key==="ArrowLeft"&&o>0)c.preventDefault(),c.stopPropagation(),o>0?(Mr(o),r.focus()):Mr();else if(c.key==="Tab")c.preventDefault(),Mr();else if(c.key.length===1&&/\S/.test(c.key)){let h=c.key.toLowerCase();[...u.slice(d+1),...u.slice(0,d+1)].find(y=>y.textContent?.trim().toLowerCase().startsWith(h))?.focus()}}),a.querySelector(".tb-menu-item > svg:first-child")===null&&a.querySelectorAll(".tb-menu-gap").forEach(c=>c.remove()),document.body.append(a),a.showPopover?.();let l=a.getBoundingClientRect();a.style.left=`${Math.max(8,Math.min(t,innerWidth-l.width-8))}px`,a.style.top=`${Math.max(8,n+l.height>innerHeight-8?n-l.height:n)}px`,Na.push(a),dd(a)[0]?.focus()}var Qe=null,Yi=864e5;function ll(e){return e.t===s.Date?new Date(Date.UTC(e.v.y,e.v.m-1,e.v.d)):null}function Pa(e){return e.toISOString().slice(0,10)}function fd(e,t){let n=$(e,"rules");if(n.t!==s.Block)return null;for(let r of n.s.data)if(!(r.t!==s.Block||r.s.data[0]?.t!==s.Word||M(r.s.data[0].sym)!==t))return ll(r.s.data[1]??k);return null}function Qh(e,t){Ir(!1);let n=new Date(Date.UTC(new Date().getFullYear(),new Date().getMonth(),new Date().getDate())),r=m("div","tb-calendar");r.setAttribute("role","dialog"),r.setAttribute("aria-label",t.getAttribute("aria-label")??de("choose-date")),r.setAttribute("popover","manual");let o=m("h2","tb-calendar-month");o.id=`tb-${tt++}`,o.setAttribute("aria-live","polite");let a=(u,d,f)=>{let p=m("button","tb-calendar-step");p.type="button",p.setAttribute("aria-label",d);let h=et(u);return h!==null&&p.append(h),p.addEventListener("click",()=>{Qe!==null&&(Qe.at=Hd(Qe.at,f),Zi())}),p},i=m("div","tb-calendar-head");i.append(a("chevron-left",de("previous-month"),-1),o,a("chevron-right",de("next-month"),1)),r.append(i),Qe={face:e,opener:t,box:r,month:o,at:ll($(e,"value"))??n},t.setAttribute("aria-expanded","true"),r.addEventListener("keydown",em),r.addEventListener("focusout",u=>{Qe?.box===r&&!r.contains(u.relatedTarget)&&u.relatedTarget!==null&&Ir(!1)}),document.addEventListener("pointerdown",Fd,!0),document.body.append(r),r.showPopover?.(),Zi();let l=t.closest(".tb-date").getBoundingClientRect(),c=r.getBoundingClientRect();r.style.left=`${Math.max(8,Math.min(l.right-c.width,innerWidth-c.width-8))}px`,r.style.top=`${l.bottom+4+c.height>innerHeight-8?Math.max(8,l.top-4-c.height):l.bottom+4}px`,Ud()}function Ir(e=!0){if(Qe===null)return;let{box:t,opener:n}=Qe;Qe=null,t.hidePopover?.(),t.remove(),n.setAttribute("aria-expanded","false"),document.removeEventListener("pointerdown",Fd,!0),e&&n.focus()}function Fd(e){Qe!==null&&!Qe.box.contains(e.target)&&!Qe.opener.contains(e.target)&&Ir(!1)}function Zi(){let e=Qe,t=lt(K.rt),n=e.at,r=fd(e.face,"min"),o=fd(e.face,"max"),a=ll($(e.face,"value")),i=new Date,l=Date.UTC(i.getFullYear(),i.getMonth(),i.getDate()),c=x=>new Intl.DateTimeFormat(t,{timeZone:"UTC",...x});e.month.textContent=c({month:"long",year:"numeric"}).format(n);let u=m("table","tb-calendar-grid");u.setAttribute("role","grid"),u.setAttribute("aria-labelledby",e.month.id);let d=ca(t)%7,f=m("tr");for(let x=0;x<7;x++){let w=new Date(Date.UTC(1970,0,4+(d+x)%7)),E=m("th");E.scope="col",E.abbr=c({weekday:"long"}).format(w),E.textContent=c({weekday:"narrow"}).format(w),f.append(E)}let p=m("thead");p.append(f);let h=m("tbody"),v=Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),1),y=v-(new Date(v).getUTCDay()-d+7)%7*Yi,C=c({dateStyle:"full"});do{let x=m("tr");for(let w=0;w<7;w++,y+=Yi){let E=new Date(y),S=m("td","tb-calendar-day");S.setAttribute("role","gridcell"),S.textContent=String(E.getUTCDate()),S.setAttribute("aria-label",C.format(E)),S.dataset.day=Pa(E),S.tabIndex=y===n.getTime()?0:-1,E.getUTCMonth()!==n.getUTCMonth()&&S.classList.add("tb-calendar-other"),y===l&&S.setAttribute("aria-current","date"),S.setAttribute("aria-selected",a!==null&&y===a.getTime()?"true":"false"),(r!==null&&E<r||o!==null&&E>o)&&S.setAttribute("aria-disabled","true"),S.addEventListener("click",()=>zd(E)),x.append(S)}h.append(x)}while(new Date(y).getUTCMonth()===n.getUTCMonth());u.append(p,h),e.box.querySelector("table")?.remove(),e.box.append(u)}function Hd(e,t){let n=e.getUTCFullYear(),r=e.getUTCMonth()+t,o=new Date(Date.UTC(n,r+1,0)).getUTCDate();return new Date(Date.UTC(n,r,Math.min(e.getUTCDate(),o)))}function Ud(){Qe?.box.querySelector('td[tabindex="0"]')?.focus()}function zd(e){let t=Qe;if(t===null||t.box.querySelector(`td[data-day="${Pa(e)}"]`)?.getAttribute("aria-disabled")==="true")return;let n=t.face;Ir(),F("ui-input",n,j(Pa(e))).then(()=>F("ui-blur",n))}function em(e){let t=Qe;if(t===null)return;if(Tn.add(e),e.key==="Escape"){e.preventDefault(),e.stopPropagation(),Ir();return}if(!(e.target instanceof HTMLTableCellElement))return;let n=t.at,r=ca(lt(K.rt))%7,o=(n.getUTCDay()-r+7)%7,a={ArrowLeft:-1,ArrowRight:1,ArrowUp:-7,ArrowDown:7,Home:-o,End:6-o},i=null;if(e.key in a)i=new Date(n.getTime()+a[e.key]*Yi);else if(e.key==="PageUp"||e.key==="PageDown")i=Hd(n,(e.key==="PageUp"?-1:1)*(e.shiftKey?12:1));else if(e.key==="Enter"||e.key===" "){e.preventDefault(),zd(n);return}if(i!==null)if(e.preventDefault(),t.at=i,i.getUTCMonth()===n.getUTCMonth()){t.box.querySelectorAll('td[tabindex="0"]').forEach(c=>{c.tabIndex=-1});let l=t.box.querySelector(`td[data-day="${Pa(i)}"]`);l.tabIndex=0,l.focus()}else Zi(),Ud()}var tm=new Set(["Shift","Control","Alt","Meta","AltGraph","CapsLock","Dead","Unidentified"]),nm={Enter:13,Escape:27,Tab:9,Backspace:8},rm={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down",Home:"home",End:"end",PageUp:"page-up",PageDown:"page-down",Insert:"insert",Delete:"delete"};function cl(e){if(tm.has(e.key))return null;let t=nm[e.key];if(t!==void 0)return pt(t);let n=[...e.key];return n.length===1?pt(n[0].codePointAt(0)):/^F\d+$/.test(e.key)?st(s.LitWord,e.key):st(s.LitWord,rm[e.key]??e.key.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase())}function _d(e){let t=n=>n?P:we;return[["key",cl(e)],["ctrl?",t(e.ctrlKey)],["shift?",t(e.shiftKey)],["alt?",t(e.altKey)],["meta?",t(e.metaKey)]]}var fo=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),om={esc:"escape",space:" ",del:"delete",up:"arrowup",down:"arrowdown",left:"arrowleft",right:"arrowright"};function am(e){let t=e.toLowerCase().split("+").map(o=>o.trim()),n=t.pop()??"",r=(...o)=>t.some(a=>o.includes(a));return{key:om[n]??n,ctrl:r("ctrl","control"),shift:r("shift"),alt:r("alt","option"),meta:r("meta","cmd")}}function sm(e,t){return(fo&&e.metaKey||e.ctrlKey)!==(t.ctrl||fo&&t.meta)||e.shiftKey!==t.shift||e.altKey!==t.alt||!fo&&e.metaKey!==t.meta?!1:/^[a-z]$/.test(t.key)?e.code===`Key${t.key.toUpperCase()}`:/^[0-9]$/.test(t.key)?e.code===`Digit${t.key}`:e.key.toLowerCase()===t.key}function im(e){return e.split("+").map(t=>{let n=t.trim().toLowerCase();return n==="ctrl"||n==="control"?fo?"Meta":"Control":n==="cmd"?"Meta":t.trim().length===1?t.trim().toUpperCase():t.trim()}).join("+")}function lm(e){return fo?e.replace(/ctrl|control/i,"Cmd"):e}function cm(e){if(qn(e.target))return;let t=Array.from(document.querySelectorAll("dialog[open]")).pop();for(let n of Ki){if(!n.el.isConnected){Ki.delete(n);continue}let r=R(n.face,"shortcut");if(!(r===null||!sm(e,am(r)))&&!(n.el.getClientRects().length===0||t!==void 0&&!t.contains(n.el))){e.preventDefault(),Tn.add(e),n.el.click();return}}}function um(e){qn(e.target)||Oa===null||Tn.has(e)||cl(e)===null||an(Oa,"on-key",_d(e))}function Hi(e,t,n){let r=wo(t),o=r!==null?et(r):null;o!==null&&(n.label=m("span"),e.append(o,n.label),e.classList.add("tb-has-icon"))}function dm(e){let t=wo(e);if(t===null||(R(e,"text")??"")!=="")return null;let n=R(e,"hint");if(n!==null)return n;let r=t.replace(/-/g," ");return r.charAt(0).toUpperCase()+r.slice(1)}function ul(e,t,n){let r=null;for(let o of Ln(t)){let a=Pe(o,"style")==="button";if(n==="form"&&a)r===null&&(r=m("div","tb-actions"),e.append(r)),r.append(Gn(o));else{r=null;let i=Gn(o);n==="toolbar"&&i.tagName==="HR"&&i.setAttribute("aria-orientation","vertical"),e.append(i)}}}function fm(e,t){F("ui-click",e).then(()=>{for(let n of Array.from(t.querySelectorAll("input, textarea, select"))){let r=Mn.get(n);if(r!==void 0&&$(r.face,"error").t===s.String)return n.focus()}})}function pm(e,t,n){let r=`tb-${tt++}`,o=m("div","tb-field"),a=m("label","tb-label");a.htmlFor=r;let i=m("div","tb-control"),l;if(t==="area")l=m("textarea","tb-input");else if(t==="choice"){let p=m("select","tb-input");Ld(p,e),l=p}else{let p=m("input","tb-input");p.type=t==="password"?"password":co(e,"email")?"email":co(e,"url")?"url":"text",(t==="number"||t==="money"||co(e,"integer"))&&(p.inputMode=co(e,"integer")?"numeric":"decimal"),t==="password"&&(p.autocomplete="new-password"),l=p}l.addEventListener("focus",()=>of.add(l)),l.id=r;let c=m("div","tb-error");c.id=`${r}-error`,c.setAttribute("aria-live","polite"),l.setAttribute("aria-describedby",c.id);let u=Pe(e,"name");u!==null&&(l.name=u),l.addEventListener(t==="choice"?"change":"input",()=>{let p=lt(K.rt),h=t==="money"?pi(l.value,p)??l.value:t==="date"?bi(l.value,p)??l.value:l.value;n.typing++;let v=()=>{n.typing--,n.typed=$(e,"value")};F("ui-input",e,h===""?k:j(h)).then(v,v)}),t==="money"&&l.addEventListener("focus",()=>{O(e,"readonly")||(l.value=fi($(e,"value"),lt(K.rt)))}),l.addEventListener("blur",p=>{qn(p.relatedTarget)||F("ui-blur",e)});let d=t==="area"||t==="choice"?null:wo(e),f=d!==null?et(d):null;if(t==="date"){let p=m("div","tb-date"),h=m("button","tb-date-button");h.type="button",h.setAttribute("aria-haspopup","dialog"),h.setAttribute("aria-expanded","false");let v=et("calendar");v!==null&&h.append(v),h.addEventListener("click",()=>Qe?.opener===h?Ir():Qh(e,h)),p.append(l,h),i.append(p,c)}else if(f!==null){let p=m("div","tb-input-icon");p.append(f,l),i.append(p,c)}else i.append(l,c);return o.append(a,i),n.input=l,n.label=a,n.error=c,o}function bm(e,t,n){let r=m("div","tb-check-row tb-control"),o=m("label",n?"tb-check tb-switch":"tb-check"),a=m("input");a.type="checkbox",n&&a.setAttribute("role","switch");let i=m("span"),l=m("div","tb-error");return l.id=`tb-${tt++}-error`,l.setAttribute("aria-live","polite"),a.setAttribute("aria-describedby",l.id),a.addEventListener("change",()=>{F("ui-input",e,a.checked?P:we).then(()=>F("ui-blur",e))}),o.append(a,i),r.append(o,l),t.input=a,t.label=i,t.error=l,r}function hm(e,t){let n=`tb-${tt++}`,r=m("div","tb-field"),o=m("span","tb-label");o.id=n;let a=m("div","tb-control"),i=m("div","tb-radios");i.setAttribute("role","radiogroup"),i.setAttribute("aria-labelledby",n);let l=m("div","tb-error");l.id=`${n}-error`,l.setAttribute("aria-live","polite"),i.setAttribute("aria-describedby",l.id),t.radios=[];let c=u=>{let d=m("label","tb-check"),f=m("input");f.type="radio",f.name=n,f.value=Ar(u),f.addEventListener("change",()=>{f.checked&&F("ui-input",e,j(f.value)).then(()=>F("ui-blur",e))});let p=m("span");return p.textContent=yo(u),d.append(f,p),t.radios.push(f),d};for(let u of Br(e))if(Or(u)){let d=m("div","tb-radio-group");d.setAttribute("role","group");let f=m("span","tb-radio-title");f.id=`tb-${tt++}`,f.textContent=Ce(u.title,K.rt),d.setAttribute("aria-labelledby",f.id);let p=m("div","tb-radios");p.append(...u.options.map(c)),d.append(f,p),i.append(d)}else i.append(c(u));return a.append(i,l),r.append(o,a),t.label=o,t.error=l,r}function mm(e,t){let n=`tb-${tt++}`,r=m("div","tb-field"),o=m("label","tb-label");o.htmlFor=n;let a=m("div","tb-control"),i=m("div","tb-upload"),l=m("input");l.type="file",l.hidden=!0,l.tabIndex=-1;let c=m("button","tb-button");c.type="button",c.id=n;let u=et("upload");u!==null&&c.append(u),c.append(m("span"));let d=m("span","tb-upload-hint"),f=m("div","tb-error");f.id=`${n}-error`,f.setAttribute("aria-live","polite"),c.setAttribute("aria-describedby",f.id);let p=m("ul","tb-upload-list"),h=Gd(o,n);return c.addEventListener("click",()=>l.click()),l.addEventListener("change",()=>{let v=[...l.files??[]];l.value="",v.length>0&&fl(e,v)}),Kd(e,i,c),i.append(c,d,l),a.append(i,p,h,f),r.append(o,a),t.label=o,t.error=f,t.button=c,t.box=p,r}function dl(e){let t=$(e,"accept");return t.t!==s.Block&&Pe(e,"style")==="photo"?["image/*"]:t.t===s.Block?t.s.data.slice(t.i).map(n=>D(n).trim().toLowerCase()).filter(n=>n!==""):[]}function qd(e){return e.map(t=>t.includes("/")||t.startsWith(".")?t:`.${t}`).join(",")}function Kd(e,t,n){let r=o=>o.dataTransfer?.types.includes("Files")===!0;t.addEventListener("dragover",o=>{!r(o)||n.disabled||(o.preventDefault(),o.dataTransfer.dropEffect="copy",t.classList.add("tb-drop-over"))}),t.addEventListener("dragleave",o=>{t.contains(o.relatedTarget)||t.classList.remove("tb-drop-over")}),t.addEventListener("drop",o=>{t.classList.remove("tb-drop-over"),!(!r(o)||n.disabled)&&(o.preventDefault(),fl(e,[...o.dataTransfer.files]))})}function Gd(e,t){e.id=`${t}-label`;let n=m("div","tb-progress tb-upload-progress");return n.setAttribute("role","progressbar"),n.setAttribute("aria-valuemin","0"),n.setAttribute("aria-valuemax","100"),n.setAttribute("aria-labelledby",e.id),n.hidden=!0,n.append(m("div","tb-progress-bar")),n}function Vd(e){let t=e.el.querySelector(".tb-upload-progress"),n=$(e.face,"sent"),r=Jd(n)??0;t.hidden=n.t===s.None,t.setAttribute("aria-valuenow",String(Math.round(r*100))),t.firstChild.style.width=`${r*100}%`}function gm(e){let t=$(e,"captions");if(t.t===s.File||t.t===s.Url||t.t===s.String)return[[lt(K.rt),D(t)]];if(t.t!==s.Block)return[];let n=t.s.data.slice(t.i),r=[];for(let o=0;o+1<n.length;o+=2)r.push([D(n[o]),D(n[o+1])]);return r}function vm(e){let t=e.face,n=e.el,r=R(t,"value")??"";n.getAttribute("src")!==r&&(n.src=r);let o=R(t,"text");o!==null?n.setAttribute("aria-label",o):n.removeAttribute("aria-label"),n.loop=O(t,"looping");let a=O(t,"autoplay");if(n.muted=O(t,"silent")||a,n.autoplay=a,!(n instanceof HTMLVideoElement))return;let i=R(t,"poster")??"";n.getAttribute("poster")!==i&&(n.poster=i);let l=lt(K.rt),c=gm(t),u=new Intl.DisplayNames([l],{type:"language"});Array.from(n.querySelectorAll("track")).map(h=>`${h.srclang} ${h.getAttribute("src")}`).join("|")!==c.map(([h,v])=>`${h} ${v}`).join("|")&&n.replaceChildren(...c.map(([h,v])=>{let y=m("track");return y.kind="captions",y.srclang=h,y.src=v,y}));let f=Array.from(n.textTracks).some(h=>h.mode==="showing"),p=c.findIndex(([h])=>h===l);n.querySelectorAll("track").forEach((h,v)=>{h.label=u.of(h.srclang)??h.srclang,h.default=v===Math.max(0,p),f&&(h.track.mode=v===Math.max(0,p)?"showing":"disabled")})}var Ui=new WeakMap;function ym(e,t){let n=`tb-${tt++}`,r=m("div","tb-field"),o=m("label","tb-label");o.htmlFor=n;let a=m("div","tb-control"),i=m("div","tb-photo"),l=m("div","tb-photo-frame");l.addEventListener("click",()=>{d.disabled||c.click()});let c=m("input");c.type="file",c.hidden=!0,c.tabIndex=-1;let u=m("div","tb-photo-actions"),d=m("button","tb-button");d.type="button",d.id=n;let f=et("upload");f!==null&&d.append(f),d.append(m("span"));let p=m("button","tb-button tb-photo-remove");p.type="button",p.addEventListener("click",()=>{d.focus(),F("ui-remove-file",e,Ut(1))});let h=m("div","tb-error");return h.id=`${n}-error`,h.setAttribute("aria-live","polite"),d.setAttribute("aria-describedby",h.id),d.addEventListener("click",()=>c.click()),c.addEventListener("change",()=>{let v=[...c.files??[]];c.value="",v.length>0&&fl(e,v)}),Kd(e,i,d),u.append(d,p),i.append(l,u,c),a.append(i,Gd(o,n),h),r.append(o,a),t.label=o,t.error=h,t.button=d,t.box=l,r}function wm(e,t){let n=Ui.get(e),r=t.t===s.Object?Et($(t,"file"),"file"):null;if(r!==null&&n!==void 0&&n.blob===r)return n.url;if(n!==void 0&&(URL.revokeObjectURL(n.url),Ui.delete(e)),r!==null){let o=URL.createObjectURL(r);return Ui.set(e,{blob:r,url:o}),o}return t.t===s.String||t.t===s.Url||t.t===s.File?D(t):null}function km(e,t){let n=e.face,r=R(n,"text")??"";e.label.textContent=r,e.label.classList.toggle("tb-required",At(n));let o=O(n,"readonly"),a=e.button;a.disabled=O(n,"disabled")||o,a.setAttribute("aria-invalid",t!==null?"true":"false");let i=e.box;i.classList.toggle("tb-round",O(n,"round")),i.classList.toggle("tb-photo-pick",!a.disabled);let l=wm(i,$(n,"value")),c=i.querySelector("img");if(l===null){if(c!==null||i.firstChild===null){let d=et(O(n,"round")?"user":"image");i.replaceChildren(...d!==null?[d]:[])}}else c===null&&(c=m("img"),i.replaceChildren(c)),c.getAttribute("src")!==l&&(c.src=l),c.alt=r;a.lastChild.textContent=de(l===null?"choose-photo":"change-photo");let u=e.el.querySelector(".tb-photo-remove");u.textContent=de("remove-photo"),u.hidden=l===null||o,u.disabled=a.disabled,e.el.querySelector(".tb-photo-actions").hidden=o,e.el.querySelector('input[type="file"]').accept=qd(dl(n)),e.error.textContent=t??"",Vd(e)}var Ji=new WeakMap,xm=new Set(["on-change","on-focus","on-unfocus","on-over","on-dbl-click","on-key","on-end","on-drop","on-reorder","on-menu","on-select"]);function pd(e){let t;try{t=JSON.stringify(e)}catch{t=void 0}if(t===void 0)return k;let n=Gt(t);return typeof n=="string"?k:n}function Cm(e,t){let n=`tb-${tt++}`,r=m("div","tb-field"),o=m("label","tb-label");o.htmlFor=n;let a=m("div","tb-control"),i;try{i=document.createElement(R(e,"tag")??"div")}catch{i=m("div")}i.classList.add("tb-widget"),i.id=n;let l=m("div","tb-error");l.id=`${n}-error`,l.setAttribute("aria-live","polite"),i.setAttribute("aria-describedby",l.id),Ji.set(i,{value:"",props:""}),i.addEventListener("change",u=>{if(u.target!==i)return;let d=pd(i.value);Ji.get(i).value=Re(d),F("ui-input",e,d)});let c=$(e,"events");if(c.t===s.Block)for(let u of c.s.data){let d=u.t===s.Word?M(u.sym).toLowerCase():"";!d.startsWith("on-")||xm.has(d)||i.addEventListener(d.slice(3),f=>an(e,d,[["detail",pd(f.detail)]]))}return a.append(i,l),r.append(o,a),t.label=o,t.error=l,t.box=i,r}function Sm(e,t){let n=e.face,r=R(n,"text")??"";e.label.textContent=r,e.label.hidden=r==="",e.label.classList.toggle("tb-required",At(n));let o=e.box,a=Ji.get(o),i=$(n,"props"),l=i.t===s.Object||i.t===s.Map?Re(i):"{}";l!==a.props&&(Object.assign(o,JSON.parse(l)),a.props=l);let c=Re($(n,"value"));c!==a.value&&(o.value=JSON.parse(c),a.value=c);let u=O(n,"disabled");o.toggleAttribute("disabled",u),"disabled"in o&&(o.disabled=u),"readOnly"in o&&(o.readOnly=O(n,"readonly")),o.setAttribute("aria-invalid",t!==null?"true":"false"),r!==""&&o.setAttribute("aria-label",r),e.error.textContent=t??""}function bd(e,t){if(t.length===0)return!0;let n=e.name.toLowerCase(),r=e.type.toLowerCase();return t.some(o=>o.includes("/")?o.endsWith("/*")?r.startsWith(o.slice(0,-1)):r===o:n.endsWith(o.startsWith(".")?o:`.${o}`))}function fl(e,t){let n=dl(e),r=t.filter(l=>bd(l,n)),o=O(e,"multiple")?r:r.slice(0,1),a=[];for(let l of o)a.push(j(l.name),Ut(l.size),j(l.type),li(l));let i=t.filter(l=>!bd(l,n)).map(l=>j(l.name));F("ui-files",e,Ye(s.Block,a),Ye(s.Block,i))}function Em(e){try{let t=new URL(e,location.href);return t.protocol==="http:"||t.protocol==="https:"?t.href:null}catch{return null}}function Mm(e,t){let n=e.face,r=e.label;r.textContent=R(n,"text")??"",r.classList.toggle("tb-required",At(n));let o=O(n,"multiple"),a=e.button;a.lastChild.textContent=de(o?"choose-files":"choose-file");let i=O(n,"readonly");a.disabled=O(n,"disabled")||i,a.setAttribute("aria-invalid",t!==null?"true":"false");let l=a.parentElement;l.hidden=i,l.querySelector(".tb-upload-hint").textContent=de(o?"drop-files":"drop-file");let c=l.querySelector("input");c.multiple=o,c.accept=qd(dl(n)),e.error.textContent=t??"";let u=$(n,"value"),d=u.t===s.Block?u.s.data.slice(u.i).filter(h=>h.t===s.Object):[],f=lt(K.rt),p=d.map((h,v)=>{let y=m("li"),C=R(h,"url"),x=C!==null?Em(C):null,w=m(x!==null?"a":"span","tb-upload-name");if(w.textContent=R(h,"name")??"",w instanceof HTMLAnchorElement&&x!==null&&(w.href=x,w.target="_blank",w.rel="noopener"),x!==null&&(R(h,"type")??"").startsWith("image/")){let J=m("img","tb-upload-thumb");J.src=x,J.alt="",y.append(J)}let E=m("span","tb-upload-size"),S=$(h,"size");if(E.textContent=S.t===s.Integer?mi(Number(S.v),f):"",i)return y.append(w,E),y;let T=m("button","tb-upload-remove");T.type="button",T.disabled=a.disabled,T.setAttribute("aria-label",de("remove-file",w.textContent??""));let V=et("close");return V!==null&&T.append(V),T.addEventListener("click",()=>{a.focus(),F("ui-remove-file",n,Ut(v+1))}),y.append(w,E,T),y});e.box.replaceChildren(...p),e.box.hidden=p.length===0,Vd(e)}var ye=null,Xi,Tm=200;function Ra(e){let t=$(e,"value");return t.t===s.None?[]:t.t===s.Block?t.s.data.slice(t.i):[t]}function Qi(e,t){let n=$(e,"known"),r=n.t===s.Map?Zt(n,D(t)):null;return r!==null?Ce(r,K.rt):D(t)}function hd(e,t){let n=$(e,"links");if(!O(e,"readonly")||n.t!==s.Map)return null;let r=Zt(n,D(t));return r===null?null:r.t===s.LitWord?bo({...r,t:s.Word}):r.t===s.LitPath?bo({...r,t:s.Path}):bo(r)??(r.t===s.Url||r.t===s.File||r.t===s.String?D(r):null)}function Lm(e,t){let n=`tb-${tt++}`,r=m("div","tb-field"),o=m("label","tb-label");o.htmlFor=n;let a=m("div","tb-control"),i=m("div","tb-lookup"),l=m("ul","tb-lookup-chosen"),c=m("input","tb-input");c.id=n,c.type="text",c.autocomplete="off",c.setAttribute("role","combobox"),c.setAttribute("aria-autocomplete","list"),c.setAttribute("aria-expanded","false");let u=Pe(e,"name");u!==null&&(c.name=u);let d=m("div","tb-error");return d.id=`${n}-error`,d.setAttribute("aria-live","polite"),c.setAttribute("aria-describedby",d.id),c.addEventListener("click",()=>{ye?.m!==t&&el(t,c,"")}),c.addEventListener("input",()=>{ye?.m!==t&&el(t,c,null),clearTimeout(Xi),Xi=setTimeout(()=>{F("ui-lookup-search",e,j(c.value))},Tm)}),c.addEventListener("keydown",f=>Bm(t,c,f)),c.addEventListener("blur",()=>{if(Fa(),c.readOnly)return;let f=O(e,"multiple");!f&&c.value===""&&$(e,"value").t!==s.None?F("ui-input",e,k):c.value=f?"":Ra(e).map(h=>Qi(e,h)).join(""),F("ui-blur",e)}),i.append(l,c),a.append(i,d),r.append(o,a),t.input=c,t.label=o,t.error=d,t.box=l,r}function Am(e,t){let n=e.face,r=e.input,o=e.label;o.textContent=R(n,"text")??"",o.classList.toggle("tb-required",At(n));let a=O(n,"multiple"),i=O(n,"readonly"),l=O(n,"disabled"),c=Ra(n),u=a||c.some(f=>hd(n,f)!==null);r.readOnly=i,r.disabled=l,r.hidden=u&&i&&c.length>0,r.setAttribute("aria-required",At(n)?"true":"false"),r.setAttribute("aria-invalid",t!==null?"true":"false");let d=R(n,"hint");if(d!==null&&(r.placeholder=d),e.error.textContent=t??"",u)e.box.replaceChildren(...c.map((f,p)=>{let h=m("li","tb-lookup-chip"),v=hd(n,f),y=m(v!==null?"a":"span",v!==null?"tb-link":"");if(y instanceof HTMLAnchorElement&&(y.href=v),y.textContent=Qi(n,f),h.append(y),!i&&!l){let C=m("button","tb-upload-remove");C.type="button",C.setAttribute("aria-label",de("remove-value",y.textContent));let x=et("close");x!==null&&C.append(x),C.addEventListener("click",()=>{r.focus(),F("ui-lookup-remove",n,Ut(p+1))}),h.append(C)}return h}));else{e.box.replaceChildren();let f=c.map(p=>Qi(n,p)).join("");document.activeElement!==r&&r.value!==f&&(r.value=f)}ye?.m===e&&Im()}function el(e,t,n){if(t.readOnly||t.disabled)return;Fa();let r=m("ul","tb-lookup-list");r.id=`tb-${tt++}`,r.setAttribute("role","listbox"),r.setAttribute("popover","manual"),r.addEventListener("pointerdown",o=>o.preventDefault()),ye={m:e,list:r,shown:null,items:[],active:-1},t.setAttribute("aria-expanded","true"),t.setAttribute("aria-controls",r.id),(t.closest("dialog")??document.body).append(r),r.showPopover?.(),Yd(),n!==null&&F("ui-lookup-search",e.face,j(n))}function Yd(){if(ye===null)return;let{list:e,m:t}=ye,n=t.input.getBoundingClientRect();e.style.width=`${n.width}px`,e.style.left=`${n.left}px`;let r=e.getBoundingClientRect().height;e.style.top=`${n.bottom+4+r>innerHeight-8?Math.max(8,n.top-4-r):n.bottom+4}px`}function Fa(){if(clearTimeout(Xi),ye===null)return;let{list:e,m:t}=ye;ye=null,e.hidePopover?.(),e.remove(),t.input.setAttribute("aria-expanded","false"),t.input.removeAttribute("aria-controls"),t.input.removeAttribute("aria-activedescendant")}function Im(){if(ye===null)return;let e=ye,t=$(e.m.face,"options");if(t.t!==s.Block||t===e.shown||e.shown===null&&$(e.m.face,"query").t===s.None)return;e.shown=t;let n=new Set(O(e.m.face,"multiple")?Ra(e.m.face).map(r=>D(r)):[]);if(e.items=Md(e.m.face).filter(r=>!n.has(Ar(r))),e.active=-1,e.list.replaceChildren(...e.items.map((r,o)=>{let a=m("li","tb-lookup-option");return a.id=`${e.list.id}-${o}`,a.setAttribute("role","option"),a.setAttribute("aria-selected","false"),a.textContent=yo(r),a.addEventListener("click",()=>Zd(r)),a})),e.items.length===0){let r=m("li","tb-lookup-none");r.textContent=de("no-matches"),e.list.append(r)}Yd()}function Zd(e){if(ye===null)return;let{m:t}=ye,n=t.input;Fa(),n.value=O(t.face,"multiple")?"":yo(e),F("ui-lookup-pick",t.face,e)}function $m(e){if(ye===null||ye.items.length===0)return;let{list:t,items:n,m:r}=ye,o=ye.active<0&&e<0?n.length-1:(ye.active+e+n.length)%n.length;t.children[ye.active]?.setAttribute("aria-selected","false"),ye.active=o;let a=t.children[o];a.setAttribute("aria-selected","true"),a.scrollIntoView({block:"nearest"}),r.input.setAttribute("aria-activedescendant",a.id)}function Bm(e,t,n){let r=ye?.m===e,o=()=>{n.preventDefault(),n.stopPropagation()};switch(n.key){case"ArrowDown":case"ArrowUp":o(),r?$m(n.key==="ArrowDown"?1:-1):el(e,t,"");break;case"Enter":if(!r)break;o(),ye.active>=0&&Zd(ye.items[ye.active]);break;case"Escape":r&&(o(),Fa());break;case"Backspace":if(O(e.face,"multiple")&&t.value===""&&!t.readOnly){let a=Ra(e.face).length;a>0&&F("ui-lookup-remove",e.face,Ut(a))}break}}function Om(e){let t=m("div","tb-progress-wrap"),n=m("span","tb-progress-label");n.id=`tb-${tt++}`;let r=m("div","tb-progress");return r.setAttribute("role","progressbar"),r.setAttribute("aria-valuemin","0"),r.setAttribute("aria-valuemax","100"),r.append(m("div","tb-progress-bar")),t.append(n,r),e.label=n,e.box=r,t}function Jd(e){let t=e.t===s.Percent||e.t===s.Decimal?e.v:e.t===s.Integer?Number(e.v):null;return t===null||Number.isNaN(t)?null:Math.min(1,Math.max(0,t))}function Nm(e){let t=R(e.face,"text"),n=e.label;n.textContent=t??"",n.hidden=t===null;let r=e.box;t!==null?r.setAttribute("aria-labelledby",n.id):r.removeAttribute("aria-labelledby");let o=Jd($(e.face,"value"));r.classList.toggle("tb-indeterminate",o===null);let a=r.firstChild;o===null?(r.removeAttribute("aria-valuenow"),a.style.removeProperty("width")):(r.setAttribute("aria-valuenow",String(Math.round(o*100))),a.style.width=`${o*100}%`)}var wt="http://www.w3.org/2000/svg";function xo(e){let t=document.createElementNS(wt,e.tag);for(let[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);e.text!==void 0&&(t.textContent=e.text);for(let n of e.kids)t.append(xo(n));return t}function jm(e){let t=m("div","tb-canvas"),n=document.createElementNS(wt,"svg");return t.append(n),e.kids=n,t}function Pm(e){let t=e.kids,n=$(e.face,"extent"),[r,o]=n.t===s.Pair?[n.x,n.y]:[300,150];t.setAttribute("viewBox",`0 0 ${r} ${o}`),t.setAttribute("width",String(r)),t.setAttribute("height",String(o));let a=R(e.face,"text");a!==null?(t.setAttribute("role","img"),t.setAttribute("aria-label",a),t.removeAttribute("aria-hidden")):(t.removeAttribute("role"),t.removeAttribute("aria-label"),t.setAttribute("aria-hidden","true"));let{kids:i,error:l}=Mu($(e.face,"draw"));l!==null&&console.warn(`Trebol: ${l}`),t.replaceChildren(...i.map(xo))}var Dm={small:160,medium:240,large:360};function Wm(e){let t=m("figure","tb-chart"),n=m("figcaption","tb-chart-caption"),r=m("div","tb-chart-plot"),o=document.createElementNS(wt,"svg");o.setAttribute("aria-hidden","true"),r.append(o);let a=m("ul","tb-chart-legend"),i=m("table","tb-sr-only"),l=m("p","tb-chart-empty");t.append(n,r,a,l,i);let c={caption:n,plot:r,svg:o,legend:a,table:i,empty:l,width:0};return e.kids=c,typeof ResizeObserver<"u"&&new ResizeObserver(()=>{r.clientWidth!==c.width&&Xd(e)}).observe(r),t}function Rm(e){return e.t===s.Integer?Number(e.v):e.t===s.Decimal||e.t===s.Percent?e.v:e.t===s.Money?xt(e.v):null}function Fm(e){return t=>{if(e!==null&&e.t===s.Money){let n=Qt(Math.round(t*100)/100);if(n!==null)return Tr(ft(n,e.cur))}return e!==null&&e.t===s.Percent?Tr({t:s.Percent,v:t}):Tr(Number.isInteger(t)?{t:s.Integer,v:t}:{t:s.Decimal,v:t})}}function Hm(e){let t=e.kids,n=R(e.face,"text");t.caption.textContent=n??"",t.caption.hidden=n===null,Xd(e)}function Xd(e){let t=e.face,n=e.kids,r=Co(t),o=$(t,"data"),a=o.t===s.Block?o.s.data.slice(o.i):[],i=Pe(t,"kind")??"bar",l=a.map(w=>$r(at(w,r[0]?.sym??A("label")))),c=null,u=r.slice(1).map((w,E)=>({name:w.label,color:no[E%no.length],values:a.map(S=>{let T=at(S,w.sym),V=Rm(T);return V!==null&&c===null&&(c=T),V})})),d=Fm(c),f=a.length===0||u.length===0;if(n.empty.hidden=!f,n.plot.hidden=f,f){n.empty.textContent=de("empty"),n.legend.replaceChildren(),n.table.replaceChildren();return}let p=n.plot.clientWidth||600,h=Dm[Pe(t,"size")??"medium"]??240;n.width=n.plot.clientWidth,n.svg.setAttribute("viewBox",`0 0 ${p} ${h}`),n.svg.replaceChildren(...zu({kind:i,labels:l,series:u,stacked:O(t,"stacked"),width:p,height:h,format:d}).map(xo));let v=i==="pie"?l.map((w,E)=>[w,Ti(E)]):u.length>1?u.map(w=>[w.name,w.color]):[];n.legend.replaceChildren(...v.map(([w,E])=>{let S=m("li","tb-chart-key"),T=m("span","tb-chart-swatch");return T.style.setProperty("--tb-swatch",E),S.append(T,w),S})),n.legend.hidden=v.length===0;let y=m("caption");y.textContent=R(t,"text")??"";let C=m("tr");for(let w of r){let E=m("th");E.textContent=w.label,C.append(E)}let x=a.map(w=>{let E=m("tr");for(let S of r){let T=m("td");T.textContent=$r(at(w,S.sym)),E.append(T)}return E});n.table.replaceChildren(y,m("thead"),m("tbody")),n.table.tHead.append(C),n.table.tBodies[0].append(...x)}var Qd=0;function Um(e){let t=m("div","tb-orbit"),n=document.createElementNS(wt,"svg");n.setAttribute("role","group"),n.setAttribute("tabindex","-1");let r=document.createElementNS(wt,"defs"),o=document.createElementNS(wt,"g"),a=document.createElementNS(wt,"g"),i=document.createElementNS(wt,"g");o.append(a,i),n.append(r,o),t.append(n);let l={svg:n,defs:r,world:o,lines:a,bubbles:i,vis:new Map,edges:[],spec:Ii(k).spec,signature:"",page:0,pageOf:null,box:{x0:-100,y0:-100,x1:100,y1:100},placed:[],left:0,cam:{x:0,y:0,s:1},camFrom:null,camTo:null,anim:0,picked:null,byKey:!1,dragged:!1,gradients:new Map,width:0,height:0};return e.kids=l,zm(e,l),_m(e,l),typeof ResizeObserver<"u"&&new ResizeObserver(()=>{if(n.clientWidth===l.width&&n.clientHeight===l.height)return;l.width=n.clientWidth,l.height=n.clientHeight;let c=ya(l.width,l.height,l.box);l.camTo!==null?l.camTo=c:l.cam=c,tf(e,l,c.s),Da(l),rf(l)}).observe(n),t}function zm(e,t){let{svg:n}=t,r=null;n.addEventListener("pointerdown",a=>{a.button===0&&(r={x:a.clientX,y:a.clientY,cx:t.cam.x,cy:t.cam.y,id:a.pointerId},t.dragged=!1)}),n.addEventListener("pointermove",a=>{if(r===null||a.pointerId!==r.id)return;let i=a.clientX-r.x,l=a.clientY-r.y;!t.dragged&&Math.hypot(i,l)>4&&(t.dragged=!0,n.setPointerCapture(a.pointerId),n.classList.add("tb-orbit-panning")),t.dragged&&(t.cam={...t.cam,x:r.cx+i,y:r.cy+l},Da(t))});let o=()=>{r=null,n.classList.remove("tb-orbit-panning"),setTimeout(()=>{t.dragged=!1},0)};n.addEventListener("pointerup",o),n.addEventListener("pointercancel",o),n.addEventListener("wheel",a=>{if(!a.ctrlKey&&!a.metaKey&&!O(e.face,"fit"))return;a.preventDefault();let i=n.getBoundingClientRect(),l=i.width/2+t.cam.x,c=i.height/2+t.cam.y,u=Math.max(.15,Math.min(4,t.cam.s*Math.exp(-a.deltaY*(a.ctrlKey?.01:.0015)))),d=a.clientX-i.left,f=a.clientY-i.top,p=(d-l)/t.cam.s,h=(f-c)/t.cam.s;t.cam={x:d-i.width/2-p*u,y:f-i.height/2-h*u,s:u},Da(t)},{passive:!1}),n.addEventListener("dblclick",a=>{a.target.closest(".tb-orbit-node")===null&&(t.camFrom={...t.cam},t.camTo=ya(t.width,t.height,t.box),nf(t,500))})}function _m(e,t){t.svg.addEventListener("keydown",n=>{let r=n.target.closest(".tb-orbit-node");if((n.key==="Enter"||n.key===" ")&&r!==null)n.preventDefault(),tl(e,t,r.dataset.key,!0);else if((n.key==="Escape"||n.key==="Backspace")&&t.spec.trail.length>0){let o=[...t.spec.trail].reverse().find(a=>t.spec.nodes.has(a));if(o===void 0)return;n.preventDefault(),n.stopPropagation(),tl(e,t,o,!0)}})}function tl(e,t,n,r){if(O(e.face,"disabled"))return;let o=t.vis.get(n);if(o===void 0||o.dying)return;if(o.role==="more"){t.page++,t.picked=t.spec.focus,ef(e,t);return}let a=t.spec.nodes.get(n);a===void 0||o.role==="focus"||(t.picked=n,t.byKey=r,F("ui-orbit",e.face,a.id,o.role==="trail"?P:we))}function qm(e){let t=e.kids,{spec:n,error:r}=Ii($(e.face,"data"));r!==null&&console.warn(`Trebol: ${r}`);let o=R(e.face,"text"),a=n.focus===null?void 0:n.nodes.get(n.focus),i=a===void 0?"":Ce(a.title,K.rt);t.svg.setAttribute("aria-label",o===null?i:i===""?o:`${o}: ${i}`);let l=Km(n);l!==t.signature&&(t.signature=l,t.spec=n,n.focus!==t.pageOf&&(t.page=0,t.pageOf=n.focus),ef(e,t))}function Km(e){let t=o=>o===null?"":Ce(o,K.rt),n=[...e.nodes.values()].map(o=>[o.key,t(o.title),o.color,o.count,o.many,o.dashed,o.steps,o.at].join("")),r=e.edges.map(o=>[o.from,o.to,t(o.label),o.look].join(""));return[e.focus??"",n.join(""),r.join(""),e.trail.join("")].join("\0")}function Gm(e,t){let n=e.gradients.get(t);if(n===void 0){let r=`tb-orbit${Qd++}`;n=[`${r}-body`,`${r}-halo`],e.gradients.set(t,n),e.defs.append(...Zu(t,n[0],n[1]).map(xo))}return n}function ef(e,t){let{spec:n}=t,r=Ku(n,t.page);t.box=r.box;let o=new Map(r.placed.map(l=>[l.key,l]));for(let[l,c]of[...t.vis]){if(c.dying)continue;let u=o.get(l);u===void 0||u.role!==c.role||u.role==="more"?(c.dying=!0,c.from={...c.cur},c.to={...c.cur,r:c.cur.r*(u===void 0?.4:1),o:0},c.g.setAttribute("tabindex","-1"),c.g.setAttribute("aria-hidden","true"),t.vis.delete(l),t.vis.set(`${l}\0old${Qd++}`,c),u!==void 0&&t.vis.set(l,md(e,t,u,{...c.cur}))):(c.from={...c.cur},c.to=u)}let a=t.picked===null?void 0:[...t.vis.values()].find(l=>l.key===t.picked),i=a!==void 0?a.cur:{x:0,y:0};for(let l of r.placed)t.vis.has(l.key)||t.vis.set(l.key,md(e,t,l,{x:i.x,y:i.y,r:l.r*.2,o:0}));t.width=t.svg.clientWidth,t.height=t.svg.clientHeight,t.camFrom={...t.cam},t.camTo=ya(t.width||600,t.height||480,r.box),t.placed=r.placed,t.left=r.left,tf(e,t,t.camTo.s),t.bubbles.append(...r.placed.map(l=>t.vis.get(l.key).g)),t.picked=null,nf(t,matchMedia("(prefers-reduced-motion: reduce)").matches?0:900),t.byKey&&(t.byKey=!1,t.svg.focus())}function tf(e,t,n){for(let r of t.placed){let o=t.vis.get(r.key);o!==void 0&&Vm(e,t,o,r,t.left,n)}Zm(t,t.placed,n)}function md(e,t,n,r){let o=document.createElementNS(wt,"g"),a=document.createElementNS(wt,"g");return o.append(a),o.dataset.key=n.key,o.addEventListener("click",i=>{t.dragged||(i.stopPropagation(),tl(e,t,n.key,!1))}),o.addEventListener("pointerenter",()=>Ma(t,n.key,!0)),o.addEventListener("pointerleave",()=>Ma(t,n.key,!1)),o.addEventListener("focus",()=>Ma(t,n.key,!0)),o.addEventListener("blur",()=>Ma(t,n.key,!1)),t.bubbles.append(o),{key:n.key,g:o,inner:a,role:n.role,cur:r,from:{...r},to:n,dying:!1}}function Vm(e,t,n,r,o,a){let i=t.spec.nodes.get(r.key)??null,l=r.role==="more"?o>0?de("orbit-more",String(o)):de("orbit-first"):i===null?"":Ce(i.title,K.rt),c=r.role==="more"?"var(--tb-muted)":i?.color??"var(--tb-primary)",[u,d]=Gm(t,c),f=r.role==="near"?Ym(t.spec,r.key):"",p=r.role==="trail"?de("orbit-back-to",l):f===""?l:`${l}, ${f}`;n.g.setAttribute("class",`tb-orbit-node tb-orbit-${r.role}`);let h=document.createElementNS(wt,"title");h.textContent=p,n.g.replaceChildren(h,n.inner),n.inner.replaceChildren(...Yu({role:r.role,r:r.r,scale:a,above:r.role!=="trail"&&r.y<-1,title:l,color:c,body:u,halo:d,node:i}).map(xo)),r.role==="focus"?(n.g.setAttribute("tabindex","-1"),n.g.removeAttribute("role"),n.g.removeAttribute("aria-label"),n.g.setAttribute("aria-hidden","true")):(n.g.setAttribute("tabindex","0"),n.g.setAttribute("role",r.role==="more"?"button":"link"),n.g.setAttribute("aria-label",p),n.g.removeAttribute("aria-hidden")),O(e.face,"disabled")&&n.g.setAttribute("tabindex","-1")}function Ym(e,t){let n=Vu(e,t);return n===null?"":Ce(n,K.rt)}function Zm(e,t,n){let r=t.filter(o=>o.role==="near").length>qu;e.edges=Gu(e.spec,t).map(o=>{let a=document.createElementNS(wt,"path");a.setAttribute("class",`tb-orbit-edge tb-orbit-edge-${o.trail?"trail":o.look}`);let i=null;return o.label!==null&&(i=document.createElementNS(wt,"text"),i.setAttribute("class",r?"tb-orbit-label tb-orbit-later":"tb-orbit-label"),i.style.fontSize=`${11/n}px`,i.style.strokeWidth=`${3/n}px`,i.textContent=Ce(o.label,K.rt)),{a:o.from,b:o.to,path:a,text:i,curve:o.curve}}),e.lines.replaceChildren(...e.edges.flatMap(o=>o.text===null?[o.path]:[o.path,o.text])),e.lines.setAttribute("aria-hidden","true")}function Ma(e,t,n){for(let r of e.edges)r.text!==null&&(r.a===t||r.b===t)&&r.text.classList.toggle("tb-orbit-shown",n)}function Da(e){let t=e.svg.clientWidth||e.width,n=e.svg.clientHeight||e.height;e.world.setAttribute("transform",`translate(${t/2+e.cam.x},${n/2+e.cam.y}) scale(${e.cam.s})`)}function nf(e,t){cancelAnimationFrame(e.anim);let n=performance.now(),r=o=>{let a=t===0?1:Xu(Math.min(1,(o-n)/t));for(let i of e.vis.values()){if(i.from!==i.to||i.dying){let l=i.from,c=i.to;i.cur={x:l.x+(c.x-l.x)*a,y:l.y+(c.y-l.y)*a,r:l.r+(c.r-l.r)*a,o:l.o+(c.o-l.o)*a}}i.g.setAttribute("transform",`translate(${i.cur.x},${i.cur.y})`),i.inner.setAttribute("transform",`scale(${Math.max(i.cur.r,.001)})`),i.g.style.opacity=String(i.cur.o),i.g.style.pointerEvents=i.cur.o<.05?"none":""}if(e.camFrom!==null&&e.camTo!==null){let i=e.camFrom,l=e.camTo;e.cam={x:i.x+(l.x-i.x)*a,y:i.y+(l.y-i.y)*a,s:i.s+(l.s-i.s)*a}}if(Da(e),rf(e),a<1)e.anim=requestAnimationFrame(r);else{e.camFrom=e.camTo=null;for(let[i,l]of e.vis)l.dying&&(l.g.remove(),e.vis.delete(i))}};t===0?r(n):e.anim=requestAnimationFrame(r)}function rf(e){for(let t of e.edges){let n=e.vis.get(t.a),r=e.vis.get(t.b);if(n===void 0||r===void 0){t.path.setAttribute("d","");continue}let o=Ju(n.cur,r.cur,t.curve);t.path.setAttribute("d",o.d);let a=String(Math.min(n.cur.o,r.cur.o));t.path.style.opacity=a,t.text!==null&&(t.text.setAttribute("transform",`translate(${o.x},${o.y}) rotate(${o.angle}) translate(0,-5)`),t.text.style.opacity=a)}}function Jm(e){let t=wo(e.face)??"",n=R(e.face,"text"),r=`${t} ${n??""}`;if(e.el.dataset.icon===r)return;e.el.dataset.icon=r;let o=t!==""?et(t,n):null;e.el.replaceChildren(...o!==null?[o]:[])}function At(e){return co(e,"required")&&!O(e,"readonly")}function Xm(e,t){let n=e.face;e.label.textContent=R(n,"text")??"",e.label.classList.toggle("tb-required",At(n));let r=$(n,"value"),o=r.t===s.None?null:D(r);for(let i of e.radios)i.checked=i.value===o,i.disabled=O(n,"disabled")||O(n,"readonly");let a=e.radios[0]?.closest('[role="radiogroup"]');a?.querySelectorAll(".tb-radio-title").forEach((i,l)=>{let c=Br(n).filter(Or)[l];c&&(i.textContent=Ce(c.title,K.rt))}),a?.setAttribute("aria-invalid",t!==null?"true":"false"),a?.setAttribute("aria-required",At(n)?"true":"false"),e.error.textContent=t??""}function Qm(e){let t=`tb-${tt++}`,n=m("div","tb-field"),r=m("div","tb-label");r.id=t;let o=m("div","tb-control"),a=m("div","tb-rows");a.setAttribute("role","group"),a.setAttribute("aria-labelledby",t);let i=m("div","tb-error");return i.setAttribute("aria-live","polite"),o.append(a,i),n.append(r,o),e.label=r,e.error=i,e.box=a,n}function eg(e,t){let n=e.face;e.label.textContent=R(n,"text")??"",e.label.classList.toggle("tb-required",At(n)),e.error.textContent=t??"";let r=$(n,"value"),o=[r.t===s.Block?r.s:null,O(n,"readonly"),O(n,"disabled")],a=e.shown;(a===void 0||o.some((i,l)=>i!==a[l]))&&(e.shown=o,F("ui-rows",n))}function tg(e){let t=e.box,n=Ln(e.face),r=document.activeElement,o=[],a=n.map(c=>{let u=cn.get(c.ctx);if(u!==void 0&&u.el.parentElement===t)return u.el;let d=Gn(c);return o.push(d),d}),i=t.firstChild;for(let c of a)c===i?i=i.nextSibling:t.insertBefore(c,i);for(;i!==null;){let c=i.nextSibling;t.removeChild(i),i=c}let l=a[a.length-1];r!==null&&r!==document.body&&!r.isConnected?l?.focus():o.length===1&&(r===l||r===document.body)&&o[0].querySelector('input, textarea, select, [contenteditable="true"]')?.focus()}var ng=[["bold","bold"],["italic","italic"],["heading","heading"],["list","bullet-list"],["list-ordered","number-list"],["link","link"]];function po(e){return e.flatMap(t=>{switch(t.k){case"text":return[document.createTextNode(t.text)];case"br":return[m("br")];case"b":case"i":{let n=m(t.k);return n.append(...po(t.kids)),[n]}case"a":{if(!Ei(t.href))return po(t.kids);let n=m("a");return n.href=t.href,n.rel="noopener noreferrer",n.target="_blank",n.append(...po(t.kids)),[n]}}})}function rg(e){return e.map(t=>{if(t.k==="p"||t.k==="h"){let r=t.k==="p"?m("p"):m(`h${t.level}`);return r.append(...po(t.kids)),r}let n=m(t.k);for(let r of t.items){let o=m("li");o.append(...po(r)),n.append(o)}return n})}function Aa(e){let t=[];for(let n of e)if(n.nodeType===Node.TEXT_NODE){let r=(n.textContent??"").replace(/\u00a0/g," ").replace(/[\n\r]+/g," "),o=t[t.length-1];if(r==="")continue;o?.k==="text"?o.text+=r:t.push({k:"text",text:r})}else if(n instanceof HTMLElement){let r=Aa(n.childNodes);switch(n.tagName){case"BR":t.push({k:"br"});break;case"B":case"STRONG":r.length>0&&t.push({k:"b",kids:r});break;case"I":case"EM":r.length>0&&t.push({k:"i",kids:r});break;case"A":r.length>0&&t.push({k:"a",href:n.getAttribute("href")??"",kids:r});break;default:t.push(...r)}}for(;t[t.length-1]?.k==="br";)t.pop();return t}var og=/^(P|DIV|H[1-6]|UL|OL|BLOCKQUOTE|SECTION)$/;function pl(e){let t=[],n=[],r=()=>{let o=Aa(n);o.length>0&&t.push({k:"p",kids:o}),n=[]};for(let o of e.childNodes){if(!(o instanceof HTMLElement)||!og.test(o.tagName)){n.push(o);continue}if(r(),o.tagName==="UL"||o.tagName==="OL"){let a=[...o.children].map(i=>Aa(i.childNodes)).filter(i=>i.length>0);a.length>0&&t.push({k:o.tagName==="UL"?"ul":"ol",items:a})}else if(o.tagName==="DIV"||o.tagName==="SECTION"||o.tagName==="BLOCKQUOTE")t.push(...pl(o));else{let a=Aa(o.childNodes);if(a.length===0)continue;o.tagName==="P"?t.push({k:"p",kids:a}):t.push({k:"h",level:Math.min(3,Number(o.tagName[1])),kids:a})}}return r(),t}function ag(e,t){let n=`tb-${tt++}`,r=m("div","tb-field"),o=m("div","tb-label");o.id=n;let a=m("div","tb-control"),i=m("div","tb-rich"),l=m("div","tb-rich-tools");l.setAttribute("role","toolbar");let c=m("div","tb-input tb-rich-box");c.setAttribute("role","textbox"),c.setAttribute("aria-multiline","true"),c.setAttribute("aria-labelledby",n);let u=m("div","tb-rich-link");u.hidden=!0;let d=m("input","tb-input");d.type="url";let f=m("button","tb-button tb-small");f.type="button",u.append(d,f);let p=m("div","tb-error");p.id=`${n}-error`,p.setAttribute("aria-live","polite"),c.setAttribute("aria-describedby",p.id),o.addEventListener("click",()=>c.focus()),ig();let h=()=>{if(nl)return;let w=ha(pl(c));w!==t.shown&&(t.shown=w,F("ui-input",e,w===""?k:j(w)))};c.addEventListener("input",h),c.addEventListener("paste",w=>{w.preventDefault(),document.execCommand("insertText",!1,w.clipboardData?.getData("text/plain")??"")}),c.addEventListener("drop",w=>w.preventDefault()),r.addEventListener("focusout",w=>{!r.contains(w.relatedTarget)&&!qn(w.relatedTarget)&&F("ui-blur",e)});let v=null,y=()=>{let w=getSelection()?.anchorNode??null;return(w instanceof Element?w:w?.parentElement)?.closest("h1, h2, h3")!=null},C=w=>{switch(c.focus(),w){case"bold":case"italic":document.execCommand(w);break;case"heading":document.execCommand("formatBlock",!1,y()?"P":"H2");break;case"bullet-list":document.execCommand("insertUnorderedList");break;case"number-list":document.execCommand("insertOrderedList");break;case"link":{let E=getSelection();v=E!==null&&E.rangeCount>0&&c.contains(E.anchorNode)?E.getRangeAt(0).cloneRange():null,u.hidden=!1,d.value="",d.removeAttribute("aria-invalid"),d.focus();return}}h()};for(let[w,E]of ng){let S=m("button","tb-rich-tool");S.type="button",S.dataset.tool=E;let T=et(w);T!==null&&S.append(T),S.addEventListener("mousedown",V=>V.preventDefault()),S.addEventListener("click",()=>C(E)),l.append(S)}let x=()=>{let w=d.value.trim(),E=/^[a-z][a-z0-9+.-]*:/i.test(w)?w:`https://${w}`;if(w===""||!Ei(E)){d.setAttribute("aria-invalid","true");return}u.hidden=!0,c.focus();let S=getSelection();if(v!==null&&S!==null&&(S.removeAllRanges(),S.addRange(v)),(v===null||v.collapsed)&&document.execCommand("insertText",!1,w),v!==null&&!v.collapsed)document.execCommand("createLink",!1,E);else{let T=getSelection()?.getRangeAt(0);if(T!==void 0){let V=T.startContainer,J=Math.max(0,T.startOffset-w.length),Ge=document.createRange();Ge.setStart(V,J),Ge.setEnd(V,T.startOffset),S?.removeAllRanges(),S?.addRange(Ge),document.execCommand("createLink",!1,E)}}h()};return f.addEventListener("click",x),d.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),x()):w.key==="Escape"&&(w.stopPropagation(),u.hidden=!0,c.focus())}),i.append(l,u,c),a.append(i,p),r.append(o,a),t.label=o,t.error=p,t.box=c,r}function sg(e,t){let n=e.face,r=e.box;e.label.textContent=R(n,"text")??"",e.label.classList.toggle("tb-required",At(n));let o=r.parentElement,a=O(n,"readonly"),i=O(n,"disabled"),l=a||i;r.contentEditable=l?"false":"true",r.tabIndex=i?-1:0,r.setAttribute("aria-readonly",l?"true":"false"),r.setAttribute("aria-disabled",i?"true":"false"),r.setAttribute("aria-required",At(n)?"true":"false"),r.setAttribute("aria-invalid",t!==null?"true":"false");let c=o.querySelector(".tb-rich-tools");c.hidden=l,c.setAttribute("aria-label",R(n,"text")??"");for(let f of c.querySelectorAll("button")){let p=de(f.dataset.tool);f.setAttribute("aria-label",p),f.title=p}let u=o.querySelector(".tb-rich-link");l&&(u.hidden=!0),u.querySelector("input").placeholder=de("link-url"),u.querySelector("button").textContent=de("link-add"),e.error.textContent=t??"";let d=R(n,"value")??"";d!==e.shown&&document.activeElement!==r&&(e.shown=d,r.replaceChildren(...rg(Si(d))),bl.delete(r))}var of=new WeakSet,bl=new WeakMap,nl=!1,gd=!1;function ig(){gd||(gd=!0,document.addEventListener("selectionchange",()=>{let e=getSelection();if(e===null||e.rangeCount===0)return;let t=e.anchorNode,n=(t instanceof Element?t:t?.parentElement)?.closest(".tb-rich-box");n!=null&&bl.set(n,e.getRangeAt(0).cloneRange())}))}g("insert-at-caret",'["The value of a field, area or rich text with text put where its cursor was; the cursor goes after it." face [object!] text [string!]]',(e,t)=>{let n=t.args[0],r=B(t.args[1]),o=Pe(n,"style")==="rich",a=R(n,"value")??"",i=cn.get(n.ctx);if(i===void 0||!i.el.isConnected)return b(j(o?Du(a,r):a+r));if(o){let f=i.box,p=bl.get(f);f.focus();let h=getSelection();p!==void 0&&f.contains(p.commonAncestorContainer)?(h.removeAllRanges(),h.addRange(p)):(h.selectAllChildren(f),h.collapseToEnd()),nl=!0;try{document.execCommand("insertText",!1,r)}finally{nl=!1}let v=ha(pl(f));return i.shown=v,b(j(v))}let l=i.input,c=l.value.length,[u,d]=of.has(l)?[l.selectionStart??c,l.selectionEnd??c]:[c,c];return l.focus(),l.setRangeText(r,u,d,"end"),b(j(l.value))});function Co(e){let t=$(e,"columns");if(t.t!==s.Block)return[];let n=[],r=t.s.data;for(let o=t.i;o+1<r.length;o+=2){let a=r[o];if(a.t!==s.Word)continue;let i=r[o+1],l=i.t===s.Block?i.s.data.slice(i.i):[i],c=u=>l.some(d=>d.t===s.Word&&I(d.sym)===I(A(u)));n.push({sym:a.sym,word:a,label:Ce(l[0]??k,K.rt),image:c("image"),round:c("round")})}return n}function vd(e,t,n){let r=t.t===s.String||t.t===s.Url||t.t===s.File?D(t):"",o=e.querySelector(":scope > .tb-thumb"),a=o;(r===""?a?.tagName!=="SPAN":a?.tagName!=="IMG")&&(a=m(r===""?"span":"img","tb-thumb"),r!==""&&(a.alt=""),o!==null?o.replaceWith(a):e.prepend(a)),r!==""&&a.getAttribute("src")!==r&&(a.src=r),a.classList.toggle("tb-round",n)}function af(e,t){return e.t===s.Map&&t.t===s.Map?e.s===t.s:e.t===s.Object&&t.t===s.Object?e.ctx===t.ctx:!1}function $r(e){return e.t===s.None?"":e.t===s.Logic?de(e.v?"yes":"no"):Tr(e)}var lg=new Set([s.Integer,s.Decimal,s.Money,s.Percent]);function cg(e,t,n){let r=m("div",t==="table"?"tb-table-wrap":"tb-list-wrap"),o;if(t==="table"){let l=m("table","tb-table");l.setAttribute("role","table");let c=m("thead"),u=m("tr");u.setAttribute("role","row");let d=Co(e);for(let v of d){let y=m("th");y.scope="col",y.setAttribute("role","columnheader"),u.append(y)}c.append(u),c.addEventListener("click",v=>{let y=v.target.closest("th"),C=y!==null&&y.querySelector(".tb-sort")!==null?d[y.cellIndex]:void 0;C!==void 0&&F("ui-sort",e,C.word)}),o=m("tbody");let f=m("tfoot"),p=ol(d);p.className="tb-totals",f.append(p);let h=()=>{let v=m("tbody","tb-room");v.setAttribute("aria-hidden","true");let y=m("tr");return y.append(m("td")),v.append(y),v};l.append(c,h(),o,h(),f),r.append(l)}else o=m("ul","tb-list"),r.append(o);let a=m("p","tb-empty");r.append(a);let i=l=>{let c=l?.closest(t==="table"?"tr":"li"),u=c?ln.get(c):void 0;u!==void 0&&F("ui-select",e,u)};return o.addEventListener("click",l=>i(l.target)),o.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),i(l.target))}),n.box=o,n.rows=new Map,n.empty=a,r}function ug(e){let t=e.face,n=$(t,"data"),r=n.t===s.Block?n.s.data.slice(n.i):[];if(e.box.tagName==="TBODY"){dg(t,e.box.parentElement,Co(t));let l=cf(t);l!==null&&(r=Fu(r,l.sym,l.desc,lt(K.rt),$r))}let o=$(t,"key"),a=o.t===s.Word||o.t===s.LitWord?o.sym:A("id"),i=new Set;e.items=r.map((l,c)=>{let u=ga(l),d;if(u!==null)d=`${u.kind}#${c}`;else{let f=at(l,a);d=f.t===s.None?`#${c}`:`${f.t}:${D(f)}`,i.has(d)&&(d=`${d}#${c}`)}return i.add(d),{row:l,k:d}}),Ha(e),e.empty.textContent=R(t,"text")??de("empty"),e.empty.hidden=r.length>0}var Lr=new Set,sf=!1;function rl(e){let t=e.items.length;if(t<=Mi||sf)return{first:0,end:t};let n=e.box.getBoundingClientRect().top-e.first*e.rowHeight,r=e.end>e.first?{first:e.first,end:e.end}:void 0;return Hu(t,e.rowHeight||48,-n,innerHeight,r)}function Ha(e,t=!0){let n=e.face,r=e.box,o=r.tagName==="TBODY",a=Co(n),i=$(n,"selected"),l=sn(n,"on-select");r.parentElement.classList.toggle("tb-selectable",l);let{first:c,end:u}=rl(e),d=e.items.length,f=e.rows,p=new Map,h=r.firstChild;for(let C=c;C<u;C++){let{row:x,k:w}=e.items[C],E=ga(x),S=f.get(w);if(E!==null)if(S===void 0&&(S=E.kind==="head"?fg(a,o):o?ol(a):Cd()),S.className=`tb-group-${E.kind} tb-level-${E.level}`,E.kind==="head"){let T=Ce(E.value,K.rt),V=S.firstElementChild;V.textContent!==T&&(V.textContent=T),o&&(V.colSpan=Math.max(1,a.length))}else al(S,E.value,a,o);else{S===void 0&&(S=o?ol(a):Cd()),ln.set(S,x),al(S,x,a,o),l?S.tabIndex=0:S.removeAttribute("tabindex");let T=i.t!==s.None&&af(i,x);S.classList.toggle("tb-selected",T),l?S.setAttribute("aria-selected",T?"true":"false"):S.removeAttribute("aria-selected")}p.set(w,S),d>u-c?(S.setAttribute(o?"aria-rowindex":"aria-posinset",String(o?C+2:C+1)),o||S.setAttribute("aria-setsize",String(d))):(S.removeAttribute(o?"aria-rowindex":"aria-posinset"),S.removeAttribute("aria-setsize")),S!==h?r.insertBefore(S,h):h=h.nextSibling}for(let[C,x]of f)p.get(C)!==x&&x.remove();if(e.rows=p,e.first=c,e.end=u,o&&(d>u-c?r.parentElement.setAttribute("aria-rowcount",String(d+1)):r.parentElement.removeAttribute("aria-rowcount")),d<=Mi){Lr.delete(e),wd(e,0,0),o&&yd(r.parentElement,!1);return}Lr.add(e),o&&yd(r.parentElement,!0);let v=u-c,y=r.getBoundingClientRect().height-(o?0:parseFloat(r.style.paddingTop||"0")+parseFloat(r.style.paddingBottom||"0"));if(v>0&&y>0&&(e.rowHeight=y/v),wd(e,c*e.rowHeight,(d-u)*e.rowHeight),t){let C=rl(e);(C.first!==c||C.end!==u)&&Ha(e,!1)}}function yd(e,t){let n=Array.from(e.tHead.rows[0].cells);if(!t){e.classList.remove("tb-fixed");for(let a of n)a.style.width="";return}if(e.classList.contains("tb-fixed"))return;let r=n.map(a=>a.getBoundingClientRect().width),o=r.reduce((a,i)=>a+i,0);o!==0&&(n.forEach((a,i)=>{a.style.width=`${r[i]/o*100}%`}),e.classList.add("tb-fixed"))}function wd(e,t,n){let r=e.box;if(r.tagName==="TBODY"){for(let[o,a]of[[r.previousElementSibling,t],[r.nextElementSibling,n]]){let i=o.querySelector("td");i.style.height=`${a}px`,o.hidden=a===0}return}r.style.paddingTop=t>0?`${t}px`:"",r.style.paddingBottom=n>0?`${n}px`:""}var zi=0;function kd(){zi!==0||Lr.size===0||(zi=requestAnimationFrame(()=>{zi=0;for(let e of Lr){if(!e.box.isConnected){Lr.delete(e);continue}let t=rl(e);(t.first!==e.first||t.end!==e.end)&&Ha(e)}}))}function xd(e){sf=e;for(let t of Lr)t.box.isConnected&&(e||(t.end=t.first),Ha(t))}function dg(e,t,n){let r=O(e,"sortable")||sn(e,"on-sort"),o=lf(e),a=t.tHead.rows[0].cells;n.forEach((c,u)=>{let d=a[u];if(d===void 0)return;let f=o!==null&&I(o.sym)===I(c.sym),p=d.querySelector(".tb-sort");r&&p===null?(p=m("button","tb-sort"),p.type="button",p.append(m("span")),d.replaceChildren(p)):!r&&p!==null&&(d.replaceChildren(),p=null);let h=p!==null?p.firstChild:d;if(h.textContent!==c.label&&(h.textContent=c.label),p!==null){let v=f&&o.desc?"arrow-down":"arrow-up",y=p.querySelector("svg");if(y?.dataset.icon!==v){let C=et(v);C!==null&&(C.dataset.icon=v,y?y.replaceWith(C):p.append(C))}p.querySelector("svg")?.classList.toggle("tb-sort-idle",!f)}f?d.setAttribute("aria-sort",o.desc?"descending":"ascending"):d.removeAttribute("aria-sort")});let i=$(e,"totals"),l=t.tFoot;l.hidden=i.t===s.None,i.t!==s.None&&al(l.rows[0],i,n,!0)}function lf(e){let t=$(e,"sorted");if(t.t!==s.Block||t.s.data.length-t.i<2)return null;let n=t.s.data[t.i],r=t.s.data[t.i+1];return n.t!==s.Word&&n.t!==s.LitWord||r.t!==s.Word&&r.t!==s.LitWord?null:{sym:n.sym,desc:I(r.sym)===I(A("desc"))}}function cf(e){return O(e,"sortable")&&!sn(e,"on-sort")?lf(e):null}function fg(e,t){if(!t){let o=m("li");return o.append(m("span")),o}let n=m("tr");n.setAttribute("role","row");let r=m("th");return r.scope="rowgroup",r.setAttribute("role","rowheader"),r.colSpan=Math.max(1,e.length),n.append(r),n}function ol(e){let t=m("tr");t.setAttribute("role","row");for(let n of e){let r=m("td");r.setAttribute("role","cell"),r.dataset.label=n.label,t.append(r)}return t}function Cd(){let e=m("li"),t=m("span","tb-list-texts");return t.append(m("span","tb-list-primary"),m("span","tb-list-secondary")),e.append(t),e}function al(e,t,n,r){let o=(u,d)=>{u.textContent!==d&&(u.textContent=d)};if(r){n.forEach((u,d)=>{let f=at(t,u.sym),p=e.children[d];if(u.image)return p.classList.add("tb-thumb-cell"),vd(p,f,u.round);o(p,$r(f)),p.classList.toggle("tb-num",lg.has(f.t))});return}let a=n.find(u=>u.image);a!==void 0?vd(e,at(t,a.sym),a.round):e.querySelector(":scope > .tb-thumb")?.remove();let[i,...l]=n.filter(u=>!u.image).map(u=>$r(at(t,u.sym))),c=e.querySelector(":scope > .tb-list-texts");o(c.children[0],i??""),o(c.children[1],l.filter(Boolean).join(" \xB7 "))}function sn(e,t){let n=$(e,"events");if(n.t!==s.Block)return!1;let r=I(A(t));return n.s.data.some(o=>o.t===s.Word&&I(o.sym)===r)}var uf=A("children"),Sd=A("expanded");function hl(e){return Array.from(e.box.querySelectorAll('[role="treeitem"]'))}function df(e,t){if(t===e.box)return k;let n=t.closest('[role="treeitem"]');return n!==null?ln.get(n)??k:k}function pg(e,t){let n=m("div","tb-tree-wrap"),r=m("ul","tb-tree");r.setAttribute("role","tree");let o=m("p","tb-empty");return n.append(r,o),r.addEventListener("click",a=>{let i=a.target,l=i.closest('[role="treeitem"]');if(l!==null){if(i.closest(".tb-tree-toggle")!==null)return sl(t,l);ml(t,l),pf(t,l)}}),r.addEventListener("keydown",a=>hg(t,a)),t.box=r,t.rows=new Map,t.empty=o,t.open=new Set,n}function bg(){let e=m("li");e.setAttribute("role","treeitem");let t=m("div","tb-tree-row"),n=m("span","tb-tree-toggle");n.setAttribute("aria-hidden","true");let r=et("chevron-right");r!==null&&n.append(r),t.append(n,m("span","tb-tree-label"));let o=m("ul");return o.setAttribute("role","group"),e.append(t,o),e}function ff(e){let t=e.face,n=Co(t)[0]?.sym??A("name"),r=$(t,"key"),o=r.t===s.Word||r.t===s.LitWord?r.sym:A("id"),a=$(t,"selected"),i=e.rows,l=e.open,c=new Map,u=(h,v,y,C)=>{let x=h.firstChild;for(v.forEach((w,E)=>{let S=at(w,o),T=S.t===s.None?`${C}/${E}`:`${S.t}:${D(S)}`;c.has(T)&&(T=`${C}/${E}#${T}`);let V=i.get(T),J=V??bg();c.set(T,J),ln.set(J,w),J.dataset.key=T,J.setAttribute("aria-level",String(y)),J.style.setProperty("--tb-level",String(y-1));let Ge=$r(at(w,n)),Fe=J.firstElementChild.lastElementChild;Fe.textContent!==Ge&&(Fe.textContent=Ge);let He=at(w,uf),Ue=He.t===s.Block;Ue&&V===void 0&&at(w,Sd).t===s.Logic&&at(w,Sd).v&&l.add(T);let Oe=Ue&&l.has(T);Ue?J.setAttribute("aria-expanded",Oe?"true":"false"):J.removeAttribute("aria-expanded");let W=J.lastElementChild;Oe?u(W,He.s.data.slice(He.i),y+1,T):W.replaceChildren(),W.hidden=W.childElementCount===0;let ue=a.t!==s.None&&af(a,w);J.classList.toggle("tb-selected",ue),J.setAttribute("aria-selected",ue?"true":"false"),J!==x?h.insertBefore(J,x):x=x.nextSibling});x!==null;){let w=x;x=x.nextSibling,w.remove()}},d=$(t,"data");u(e.box,d.t===s.Block?d.s.data.slice(d.i):[],1,""),e.rows=c;let f=hl(e),p=f.find(h=>h.tabIndex===0&&h.hasAttribute("tabindex"))??f.find(h=>h.classList.contains("tb-selected"))??f[0];for(let h of f)h.tabIndex=h===p?0:-1;e.empty.textContent=R(t,"text")??de("empty"),e.empty.hidden=f.length>0}function ml(e,t){for(let n of hl(e))n.tabIndex=n===t?0:-1;t.focus()}function pf(e,t){let n=ln.get(t);n!==void 0&&F("ui-select",e.face,n)}function sl(e,t,n){if(!t.hasAttribute("aria-expanded"))return;let r=t.dataset.key,o=n??!e.open.has(r);if(o===e.open.has(r))return;let a=document.activeElement!==t&&t.contains(document.activeElement);o?e.open.add(r):e.open.delete(r),ff(e),a&&ml(e,t);let i=ln.get(t);o&&i!==void 0&&F("ui-expand",e.face,i)}function hg(e,t){let n=t.target.closest('[role="treeitem"]');if(n===null||t.altKey||t.ctrlKey||t.metaKey)return;let r=hl(e),o=r.indexOf(n),a=n.getAttribute("aria-expanded"),i=null;switch(t.key){case"ArrowDown":i=r[o+1];break;case"ArrowUp":i=r[o-1];break;case"Home":i=r[0];break;case"End":i=r[r.length-1];break;case"ArrowRight":a==="false"?sl(e,n,!0):a==="true"&&(i=n.querySelector('[role="treeitem"]'));break;case"ArrowLeft":a==="true"?sl(e,n,!1):i=n.parentElement.closest('[role="treeitem"]');break;case"Enter":case" ":pf(e,n);break;default:{if(t.key.length!==1||t.key.trim()==="")return;let l=t.key.toLowerCase(),c=u=>(u.querySelector(".tb-tree-label")?.textContent??"").toLowerCase();i=[...r.slice(o+1),...r.slice(0,o)].find(u=>c(u).startsWith(l))}}t.preventDefault(),i&&ml(e,i)}function mg(e,t,n,r){let o=document.elementFromPoint(n,r)?.closest('[role="treeitem"]'),a=O(e.face,"drop"),i;if(o==null||!e.box.contains(o))i={m:e,index:Od(e,n,r),reorder:!1,group:e.box,parent:k};else{let l=o.querySelector(":scope > .tb-tree-row").getBoundingClientRect();if(o.hasAttribute("aria-expanded")&&r>l.top+l.height/4&&r<l.bottom-l.height/4){let c=ln.get(o),u=at(c,uf);i={m:e,index:u.s.data.length-u.i,reorder:!1,group:o.lastElementChild,parent:c,into:o}}else{let c=o.parentElement,u=Array.prototype.indexOf.call(c.children,o)+(r>l.top+l.height/2?1:0);i={m:e,index:u,reorder:!1,group:c,parent:df(e,c)}}}return t.el===i.into||t.el.contains(i.group)?null:(i.reorder=t.within===e&&i.group===t.group&&i.into===void 0,i.reorder||a?i:null)}var gg="button, a[href], input, select, textarea, [tabindex]";function Ia(e,t=!0){return Array.from(e.querySelectorAll(gg)).filter(n=>n.closest(".tb-toolbar")===e&&(!t||n.getClientRects().length>0&&!n.disabled))}function vg(){let e=m("div","tb-toolbar");return e.setAttribute("role","toolbar"),e.addEventListener("keydown",t=>{let n=t.target;if(t.altKey||t.ctrlKey||t.metaKey||n.matches("input, select, textarea"))return;let r=Ia(e),o=r.indexOf(n);if(o<0)return;let a=t.key==="ArrowRight"?(o+1)%r.length:t.key==="ArrowLeft"?(o-1+r.length)%r.length:t.key==="Home"?0:t.key==="End"?r.length-1:-1;a<0||(t.preventDefault(),r[a].focus())}),e.addEventListener("focusin",t=>{let n=t.target;if(Ia(e,!1).includes(n))for(let r of Ia(e,!1))r.tabIndex=r===n?0:-1}),e}function yg(e){for(let r of Array.from(e.children)){let o=Mn.get(r);o!==void 0&&o.el===r&&Pe(o.face,"style")==="button"&&Ua(o)}let t=Ia(e,!1),n=t.find(r=>r.tabIndex===0&&r.hasAttribute("tabindex"))??t[0];for(let r of t)r.tabIndex=r===n?0:-1}function wg(e){let t=$(e,"data");if(t.t!==s.Block)return[];let n=[],r=t.s.data.slice(t.i);for(let o=0;o<r.length;o++){let a=r[o];if(a.t!==s.String&&a.t!==s.Map)continue;let i=r[o+1],l=i!==void 0&&(i.t===s.Word||i.t===s.Path)?i:k;l!==k&&o++,n.push({text:Ce(a,K.rt),id:l})}return n}function kg(e){let t=m("nav","tb-breadcrumb");return ho(t,"breadcrumb","aria-label"),e.box=m("ol"),t.append(e.box),t}function xg(e){let t=e.face,n=wg(t),r=n.map(l=>`${l.text}\0${D(l.id)}`).join("");if(e.kids===r)return;e.kids=r;let o=l=>{F("ui-crumb",t,l.id.t===s.Path?{...l.id,t:s.LitPath}:st(s.LitWord,D(l.id)))},a=n.length>3?n.slice(1,-2):[],i=n.map((l,c)=>{let u=m("li");if(a.includes(l)&&(u.className="tb-crumb-middle"),l.id===k){let d=m("span","tb-crumb");d.textContent=l.text,c===n.length-1&&d.setAttribute("aria-current","page"),u.append(d)}else{let d=m("button","tb-crumb");d.type="button",d.textContent=l.text,d.addEventListener("click",()=>o(l)),u.append(d)}return u});if(a.length>0){let l=m("li","tb-crumb-more"),c=m("button","tb-crumb");c.type="button",c.textContent="\u2026",ho(c,"more-levels","aria-label"),c.setAttribute("aria-haspopup","menu"),c.setAttribute("aria-expanded","false"),c.addEventListener("click",()=>{let u=c.getBoundingClientRect();ja(a.map(d=>({text:d.text,run:()=>o(d)})),u.left,u.bottom+4,c)}),l.append(c),i.splice(1,0,l)}e.box.replaceChildren(...i)}function Cg(e,t){let n=m("dialog","tb-dialog"),r=m("header","tb-dialog-head"),o=m("h2","tb-dialog-title");o.id=`tb-${tt++}`,n.setAttribute("aria-labelledby",o.id);let a=m("button","tb-dialog-close");a.type="button",ho(a,"close","aria-label"),a.textContent="\xD7",a.addEventListener("click",()=>{F("ui-close",e)}),r.append(o,a);let i=m("div","tb-dialog-body");return n.append(r,i),n.addEventListener("cancel",l=>{l.preventDefault(),F("ui-close",e)}),t.label=o,t.box=i,n}function bf(e){let t=e.el;e.label.textContent=R(e.face,"text")??"";let n=!O(e.face,"hidden");if(n!==t.open){if(!t.isConnected){queueMicrotask(()=>{t.isConnected&&bf(e)});return}if(!n)return t.close();t.showModal(),queueMicrotask(()=>t.querySelector("input, textarea, select")?.focus())}}function Sg(e,t){let n=m("div","tb-tabs"),r=m("div","tb-tablist");r.setAttribute("role","tablist"),n.append(r);let o=Ln(e),a=i=>{F("ui-input",e,{t:s.Integer,v:i+1}),r.children[i]?.focus()};return o.forEach((i,l)=>{let c=Gn(i),u=m("button","tb-tab");u.type="button",u.id=`tb-${tt++}`,c.id=`${u.id}-panel`,u.setAttribute("role","tab"),u.setAttribute("aria-controls",c.id),c.setAttribute("aria-labelledby",u.id),u.textContent=R(i,"text")??"",u.addEventListener("click",()=>a(l));let d=cn.get(i.ctx);d.button=u,r.append(u),n.append(c)}),r.addEventListener("keydown",i=>{let l=Array.prototype.indexOf.call(r.children,document.activeElement),c=o.length,u=i.key==="ArrowRight"?(l+1)%c:i.key==="ArrowLeft"?(l-1+c)%c:i.key==="Home"?0:i.key==="End"?c-1:-1;u<0||l<0||(i.preventDefault(),a(u))}),t.box=r,n}function Eg(e){let t=$(e.face,"value"),n=Ln(e.face),r=t.t===s.Integer?Math.min(Math.max(Number(t.v),1),n.length)-1:0;n.forEach((o,a)=>{let i=cn.get(o.ctx);if(i===void 0||i.button===null)return;let l=a===r;i.button.setAttribute("aria-selected",l?"true":"false"),i.button.tabIndex=l?0:-1,i.el.hidden=!l})}function Mg(e,t){let n=m("div","tb-split"),[r,o]=Ln(e),a=m("div","tb-split-pane"),i=m("div","tb-split-pane");a.tabIndex=i.tabIndex=-1;let l=m("div","tb-split-handle");l.tabIndex=0,l.setAttribute("role","separator"),l.setAttribute("aria-orientation","vertical"),ho(l,"resize-panes","aria-label"),l.setAttribute("aria-valuemin","20"),l.setAttribute("aria-valuemax","80");let c=p=>{let h=Math.round(Math.min(80,Math.max(20,p)));n.style.setProperty("--tb-split",`${h}%`),l.setAttribute("aria-valuenow",String(h))};c(40),l.addEventListener("pointerdown",p=>{l.setPointerCapture(p.pointerId),p.preventDefault()}),l.addEventListener("pointermove",p=>{if(!l.hasPointerCapture(p.pointerId))return;let h=n.getBoundingClientRect();c((p.clientX-h.left)/h.width*100)}),l.addEventListener("keydown",p=>{let h=Number(l.getAttribute("aria-valuenow")),v=p.key==="ArrowLeft"?h-5:p.key==="ArrowRight"?h+5:p.key==="Home"?20:p.key==="End"?80:null;v!==null&&(p.preventDefault(),c(v))});let u=m("button","tb-button tb-split-back");u.type="button";let d=xi("arrow-left"),f=m("span");return ho(f,"back"),u.append(...d!==null?[d]:[],f),u.addEventListener("click",()=>{F("ui-input",e,{t:s.Integer,v:1})}),r!==void 0&&a.append(Gn(r)),i.append(u),o!==void 0&&i.append(Gn(o)),n.append(a,l,i),n}function Tg(e){let t=$(e.face,"value"),n=t.t===s.Integer&&Number(t.v)===2?"2":"1",r=e.el.dataset.pane;if(r!==n&&(e.el.dataset.pane=n,r!==void 0&&matchMedia("(max-width: 640px)").matches)){let o=e.el.children[n==="2"?2:0];(o.querySelector(".tb-selected")??o).focus()}}var Sr=null;g("show-toast",'["Shows a short message at the edge of the screen." message [string!] kind [word! none!]]',(e,t)=>{Sr===null&&(Sr=m("div","tb-toasts"),Sr.popover="manual",Sr.setAttribute("aria-live","polite"),document.body.append(Sr));let n=t.args[1].t===s.Word?M(t.args[1].sym).toLowerCase():null,r=m("div",n!==null?`tb-toast tb-${n}`:"tb-toast");n==="danger"&&r.setAttribute("role","alert");let o=B(t.args[0]);mt.note("toast",n!==null?`${n}: ${o}`:o);let a=Sr,i=()=>{r.remove(),a.childElementCount===0&&a.matches(":popover-open")&&a.hidePopover()};return r.addEventListener("click",i),setTimeout(i,n==="danger"?6e3:4e3),a.matches(":popover-open")&&a.hidePopover(),a.append(r),a.showPopover(),setTimeout(()=>{r.textContent=o},50),b(t.args[0])});g("show-confirm",'["Asks a question in a small dialog; true when the user says yes." question [string!] yes [string! none!] no [string! none!] kind [word! none!]]',(e,t,n)=>{if(t.phase===1)return b(n);t.phase=1;let r=(p,h)=>t.args[p].t===s.String?B(t.args[p]):de(h),o=t.args[3].t===s.Word&&M(t.args[3].sym).toLowerCase()==="danger",a=m("dialog","tb-dialog tb-confirm");a.setAttribute("role","alertdialog");let i=m("div","tb-dialog-body"),l=m("p","tb-confirm-question");l.id=`tb-${tt++}`,l.textContent=B(t.args[0]),a.setAttribute("aria-labelledby",l.id);let c=m("div","tb-row tb-right"),u=m("button","tb-button"),d=m("button",o?"tb-button tb-danger":"tb-button tb-primary");u.type=d.type="button",u.textContent=r(2,"no"),d.textContent=r(1,"yes"),c.append(u,d),i.append(l,c),a.append(i);let f=new Promise(p=>{let h=v=>{a.close(),a.remove(),p(v?P:we)};d.addEventListener("click",()=>h(!0)),u.addEventListener("click",()=>h(!1)),a.addEventListener("cancel",v=>{v.preventDefault(),h(!1)})});return document.body.append(a),a.showModal(),(o?u:d).focus(),{k:"await",p:f}});g("print-faces",'["Opens the print dialog for the page, or for one face only." face [object! none!]]',(e,t)=>{let n=t.args[0].t===s.Object?cn.get(t.args[0].ctx)?.el:void 0;return t.args[0].t===s.Object&&(n===void 0||!n.isConnected)?Q("script","not-shown","print-page/only needs a face on the screen"):(n!==void 0&&(n.classList.add("tb-print-target"),document.documentElement.classList.add("tb-print-only"),addEventListener("afterprint",()=>{n.classList.remove("tb-print-target"),document.documentElement.classList.remove("tb-print-only")},{once:!0})),print(),b(re))});function Ua(e){let t=e.face,n=Pe(t,"style")??"",r=Pe(t,"role"),o=R(t,"text"),a=O(t,"hidden"),i=R(t,"error"),l=[];a&&n!=="dialog"&&l.push("tb-hidden"),O(t,"fill")&&l.push("tb-fill"),O(t,"narrow-only")&&l.push("tb-narrow-only"),O(t,"wide-only")&&l.push("tb-wide-only"),O(t,"fit")&&l.push("tb-fit"),O(t,"drop")&&l.push("tb-drop-zone"),r!==null&&!Id.has(n)&&l.push(`tb-${r}`);let c=Pe(t,"size");c!==null&&l.push(`tb-${c}`);let u=Pe(t,"align");u!==null&&n==="row"&&l.push(`tb-${u}`);let d=Pe(t,"valign");if(d!==null&&n==="row"&&l.push(`tb-${d}`),i!==null&&l.push("tb-invalid"),O(t,"pending")&&l.push("tb-pending"),Lg(e.el,l),e.el.inert=O(t,"inert"),O(t,"drag")&&!mo(e)&&e.el.tabIndex<0&&(e.el.tabIndex=0),Ed(e.el,"padding",$(t,"pad")),Ed(e.el,"gap",$(t,"gap")),n==="radio")return Xm(e,i);if(n==="upload")return Mm(e,i);if(n==="photo")return km(e,i);if(n==="widget")return Sm(e,i);if(n==="lookup")return Am(e,i);if(n==="rich")return sg(e,i);if(e.input!==null){e.label!==null&&(e.label.textContent=o??"",e.label.classList.toggle("tb-required",At(t)&&n!=="check"));let p=$(t,"value");if(e.input instanceof HTMLInputElement&&e.input.type==="checkbox")e.input.checked=p.t===s.Logic&&p.v;else{e.input instanceof HTMLSelectElement&&e.input.dataset.options!==Td(t)&&Ld(e.input,t);let y=p.t===s.None?R(t,"typed")??"":n==="money"||n==="date"?Tr(p):D(p);!(document.activeElement===e.input&&!O(t,"readonly")&&(e.typing>0||p===e.typed))&&e.input.value!==y&&(e.input.value=y);let x=R(t,"hint");if(e.input instanceof HTMLSelectElement){let w=e.input;w.options[0].textContent=x??de("choose"),Md(t).forEach((S,T)=>{let V=w.options[T+1];V&&(V.textContent=yo(S))});let E=w.querySelectorAll("optgroup");Br(t).filter(Or).forEach((S,T)=>{E[T]&&(E[T].label=Ce(S.title,K.rt))})}else x!==null&&(e.input.placeholder=x)}let h=O(t,"readonly"),v=e.input instanceof HTMLTextAreaElement||e.input instanceof HTMLInputElement&&e.input.type!=="checkbox";if(v&&(e.input.readOnly=h),e.input.disabled=O(t,"disabled")||h&&!v,n==="date"){let y=e.input.nextElementSibling;y.disabled=e.input.disabled||h,y.setAttribute("aria-label",o!==null?de("choose-date-of",o):de("choose-date"))}e.input.setAttribute("aria-required",At(t)?"true":"false"),e.input.setAttribute("aria-invalid",i!==null?"true":"false"),e.error!==null&&(e.error.textContent=i??"");return}switch(n){case"title":case"heading":case"text":{let p=$(t,"text");e.el.textContent=p.t===s.None?"":p.t===s.Map||p.t===s.Word?Ce(p,K.rt):Tr(p);break}case"tile":(e.label??e.el).textContent=o??"";break;case"button":case"link":{(e.label??e.el).textContent=o??"";let p=dm(t);p!==null?e.el.setAttribute("aria-label",p):e.el.removeAttribute("aria-label");let h=R(t,"shortcut");h!==null?e.el.setAttribute("aria-keyshortcuts",im(h)):e.el.removeAttribute("aria-keyshortcuts");let v=e.label!==null&&e.el.parentElement?.classList.contains("tb-toolbar")===!0,y=p??(h!==null||v?o:null);e.el.title=y===null?"":h===null?y:`${y} (${lm(h)})`;break}case"progress":Nm(e);return;case"canvas":Pm(e);return;case"chart":Hm(e);return;case"orbit":qm(e);return;case"icon":Jm(e);return;case"video":case"audio":vm(e);return;case"image":{let p=e.el,h=R(t,"value")??"";p.getAttribute("src")!==h&&(p.src=h),p.alt=o??"",p.classList.toggle("tb-round",O(t,"round"));let v=$(t,"extent");p.style.width=v.t===s.Pair?`${v.x}px`:"",p.style.height=v.t===s.Pair?`${v.y}px`:"";return}case"table":case"list":ug(e);return;case"rows":eg(e,i);break;case"tree":ff(e);return;case"breadcrumb":xg(e);return;case"toolbar":{o!==null?e.el.setAttribute("aria-label",o):e.el.removeAttribute("aria-label");break}case"desktop":case"backdrop":{let p=R(t,"value");e.el.style.backgroundImage=p!==null?`url(${JSON.stringify(p)})`:"";break}case"dialog":bf(e);break;case"tabs":Eg(e);return;case"split":Tg(e);return;case"tab":e.button!==null&&(e.button.textContent=o??"");break;case"panel":{let p=e.el.querySelector(":scope > .tb-panel-title");o===null?p?.remove():(p===null&&(p=m("h2","tb-panel-title"),e.el.prepend(p)),p.textContent=o);break}case"scroll":{o!==null?e.el.setAttribute("aria-label",o):e.el.removeAttribute("aria-label");break}case"grid":{let p=$(t,"cols");e.el.style.setProperty("--tb-cols",p.t===s.Integer?String(p.v):"2");let h=p.t===s.Block?p.s.data.slice(p.i).filter(v=>v.t===s.Integer):[];h.length>0?e.el.style.setProperty("--tb-tracks",h.map(v=>`minmax(min-content, ${D(v)}fr)`).join(" ")):e.el.style.removeProperty("--tb-tracks");break}}n==="toolbar"&&yg(e.el),e.el instanceof HTMLButtonElement&&(O(t,"submit")?e.el.setAttribute("aria-disabled",O(t,"disabled")?"true":"false"):e.el.disabled=O(t,"disabled"));let f=$(t,"pane");if(f.t===s.Block&&e.kids?.s!==f.s){if(e.kids=f,n==="rows"){tg(e),F("ui-pane",t);return}let p=e.box??e.el;if(n==="screens")hf(e,p);else{let h=p.querySelector(":scope > .tb-panel-title");p.replaceChildren(...h?[h]:[]),ul(p,t,n)}F("ui-pane",t)}n==="screens"&&mf(e.box??e.el,t)}function hf(e,t){Kn=m("div"),ul(Kn,e.face,"screens"),mf(t,e.face)}function mf(e,t){let n=O(t,"entering");e.toggleAttribute("aria-busy",n),!(n||Kn===null)&&(e.replaceChildren(...Kn.childNodes),Kn=null,Og(e))}function Ed(e,t,n){n.t===s.Integer?e.style.setProperty(t,`var(--tb-space-${n.v})`):e.style.removeProperty(t)}function Lg(e,t){let n=(e.dataset.tb??"").split(" ").filter(Boolean);for(let r of n)t.includes(r)||e.classList.remove(r);for(let r of t)e.classList.add(r);e.dataset.tb=t.join(" ")}function Ag(){for(let r of uo)!r.el.isConnected&&Kn?.contains(r.el)!==!0&&uo.delete(r);if(Fi!==null||uo.size===0||Ba.length===0&&!Ta)return;Ta=!1;let e=Ye(s.Block,[...uo].map(r=>r.face)),t=lu(K.sch,{data:[{t:s.Word,sym:A("ui-react"),bind:K.rt.user},e]},0),n=r=>{if(!(r.state!=="done"||r.result.t!==s.Block))for(let o of r.result.s.data)console.warn(`Trebol: ${B(o)}`),mt.note("warning",B(o))};t.state==="done"?n(t):t.state!=="failed"&&(Fi=t,t.watchers.push(r=>{Fi=null,Ta=!0,n(r)}))}function gf(){for(let e of Ba){e.dirty=!1;let t=cn.get(e);t!==void 0&&(t.el.isConnected||Kn?.contains(t.el))&&Ua(t)}Ba.length=0}var vo=null,Kn=null,lo=null;function Ig(){let e=location.hash.replace(/^#\/?/,"");return e===""?[]:e.split("/").map(t=>{try{return decodeURIComponent(t)}catch{return t}})}function vf(){return Ye(s.Block,Ig().map(e=>j(e)))}function bo(e){let t=n=>encodeURIComponent(n.t===s.String?B(n):n.t===s.Word?M(n.sym):D(n));return e.t===s.Word?"#/"+t(e):e.t===s.Path?"#/"+e.s.data.slice(e.i).map(t).join("/"):null}g("route",'["The screen and arguments in the address bar." ]',()=>b(vf()));var Se={depth:0,top:0};function $g(){let e=history.state;typeof e?.depth=="number"&&(Se={depth:e.depth,top:e.top??e.depth}),history.replaceState({...Se},"")}var il={depth:0,top:0},$a=null;function Bg(){let e=history.state;il={...Se},typeof e?.depth=="number"?Se={depth:e.depth,top:Se.top}:Se={depth:Se.depth+1,top:Se.depth+1},history.replaceState({...Se},"")}g("set-route",'["Puts a screen and arguments in the address bar." route [block!] replace [logic!]]',(e,t)=>{let n=bo({...t.args[0],t:s.Path})??"#/";return t.args[1].t===s.Logic&&t.args[1].v?(history.replaceState({...Se},"",n),b(t.args[0])):(Se={depth:Se.depth+1,top:Se.depth+1},history.pushState({...Se},"",n),b(t.args[0]))});g("route-undo",'["Puts back the link the page had before the last change." ]',()=>{let e=il.depth-Se.depth;return e===0?b(k):($a=il,history.go(e),b(k))});var yf=!1;g("set-unsaved",'["Whether the browser asks before closing the page." on [logic!]]',(e,t)=>(yf=t.args[0].t===s.Logic&&t.args[0].v,b(t.args[0])));g("route-steps",'["How many steps back and forward the history has." ]',()=>b(Ye(s.Block,[Ut(Se.depth),Ut(Se.top-Se.depth)])));g("route-back",'["Goes one step back in the history." ]',()=>Se.depth===0?b(ee(!1)):(history.back(),b(ee(!0))));g("route-forward",'["Goes one step forward in the history." ]',()=>Se.depth>=Se.top?b(ee(!1)):(history.forward(),b(ee(!0))));function Og(e){let t=e.firstElementChild;if(t===null)return;let r=t.querySelector("h1, h2")??t;r.tabIndex<0&&(r.tabIndex=-1),r.focus({preventScroll:!0}),window.scrollTo(0,0),lo===null&&(lo=m("div","tb-sr-only"),lo.setAttribute("aria-live","polite"),document.body.append(lo));let o=lo;o.textContent="",setTimeout(()=>{o.textContent=t.getAttribute("aria-label")??""},50)}g("repaint",'["Redraws the faces that changed." ]',()=>{document.documentElement.lang=lt(K.rt),Wa!==null&&(document.title=R(Wa,"text")??document.title);for(let e of Array.from(document.querySelectorAll("[data-tb-own]")))Ad(e);for(let e of Array.from(document.querySelectorAll("*"))){let t=Mn.get(e);t!==void 0&&t.el===e&&Ua(t)}return b(k)});var _i=null,Wa=null;g("show",'["Draws a face and everything in it." face [object!]]',(e,t)=>{let n=t.args[0];Oa=null,vo=null,document.documentElement.lang=lt(K.rt);let r=Gn(n);_i!==null?_i.replaceWith(r):document.body.append(r),_i=r;let o=Ln(n).find(a=>Pe(a,"style")==="title");return o!==void 0&&vo===null&&(document.title=R(o,"text")??document.title,Wa=o),b(n)});function Ng(e){let t=Pe(e,"look"),n={...wi,...t!==null?ki[t]:void 0},r=l=>{let c=$(e,l);return c.t===s.Integer?Number(c.v):c.t===s.Decimal?c.v:null};n.base=r("base")??n.base;let o=r("accent");n.accent=o??(t!==null&&r("base")===null&&t in ki?n.accent:(n.base+180)%360),n.color=Math.min(1,Math.max(0,r("color")??n.color)),(r("line")===2||r("line")===1)&&(n.line=r("line"));for(let[l,c]of Object.entries(Au)){let u=Pe(e,l);u!==null&&c.includes(u)&&(n[l]=u)}let a=$(e,"font");a.t===s.Word?n.font=M(a.sym).toLowerCase():a.t===s.String&&(n.font=B(a));let i=$(e,"headings");return i.t===s.Word?n.headings=M(i.sym).toLowerCase():i.t===s.String&&(n.headings=B(i)),n}function wf(e){let t=document.getElementById("tb-theme");t===null&&(t=m("style"),t.id="tb-theme",document.head.append(t)),t.textContent=$u(e)}g("apply-theme",'["Changes the look of the whole screen." spec [object!]]',(e,t)=>(wf(Ng(t.args[0])),b(t.args[0])));async function jg(){let e=document.getElementById("trebol-files");if(e!==null)for(let[n,r]of Object.entries(JSON.parse(e.textContent??"{}")))pr(new URL(n,location.href).href,r);if(document.querySelector("style[data-tb-fonts]")===null){let n=m("style");n.dataset.tbFonts="",n.textContent=Nu(r=>new URL(`fonts/${r}`,import.meta.url).href),document.head.append(n)}wf(wi),K=xu({onError:n=>qi(Hn(n))}),K.sch.afterPump=()=>{Ag(),gf(),mt.repainted()},document.addEventListener("keydown",cm,!0),document.addEventListener("keydown",Xh),document.addEventListener("scroll",kd,{capture:!0,passive:!0}),addEventListener("resize",kd),addEventListener("beforeunload",n=>{yf&&n.preventDefault()}),addEventListener("beforeprint",()=>xd(!0)),addEventListener("afterprint",()=>xd(!1)),document.addEventListener("pointerdown",Zh),document.addEventListener("pointermove",Jh,{passive:!1}),document.addEventListener("pointerup",()=>La(!0)),document.addEventListener("pointercancel",()=>La(!1)),document.addEventListener("keydown",n=>{n.key==="Escape"&&En?.on&&(n.preventDefault(),Tn.add(n),La(!1))},!0),document.addEventListener("touchmove",n=>{En?.on&&n.preventDefault()},{passive:!1}),document.addEventListener("keydown",um);let t=document.querySelector('meta[name="trebol-dev"]');t!==null&&sd({host:K,root:t.getAttribute("content"),faceOf:n=>{let r=Mn.get(n);return r!==void 0&&r.el===n?r.face:null},faceAt:n=>{let r=go(n);return r===void 0?null:{face:r.face,el:r.el}},nodeOf:n=>{let r=cn.get(n.ctx)?.el;return r?.isConnected===!0?r:null}}),$g(),window.addEventListener("hashchange",()=>{if($a!==null){Se=$a,$a=null,history.replaceState({...Se},"");return}Bg(),vo!==null&&F("ui-route",vo,vf())}),await Cu(K);for(let n of Array.from(document.querySelectorAll('script[type="text/trebol"]'))){let r=n.getAttribute("src"),o=r!==null?new URL(r,location.href).href:location.href,a=r!==null?ru(o)??await(await fetch(o)).text():n.textContent??"";try{await vi(K,a,o)}catch(i){qi(i instanceof Error?i.message:Hn(i))}}}jg();