millirec 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +171 -58
  3. package/dist/char-cnn/cnn-web.wasm +0 -0
  4. package/dist/char-cnn/core.d.ts +3 -1
  5. package/dist/char-cnn/core.js +145 -99
  6. package/dist/char-cnn/index.d.ts +1 -1
  7. package/dist/char-cnn/index.js +198 -136
  8. package/dist/char-cnn/millirec-char-cnn-core.min.js +1 -1
  9. package/dist/char-cnn/millirec-char-cnn.min.js +1 -1
  10. package/dist/char-cnn/options/accurate/tiny.head.bin +0 -0
  11. package/dist/char-cnn/options/accurate.js +2 -2
  12. package/dist/char-cnn/options/accurate.json +1 -1
  13. package/dist/char-cnn/options/all/all-base.head.bin +0 -0
  14. package/dist/char-cnn/options/all/all-base.q4.bin +0 -0
  15. package/dist/char-cnn/options/all/all-tiny.bin +0 -0
  16. package/dist/char-cnn/options/all/all-tiny.head.bin +0 -0
  17. package/dist/char-cnn/options/all-fast/all-base-p25.bin +0 -0
  18. package/dist/char-cnn/options/all-fast/all-base-p25.head.bin +0 -0
  19. package/dist/char-cnn/options/all-fast/all-tiny.bin +0 -0
  20. package/dist/char-cnn/options/all-fast/all-tiny.head.bin +0 -0
  21. package/dist/char-cnn/options/all-fast.js +17 -0
  22. package/dist/char-cnn/options/all-fast.json +15 -0
  23. package/dist/char-cnn/options/all-small/all-tiny-qat4.head.bin +0 -0
  24. package/dist/char-cnn/options/all-small/all-tiny-qat4.q4.bin +0 -0
  25. package/dist/char-cnn/options/all-small.js +11 -0
  26. package/dist/char-cnn/options/all-small.json +9 -0
  27. package/dist/char-cnn/options/all.js +17 -0
  28. package/dist/char-cnn/options/all.json +15 -0
  29. package/dist/char-cnn/options/digits/digits-base.head.bin +0 -0
  30. package/dist/char-cnn/options/digits/digits-tiny.head.bin +0 -0
  31. package/dist/char-cnn/options/digits-fast/digits-base-p25.bin +0 -0
  32. package/dist/char-cnn/options/digits-fast/digits-base-p25.head.bin +0 -0
  33. package/dist/char-cnn/options/digits-fast/digits-tiny.bin +0 -0
  34. package/dist/char-cnn/options/digits-fast/digits-tiny.head.bin +0 -0
  35. package/dist/char-cnn/options/digits-fast.js +17 -0
  36. package/dist/char-cnn/options/digits-fast.json +15 -0
  37. package/dist/char-cnn/options/digits-small/digits-tiny-qat4.head.bin +0 -0
  38. package/dist/char-cnn/options/digits-small/digits-tiny-qat4.q4.bin +0 -0
  39. package/dist/char-cnn/options/digits-small.js +11 -0
  40. package/dist/char-cnn/options/digits-small.json +9 -0
  41. package/dist/char-cnn/options/digits.js +2 -2
  42. package/dist/char-cnn/options/digits.json +1 -1
  43. package/dist/char-cnn/options/fast/base-p25.head.bin +0 -0
  44. package/dist/char-cnn/options/fast/tiny.head.bin +0 -0
  45. package/dist/char-cnn/options/fast.js +2 -2
  46. package/dist/char-cnn/options/fast.json +1 -1
  47. package/dist/char-cnn/options/lowercase/lowercase-tiny.head.bin +0 -0
  48. package/dist/char-cnn/options/lowercase-fast/lowercase-base-p25.bin +0 -0
  49. package/dist/char-cnn/options/lowercase-fast/lowercase-base-p25.head.bin +0 -0
  50. package/dist/char-cnn/options/lowercase-fast/lowercase-tiny.bin +0 -0
  51. package/dist/char-cnn/options/lowercase-fast/lowercase-tiny.head.bin +0 -0
  52. package/dist/char-cnn/options/lowercase-fast.js +17 -0
  53. package/dist/char-cnn/options/lowercase-fast.json +15 -0
  54. package/dist/char-cnn/options/lowercase-small/lowercase-tiny-qat4.head.bin +0 -0
  55. package/dist/char-cnn/options/lowercase-small/lowercase-tiny-qat4.q4.bin +0 -0
  56. package/dist/char-cnn/options/lowercase-small.js +11 -0
  57. package/dist/char-cnn/options/lowercase-small.json +9 -0
  58. package/dist/char-cnn/options/lowercase.js +2 -2
  59. package/dist/char-cnn/options/lowercase.json +1 -1
  60. package/dist/char-cnn/options/small/tiny.head.bin +0 -0
  61. package/dist/char-cnn/options/small/tiny.q4.bin +0 -0
  62. package/dist/char-cnn/options/small.js +2 -2
  63. package/dist/char-cnn/options/small.json +1 -1
  64. package/dist/char-lite/core.d.ts +1 -0
  65. package/dist/char-lite/core.js +628 -0
  66. package/dist/char-lite/index.d.ts +28 -8
  67. package/dist/char-lite/index.js +845 -717
  68. package/dist/char-lite/millirec-char-lite.min.js +1 -1
  69. package/dist/char-lite/sets.json +17 -17
  70. package/dist/index.d.ts +35 -0
  71. package/dist/index.js +88 -0
  72. package/dist/overlap/millirec-overlap.min.js +7 -7
  73. package/dist/pad/index.d.ts +8 -0
  74. package/dist/pad/index.js +482 -0
  75. package/package.json +21 -7
  76. package/dist/char-cnn/options/small/tiny.bin +0 -0
@@ -1 +1 @@
1
- "use strict";(()=>{var ct={image:{margin:.6884,mag:.6846,bias:-1.0768},imageGeom:{margin:.6925,mag:1.0731,bias:-2.4927}};function ht(r,t,{margin:e,mag:s,bias:n}){return r<1e-9?.99:1/(1+Math.exp(-(e*Math.log(Math.max(t,1e-9)/r)-s*Math.log(r)-n)))}function tt(r,t,e,s=1e3){let n=[];for(let u=0;u<3;u++)n.push(t[r[2*u]]);let a=ct[e];if(a){let u=[r[1],r[3],r[5]],l=u.map((h,d)=>{let m=1/0;for(let p=0;p<3;p++)p!==d&&(m=Math.min(m,u[p]));return ht(h,m,a)});return{chars:n,probs:l}}let o=Math.max(r[1],s/1e3),c=Math.exp(-1*s/o);for(let u=0;u<3;u++)c+=Math.exp(-1*r[2*u+1]/o);let i=[];for(let u=0;u<3;u++)i.push(Math.exp(-1*r[2*u+1]/o)/c);return{chars:n,probs:i}}function q(r){let t=[],e=0,s=0;for(let n=0;n<r.x.length;n++)e+=r.x[n],s+=r.y[n],t.push({x:e,y:s});return t}function et(r){let t=[],e=[],s=[0,0];for(let n=0;n<r.length;n++){let a=Math.round(r[n].x),o=Math.round(r[n].y);t.push(n===0?a:a-s[0]),e.push(n===0?o:o-s[1]),s=[a,o]}return{x:t,y:e}}function G(r){let t=r.length,e=[0,0],s=[0,0],n=[];for(let l=0;l<t;l++){let h=r[l];e[0]+=h.x,e[1]+=h.y;let d={x:h.x,y:h.y,a:1.570795};l>0&&h.x!==s[0]&&(d.a=Math.atan2(h.y-s[1],h.x-s[0])),d.s=Math.sin(d.a),d.c=Math.cos(d.a),l===1&&(n[0].s=d.s,n[0].c=d.c),s=[h.x,h.y],n.push(d)}e[0]/=t,e[1]/=t;let a=[0,0],o=[0,0],c=[0,0],i=[0,0];for(let l of n)l.x<e[0]?(c[0]+=l.x-e[0],c[1]++):(i[0]+=l.x-e[0],i[1]++),l.y<e[1]?(a[0]+=l.y-e[1],a[1]++):(o[0]+=l.y-e[1],o[1]++),l.x-=e[0],l.y-=e[1];a[1]>0&&(a[0]/=a[1]),o[1]>0&&(o[0]/=o[1]),c[1]>0&&(c[0]/=c[1]),i[1]>0&&(i[0]/=i[1]);let u=o[0]-a[0]<i[0]-c[0]?100/(i[0]-c[0]):a[0]<o[0]?100/(o[0]-a[0]):1;return{points:n,scale:u}}function N(r,t=50){let e=[],s=0;for(let o of r)for(let c=1;c<o.length;c++){let i=o[c].x-o[c-1].x,u=o[c].y-o[c-1].y,l=Math.sqrt(i*i+u*u);e.push({ax:o[c-1].x,ay:o[c-1].y,bx:o[c].x,by:o[c].y,cumStart:s,cumEnd:s+l}),s+=l}if(!s||!e.length)return null;let n=[],a=0;for(let o=0;o<t;o++){let c=o*s/(t-1);for(;a<e.length-1&&e[a].cumEnd<c;)a++;let i=e[a],u=i.cumEnd-i.cumStart,l=u?Math.min(1,Math.max(0,(c-i.cumStart)/u)):0;n.push({x:i.ax+(i.bx-i.ax)*l,y:i.ay+(i.by-i.ay)*l})}return n}function V(r){return et(r)}var ft=r=>Array.isArray(r),ut=r=>ft(r)?r.every(t=>typeof t?.x=="number"&&typeof t?.y=="number"):Array.isArray(r?.x)&&Array.isArray(r?.y)&&r.x.length===r.y.length;function pt(r){return!!r&&typeof r=="object"&&!r.version&&!r.classes&&Object.values(r).every(Array.isArray)}function yt(r,{mode:t="both"}={}){let e={};for(let[s,n]of Object.entries(r))e[s]={samples:n,geometry:null};return{version:2,mode:t,pointsPerShape:50,classes:e,ext:{}}}function dt(r){let t=[];if(!r||typeof r!="object")return["not an object"];if((typeof r.version!="number"||r.version<2)&&t.push("bad version"),!r.classes||typeof r.classes!="object"||!Object.keys(r.classes).length)return t.push("no classes"),t;for(let[e,s]of Object.entries(r.classes)){if(!Array.isArray(s?.samples)||!s.samples.length){t.push(`class ${e}: no samples`);continue}s.samples.forEach((a,o)=>{ut(a)||t.push(`class ${e} sample ${o}: bad shape`)});let n=s.geometry;n!=null&&typeof n!="object"&&t.push(`class ${e}: bad geometry`)}return r.wordList!=null&&!Array.isArray(r.wordList)&&t.push("bad wordList"),r.params!=null&&typeof r.params!="object"&&t.push("bad params"),t}function J(r){let t=pt(r)?yt(r):r,e=dt(t);if(e.length)throw new Error("invalid training data: "+e.join("; "));return t.mode||(t.mode="both"),t.pointsPerShape||(t.pointsPerShape=50),t.ext||(t.ext={}),t}function st(r){let t={};for(let[e,s]of Object.entries(r.classes))t[e]=s.samples;return t}var it={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},R=2;function rt(r){return{x0:r.x0-R,y0:r.y0-R,x1:r.x1+R,y1:r.y1+R,w:r.w+2*R,h:r.h+2*R}}function nt(r){let t=1/0,e=1/0,s=-1/0,n=-1/0;for(let a of r){let o=a.x!==void 0?a.x:a[0],c=a.y!==void 0?a.y:a[1];o<t&&(t=o),o>s&&(s=o),c<e&&(e=c),c>n&&(n=c)}return{x0:t,y0:e,x1:s,y1:n,w:s-t,h:n-e}}function ot(r,t){let e=1/0,s=-1/0;for(let i of r)i<e&&(e=i),i>s&&(s=i);let n=(s-e)*t;if(!(n>0))return 0;let a=0,o=r[0],c=0;for(let i of r)a>0?i>o?o=i:i<o-n&&(c++,a=-1,o=i):a<0?i<o?o=i:i>o+n&&(c++,a=1,o=i):i>o+n?(a=1,o=i):i<o-n&&(a=-1,o=i);return c}function mt(r){let t=0,e=0;for(let d of r)t+=d.x,e+=d.y;t/=r.length,e/=r.length;let s=0,n=0,a=0;for(let d of r){let m=d.x-t,p=d.y-e;s+=m*m,n+=m*p,a+=p*p}let o=s+a,c=s*a-n*n,i=o/2+Math.sqrt(Math.max(0,o*o/4-c)),u=n,l=i-s;Math.hypot(u,l)<1e-9&&(u=1,l=0);let h=Math.hypot(u,l);return{ux:u/h,uy:l/h}}var gt=.09,xt=4;function wt(r,t){let e=Math.max(2,t*gt),s=e/2,n=[r[0]],a=0;for(let l=1;l<r.length;l++){let h=r[l].x-r[l-1].x,d=r[l].y-r[l-1].y,m=Math.hypot(h,d);if(!(m>0))continue;let p=(s-a)/m;for(;p<=1;)n.push({x:r[l-1].x+h*p,y:r[l-1].y+d*p}),p+=s/m;a=(a+m)%s}if(n.length<8)return 0;let o=Math.round(xt*e/s),c=l=>`${Math.floor(l.x/e)},${Math.floor(l.y/e)}`,i=new Map;n.forEach((l,h)=>{let d=c(l);i.has(d)||i.set(d,[]),i.get(d).push(h)});let u=0;for(let l=0;l<n.length;l++){let h=n[l],d=Math.floor(h.x/e),m=Math.floor(h.y/e),p=!1;for(let b=-1;b<=1&&!p;b++)for(let y=-1;y<=1&&!p;y++)for(let g of i.get(`${d+b},${m+y}`)||[])if(!(Math.abs(l-g)<=o)&&Math.hypot(n[g].x-h.x,n[g].y-h.y)<=e){p=!0;break}p&&u++}return u/n.length}function bt(r,t=[],e={}){let s={...it,...e},n=[];for(let y of r){let g={x:y.x!==void 0?y.x:y[0],y:y.y!==void 0?y.y:y[1]},A=n[n.length-1];(!A||Math.hypot(g.x-A.x,g.y-A.y)>.75)&&n.push(g)}if(n.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let a=0;for(let y=1;y<n.length;y++)a+=Math.hypot(n[y].x-n[y-1].x,n[y].y-n[y-1].y);let o=nt(n),c=Math.hypot(o.w,o.h),{ux:i,uy:u}=mt(n),l=n.map(y=>y.x*i+y.y*u),h=n.map(y=>-y.x*u+y.y*i),d=ot(l,s.deadband),m=ot(h,s.deadband),p=0,b=[];for(let y of t)for(let g of y)b.push(g);if(b.length){let y=rt(nt(b)),g=rt(o),A=Math.max(0,Math.min(y.x1,g.x1)-Math.max(y.x0,g.x0)),P=Math.max(0,Math.min(y.y1,g.y1)-Math.max(y.y0,g.y0));p=A/Math.min(y.w,g.w)*(P/Math.min(y.h,g.h))}return{turns:d,cross:m,retrace:wt(n,c),winding:c>0?a/c:0,cover:p,length:a,span:c}}function at(r,t=[],e={}){let s={...it,...e};if(!t||!t.length)return!1;let n=bt(r,t,s);return n.length>=s.minLength&&n.span>=s.minSpan&&n.turns>=s.turns&&n.retrace>=s.retrace&&n.winding>=s.winding&&n.cover>=s.cover}var Mt=12,O=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function X({width:r=160,height:t=90,ink:e="#111827",onStrokeEnd:s,colorOf:n=null,idleOverwrite:a=0,scribbleClear:o=!1,scribble:c=null,onClear:i=null,staleAlpha:u=.3,onStale:l=null}){let h=document.createElement("canvas"),d=typeof devicePixelRatio<"u"&&devicePixelRatio||1;h.width=r*d,h.height=t*d,h.style.width=r+"px",h.style.height=t+"px",h.style.touchAction="none";let m=h.getContext("2d");m.scale(d,d);let p=[],b=[],y=null,g=!1,A=1,P=0,E=0,I=!1,k=null,C=!1;function z(f,x){if(!(f.length<2)){m.strokeStyle=x||e,m.beginPath(),m.moveTo(f[0].x,f[0].y);for(let w=1;w<f.length;w++)m.lineTo(f[w].x,f[w].y);m.stroke()}}function M(){m.clearRect(0,0,r,t),m.lineWidth=2.5,m.lineCap="round",m.lineJoin="round",m.globalAlpha=I?u:1;for(let f of p)z(f,n&&n(f));m.globalAlpha=1,z(b,null)}function L(f){I!==f&&(I=f,M(),l&&l(f))}function _(){clearTimeout(E),E=0;let f=(Number(a)||0)*1e3;if(!f||!p.length){L(!1);return}let x=f-(O()-P);if(x<=0){L(!0);return}L(!1),E=setTimeout(()=>L(!0),x)}function Q(f){p.length&&(k=p,p=[],clearTimeout(E),E=0,L(!1),M(),i&&i(f))}function Z(f,x){let w=p.filter(v=>!v.some(S=>Math.hypot(S.x-f,S.y-x)<=Mt));return w.length===p.length?!1:(p=w,M(),!0)}let T=null,B=f=>{let x=T||(T=h.getBoundingClientRect()),w=r/(h.clientWidth||r),v=t/(h.clientHeight||t);return{x:(f.clientX-x.left-h.clientLeft)*w,y:(f.clientY-x.top-h.clientTop)*v,p:f.pressure||.5}},U=!1,j=null,D=f=>f.preventDefault();h.addEventListener("touchstart",D,{passive:!1}),h.addEventListener("touchmove",D,{passive:!1}),h.addEventListener("contextmenu",D),h.style.userSelect=h.style.webkitUserSelect="none",h.style.webkitTouchCallout="none",h.addEventListener("pointerdown",f=>{if(f.button>0)return;if(y!==null&&y!==f.pointerId){if(j==="pen"&&f.pointerType!=="pen")return;W({pointerId:y})}f.preventDefault(),y=f.pointerId,j=f.pointerType,T=h.getBoundingClientRect();try{h.setPointerCapture(f.pointerId)}catch{}let x=B(f);if(g){U=Z(x.x,x.y);return}I&&p.length&&(Q("idle"),C=!0),b=[x],M()},{passive:!1}),h.addEventListener("pointermove",f=>{if(y!==f.pointerId)return;f.preventDefault();let x=f.getCoalescedEvents?f.getCoalescedEvents():null,w=x&&x.length?x:[f];if(g){for(let v of w){let S=B(v);Z(S.x,S.y)&&(U=!0)}return}for(let v of w)b.push(B(v));M()},{passive:!1});let W=(f,x=!1)=>{if(y===f.pointerId){try{h.releasePointerCapture(f.pointerId)}catch{}if(y=null,j=null,T=null,g){U&&(P=O(),_(),s&&s(p)),U=!1;return}if(b.length>0){let w=b;if(w.length===1){if(x){b=[],M(),C&&(C=!1,s&&s(p));return}let S=w[0];w=[{x:S.x-1,y:S.y,p:S.p},{x:S.x+1,y:S.y,p:S.p}]}let v=p.length?p:C?k:null;if(o&&v&&v.length&&at(w,v,c||{})){b=[],P=O(),C=!1,p.length?Q("scribble"):(M(),i&&i("scribble")),s&&s(p);return}w.id=A++,p=[...p,w],b=[],C=!1,P=O(),_(),s&&s(p)}M()}};return h.addEventListener("pointerup",f=>W(f)),h.addEventListener("pointercancel",f=>W(f,!0)),{el:h,getStrokes:()=>p,setInk(f){e=f,M()},setErasing(f){g=!!f,h.style.cursor=g?"cell":"crosshair"},isErasing:()=>g,repaint:M,isStale:()=>I,undoClear(){return!k||!k.length?!1:(p=p.length?[...k,...p]:k,k=null,P=O(),_(),M(),s&&s(p),!0)},configure(f={}){"idleOverwrite"in f&&(a=Number(f.idleOverwrite)||0),"scribbleClear"in f&&(o=!!f.scribbleClear),"scribble"in f&&(c=f.scribble),"staleAlpha"in f&&(u=Number(f.staleAlpha)),_()},clear(){p=[],b=[],y=null,j=null,T=null,clearTimeout(E),E=0,L(!1),C=!1,M(),s&&s(p)}}}function lt(r){let t=r?String(r):"";return t?(t.endsWith("/")||(t+="/"),typeof location<"u"?new URL(t,location.href).href:t):typeof location<"u"?new URL("./",location.href).href:""}var K=(r,t,e,s)=>new Error(`millirec: ${r} is not ${t} \u2014 the package files are not served at ${e}; copy node_modules/millirec/dist/${s}/ and pass assetBase (see README "Serving the files")`);function St(){let r=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return r?r.slice(0,r.lastIndexOf("/")+1):""}var vt=St(),At=256,Y=class{constructor({assetBase:t,workerName:e,training:s,params:n}){t=lt(t);let a=J(s);this.trainPaths=st(a),this.charList=Object.keys(this.trainPaths),this.samplesPerChar=Math.max(1,...this.charList.map(i=>this.trainPaths[i].length)),this.pointsPerShape=a.pointsPerShape||50,this.params=n||a.params||null,this.plugins=[],this.cache=new Map,this.inFlight=new Map,this.allWaiters=new Map,this.reqCounter=0;let o=`self.__MILLIREC_ASSET_BASE=${JSON.stringify(t)};importScripts(${JSON.stringify(t+e)});`;this.bootUrl=URL.createObjectURL(new Blob([o],{type:"text/javascript"})),this.worker=new Worker(this.bootUrl),this.readyPromise=new Promise((i,u)=>{this.readyResolve=i,this.readyReject=u}),this.worker.onmessage=i=>this.onMessage(i);let c=t+e;this.worker.onerror=i=>{if(this.booted){this.flush();return}let u=K(c,"the char-lite worker",t,"char-lite");u.message+=` (${i.message||"script failed to load"})`,this.failBoot(u)},this.assetBase=t}onMessage(t){let e=t.data;if(this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null),e.type==="getCharList")this.params&&this.worker.postMessage({type:"setParams",params:this.params}),this.worker.postMessage({type:"charList",charList:this.charList,pointsPerShape:this.pointsPerShape,samplesPerChar:this.samplesPerChar});else if(e.type==="prepAll")this.charList.forEach((s,n)=>{this.trainPaths[s].forEach((a,o)=>{let{points:c,scale:i}=G(q(a));this.worker.postMessage({type:"addPoints",points:c,m:n*this.samplesPerChar+o,scale:i})})}),this.booted=!0,this.readyResolve();else if(e.type==="addResult"&&e.result){this.cache.delete(e.path),this.cache.set(e.path,e.result),this.cache.size>At&&this.cache.delete(this.cache.keys().next().value);let s=this.inFlight.get(e.path)||[];this.inFlight.delete(e.path);for(let n of s)n(this.applyPlugins(e.result,e.path))}else if(e.type==="allResult"){let s=this.allWaiters.get(e.path)||[];this.allWaiters.delete(e.path);for(let n of s)n(e.costs)}else if(e.type==="bootError"){let s=K(this.assetBase+"millirec.wasm","the char-lite matcher",this.assetBase,"char-lite");s.message+=` (worker boot failed: ${e.message})`,this.failBoot(s)}}flush(){for(let t of[this.inFlight,this.allWaiters]){let e=[...t.values()];t.clear();for(let s of e)for(let n of s)n(null)}}failBoot(t){this.readyReject(t),this.destroyed=!0;try{this.worker.terminate()}catch{}this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null)}applyPlugins(t,e){let s=tt(t,this.charList,"stroke",1e3);for(let n of this.plugins)n.rerank&&(s=n.rerank(s,{raw:t,path:e,charList:this.charList,mode:"stroke",recognizer:this})||s);return s}uploadTest(t){let e=Array.isArray(t[0])?t:[t],s=N(e,this.pointsPerShape);if(!s)return!1;let{points:n,scale:a}=G(s);return this.worker.postMessage({type:"addPoints",points:n,m:-1,scale:a}),!0}keyFor(t){let e=Array.isArray(t[0])?t.flat():t,s=5381;for(let n of e)s=(s*33^(n.x*7919+n.y|0))>>>0;return"strokes:"+e.length+":"+s.toString(36)}async recognize(t){if(this.destroyed||!t||!t.length||(await this.readyPromise,this.destroyed))return null;let e=this.keyFor(t);if(this.cache.has(e)){let s=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,s),this.applyPlugins(s,e)}return this.uploadTest(t)?new Promise(s=>{let n,a=o=>{clearTimeout(n),s(o)};this.inFlight.has(e)?this.inFlight.get(e).push(a):(this.inFlight.set(e,[a]),this.worker.postMessage({type:"compare",path:e,elementID:"req"+ ++this.reqCounter})),n=setTimeout(()=>{let o=this.inFlight.get(e);if(o){let c=o.indexOf(a);c>=0&&o.splice(c,1),o.length||this.inFlight.delete(e)}a(null)},4e3)}):null}async rawScores(t){if(this.destroyed||(await this.readyPromise,this.destroyed)||!this.uploadTest(t))return null;let e="all:"+ ++this.reqCounter,s=await new Promise(n=>{let a,o=c=>{clearTimeout(a),n(c)};this.allWaiters.set(e,[o]),this.worker.postMessage({type:"compareAll",path:e,counts:this.charList.map(c=>this.trainPaths[c].length)}),a=setTimeout(()=>{this.allWaiters.delete(e),o(null)},8e3)});return s?{classes:this.charList,costs:s}:null}destroy(){this.destroyed||(this.destroyed=!0,this.worker.terminate(),this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null),this.flush(),this.cache.clear(),this.readyResolve())}},Pt=r=>r?r.chars.map((t,e)=>({char:t,prob:r.probs[e]})):null,$=class{static strokesToSample(t,e=50){let s=N(Array.isArray(t[0])?t:[t],e);return s?V(s):null}static withSamples(t,e,{replace:s=!1}={}){let n=J({...t}),a=n.pointsPerShape,o=i=>{let u=Array.isArray(i)?Array.isArray(i[0])?i:[i]:[q(i)],l=N(u,a);return l?V(l):null},c={...n.classes};for(let[i,u]of Object.entries(e||{})){let l=(u||[]).map(o).filter(Boolean);if(!l.length)continue;let h=c[i]?.samples||[];c[i]={...c[i]||{},samples:s?l:h.concat(l)}}return{...n,classes:c}}static createDrawCanvas(t){return X(t)}static async create(t={}){let e=typeof window<"u"?window:globalThis,s={...e.MILLIREC_CONFIG||{},...t},n=t.training||e.MILLIREC_TRAINING;if(!n)throw new Error("MillirecCharLite: no training data (training.js missing?)");if(typeof Worker>"u"||typeof Blob>"u")throw new Error("millirec: char-lite needs a browser (Worker, fetch, canvas); importing is SSR-safe but call create() on the client");let a=new this(s,n);return await a.ready,a}constructor(t,e){this.config=t,this.stroke=new Y({assetBase:t.assetBase||vt,workerName:t.workerStroke||"worker-stroke.js",training:e,params:t.params?.stroke||t.params||null}),this.charList=this.stroke.charList,this.ready=this.stroke.readyPromise}use(t){return this.stroke.plugins.push(t),this}async recognize(t){return Pt(await this.stroke.recognize(t))}rawScores(t){return this.stroke.rawScores(t)}attach(t,{width:e=240,height:s=240,ink:n="#1e293b",idleOverwrite:a=2,scribbleClear:o=!0,scribble:c=null,staleAlpha:i,onStale:u}={}){let l=X({width:e,height:s,ink:n,idleOverwrite:a,scribbleClear:o,scribble:c,onStale:u,...i===void 0?{}:{staleAlpha:i},onClear:h=>t.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:h,undo:()=>l.undoClear()}})),onStrokeEnd:async h=>{if(!h.length){t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let d=await this.recognize(h);t.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:d,strokes:h}}))}});return t.appendChild(l.el),{clear:l.clear,undoClear:l.undoClear,isStale:l.isStale,configure:l.configure,setInk:l.setInk,repaint:l.repaint,getStrokes:l.getStrokes,canvas:l.el}}destroy(){this.stroke.destroy()}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharLite=$,window.MillirecChar||(window.MillirecChar=$));})();
1
+ "use strict";(()=>{var yt={image:{margin:.6884,mag:.6846,bias:-1.0768},imageGeom:{margin:.6925,mag:1.0731,bias:-2.4927}};function mt(r,t,{margin:e,mag:s,bias:n}){return r<1e-9?.99:1/(1+Math.exp(-(e*Math.log(Math.max(t,1e-9)/r)-s*Math.log(r)-n)))}function V(r,t,e,s=1e3){let n=[];for(let u=0;u<3;u++)n.push(t[r[2*u]]);let a=yt[e];if(a){let u=[r[1],r[3],r[5]],f=u.map((h,m)=>{let y=1/0;for(let p=0;p<3;p++)p!==m&&(y=Math.min(y,u[p]));return mt(h,y,a)});return{chars:n,probs:f}}let i=Math.max(r[1],s/1e3),l=Math.exp(-1*s/i);for(let u=0;u<3;u++)l+=Math.exp(-1*r[2*u+1]/i);let o=[];for(let u=0;u<3;u++)o.push(Math.exp(-1*r[2*u+1]/i)/l);return{chars:n,probs:o}}function J(r){let t=[],e=0,s=0;for(let n=0;n<r.x.length;n++)e+=r.x[n],s+=r.y[n],t.push({x:e,y:s});return t}function rt(r){let t=[],e=[],s=[0,0];for(let n=0;n<r.length;n++){let a=Math.round(r[n].x),i=Math.round(r[n].y);t.push(n===0?a:a-s[0]),e.push(n===0?i:i-s[1]),s=[a,i]}return{x:t,y:e}}function X(r){let t=r.length,e=[0,0],s=[0,0],n=[];for(let f=0;f<t;f++){let h=r[f];e[0]+=h.x,e[1]+=h.y;let m={x:h.x,y:h.y,a:1.570795};f>0&&h.x!==s[0]&&(m.a=Math.atan2(h.y-s[1],h.x-s[0])),m.s=Math.sin(m.a),m.c=Math.cos(m.a),f===1&&(n[0].s=m.s,n[0].c=m.c),s=[h.x,h.y],n.push(m)}e[0]/=t,e[1]/=t;let a=[0,0],i=[0,0],l=[0,0],o=[0,0];for(let f of n)f.x<e[0]?(l[0]+=f.x-e[0],l[1]++):(o[0]+=f.x-e[0],o[1]++),f.y<e[1]?(a[0]+=f.y-e[1],a[1]++):(i[0]+=f.y-e[1],i[1]++),f.x-=e[0],f.y-=e[1];a[1]>0&&(a[0]/=a[1]),i[1]>0&&(i[0]/=i[1]),l[1]>0&&(l[0]/=l[1]),o[1]>0&&(o[0]/=o[1]);let u=i[0]-a[0]<o[0]-l[0]?100/(o[0]-l[0]):a[0]<i[0]?100/(i[0]-a[0]):1;return{points:n,scale:u}}function $(r,t=50){let e=[],s=0;for(let i of r){let l=i.length===1?[{x:i[0].x-.5,y:i[0].y},{x:i[0].x+.5,y:i[0].y}]:i;for(let o=1;o<l.length;o++){let u=l[o].x-l[o-1].x,f=l[o].y-l[o-1].y,h=Math.sqrt(u*u+f*f);e.push({ax:l[o-1].x,ay:l[o-1].y,bx:l[o].x,by:l[o].y,cumStart:s,cumEnd:s+h}),s+=h}}if(!s||!e.length)return null;let n=[],a=0;for(let i=0;i<t;i++){let l=i*s/(t-1);for(;a<e.length-1&&e[a].cumEnd<l;)a++;let o=e[a],u=o.cumEnd-o.cumStart,f=u?Math.min(1,Math.max(0,(l-o.cumStart)/u)):0;n.push({x:o.ax+(o.bx-o.ax)*f,y:o.ay+(o.by-o.ay)*f})}return n}function z(r){return rt(r)}var gt=r=>Array.isArray(r),xt=r=>gt(r)?r.every(t=>typeof t?.x=="number"&&typeof t?.y=="number"):Array.isArray(r?.x)&&Array.isArray(r?.y)&&r.x.length===r.y.length;function wt(r){return!!r&&typeof r=="object"&&!r.version&&!r.classes&&Object.values(r).every(Array.isArray)}function bt(r,{mode:t="both"}={}){let e={};for(let[s,n]of Object.entries(r))e[s]={samples:n,geometry:null};return{version:2,mode:t,pointsPerShape:50,classes:e,ext:{}}}function Mt(r){let t=[];if(!r||typeof r!="object")return["not an object"];if((typeof r.version!="number"||r.version<2)&&t.push("bad version"),!r.classes||typeof r.classes!="object"||!Object.keys(r.classes).length)return t.push("no classes"),t;for(let[e,s]of Object.entries(r.classes)){if(!Array.isArray(s?.samples)||!s.samples.length){t.push(`class ${e}: no samples`);continue}s.samples.forEach((a,i)=>{xt(a)||t.push(`class ${e} sample ${i}: bad shape`)});let n=s.geometry;n!=null&&typeof n!="object"&&t.push(`class ${e}: bad geometry`)}return r.wordList!=null&&!Array.isArray(r.wordList)&&t.push("bad wordList"),r.params!=null&&typeof r.params!="object"&&t.push("bad params"),t}function K(r){let t=wt(r)?bt(r):r,e=Mt(t);if(e.length)throw new Error("invalid training data: "+e.join("; "));return t.mode||(t.mode="both"),t.pointsPerShape||(t.pointsPerShape=50),t.ext||(t.ext={}),t}function nt(r){let t={};for(let[e,s]of Object.entries(r.classes))t[e]=s.samples;return t}function it(r){let t=r?String(r):"";return t?(t.endsWith("/")||(t+="/"),typeof location<"u"?new URL(t,location.href).href:t):typeof location<"u"?new URL("./",location.href).href:""}var Y=(r,t,e,s)=>new Error(`millirec: ${r} is not ${t} \u2014 the package files are not served at ${e}; copy node_modules/millirec/dist/${s}/ and pass assetBase (see README "Serving the files")`);function vt(){let r=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return r?r.slice(0,r.lastIndexOf("/")+1):""}var St=vt(),Pt=256,Q=class{constructor({assetBase:t,workerName:e,training:s,params:n}){t=it(t);let a=K(s);this.trainPaths=nt(a),this.charList=Object.keys(this.trainPaths),this.samplesPerChar=Math.max(1,...this.charList.map(o=>this.trainPaths[o].length)),this.pointsPerShape=a.pointsPerShape||50,this.params=n||a.params||null,this.plugins=[],this.cache=new Map,this.inFlight=new Map,this.allWaiters=new Map,this.reqCounter=0;let i=`self.__MILLIREC_ASSET_BASE=${JSON.stringify(t)};importScripts(${JSON.stringify(t+e)});`;this.bootUrl=URL.createObjectURL(new Blob([i],{type:"text/javascript"})),this.worker=new Worker(this.bootUrl),this.readyPromise=new Promise((o,u)=>{this.readyResolve=o,this.readyReject=u}),this.worker.onmessage=o=>this.onMessage(o);let l=t+e;this.worker.onerror=o=>{if(this.booted){this.flush();return}let u=Y(l,"the char-lite worker",t,"char-lite");u.message+=` (${o.message||"script failed to load"})`,this.failBoot(u)},this.assetBase=t}onMessage(t){let e=t.data;if(this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null),e.type==="getCharList")this.params&&this.worker.postMessage({type:"setParams",params:this.params}),this.worker.postMessage({type:"charList",charList:this.charList,pointsPerShape:this.pointsPerShape,samplesPerChar:this.samplesPerChar});else if(e.type==="prepAll")this.charList.forEach((s,n)=>{this.trainPaths[s].forEach((a,i)=>{let{points:l,scale:o}=X(J(a));this.worker.postMessage({type:"addPoints",points:l,m:n*this.samplesPerChar+i,scale:o})})}),this.booted=!0,this.readyResolve();else if(e.type==="addResult"&&e.result){this.cache.delete(e.path),this.cache.set(e.path,e.result),this.cache.size>Pt&&this.cache.delete(this.cache.keys().next().value);let s=this.inFlight.get(e.path)||[];this.inFlight.delete(e.path);for(let n of s)n(this.applyPlugins(e.result,e.path))}else if(e.type==="allResult"){let s=this.allWaiters.get(e.path)||[];this.allWaiters.delete(e.path);for(let n of s)n(e.costs)}else if(e.type==="bootError"){let s=Y(this.assetBase+"millirec.wasm","the char-lite matcher",this.assetBase,"char-lite");s.message+=` (worker boot failed: ${e.message})`,this.failBoot(s)}}flush(){for(let t of[this.inFlight,this.allWaiters]){let e=[...t.values()];t.clear();for(let s of e)for(let n of s)n(null)}}failBoot(t){this.readyReject(t),this.destroyed=!0;try{this.worker.terminate()}catch{}this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null)}applyPlugins(t,e){let s=V(t,this.charList,"stroke",1e3);for(let n of this.plugins)n.rerank&&(s=n.rerank(s,{raw:t,path:e,charList:this.charList,mode:"stroke",recognizer:this})||s);return s}uploadTest(t){let e=Array.isArray(t[0])?t:[t],s=$(e,this.pointsPerShape);if(!s)return!1;let{points:n,scale:a}=X(s);return this.worker.postMessage({type:"addPoints",points:n,m:-1,scale:a}),!0}keyFor(t){let e=Array.isArray(t[0])?t:[t],s=2166136261,n=16777619,a=0,i=l=>{s=Math.imul(s^l,16777619),n=Math.imul(n^l,2246822519)};for(let l of e){i(2147483647^l.length);for(let o of l)i(Math.round(o.x*1e3)|0),i(Math.round(o.y*1e3)|0),a++}return"strokes:"+e.length+":"+a+":"+(s>>>0).toString(36)+(n>>>0).toString(36)}async recognize(t){if(this.destroyed||!t||!t.length||(await this.readyPromise,this.destroyed))return null;let e=this.keyFor(t);if(this.cache.has(e)){let s=this.cache.get(e);return this.cache.delete(e),this.cache.set(e,s),this.applyPlugins(s,e)}return this.uploadTest(t)?new Promise(s=>{let n,a=i=>{clearTimeout(n),s(i)};this.inFlight.has(e)?this.inFlight.get(e).push(a):(this.inFlight.set(e,[a]),this.worker.postMessage({type:"compare",path:e,elementID:"req"+ ++this.reqCounter})),n=setTimeout(()=>{let i=this.inFlight.get(e);if(i){let l=i.indexOf(a);l>=0&&i.splice(l,1),i.length||this.inFlight.delete(e)}a(null)},4e3)}):null}async rawScores(t){if(this.destroyed||!t||!t.length||(await this.readyPromise,this.destroyed)||!this.uploadTest(t))return null;let e="all:"+ ++this.reqCounter,s=await new Promise(n=>{let a,i=l=>{clearTimeout(a),n(l)};this.allWaiters.set(e,[i]),this.worker.postMessage({type:"compareAll",path:e,counts:this.charList.map(l=>this.trainPaths[l].length)}),a=setTimeout(()=>{this.allWaiters.delete(e),i(null)},8e3)});return s?{classes:this.charList,costs:s}:null}destroy(){this.destroyed||(this.destroyed=!0,this.worker.terminate(),this.bootUrl&&(URL.revokeObjectURL(this.bootUrl),this.bootUrl=null),this.flush(),this.cache.clear(),this.readyResolve())}},ot=r=>{if(!r)return null;let t=new Set,e=[];return r.chars.forEach((s,n)=>{s!==void 0&&!t.has(s)&&(t.add(s),e.push({char:s,prob:r.probs[n]}))}),e},kt=r=>{let t=1/0,e=1/0;for(let s of r||[])s<t?(e=t,t=s):s<e&&(e=s);return t===1/0?1/0:e===1/0?.9*t*t*t:t*t*e};function at(r,t,{replace:e=!1}={}){let n=r&&r.classes&&!Object.keys(r.classes).length?{version:2,mode:"stroke",ext:{},...r,pointsPerShape:r.pointsPerShape||50,classes:{}}:K({...r}),a=n.pointsPerShape,i=o=>{let u=Array.isArray(o)?Array.isArray(o[0])?o:[o]:[J(o)],f=$(u,a);return f?z(f):null},l={...n.classes};for(let[o,u]of Object.entries(t||{})){let f=(u||[]).map(i).filter(Boolean);if(!f.length)continue;let h=l[o]?.samples||[];l[o]={...l[o]||{},samples:e?f:h.concat(f)}}return{...n,classes:l}}var B=class{static strokesToSample(t,e=50){let s=$(Array.isArray(t[0])?t:[t],e);return s?z(s):null}static withSamples(t,e,s){return at(t,e,s)}static async create(t={}){let e=typeof window<"u"?window:globalThis,s={...e.MILLIREC_CONFIG||{},...t},n=t.training||e.MILLIREC_TRAINING;if(!n)throw new Error("MillirecCharLite: no training data (training.js missing?)");if(typeof Worker>"u"||typeof Blob>"u")throw new Error("millirec: char-lite needs a browser (Worker, fetch, canvas); importing is SSR-safe but call create() on the client");let a=new this(s,n);return await a.ready,a}constructor(t,e){this.config=t,this.plugins=[],this.shipped=this.stroke=this.newWorker(e),this.ready=this.stroke.readyPromise}newWorker(t){let e=new Q({assetBase:this.config.assetBase||St,workerName:this.config.workerStroke||"worker-stroke.js",training:t,params:this.config.params?.stroke||this.config.params||null});return e.plugins=this.plugins,e}get engine(){return"char-lite"}get classes(){return this.shipped.charList}get charList(){return this.shipped.charList}use(t){return this.plugins.push(t),this}async recognize(t,{only:e=null}={}){if(!e)return ot(await this.stroke.recognize(t));let s=new Set(typeof e=="string"?[...e]:e),n=await this.stroke.rawScores(t);if(!n)return null;let a=n.classes.map((i,l)=>({i:l,c:i,v:kt(n.costs[l])})).filter(i=>s.has(i.c)&&i.v<1/0).sort((i,l)=>i.v-l.v).slice(0,3);if(!a.length)return[];for(;a.length<3;)a.push({...a[0],v:1e30});return ot(V(a.flatMap(i=>[i.i,i.v]),n.classes,"stroke",1e3))}async teach(t,{add:e=!1}={}){if(await this.ready,this.destroyed)return null;let s=e&&this.taught?this.taught:{version:2,mode:"stroke",pointsPerShape:this.shipped.pointsPerShape,classes:{}},n=at(s,t),a=Object.values(n.classes).reduce((l,o)=>l+o.samples.length,0);if(!a)return null;let i=this.newWorker(n);return await i.readyPromise,this.destroyed?(i.destroy(),null):(this.stroke!==this.shipped&&this.stroke.destroy(),this.stroke=i,this.taught=n,{classes:i.charList,n:a})}forget(){this.stroke!==this.shipped&&this.stroke.destroy(),this.stroke=this.shipped,this.taught=null}rawScores(t){return this.stroke.rawScores(t)}destroy(){this.destroyed=!0,this.stroke!==this.shipped&&this.stroke.destroy(),this.shipped.destroy()}};var ft={turns:5,retrace:.5,winding:3.5,cover:.6,minLength:40,minSpan:12,deadband:.22},I=2;function lt(r){return{x0:r.x0-I,y0:r.y0-I,x1:r.x1+I,y1:r.y1+I,w:r.w+2*I,h:r.h+2*I}}function ct(r){let t=1/0,e=1/0,s=-1/0,n=-1/0;for(let a of r){let i=a.x!==void 0?a.x:a[0],l=a.y!==void 0?a.y:a[1];i<t&&(t=i),i>s&&(s=i),l<e&&(e=l),l>n&&(n=l)}return{x0:t,y0:e,x1:s,y1:n,w:s-t,h:n-e}}function ht(r,t){let e=1/0,s=-1/0;for(let o of r)o<e&&(e=o),o>s&&(s=o);let n=(s-e)*t;if(!(n>0))return 0;let a=0,i=r[0],l=0;for(let o of r)a>0?o>i?i=o:o<i-n&&(l++,a=-1,i=o):a<0?o<i?i=o:o>i+n&&(l++,a=1,i=o):o>i+n?(a=1,i=o):o<i-n&&(a=-1,i=o);return l}function At(r){let t=0,e=0;for(let m of r)t+=m.x,e+=m.y;t/=r.length,e/=r.length;let s=0,n=0,a=0;for(let m of r){let y=m.x-t,p=m.y-e;s+=y*y,n+=y*p,a+=p*p}let i=s+a,l=s*a-n*n,o=i/2+Math.sqrt(Math.max(0,i*i/4-l)),u=n,f=o-s;Math.hypot(u,f)<1e-9&&(u=1,f=0);let h=Math.hypot(u,f);return{ux:u/h,uy:f/h}}var Et=.09,Ct=4;function Lt(r,t){let e=Math.max(2,t*Et),s=e/2,n=[r[0]],a=0;for(let f=1;f<r.length;f++){let h=r[f].x-r[f-1].x,m=r[f].y-r[f-1].y,y=Math.hypot(h,m);if(!(y>0))continue;let p=(s-a)/y;for(;p<=1;)n.push({x:r[f-1].x+h*p,y:r[f-1].y+m*p}),p+=s/y;a=(a+y)%s}if(n.length<8)return 0;let i=Math.round(Ct*e/s),l=f=>`${Math.floor(f.x/e)},${Math.floor(f.y/e)}`,o=new Map;n.forEach((f,h)=>{let m=l(f);o.has(m)||o.set(m,[]),o.get(m).push(h)});let u=0;for(let f=0;f<n.length;f++){let h=n[f],m=Math.floor(h.x/e),y=Math.floor(h.y/e),p=!1;for(let b=-1;b<=1&&!p;b++)for(let d=-1;d<=1&&!p;d++)for(let w of o.get(`${m+b},${y+d}`)||[])if(!(Math.abs(f-w)<=i)&&Math.hypot(n[w].x-h.x,n[w].y-h.y)<=e){p=!0;break}p&&u++}return u/n.length}function It(r,t=[],e={}){let s={...ft,...e},n=[];for(let d of r){let w={x:d.x!==void 0?d.x:d[0],y:d.y!==void 0?d.y:d[1]},P=n[n.length-1];(!P||Math.hypot(w.x-P.x,w.y-P.y)>.75)&&n.push(w)}if(n.length<4)return{turns:0,cross:0,retrace:0,winding:0,cover:0,length:0,span:0};let a=0;for(let d=1;d<n.length;d++)a+=Math.hypot(n[d].x-n[d-1].x,n[d].y-n[d-1].y);let i=ct(n),l=Math.hypot(i.w,i.h),{ux:o,uy:u}=At(n),f=n.map(d=>d.x*o+d.y*u),h=n.map(d=>-d.x*u+d.y*o),m=ht(f,s.deadband),y=ht(h,s.deadband),p=0,b=[];for(let d of t)for(let w of d)b.push(w);if(b.length){let d=lt(ct(b)),w=lt(i),P=Math.max(0,Math.min(d.x1,w.x1)-Math.max(d.x0,w.x0)),k=Math.max(0,Math.min(d.y1,w.y1)-Math.max(d.y0,w.y0));p=P/Math.min(d.w,w.w)*(k/Math.min(d.h,w.h))}return{turns:m,cross:y,retrace:Lt(n,l),winding:l>0?a/l:0,cover:p,length:a,span:l}}function ut(r,t=[],e={}){let s={...ft,...e};if(!t||!t.length)return!1;let n=It(r,t,s);return n.length>=s.minLength&&n.span>=s.minSpan&&n.turns>=s.turns&&n.retrace>=s.retrace&&n.winding>=s.winding&&n.cover>=s.cover}var Rt=12,_=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();function D({width:r=160,height:t=90,ink:e="#111827",onStrokeEnd:s,colorOf:n=null,idleOverwrite:a=0,scribbleClear:i=!1,scribble:l=null,onClear:o=null,staleAlpha:u=.3,onStale:f=null}){let h=document.createElement("canvas"),m=typeof devicePixelRatio<"u"&&devicePixelRatio||1;h.width=r*m,h.height=t*m,h.style.width=r+"px",h.style.height=t+"px",h.style.touchAction="none";let y=h.getContext("2d");y.scale(m,m);let p=[],b=[],d=null,w=!1,P=1,k=0,A=0,R=!1,E=null,C=!1;function Z(c,g){if(!(c.length<2)){y.strokeStyle=g||e,y.beginPath(),y.moveTo(c[0].x,c[0].y);for(let x=1;x<c.length;x++)y.lineTo(c[x].x,c[x].y);y.stroke()}}function dt(c,g){if(!(c.length<2||g>=c.length-1)){y.lineWidth=2.5,y.lineCap="round",y.lineJoin="round",y.globalAlpha=1,y.strokeStyle=e,y.beginPath(),y.moveTo(c[Math.max(0,g)].x,c[Math.max(0,g)].y);for(let x=Math.max(1,g+1);x<c.length;x++)y.lineTo(c[x].x,c[x].y);y.stroke()}}function v(){y.clearRect(0,0,r,t),y.lineWidth=2.5,y.lineCap="round",y.lineJoin="round",y.globalAlpha=R?u:1;for(let c of p)Z(c,n&&n(c));y.globalAlpha=1,Z(b,null)}function L(c){R!==c&&(R=c,v(),f&&f(c))}function U(){clearTimeout(A),A=0;let c=(Number(a)||0)*1e3;if(!c||!p.length){L(!1);return}let g=c-(_()-k);if(g<=0){L(!0);return}L(!1),A=setTimeout(()=>L(!0),g)}function tt(c){p.length&&(E=p,p=[],clearTimeout(A),A=0,L(!1),v(),o&&o(c))}function et(c,g){let x=p.filter(S=>!S.some(M=>Math.hypot(M.x-c,M.y-g)<=Rt));return x.length===p.length?!1:(p=x,v(),!0)}let T=null,q=c=>{let g=T||(T=h.getBoundingClientRect()),x=r/(h.clientWidth||r),S=t/(h.clientHeight||t);return{x:(c.clientX-g.left-h.clientLeft)*x,y:(c.clientY-g.top-h.clientTop)*S,p:c.pressure||.5}},j=!1,F=null,G=c=>c.preventDefault();h.addEventListener("touchstart",G,{passive:!1}),h.addEventListener("touchmove",G,{passive:!1}),h.addEventListener("contextmenu",G),h.style.userSelect=h.style.webkitUserSelect="none",h.style.webkitTouchCallout="none",h.addEventListener("pointerdown",c=>{if(c.button>0)return;if(d!==null){if(F==="pen"&&c.pointerType!=="pen"&&c.pointerId!==d)return;N({pointerId:d})}c.preventDefault(),d=c.pointerId,F=c.pointerType,T=h.getBoundingClientRect();try{h.setPointerCapture(c.pointerId)}catch{}let g=q(c);if(w){j=et(g.x,g.y);return}R&&p.length&&(tt("idle"),C=!0),b=[g],v()},{passive:!1}),h.addEventListener("pointermove",c=>{if(d!==c.pointerId)return;c.preventDefault();let g=c.getCoalescedEvents?c.getCoalescedEvents():null,x=g&&g.length?g:[c];if(w){for(let M of x){let st=q(M);et(st.x,st.y)&&(j=!0)}return}let S=b.length-1;for(let M of x)b.push(q(M));dt(b,S)},{passive:!1});let N=(c,g=!1)=>{if(d===c.pointerId){try{h.releasePointerCapture(c.pointerId)}catch{}if(d=null,F=null,T=null,w){j&&(k=_(),U(),s&&s(p)),j=!1;return}if(b.length>0){let x=b;if(x.length===1){if(g){b=[],v(),C&&(C=!1,s&&s(p));return}let M=x[0];x=[{x:M.x-1,y:M.y,p:M.p},{x:M.x+1,y:M.y,p:M.p}]}let S=p.length?p:C?E:null;if(i&&S&&S.length&&ut(x,S,l||{})){b=[],k=_(),C=!1,p.length?tt("scribble"):(v(),o&&o("scribble")),s&&s(p);return}x.id=P++,p=[...p,x],b=[],C=!1,k=_(),U(),s&&s(p)}v()}};return h.addEventListener("pointerup",c=>{c.pointerId===d&&c.preventDefault(),N(c)},{passive:!1}),h.addEventListener("pointercancel",c=>N(c,!0),{passive:!1}),h.addEventListener("lostpointercapture",c=>{(!h.hasPointerCapture||!h.hasPointerCapture(c.pointerId))&&N(c,!0)}),{el:h,getStrokes:()=>p,setInk(c){e=c,v()},setErasing(c){w=!!c,h.style.cursor=w?"cell":"crosshair"},isErasing:()=>w,repaint:v,isStale:()=>R,undoClear(){return!E||!E.length?!1:(p=p.length?[...E,...p]:E,E=null,k=_(),U(),v(),s&&s(p),!0)},configure(c={}){"idleOverwrite"in c&&(a=Number(c.idleOverwrite)||0),"scribbleClear"in c&&(i=!!c.scribbleClear),"scribble"in c&&(l=c.scribble),"staleAlpha"in c&&(u=Number(c.staleAlpha)),U()},clear(){p=[],b=[],d=null,F=null,T=null,clearTimeout(A),A=0,L(!1),C=!1,v(),s&&s(p)}}}function pt(r,t,{width:e=240,height:s=240,ink:n="#1e293b",idleOverwrite:a=2,scribbleClear:i=!0,scribble:l=null,staleAlpha:o,onStale:u,recognizeOptions:f}={}){if(!t||typeof t.recognize!="function")throw new TypeError("millirec: attachPad(el, recognizer) needs a recognizer with recognize(strokes)");let h=D({width:e,height:s,ink:n,idleOverwrite:a,scribbleClear:i,scribble:l,onStale:u,...o===void 0?{}:{staleAlpha:o},onClear:m=>r.dispatchEvent(new CustomEvent("millirec:clear",{detail:{reason:m,undo:()=>h.undoClear()}})),onStrokeEnd:async m=>{if(!m.length){r.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:[],strokes:[]}}));return}let y=await(f?t.recognize(m,f):t.recognize(m));r.dispatchEvent(new CustomEvent("millirec:result",{detail:{results:y,strokes:m}}))}});return r.appendChild(h.el),{clear:h.clear,undoClear:h.undoClear,isStale:h.isStale,configure:h.configure,setInk:h.setInk,repaint:h.repaint,getStrokes:h.getStrokes,canvas:h.el}}var H=class extends B{static createDrawCanvas(t){return D(t)}attach(t,e){return pt(t,this,e)}};typeof window<"u"&&typeof __MILLIREC_ESM__>"u"&&(window.MillirecCharLite=H,window.MillirecChar||(window.MillirecChar=H));})();
@@ -1,8 +1,8 @@
1
1
  {
2
- "generated": "2026-11-16T20:48:50.138Z",
2
+ "generated": "2026-11-21T20:48:03.820Z",
3
3
  "pps": 25,
4
4
  "folds": 3,
5
- "fixedKB": 58.2,
5
+ "fixedKB": 60.7,
6
6
  "sets": {
7
7
  "capitals": {
8
8
  "title": "Capital letters A–Z",
@@ -14,12 +14,12 @@
14
14
  "pps": 25,
15
15
  "top1": 99.69,
16
16
  "top3": 99.69,
17
- "msPerChar": 0.49,
17
+ "msPerChar": 0.47,
18
18
  "folds": 3,
19
19
  "trainingKB": 44.2,
20
20
  "trainingGz": 10.9,
21
- "bundleKB": 102.4,
22
- "zipKB": 38.5,
21
+ "bundleKB": 104.9,
22
+ "zipKB": 39.3,
23
23
  "errors": [
24
24
  "A→R"
25
25
  ],
@@ -35,12 +35,12 @@
35
35
  "pps": 25,
36
36
  "top1": 98.69,
37
37
  "top3": 100,
38
- "msPerChar": 0.52,
38
+ "msPerChar": 0.5,
39
39
  "folds": 3,
40
40
  "trainingKB": 49.9,
41
41
  "trainingGz": 11.4,
42
- "bundleKB": 108.1,
43
- "zipKB": 38.9,
42
+ "bundleKB": 110.6,
43
+ "zipKB": 39.7,
44
44
  "errors": [
45
45
  "a→u",
46
46
  "i→j",
@@ -60,12 +60,12 @@
60
60
  "pps": 25,
61
61
  "top1": 100,
62
62
  "top3": 100,
63
- "msPerChar": 0.23,
63
+ "msPerChar": 0.21,
64
64
  "folds": 3,
65
65
  "trainingKB": 17.1,
66
66
  "trainingGz": 4.4,
67
- "bundleKB": 75.3,
68
- "zipKB": 31.8,
67
+ "bundleKB": 77.8,
68
+ "zipKB": 32.6,
69
69
  "errors": [],
70
70
  "missing": ""
71
71
  },
@@ -79,12 +79,12 @@
79
79
  "pps": 25,
80
80
  "top1": 91.78,
81
81
  "top3": 98.63,
82
- "msPerChar": 0.15,
82
+ "msPerChar": 0.14,
83
83
  "folds": 3,
84
84
  "trainingKB": 9.4,
85
85
  "trainingGz": 1.7,
86
- "bundleKB": 67.6,
87
- "zipKB": 29,
86
+ "bundleKB": 70.1,
87
+ "zipKB": 29.8,
88
88
  "errors": [
89
89
  ".→,",
90
90
  ".→-",
@@ -105,12 +105,12 @@
105
105
  "pps": 25,
106
106
  "top1": 92.03,
107
107
  "top3": 97.9,
108
- "msPerChar": 1.13,
108
+ "msPerChar": 1.11,
109
109
  "folds": 3,
110
110
  "trainingKB": 120.2,
111
111
  "trainingGz": 27,
112
- "bundleKB": 178.4,
113
- "zipKB": 55.2,
112
+ "bundleKB": 180.9,
113
+ "zipKB": 56,
114
114
  "errors": [
115
115
  "0→O",
116
116
  "1→I",
@@ -0,0 +1,35 @@
1
+ import type { MillirecCharLite, Strokes, Stroke } from './char-lite/index.js'
2
+ import type { MillirecCharCnn } from './char-cnn/index.js'
3
+ import type { OptionName } from './char-cnn/core.js'
4
+
5
+ export { MillirecCharLite, SETS, loadSet, type SetName, type Training, type Sample, type Reading, type Point, type Stroke, type Strokes, type Only, type AttachOptions, type Pad, type ResultDetail, type ClearDetail } from './char-lite/index.js'
6
+ export { attachPad, type Recognizer } from './pad/index.js'
7
+
8
+ export declare const ALPHABETS: readonly ['digits', 'capitals', 'lowercase', 'all', 'punctuation']
9
+ export type Alphabet = (typeof ALPHABETS)[number]
10
+ export declare const PRIORITIES: readonly ['accurate', 'fast', 'small']
11
+ export type Priority = (typeof PRIORITIES)[number]
12
+
13
+ export interface RecognizerOptions {
14
+ /** What to read. Required unless `examples` are given. */
15
+ alphabet?: Alphabet
16
+ /** Among the CNN options: the most accurate (default), the fastest, or the smallest download. char-lite has one build. */
17
+ priority?: Priority
18
+ /** Your own symbols, a few drawings each: added to `alphabet`, or read alone without one. */
19
+ examples?: Record<string, Array<Strokes | Stroke>>
20
+ /** 'auto' (default): the CNN for digits, capitals, lowercase and all; char-lite for punctuation and whenever
21
+ * `examples` are given. */
22
+ engine?: 'auto' | 'cnn' | 'lite'
23
+ /** Where you serve the package's dist/ folder (it holds char-cnn/ and char-lite/). Default: beside this module.
24
+ * It decides what code is loaded: never fill it from a URL parameter or user input. */
25
+ assetBase?: string
26
+ /** char-lite matcher overrides. */
27
+ params?: Record<string, number>
28
+ }
29
+
30
+ export type Choice = { engine: 'char-cnn'; option: OptionName; teach: boolean } | { engine: 'char-lite'; set: Alphabet | null; examples: boolean }
31
+
32
+ /** What createRecognizer() would load, without loading it. */
33
+ export declare function chooseEngine(opts: RecognizerOptions | Alphabet): Choice
34
+ /** Load the recognizer for an alphabet (a string is the alphabet) or for your own examples. */
35
+ export declare function createRecognizer(opts: RecognizerOptions | Alphabet): Promise<MillirecCharCnn | MillirecCharLite>
package/dist/index.js ADDED
@@ -0,0 +1,88 @@
1
+ // millirec — the package's front door: say what you want to read and how you
2
+ // want it traded off, and createRecognizer() picks the engine and loads it.
3
+ //
4
+ // import { createRecognizer } from 'millirec'
5
+ // const rec = await createRecognizer('digits') // the CNN, option 'digits'
6
+ // const rec = await createRecognizer({ alphabet: 'lowercase', priority: 'small' })
7
+ // const rec = await createRecognizer({ examples: { star: [d1, d2, d3], heart: [...] } }) // your own symbols
8
+ // rec.attach(document.querySelector('#pad'))
9
+ //
10
+ // COPIED, NOT BUNDLED, to dist/index.js (build.mjs): its imports name the
11
+ // engine entries beside it in dist/, and each engine is imported only when it
12
+ // is the one picked, so a char-lite page never downloads the CNN runtime.
13
+ //
14
+ // The engines stay importable on their own (millirec/char-cnn, millirec/char-lite,
15
+ // their /core builds without the pad, millirec/pad); 0.1's
16
+ // `import { MillirecCharLite, loadSet } from 'millirec'` still works.
17
+ // 0.1 imported char-lite from 'millirec': kept. Without a bundler this re-export makes the browser fetch char-lite's
18
+ // module (8 KB gzipped) even when the CNN is picked; a bundler drops it when nothing uses it, and splits both engines
19
+ // out of createRecognizer(), which imports each lazily.
20
+ export { MillirecCharLite, loadSet, SETS } from './char-lite/index.js'
21
+ export { attachPad } from './pad/index.js'
22
+
23
+ /** What createRecognizer() can read without examples. */
24
+ export const ALPHABETS = ['digits', 'capitals', 'lowercase', 'all', 'punctuation']
25
+ /** How a CNN option is traded off: the most accurate, the fastest, or the smallest download. */
26
+ export const PRIORITIES = ['accurate', 'fast', 'small']
27
+ const ENGINES = ['auto', 'cnn', 'lite']
28
+ // the CNN option family per alphabet: capitals are the unprefixed 'accurate' / 'fast' / 'small'
29
+ const CNN_FAMILY = { capitals: '', digits: 'digits', lowercase: 'lowercase', all: 'all' }
30
+
31
+ const oneOf = (what, v, list) => { if (!list.includes(v)) throw new Error(`millirec: ${what} "${v}" is not one of ${list.join(', ')}`) }
32
+ const hasAny = (examples) => !!examples && typeof examples === 'object' && Object.keys(examples).length > 0
33
+
34
+ /**
35
+ * The engine and shipped asset createRecognizer() would load, without loading anything:
36
+ * { engine: 'char-cnn', option, teach } or { engine: 'char-lite', set, examples }.
37
+ *
38
+ * engine 'auto' (default): the CNN for digits, capitals, lowercase and all — trained on hundreds of
39
+ * writers, it reads strangers' handwriting; the point-cloud matcher (char-lite) for punctuation and
40
+ * whenever `examples` are given, since it can add any symbol to a set or read symbols alone.
41
+ */
42
+ export function chooseEngine(opts) {
43
+ if (typeof opts === 'string') opts = { alphabet: opts }
44
+ const { alphabet = null, priority = 'accurate', engine = 'auto', examples = null } = opts || {}
45
+ if (alphabet != null) oneOf('alphabet', alphabet, ALPHABETS)
46
+ oneOf('priority', priority, PRIORITIES)
47
+ oneOf('engine', engine, ENGINES)
48
+ const own = hasAny(examples)
49
+ if (alphabet == null && !own) throw new Error(`millirec: createRecognizer needs an alphabet (${ALPHABETS.join(', ')}) or examples of your own symbols`)
50
+ const pick = engine !== 'auto' ? engine : own || !(alphabet in CNN_FAMILY) ? 'lite' : 'cnn'
51
+ if (pick === 'cnn') {
52
+ if (alphabet != null && !(alphabet in CNN_FAMILY)) throw new Error(`millirec: there is no CNN for "${alphabet}" — use engine 'lite' (or 'auto')`)
53
+ if (alphabet != null && own) throw new Error("millirec: char-cnn cannot add symbols to a shipped alphabet (its teach() reads the taught symbols alone) — use engine 'lite', or leave out the alphabet")
54
+ const family = CNN_FAMILY[alphabet ?? 'capitals']
55
+ const option = family ? (priority === 'accurate' ? family : `${family}-${priority}`) : priority
56
+ return { engine: 'char-cnn', option, teach: own }
57
+ }
58
+ return { engine: 'char-lite', set: alphabet, examples: own }
59
+ }
60
+
61
+ /**
62
+ * Load a recognizer for `alphabet` (or for your `examples`), traded off by `priority`. A string is the alphabet:
63
+ * createRecognizer('digits'). Resolves to the engine's recognizer — MillirecCharCnn or MillirecCharLite — which
64
+ * both have recognize(strokes, { only }), attach(el), teach(examples), forget(), classes, engine and destroy().
65
+ *
66
+ * alphabet 'digits' | 'capitals' | 'lowercase' | 'all' | 'punctuation'
67
+ * priority 'accurate' (default) | 'fast' | 'small' — picks among the CNN options; char-lite has one build
68
+ * examples { name: [drawing, …] } — your own symbols: added to `alphabet`, or read alone without one
69
+ * engine 'auto' (default) | 'cnn' | 'lite' — see chooseEngine()
70
+ * assetBase where you serve the package's dist/ folder (it holds char-cnn/ and char-lite/); default: beside this module
71
+ * anything else goes to the engine's create() (params for char-lite, ...)
72
+ */
73
+ export async function createRecognizer(opts) {
74
+ if (typeof opts === 'string') opts = { alphabet: opts }
75
+ const { alphabet, priority, engine, examples, assetBase, ...rest } = opts || {}
76
+ const choice = chooseEngine({ alphabet, priority, engine, examples })
77
+ const under = (dir) => (assetBase ? { assetBase: String(assetBase).replace(/\/?$/, '/') + dir + '/' } : {})
78
+ if (choice.engine === 'char-cnn') {
79
+ const { MillirecCharCnn } = await import('./char-cnn/index.js')
80
+ return MillirecCharCnn.create({ ...rest, ...under('char-cnn'), option: choice.option, ...(choice.teach ? { examples } : {}) })
81
+ }
82
+ const { MillirecCharLite, loadSet } = await import('./char-lite/index.js')
83
+ const base = under('char-lite')
84
+ let training = choice.set ? await loadSet(choice.set, base) : { version: 2, mode: 'stroke', pointsPerShape: 25, classes: {} }
85
+ if (choice.examples) training = MillirecCharLite.withSamples(training, examples)
86
+ if (!Object.keys(training.classes).length) throw new Error('millirec: none of the examples held a usable drawing')
87
+ return MillirecCharLite.create({ ...rest, ...base, training })
88
+ }
@@ -1,14 +1,14 @@
1
- "use strict";(()=>{var Ue=Object.defineProperty;var je=(u,t,s)=>t in u?Ue(u,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):u[t]=s;var He=(u=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(u,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):u)(function(u){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+u+'" is not supported')});var Zt=(u,t,s)=>je(u,typeof t!="symbol"?t+"":t,s);var ft=(()=>{var u=globalThis.document?.currentScript?.src;return async function(t={}){var s,e=t,o=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,i=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",l=(r,a)=>{throw a};typeof __filename<"u"?u=__filename:n&&(u=self.location.href);var c="",p,m;if(i){var f=He("fs");c=__dirname+"/",m=r=>(r=v(r)?new URL(r):r,f.readFileSync(r)),p=async r=>(r=v(r)?new URL(r):r,f.readFileSync(r,void 0)),process.argv.slice(2),l=(r,a)=>{throw process.exitCode=r,a}}else if(o||n){try{c=new URL(".",u).href}catch{}n&&(m=r=>{var a=new XMLHttpRequest;return a.open("GET",r,!1),a.responseType="arraybuffer",a.send(null),new Uint8Array(a.response)}),p=async r=>{if(r=await fetch(r,{credentials:"same-origin"}),r.ok)return r.arrayBuffer();throw Error(r.status+" : "+r.url)}}console.log.bind(console);var g=console.error.bind(console),M,L=!1,v=r=>r.startsWith("file://"),O,S,b,E,_,k,P,T,R,z,H,Ct,Lt=!1;function Tt(){var r=ut.buffer;b=new Int8Array(r),_=new Int16Array(r),E=new Uint8Array(r),k=new Uint16Array(r),P=new Int32Array(r),T=new Uint32Array(r),R=new Float32Array(r),z=new Float64Array(r),H=new BigInt64Array(r),Ct=new BigUint64Array(r)}function Ot(r){throw e.onAbort?.(r),r="Aborted("+r+")",g(r),L=!0,r=new WebAssembly.RuntimeError(r+". Build with -sASSERTIONS for more info."),S?.(r),r}var xt;async function we(r){if(!M)try{var a=await p(r);return new Uint8Array(a)}catch{}if(r==xt&&M)r=new Uint8Array(M);else if(m)r=m(r);else throw"both async and sync fetching of the wasm failed";return r}async function ge(r,a){try{var h=await we(r);return await WebAssembly.instantiate(h,a)}catch(d){g(`failed to asynchronously prepare wasm: ${d}`),Ot(d)}}async function ye(r){var a=xt;if(!M&&!i)try{var h=fetch(a,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(h,r)}catch(d){g(`wasm streaming compile failed: ${d}`),g("falling back to ArrayBuffer instantiation")}return ge(a,r)}class Pt{constructor(a){Zt(this,"name","ExitStatus");this.message=`Program terminated with exit(${a})`,this.status=a}}var Rt=r=>{for(;0<r.length;)r.shift()(e)},zt=[],Wt=[],xe=()=>{var r=e.preRun.shift();Wt.push(r)},Nt=!0;class ve{constructor(a){this.G=a-24}}var $t=0,be=0,ct={},Bt=r=>{for(;r.length;){var a=r.pop();r.pop()(a)}};function lt(r){return this.A(T[r>>2])}var Z={},Y={},ht={},Ft=class extends Error{constructor(r){super(r),this.name="InternalError"}},Gt=(r,a,h)=>{function d(x){if(x=h(x),x.length!==r.length)throw new Ft("Mismatched type converter count");for(var I=0;I<r.length;++I)K(r[I],x[I])}r.forEach(x=>ht[x]=a);var w=Array(a.length),y=[],C=0;a.forEach((x,I)=>{Y.hasOwnProperty(x)?w[I]=Y[x]:(y.push(x),Z.hasOwnProperty(x)||(Z[x]=[]),Z[x].push(()=>{w[I]=Y[x],++C,C===y.length&&d(w)}))}),y.length===0&&d(w)},D=r=>{for(var a="";;){var h=E[r++];if(!h)return a;a+=String.fromCharCode(h)}},j=class extends Error{constructor(r){super(r),this.name="BindingError"}},_e=r=>{throw new j(r)};function ke(r,a,h={}){var d=a.name;if(!r)throw new j(`type "${d}" must have a positive integer typeid pointer`);if(Y.hasOwnProperty(r)){if(h.L)return;throw new j(`Cannot register type '${d}' twice`)}Y[r]=a,delete ht[r],Z.hasOwnProperty(r)&&(a=Z[r],delete Z[r],a.forEach(w=>w()))}function K(r,a,h={}){return ke(r,a,h)}var Dt=(r,a,h)=>{switch(a){case 1:return h?d=>b[d]:d=>E[d];case 2:return h?d=>_[d>>1]:d=>k[d>>1];case 4:return h?d=>P[d>>2]:d=>T[d>>2];case 8:return h?d=>H[d>>3]:d=>Ct[d>>3];default:throw new TypeError(`invalid integer width (${a}): ${r}`)}},Ut=[],Q=[0,1,,1,null,1,!0,1,!1,1],Ae=r=>{switch(r){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let a=Ut.pop()||Q.length;return Q[a]=r,Q[a+1]=1,a}},Se={name:"emscripten::val",A:r=>{if(!r)throw new j(`Cannot use deleted val. handle = ${r}`);var a=Q[r];return 9<r&&--Q[r+1]===0&&(Q[r]=void 0,Ut.push(r)),a},D:(r,a)=>Ae(a),F:lt,B:null},Me=(r,a)=>{switch(a){case 4:return function(h){return this.A(R[h>>2])};case 8:return function(h){return this.A(z[h>>3])};default:throw new TypeError(`invalid float width (${a}): ${r}`)}};function jt(r){for(var a=1;a<r.length;++a)if(r[a]!==null&&r[a].B===void 0)return!0;return!1}var Ee=(r,a)=>{if(e[r].C===void 0){var h=e[r];e[r]=function(...d){if(!e[r].C.hasOwnProperty(d.length))throw new j(`Function '${a}' called with an invalid number of arguments (${d.length}) - expects one of (${e[r].C})!`);return e[r].C[d.length].apply(this,d)},e[r].C=[],e[r].C[h.H]=h}},Ie=(r,a,h)=>{if(e.hasOwnProperty(r)){if(h===void 0||e[r].C!==void 0&&e[r].C[h]!==void 0)throw new j(`Cannot register public name '${r}' twice`);if(Ee(r,r),e[r].C.hasOwnProperty(h))throw new j(`Cannot register multiple overloads of a function with the same number of arguments (${h})!`);e[r].C[h]=a}else e[r]=a,e[r].H=h},Ce=(r,a)=>{for(var h=[],d=0;d<r;d++)h.push(T[a+4*d>>2]);return h},nt=(r,a)=>{r=D(r);var h=Vt.get(a);if(typeof h!="function")throw new j(`unknown function pointer with signature ${r}: ${a}`);return h};class Le extends Error{}var Te=r=>{r=Kt(r);var a=D(r);return V(r),a},Oe=(r,a)=>{function h(y){w[y]||Y[y]||(ht[y]?ht[y].forEach(h):(d.push(y),w[y]=!0))}var d=[],w={};throw a.forEach(h),new Le(`${r}: `+d.map(Te).join([", "]))},Pe=r=>{r=r.trim();let a=r.indexOf("(");return a===-1?r:r.slice(0,a)},Re=new TextDecoder,Ht=(r,a,h,d)=>{if(h=a+h,d)return h;for(;r[a]&&!(a>=h);)++a;return a},ze=new TextDecoder("utf-16le"),We=(r,a,h)=>(r>>=1,ze.decode(k.subarray(r,Ht(k,r,a/2,h)))),Ne=(r,a,h)=>{if(h??(h=2147483647),2>h)return 0;h-=2;var d=a;h=h<2*r.length?h/2:r.length;for(var w=0;w<h;++w)_[a>>1]=r.charCodeAt(w),a+=2;return _[a>>1]=0,a-d},$e=r=>2*r.length,Be=(r,a,h)=>{var d="";r>>=2;for(var w=0;!(w>=a/4);w++){var y=T[r+w];if(!y&&!h)break;d+=String.fromCodePoint(y)}return d},Fe=(r,a,h)=>{if(h??(h=2147483647),4>h)return 0;var d=a;h=d+h-4;for(var w=0;w<r.length;++w){var y=r.codePointAt(w);if(65535<y&&w++,P[a>>2]=y,a+=4,a+4>h)break}return P[a>>2]=0,a-d},Ge=r=>{for(var a=0,h=0;h<r.length;++h)65535<r.codePointAt(h)&&h++,a+=4;return a};if(e.noExitRuntime&&(Nt=e.noExitRuntime),e.printErr&&(g=e.printErr),e.wasmBinary&&(M=e.wasmBinary),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.shift()();var Kt,Jt,vt,V,ut,Vt,De={h:(r,a,h)=>{var d=new ve(r);throw T[d.G+16>>2]=0,T[d.G+4>>2]=a,T[d.G+8>>2]=h,$t=r,be++,$t},m:()=>Ot(""),p:r=>{var a=ct[r];delete ct[r];var h=a.elements,d=h.length,w=h.map(x=>x.K).concat(h.map(x=>x.R)),y=a.N,C=a.O;Gt([r],w,x=>(h.forEach((I,A)=>{var $=x[A],U=I.I,W=I.J,J=x[A+d],q=I.P,pt=I.S;I.read=N=>$.A(U(W,N)),I.write=(N,G)=>{var B=[];q(pt,N,J.D(B,G)),Bt(B)}}),[{name:a.name,A:I=>{for(var A=Array(d),$=0;$<d;++$)A[$]=h[$].read(I);return C(I),A},D:(I,A)=>{if(d!==A.length)throw new TypeError(`Incorrect number of tuple elements for ${a.name}: expected=${d}, actual=${A.length}`);for(var $=y(),U=0;U<d;++U)h[U].write($,A[U]);return I!==null&&I.push(C,$),$},F:lt,B:C}]))},f:(r,a,h,d,w)=>{a=D(a),d=d===0n;let y=C=>C;if(d){let C=8*h;y=x=>BigInt.asUintN(C,x),w=y(w)}K(r,{name:a,A:y,D:(C,x)=>(typeof x=="number"&&(x=BigInt(x)),x),F:Dt(a,h,!d),B:null})},k:(r,a,h,d)=>{a=D(a),K(r,{name:a,A:function(w){return!!w},D:function(w,y){return y?h:d},F:function(w){return this.A(E[w])},B:null})},i:r=>K(r,Se),e:(r,a,h)=>{a=D(a),K(r,{name:a,A:d=>d,D:(d,w)=>w,F:Me(a,h),B:null})},c:(r,a,h,d,w,y,C)=>{var x=Ce(a,h);r=D(r),r=Pe(r),w=nt(d,w),Ie(r,function(){Oe(`Cannot call ${r} due to unbound types`,x)},a-1),Gt([],x,I=>{var A=[I[0],null].concat(I.slice(1));I=r;var $=r,U=w,W=A.length;if(2>W)throw new j("argTypes array size mismatch! Must at least get return value and 'this' types!");var J=A[1]!==null&&!1,q=jt(A),pt=!A[0].M,N=A[0],G=A[1];for(U=[$,_e,U,y,Bt,N.A.bind(N),G?.D.bind(G)],N=2;N<W;++N)G=A[N],U.push(G.D.bind(G));if(!q)for(N=J?1:2;N<A.length;++N)A[N].B!==null&&U.push(A[N].B);q=jt(A),N=A.length-2;var B=[];for(G=["fn"],J&&G.push("thisWired"),W=0;W<N;++W)B.push(`arg${W}`),G.push(`arg${W}Wired`);B=B.join(","),G=G.join(","),B=`return function (${B}) {
1
+ "use strict";(()=>{var Ue=Object.defineProperty;var je=(u,t,s)=>t in u?Ue(u,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):u[t]=s;var He=(u=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(u,{get:(t,s)=>(typeof require<"u"?require:t)[s]}):u)(function(u){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+u+'" is not supported')});var Zt=(u,t,s)=>je(u,typeof t!="symbol"?t+"":t,s);var ft=(()=>{var u=globalThis.document?.currentScript?.src;return async function(t={}){var s,e=t,i=!!globalThis.window,n=!!globalThis.WorkerGlobalScope,o=globalThis.process?.versions?.node&&globalThis.process?.type!="renderer",l=(r,c)=>{throw c};typeof __filename<"u"?u=__filename:n&&(u=self.location.href);var a="",d,m;if(o){var f=He("fs");a=__dirname+"/",m=r=>(r=v(r)?new URL(r):r,f.readFileSync(r)),d=async r=>(r=v(r)?new URL(r):r,f.readFileSync(r,void 0)),process.argv.slice(2),l=(r,c)=>{throw process.exitCode=r,c}}else if(i||n){try{a=new URL(".",u).href}catch{}n&&(m=r=>{var c=new XMLHttpRequest;return c.open("GET",r,!1),c.responseType="arraybuffer",c.send(null),new Uint8Array(c.response)}),d=async r=>{if(r=await fetch(r,{credentials:"same-origin"}),r.ok)return r.arrayBuffer();throw Error(r.status+" : "+r.url)}}console.log.bind(console);var w=console.error.bind(console),M,L=!1,v=r=>r.startsWith("file://"),O,S,b,E,_,k,P,T,R,z,H,Ct,Lt=!1;function Tt(){var r=ut.buffer;b=new Int8Array(r),_=new Int16Array(r),E=new Uint8Array(r),k=new Uint16Array(r),P=new Int32Array(r),T=new Uint32Array(r),R=new Float32Array(r),z=new Float64Array(r),H=new BigInt64Array(r),Ct=new BigUint64Array(r)}function Ot(r){throw e.onAbort?.(r),r="Aborted("+r+")",w(r),L=!0,r=new WebAssembly.RuntimeError(r+". Build with -sASSERTIONS for more info."),S?.(r),r}var vt;async function ge(r){if(!M)try{var c=await d(r);return new Uint8Array(c)}catch{}if(r==vt&&M)r=new Uint8Array(M);else if(m)r=m(r);else throw"both async and sync fetching of the wasm failed";return r}async function we(r,c){try{var h=await ge(r);return await WebAssembly.instantiate(h,c)}catch(p){w(`failed to asynchronously prepare wasm: ${p}`),Ot(p)}}async function ye(r){var c=vt;if(!M&&!o)try{var h=fetch(c,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(h,r)}catch(p){w(`wasm streaming compile failed: ${p}`),w("falling back to ArrayBuffer instantiation")}return we(c,r)}class Pt{constructor(c){Zt(this,"name","ExitStatus");this.message=`Program terminated with exit(${c})`,this.status=c}}var Rt=r=>{for(;0<r.length;)r.shift()(e)},zt=[],Wt=[],xe=()=>{var r=e.preRun.shift();Wt.push(r)},Nt=!0;class ve{constructor(c){this.G=c-24}}var $t=0,be=0,ct={},Bt=r=>{for(;r.length;){var c=r.pop();r.pop()(c)}};function lt(r){return this.A(T[r>>2])}var Z={},Y={},ht={},Ft=class extends Error{constructor(r){super(r),this.name="InternalError"}},Gt=(r,c,h)=>{function p(x){if(x=h(x),x.length!==r.length)throw new Ft("Mismatched type converter count");for(var I=0;I<r.length;++I)K(r[I],x[I])}r.forEach(x=>ht[x]=c);var g=Array(c.length),y=[],C=0;c.forEach((x,I)=>{Y.hasOwnProperty(x)?g[I]=Y[x]:(y.push(x),Z.hasOwnProperty(x)||(Z[x]=[]),Z[x].push(()=>{g[I]=Y[x],++C,C===y.length&&p(g)}))}),y.length===0&&p(g)},D=r=>{for(var c="";;){var h=E[r++];if(!h)return c;c+=String.fromCharCode(h)}},j=class extends Error{constructor(r){super(r),this.name="BindingError"}},_e=r=>{throw new j(r)};function ke(r,c,h={}){var p=c.name;if(!r)throw new j(`type "${p}" must have a positive integer typeid pointer`);if(Y.hasOwnProperty(r)){if(h.L)return;throw new j(`Cannot register type '${p}' twice`)}Y[r]=c,delete ht[r],Z.hasOwnProperty(r)&&(c=Z[r],delete Z[r],c.forEach(g=>g()))}function K(r,c,h={}){return ke(r,c,h)}var Dt=(r,c,h)=>{switch(c){case 1:return h?p=>b[p]:p=>E[p];case 2:return h?p=>_[p>>1]:p=>k[p>>1];case 4:return h?p=>P[p>>2]:p=>T[p>>2];case 8:return h?p=>H[p>>3]:p=>Ct[p>>3];default:throw new TypeError(`invalid integer width (${c}): ${r}`)}},Ut=[],Q=[0,1,,1,null,1,!0,1,!1,1],Ae=r=>{switch(r){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let c=Ut.pop()||Q.length;return Q[c]=r,Q[c+1]=1,c}},Se={name:"emscripten::val",A:r=>{if(!r)throw new j(`Cannot use deleted val. handle = ${r}`);var c=Q[r];return 9<r&&--Q[r+1]===0&&(Q[r]=void 0,Ut.push(r)),c},D:(r,c)=>Ae(c),F:lt,B:null},Me=(r,c)=>{switch(c){case 4:return function(h){return this.A(R[h>>2])};case 8:return function(h){return this.A(z[h>>3])};default:throw new TypeError(`invalid float width (${c}): ${r}`)}};function jt(r){for(var c=1;c<r.length;++c)if(r[c]!==null&&r[c].B===void 0)return!0;return!1}var Ee=(r,c)=>{if(e[r].C===void 0){var h=e[r];e[r]=function(...p){if(!e[r].C.hasOwnProperty(p.length))throw new j(`Function '${c}' called with an invalid number of arguments (${p.length}) - expects one of (${e[r].C})!`);return e[r].C[p.length].apply(this,p)},e[r].C=[],e[r].C[h.H]=h}},Ie=(r,c,h)=>{if(e.hasOwnProperty(r)){if(h===void 0||e[r].C!==void 0&&e[r].C[h]!==void 0)throw new j(`Cannot register public name '${r}' twice`);if(Ee(r,r),e[r].C.hasOwnProperty(h))throw new j(`Cannot register multiple overloads of a function with the same number of arguments (${h})!`);e[r].C[h]=c}else e[r]=c,e[r].H=h},Ce=(r,c)=>{for(var h=[],p=0;p<r;p++)h.push(T[c+4*p>>2]);return h},nt=(r,c)=>{r=D(r);var h=Vt.get(c);if(typeof h!="function")throw new j(`unknown function pointer with signature ${r}: ${c}`);return h};class Le extends Error{}var Te=r=>{r=Kt(r);var c=D(r);return V(r),c},Oe=(r,c)=>{function h(y){g[y]||Y[y]||(ht[y]?ht[y].forEach(h):(p.push(y),g[y]=!0))}var p=[],g={};throw c.forEach(h),new Le(`${r}: `+p.map(Te).join([", "]))},Pe=r=>{r=r.trim();let c=r.indexOf("(");return c===-1?r:r.slice(0,c)},Re=new TextDecoder,Ht=(r,c,h,p)=>{if(h=c+h,p)return h;for(;r[c]&&!(c>=h);)++c;return c},ze=new TextDecoder("utf-16le"),We=(r,c,h)=>(r>>=1,ze.decode(k.subarray(r,Ht(k,r,c/2,h)))),Ne=(r,c,h)=>{if(h??(h=2147483647),2>h)return 0;h-=2;var p=c;h=h<2*r.length?h/2:r.length;for(var g=0;g<h;++g)_[c>>1]=r.charCodeAt(g),c+=2;return _[c>>1]=0,c-p},$e=r=>2*r.length,Be=(r,c,h)=>{var p="";r>>=2;for(var g=0;!(g>=c/4);g++){var y=T[r+g];if(!y&&!h)break;p+=String.fromCodePoint(y)}return p},Fe=(r,c,h)=>{if(h??(h=2147483647),4>h)return 0;var p=c;h=p+h-4;for(var g=0;g<r.length;++g){var y=r.codePointAt(g);if(65535<y&&g++,P[c>>2]=y,c+=4,c+4>h)break}return P[c>>2]=0,c-p},Ge=r=>{for(var c=0,h=0;h<r.length;++h)65535<r.codePointAt(h)&&h++,c+=4;return c};if(e.noExitRuntime&&(Nt=e.noExitRuntime),e.printErr&&(w=e.printErr),e.wasmBinary&&(M=e.wasmBinary),e.preInit)for(typeof e.preInit=="function"&&(e.preInit=[e.preInit]);0<e.preInit.length;)e.preInit.shift()();var Kt,Jt,bt,V,ut,Vt,De={h:(r,c,h)=>{var p=new ve(r);throw T[p.G+16>>2]=0,T[p.G+4>>2]=c,T[p.G+8>>2]=h,$t=r,be++,$t},m:()=>Ot(""),p:r=>{var c=ct[r];delete ct[r];var h=c.elements,p=h.length,g=h.map(x=>x.K).concat(h.map(x=>x.R)),y=c.N,C=c.O;Gt([r],g,x=>(h.forEach((I,A)=>{var $=x[A],U=I.I,W=I.J,J=x[A+p],q=I.P,pt=I.S;I.read=N=>$.A(U(W,N)),I.write=(N,G)=>{var B=[];q(pt,N,J.D(B,G)),Bt(B)}}),[{name:c.name,A:I=>{for(var A=Array(p),$=0;$<p;++$)A[$]=h[$].read(I);return C(I),A},D:(I,A)=>{if(p!==A.length)throw new TypeError(`Incorrect number of tuple elements for ${c.name}: expected=${p}, actual=${A.length}`);for(var $=y(),U=0;U<p;++U)h[U].write($,A[U]);return I!==null&&I.push(C,$),$},F:lt,B:C}]))},f:(r,c,h,p,g)=>{c=D(c),p=p===0n;let y=C=>C;if(p){let C=8*h;y=x=>BigInt.asUintN(C,x),g=y(g)}K(r,{name:c,A:y,D:(C,x)=>(typeof x=="number"&&(x=BigInt(x)),x),F:Dt(c,h,!p),B:null})},k:(r,c,h,p)=>{c=D(c),K(r,{name:c,A:function(g){return!!g},D:function(g,y){return y?h:p},F:function(g){return this.A(E[g])},B:null})},i:r=>K(r,Se),e:(r,c,h)=>{c=D(c),K(r,{name:c,A:p=>p,D:(p,g)=>g,F:Me(c,h),B:null})},c:(r,c,h,p,g,y,C)=>{var x=Ce(c,h);r=D(r),r=Pe(r),g=nt(p,g),Ie(r,function(){Oe(`Cannot call ${r} due to unbound types`,x)},c-1),Gt([],x,I=>{var A=[I[0],null].concat(I.slice(1));I=r;var $=r,U=g,W=A.length;if(2>W)throw new j("argTypes array size mismatch! Must at least get return value and 'this' types!");var J=A[1]!==null&&!1,q=jt(A),pt=!A[0].M,N=A[0],G=A[1];for(U=[$,_e,U,y,Bt,N.A.bind(N),G?.D.bind(G)],N=2;N<W;++N)G=A[N],U.push(G.D.bind(G));if(!q)for(N=J?1:2;N<A.length;++N)A[N].B!==null&&U.push(A[N].B);q=jt(A),N=A.length-2;var B=[];for(G=["fn"],J&&G.push("thisWired"),W=0;W<N;++W)B.push(`arg${W}`),G.push(`arg${W}Wired`);B=B.join(","),G=G.join(","),B=`return function (${B}) {
2
2
  `,q&&(B+=`var destructors = [];
3
- `);var qt=q?"destructors":"null",bt="humanName throwBindingError invoker fn runDestructors fromRetWire toClassParamWire".split(" ");for(J&&(B+=`var thisWired = toClassParamWire(${qt}, this);
3
+ `);var qt=q?"destructors":"null",_t="humanName throwBindingError invoker fn runDestructors fromRetWire toClassParamWire".split(" ");for(J&&(B+=`var thisWired = toClassParamWire(${qt}, this);
4
4
  `),W=0;W<N;++W){var Xt=`toArg${W}Wire`;B+=`var arg${W}Wired = ${Xt}(${qt}, arg${W});
5
- `,bt.push(Xt)}if(B+=(pt||C?"var rv = ":"")+`invoker(${G});
5
+ `,_t.push(Xt)}if(B+=(pt||C?"var rv = ":"")+`invoker(${G});
6
6
  `,q)B+=`runDestructors(destructors);
7
7
  `;else for(W=J?1:2;W<A.length;++W)J=W===1?"thisWired":"arg"+(W-2)+"Wired",A[W].B!==null&&(B+=`${J}_dtor(${J});
8
- `,bt.push(`${J}_dtor`));if(pt&&(B+=`var ret = fromRetWire(rv);
8
+ `,_t.push(`${J}_dtor`));if(pt&&(B+=`var ret = fromRetWire(rv);
9
9
  return ret;
10
- `),A=new Function(bt,B+`}
11
- `)(...U),$=Object.defineProperty(A,"name",{value:$}),A=a-1,!e.hasOwnProperty(I))throw new Ft("Replacing nonexistent public symbol");return e[I].C!==void 0&&A!==void 0?e[I].C[A]=$:(e[I]=$,e[I].H=A),[]})},b:(r,a,h,d,w)=>{a=D(a);let y=x=>x;if(d===0){var C=32-8*h;y=x=>x<<C>>>C,w=y(w)}K(r,{name:a,A:y,D:(x,I)=>I,F:Dt(a,h,d!==0),B:null})},a:(r,a,h)=>{function d(y){return new w(b.buffer,T[y+4>>2],T[y>>2])}var w=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][a];h=D(h),K(r,{name:h,A:d,F:d},{L:!0})},j:(r,a)=>{a=D(a),K(r,{name:a,A(h){var d=(d=h+4)?Re.decode(E.subarray(d,Ht(E,d,T[h>>2],!0))):"";return V(h),d},D(h,d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));var w,y=typeof d=="string";if(!(y||ArrayBuffer.isView(d)&&d.BYTES_PER_ELEMENT==1))throw new j("Cannot pass non-string to std::string");var C;if(y)for(w=C=0;w<d.length;++w){var x=d.charCodeAt(w);127>=x?C++:2047>=x?C+=2:55296<=x&&57343>=x?(C+=4,++w):C+=3}else C=d.length;if(w=C,C=vt(4+w+1),x=C+4,T[C>>2]=w,y){if(y=x,x=w+1,w=E,0<x){x=y+x-1;for(var I=0;I<d.length;++I){var A=d.codePointAt(I);if(127>=A){if(y>=x)break;w[y++]=A}else if(2047>=A){if(y+1>=x)break;w[y++]=192|A>>6,w[y++]=128|A&63}else if(65535>=A){if(y+2>=x)break;w[y++]=224|A>>12,w[y++]=128|A>>6&63,w[y++]=128|A&63}else{if(y+3>=x)break;w[y++]=240|A>>18,w[y++]=128|A>>12&63,w[y++]=128|A>>6&63,w[y++]=128|A&63,I++}}w[y]=0}}else E.set(d,x);return h!==null&&h.push(V,C),C},F:lt,B(h){V(h)}})},d:(r,a,h)=>{if(h=D(h),a===2)var d=We,w=Ne,y=$e;else d=Be,w=Fe,y=Ge;K(r,{name:h,A:C=>{var x=d(C+4,T[C>>2]*a,!0);return V(C),x},D:(C,x)=>{if(typeof x!="string")throw new j(`Cannot pass non-string to C++ string type ${h}`);var I=y(x),A=vt(4+I+a);return T[A>>2]=I/a,w(x,A+4,I+a),C!==null&&C.push(V,A),A},F:lt,B(C){V(C)}})},o:(r,a,h,d,w,y)=>{ct[r]={name:D(a),N:nt(h,d),O:nt(w,y),elements:[]}},g:(r,a,h,d,w,y,C,x,I)=>{ct[r].elements.push({K:a,I:nt(h,d),J:w,R:y,P:nt(C,x),S:I})},l:(r,a)=>{a=D(a),K(r,{M:!0,name:a,A:()=>{},D:()=>{}})},n:r=>{var a=E.length;if(r>>>=0,2147483648<r)return!1;for(var h=1;4>=h;h*=2){var d=a*(1+.2/h);d=Math.min(d,r+100663296);t:{d=(Math.min(2147483648,65536*Math.ceil(Math.max(r,d)/65536))-ut.buffer.byteLength+65535)/65536|0;try{ut.grow(d),Tt();var w=1;break t}catch{}w=void 0}if(w)return!0}return!1}},dt;return dt=await(async function(){function r(h){return h=dt=h.exports,Kt=h.s,Jt=e._main=h.u,vt=h.v,V=h.w,ut=h.q,Vt=h.t,Tt(),dt}var a={a:De};return e.instantiateWasm?new Promise(h=>{e.instantiateWasm(a,(d,w)=>{h(r(d,w))})}):(xt??(xt=e.locateFile?e.locateFile("millirec.wasm",c):c+"millirec.wasm"),r((await ye(a)).instance))})(),(function(){function r(){if(e.calledRun=!0,!L){if(Lt=!0,dt.r(),O?.(e),e.onRuntimeInitialized?.(),!e.noInitialRun){var a=Jt;try{var h=a(0,0);Nt||(e.onExit?.(h),L=!0),l(h,new Pt(h))}catch(d){d instanceof Pt||d=="unwind"||l(1,d)}}if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)a=e.postRun.shift(),zt.push(a);Rt(zt)}}if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)xe();Rt(Wt),e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),r()},1)):r()})(),Lt?s=e:s=new Promise((r,a)=>{O=r,S=a}),s}})();typeof exports=="object"&&typeof module=="object"?(module.exports=ft,module.exports.default=ft):typeof define=="function"&&define.amd&&define([],()=>ft);var Yt=ft;var Qt={stroke:{alpha:1,beta:.003,maxCost:30,divi:1,outliersMul:1,outlierCost:0,scoreMode:0,kappaGamma:0,gateScale:1},image:{alpha:5,beta:.002,maxCost:90,divi:1,outliersMul:2,outlierCost:0,scoreMode:0,kappaGamma:3,gateScale:.6}};function te(u){let t=[],s=0,e=0;for(let o=0;o<u.x.length;o++)s+=u.x[o],e+=u.y[o],t.push({x:s,y:e});return t}function _t(u){let t=u.length,s=[0,0],e=[0,0],o=[];for(let m=0;m<t;m++){let f=u[m];s[0]+=f.x,s[1]+=f.y;let g={x:f.x,y:f.y,a:1.570795};m>0&&f.x!==e[0]&&(g.a=Math.atan2(f.y-e[1],f.x-e[0])),g.s=Math.sin(g.a),g.c=Math.cos(g.a),m===1&&(o[0].s=g.s,o[0].c=g.c),e=[f.x,f.y],o.push(g)}s[0]/=t,s[1]/=t;let n=[0,0],i=[0,0],l=[0,0],c=[0,0];for(let m of o)m.x<s[0]?(l[0]+=m.x-s[0],l[1]++):(c[0]+=m.x-s[0],c[1]++),m.y<s[1]?(n[0]+=m.y-s[1],n[1]++):(i[0]+=m.y-s[1],i[1]++),m.x-=s[0],m.y-=s[1];n[1]>0&&(n[0]/=n[1]),i[1]>0&&(i[0]/=i[1]),l[1]>0&&(l[0]/=l[1]),c[1]>0&&(c[0]/=c[1]);let p=i[0]-n[0]<c[0]-l[0]?100/(c[0]-l[0]):n[0]<i[0]?100/(i[0]-n[0]):1;return{points:o,scale:p}}function ee(u,t=50){let s=[],e=0;for(let i of u)for(let l=1;l<i.length;l++){let c=i[l].x-i[l-1].x,p=i[l].y-i[l-1].y,m=Math.sqrt(c*c+p*p);s.push({ax:i[l-1].x,ay:i[l-1].y,bx:i[l].x,by:i[l].y,cumStart:e,cumEnd:e+m}),e+=m}if(!e||!s.length)return null;let o=[],n=0;for(let i=0;i<t;i++){let l=i*e/(t-1);for(;n<s.length-1&&s[n].cumEnd<l;)n++;let c=s[n],p=c.cumEnd-c.cumStart,m=p?Math.min(1,Math.max(0,(l-c.cumStart)/p)):0;o.push({x:c.ax+(c.bx-c.ax)*m,y:c.ay+(c.by-c.ay)*m})}return o}var F={capitals:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowercase:"abcdefghijklmnopqrstuvwxyz",digits:"0123456789",punctuation:",.:/'-%$"};F.all=F.capitals+F.lowercase+F.digits+F.punctuation;var kt=["capitals","lowercase","digits","punctuation","all"],re=",.:",fs="don't can't won't isn't aren't wasn't weren't hasn't haven't hadn't doesn't didn't wouldn't couldn't shouldn't i'm i've i'll i'd you're you've you'll you'd he's he'll he'd she's she'll she'd it's we're we've we'll we'd they're they've they'll they'd that's there's here's what's who's where's when's how's let's o'clock ain't y'all ma'am".split(" "),ne=F.capitals;function et(u="capitals"){if(Array.isArray(u))return[...new Set(u.map(e=>String(e)).filter(e=>e.length===1))];let t=String(u??"capitals").trim();if(!t)return[...F.capitals];let s=t.split(/[,+\s]+/).filter(Boolean);return s.every(e=>F[e])?[...new Set(s.flatMap(e=>[...F[e]]))]:[...new Set([...t.replace(/\s+/g,"")])]}function it(u){let t=[...u].join("");for(let s of kt)if([...new Set([...F[s]])].join("")===t)return s;return null}var oe=u=>u.some(t=>t!==t.toLowerCase()),ie=u=>u.some(t=>t!==t.toUpperCase());function ae(u,t,s=null){let e=t,o=s||new Map(e.map((c,p)=>[c,p])),n=String(u??"").trim();if(!n)return null;let i=oe(e),l=ie(e);i&&!l?n=n.toUpperCase():l&&!i&&(n=n.toLowerCase());for(let c of n)if(!o.has(c))return null;return n}function st(u,{alphabet:t="capitals",weightOf:s=n=>1/(n+1),topK:e=8,variants:o="auto"}={}){let n=et(t),i=new Map(n.map((_,k)=>[_,k])),l=n.length,c=0,p=_=>({id:c++,ch:new Array(l).fill(null),mass:0,end:0,depth:_,word:null,top:[],logMass:0}),m=p(0),f=new Set,g=[],M=0,L=oe(n)&&ie(n),v=o===!0||o==="auto"&&L,O=(_,k)=>{if(f.has(_))return;f.add(_),g.push(_);let P=m,T=[m];for(let R of _){let z=i.get(R);P=P.ch[z]||(P.ch[z]=p(T.length)),T.push(P)}P.end+=k,P.word=_;for(let R of T){R.mass+=k;let z=R.top;if(z.length<e||k>z[z.length-1].wt){let H=z.length;for(;H>0&&z[H-1].wt<k;)H--;z.splice(H,0,{word:_,wt:k}),z.length>e&&z.pop()}}};for(let _ of u||[]){let k=ae(_,n,i);if(!k)continue;let P=s(M,k);if(M++,O(k,P),v&&k===k.toLowerCase()&&k!==k.toUpperCase()){let T=k[0].toUpperCase()+k.slice(1);[...T].every(z=>i.has(z))&&O(T,P/3);let R=k.toUpperCase();[...R].every(z=>i.has(z))&&O(R,P/10)}}let S=[m];for(;S.length;){let _=S.pop();_.logMass=_.mass>0?Math.log(_.mass):-1/0;for(let k of _.ch)k&&S.push(k)}let b={id:-2,ch:new Array(l).fill(null),mass:1,end:1,depth:-1,word:null,top:[],logMass:0,mark:!0},E=_=>{let k=m,P=String(_);for(let T=0;T<P.length;T++){let R=P[T],z=i.get(R),H=z==null?null:k.ch[z];if(!H)return T===P.length-1&&re.includes(R)&&k.end>0?b:null;k=H}return k};return{root:m,size:g.length,words:g,lookup:E,alphabet:n,idx:i,free:g.length===0,markNode:b}}function rt(u){return String(u||"").split(/[\s,;]+/).map(t=>t.trim()).filter(Boolean)}async function ce(u,t,{params:s=null,locateFile:e=null,alphabet:o=null}={}){let n={...Qt.stroke,...s||{}},i=await u(e?{locateFile:e}:{}),l=o?new Set(et(o)):null,c=Object.keys(t.classes).filter(b=>!l||l.has(b[0]));if(!c.length)throw new Error("createMatcher: no template class matches the alphabet");let p=new Map(c.map((b,E)=>[b,E])),m=Math.max(1,...c.map(b=>t.classes[b].length)),f=t.pointsPerShape;i.firstCall(n.alpha,n.beta,n.maxCost,n.divi,f,m,c.length),n.outlierCost&&i.setOutlierCost(n.outlierCost),n.scoreMode&&i.setScoreMode(n.scoreMode),n.kappaGamma&&i.setKappaGamma&&i.setKappaGamma(n.kappaGamma),n.gateMode!=null&&i.setGateMode&&i.setGateMode(n.gateMode),n.gateScale!=null&&i.setGateScale&&i.setGateScale(n.gateScale);let g=0,M=new Map,L=1;c.forEach((b,E)=>t.classes[b].forEach((_,k)=>{let{points:P,scale:T}=_t(te(_));if(P.forEach((R,z)=>i.addPoint(E*m+k,z,R.x*T,R.y*T,R.s,R.c)),g++,b.length===1&&_.strokes>0){M.has(b)||M.set(b,{n:0,hist:new Map});let R=M.get(b);R.n++,R.hist.set(_.strokes,(R.hist.get(_.strokes)||0)+1),_.strokes>L&&(L=_.strokes)}}));let v=L+2,O=.5,S=0;return{pps:f,keys:c,spc:m,training:t,params:n,templates:g,current:null,alphabet:[...new Set(c.map(b=>b[0]))],has:b=>p.has(b),strokeLogP(b,E){let _=M.get(b);if(!_)return 0;let k=Math.min(Math.max(1,E),v),P=((_.hist.get(k)||0)+O)/(_.n+O*v);return Math.log(P*v)},get calls(){return S},upload(b,E=null){this.current=E;let _=ee(b,f);if(!_)return!1;let{points:k,scale:P}=_t(_);for(let T=0;T<k.length;T++){let R=k[T];i.addPoint(-1,T,R.x*P,R.y*P,R.s,R.c)}return!0},costs(b){let E=p.get(b),_=new Array(t.classes[b].length);for(let k=0;k<_.length;k++)_[k]=i.getTestScore(E,k,f,n.outliersMul),S++;return _}}}function se(u,t="prod"){let s=1/0,e=1/0;for(let o of u)o<s?(e=s,s=o):o<e&&(e=o);return t==="min"||s===1/0?s:e===1/0?Math.cbrt(.9)*s:Math.cbrt(s*s*e)}var At={maxStrokes:5,costRef:.5,costEps:.02,temp:.4,shMax:4,lmW:1,commitMargin:5,beamMargin:12,beamK:32,oovPen:15,endFloor:-10,doneBoost:1,combine:"prod",combinePart:"min",pruneClasses:!0,oovTrigger:0,sizeW:1,sizeCap:8,tinyShape:1,freeMarkShare:.15,sizeRef0:160,sizeSd0:.35,sizeSd:.15,markP:.3,tinyRatio:.5,tinyPen:8,strokeCountW:"auto"},ot=class{constructor({matcher:t,lexicon:s,opts:e={}}){this.m=t,this.opts={...At,...e},this._useLexicon(s),this.reset()}_useLexicon(t){this.lex=t,this.A=t.alphabet,this.idx=t.idx,this.NA=this.A.length,this.LOGA=-Math.log(this.NA),this.ALL=Array.from({length:this.NA},(c,p)=>p),this.markIdx=[...re].map(c=>this.idx.get(c)).filter(c=>c!=null);let s=this.m.training&&this.m.training.sizes||{},e=this.m.training&&this.m.training.capRef||84;this.capRef=e,this.sizes=this.A.map(c=>s[c]?{mu:s[c].mu,sd:Math.max(.15,s[c].sd||0),eligible:Math.exp(s[c].mu)>=.4*e,minStroke:s[c].minStroke||0,tiny:Math.exp(s[c].mu)<.2*e}:null);let o=this.A.map(c=>F.punctuation.includes(c)),n=o.filter(Boolean).length,i=this.NA-n;this.freeLogP=this.A.map((c,p)=>n&&i?Math.log(o[p]?this.opts.freeMarkShare/n:(1-this.opts.freeMarkShare)/i):this.LOGA);let l=this.A.filter(c=>!this.m.has(c));l.length&&console.warn("OverlapRecognizer: no templates for "+JSON.stringify(l.join("")))}_sizeRef(){let t=[],s=o=>{for(let n of o){let i=this.idx.get(n.ch),l=i==null?null:this.sizes[i];!l||!l.eligible||!n.dim||t.push(n.dim/Math.exp(l.mu))}};for(let o of this.words)s(o.groups);s(this.beam[0].groups);let e=t.slice(-12).sort((o,n)=>o-n);return e.length?{scale:e[Math.floor(e.length/2)],known:!0}:{scale:this.opts.sizeRef0/this.capRef,known:!1}}_sizeScore(t,s){let e=this.sizes[s];if(!e||!t.dim)return 0;let o=0;if(this.opts.sizeW){let n=this._sizeZ(t,s);o-=this.opts.sizeW*Math.min(this.opts.sizeCap,.5*n*n)}return t.k>1&&e.minStroke&&t.minFrac<this.opts.tinyRatio*e.minStroke&&(o-=this.opts.tinyPen),o}get free(){return this.lex.size===0}get scw(){let t=this.opts.strokeCountW;return t==="auto"||t==null?this.free?1:.25:Number(t)}reset(){return this.strokes=[],this.erased=[],this.beam=[this._rootEntry()],this.words=[],this.cache=new Map,this.history=[],this.nextId=1,this.last=this._state([],null,0),this.last}setLexicon(t){this._snapshot();let s=this.beam[0].text,e=t.alphabet.join("")===this.A.join("");this._useLexicon(t),e||this.cache.clear();let o=t.size?t.lookup(s):null;return this.beam=[{text:s,node:t.size?o:null,score:0,groups:this.beam[0].groups}],this._report(null)}setOpts(t){return this.opts={...this.opts,...t},this._report(null)}_rootEntry(){return{text:"",node:this.lex.size?this.lex.root:null,score:0,groups:[]}}_snapshot(){this.history.push({strokes:this.strokes.slice(),erased:this.erased.slice(),beam:this.beam.slice(),words:this.words.slice()}),this.history.length>200&&this.history.shift()}clearWord(){return this._snapshot(),this.strokes=[],this.erased=[],this.beam=[this._rootEntry()],this._report(null)}undo(){let t=this.history.pop();return t?(this.strokes=t.strokes,this.erased=t.erased,this.beam=t.beam,this.words=t.words,this._report(null)):this.last}addStroke(t,{t0:s=0,t1:e=0}={}){return!t||t.length<2?this.last:(this._snapshot(),this.strokes.push({id:this.nextId++,pts:t.map(o=>({x:o.x,y:o.y})),t0:s,t1:e}),this._step())}finishWord({word:t=null}={}){if(t)return this.selectWord(t,{finish:!0});this._snapshot();let s=tt(),e=this.opts,o=null,n=new Map,i=(p,m,f,g)=>{let M=m+e.lmW*this._endLogP(f);(!n.has(p)||n.get(p).score<M)&&n.set(p,{text:p,score:M,groups:g,inList:!!(f&&f.end)}),(!o||M>o.score)&&(o=n.get(p))};if(this.strokes.length===0)for(let p of this.beam)i(p.text,p.score,p.node,p.groups);else{let{hyps:p}=this._dp(),m=(f,g)=>this.beam[g.beam].groups.concat(g.groups,[this._mkGroup(f.i,this.strokes.length,f.L,f.shapeFull)]);for(let f of p){if(f.shapeFull===-1/0)continue;let g=this._path(f);i(f.text,f.score-f.shape+f.shapeFull,f.node,m(f,g))}if(!o)for(let f of p){let g=this._path(f);i(f.text,f.score,f.node,m(f,g))}}o||(o={text:this.beam[0].text,score:0,groups:this.beam[0].groups,inList:!1});let l=[...n.values()].sort((p,m)=>m.score-p.score).slice(0,6).map(p=>({text:p.text,score:p.score,inList:p.inList})),c={word:o.text,groups:o.groups,alternatives:l,inList:o.inList,selected:!1};return this._finish(c,tt()-s)}_finish(t,s){return t.word&&this.words.push(t),this._ref=null,this.strokes=[],this.erased=[],this.beam=[this._rootEntry()],this.cache.clear(),this.last=this._state([],null,s,{finished:t}),this.last}fitToWord(t){let s=ae(t,this.A,this.idx),e=this.erased.concat(this.strokes),o=e.length;if(!s||!o)return null;let n=[...s].map(v=>this.idx.get(v)),i=this.opts,l=Math.min(n.length,o),c=-1/0,p=Array.from({length:l+1},()=>new Float64Array(o+1).fill(c)),m=Array.from({length:l+1},()=>new Int32Array(o+1).fill(-1));p[0][0]=0;for(let v=1;v<=l;v++){let O=n[v-1];for(let S=v;S<o;S++)for(let b=Math.max(v-1,S-i.maxStrokes);b<S;b++){if(p[v-1][b]===c)continue;let E=this._groupOf(e,b,S);this._cost(E,O);let _=this._closedScore(E,O);if(_===c)continue;let k=p[v-1][b]+_;k>p[v][S]&&(p[v][S]=k,m[v][S]=b)}}let f=null;for(let v=1;v<=l;v++){let O=n[v-1];for(let S=Math.max(v-1,o-i.maxStrokes);S<o;S++){if(p[v-1][S]===c)continue;let b=this._groupOf(e,S,o);this._cost(b,O);let{full:E,part:_,best:k}=this._openScore(b,O);if(k===c)continue;let P=p[v-1][S]+k;(!f||P>f.score)&&(f={score:P,m:v,i:S,partial:_>E,sF:E})}}if(!f)return null;let g=[],M=f.i;for(let v=f.m-1;v>=1;v--){let O=m[v][M];g.push(this._mkGroupOf(e,O,M,n[v-1])),M=O}return g.reverse(),g.push({...this._mkGroupOf(e,f.i,o,n[f.m-1],f.sF),open:!0,partial:f.partial}),{text:s.slice(0,f.m),groups:g,m:f.m,complete:f.m===n.length&&!f.partial,score:f.score,word:s}}selectWord(t,{finish:s=!0}={}){let e=this.fitToWord(t);if(!e)return this.last;this._snapshot();let o=tt();if(s){let p=e.groups.map(g=>({ch:g.ch,ids:g.ids,strokes:g.strokes,sh:g.sh}));for(let g=e.m;g<e.word.length;g++)p.push({ch:e.word[g],ids:[],strokes:[],sh:null});let m=this.lex.size?this.lex.lookup(e.word):null,f={word:e.word,groups:p,alternatives:[],inList:!!(m&&m.end),selected:!0,complete:e.complete};return this._finish(f,tt()-o)}let n=e.groups.slice(0,-1),i=e.groups[e.groups.length-1],l=n.map(p=>p.ch).join("");this.beam=[{text:l,node:this.lex.size?this.lex.lookup(l):null,score:0,groups:n.map(p=>({ch:p.ch,ids:p.ids,strokes:p.strokes,sh:p.sh}))}];let c=this.erased.concat(this.strokes);return this.erased=c.slice(0,c.length-i.ids.length),this.strokes=c.slice(c.length-i.ids.length),this._report({b:0,margin:1/0,erased:[],selected:e.word})}_sh(t){if(t===1/0)return-1/0;let s=(Math.log(this.opts.costRef)-Math.log(t+this.opts.costEps))/this.opts.temp,e=this.opts.shMax;return s>0&&e>0?e*Math.tanh(s/e):s}_next(t,s){if(t===null)return{node:null,lm:this.free?this.freeLogP[s]:this.LOGA};let e=t.ch[s];return e?{node:e,lm:e.logMass-t.logMass}:t.end>0&&!t.mark&&this.markIdx.includes(s)?{node:this.lex.markNode,lm:Math.log(t.end)-t.logMass+Math.log(this.opts.markP)}:{node:null,lm:this.LOGA-this.opts.oovPen}}_endLogP(t){return t===null?this.free?0:-this.opts.oovPen:t.end?Math.log(t.end)-t.logMass:this.opts.endFloor}_groupOf(t,s,e){let o=t.slice(s,e).map(M=>M.id).join(","),n=this.cache.get(o);if(n)return n;let i=t.slice(s,e).map(M=>M.pts),l=1/0,c=1/0,p=-1/0,m=-1/0;for(let M of i)for(let L of M)L.x<l&&(l=L.x),L.y<c&&(c=L.y),L.x>p&&(p=L.x),L.y>m&&(m=L.y);let f=Math.max(p-l,m-c,1),g=1/0;for(let M of i){let L=1/0,v=1/0,O=-1/0,S=-1/0;for(let E of M)E.x<L&&(L=E.x),E.y<v&&(v=E.y),E.x>O&&(O=E.x),E.y>S&&(S=E.y);let b=Math.max(O-L,S-v,1);b<g&&(g=b)}return n={key:o,k:e-s,pts:i,dim:f,minFrac:g/f,full:new Float64Array(this.NA).fill(NaN),part:new Float64Array(this.NA).fill(NaN),scored:[],ok:null},this.cache.set(o,n),n}_cost(t,s){if(Number.isNaN(t.full[s])){(t.ok===null||this.m.current!==t.key)&&(t.ok=this.m.upload(t.pts,t.key));let e=this.A[s];t.full[s]=t.ok&&this.m.has(e)?se(this.m.costs(e),this.opts.combine):1/0;let o=e+"/"+t.k;t.part[s]=t.ok&&this.m.has(o)?se(this.m.costs(o),this.opts.combinePart):1/0,t.scored.push(s)}return{full:t.full[s],part:t.part[s]}}_sizeZ(t,s){let e=this.sizes[s];if(!e||!t.dim)return 0;this._ref||(this._ref=this._sizeRef());let o=Math.sqrt(e.sd*e.sd+(this._ref.known?this.opts.sizeSd:this.opts.sizeSd0)**2);return(Math.log(t.dim/this._ref.scale)-e.mu)/o}_shOf(t,s){if(t.full[s]===1/0)return-1/0;let e=this.sizes[s];return e&&e.tiny?this._sizeZ(t,s)<3?this.opts.tinyShape:-1/0:this._sh(t.full[s])}_closedScore(t,s){let e=this._shOf(t,s);return e===-1/0?-1/0:e*t.k+this.scw*this.m.strokeLogP(this.A[s],t.k)+this._sizeScore(t,s)}_openScore(t,s){let e=this._shOf(t,s),o=this._sh(t.part[s]),n=e===-1/0?-1/0:e*t.k+this.scw*this.m.strokeLogP(this.A[s],t.k)+this._sizeScore(t,s),i=o===-1/0?-1/0:o*t.k;return{full:n,part:i,best:Math.max(n,i)}}_scoreGroup(t,s,e){if(s===this.ALL||!this.opts.pruneClasses){for(let n of this.ALL)this._cost(t,n);return t.scored}let o=-1/0;for(let n of s){let i=this._cost(t,n),l=e?Math.max(this._sh(i.full),this._sh(i.part)):this._sh(i.full);l>o&&(o=l)}if(o<this.opts.oovTrigger)for(let n of this.ALL)this._cost(t,n);return t.scored}_allowed(t){if(!this.opts.pruneClasses)return this.ALL;let s=new Set;for(let e of t){if(e.node===null)return this.ALL;let o=e.node.ch;for(let n=0;n<this.NA;n++)o[n]&&s.add(n);if(e.node.end>0&&!e.node.mark)for(let n of this.markIdx)s.add(n)}return[...s]}_group(t,s){return this._groupOf(this.strokes,t,s)}_dp(t=-1){let s=this.strokes,e=s.length,o=this.opts,n=new Array(e+1);n[0]=this.beam.map((c,p)=>({score:c.score,node:c.node,text:c.text,beam:p,back:null,pos:0}));let i=new Array(e+1);i[0]=this._allowed(n[0]);for(let c=1;c<=e;c++){let p=new Map;if(c!==t&&c<e)for(let m=Math.max(0,c-o.maxStrokes);m<c;m++){if(!n[m].length)continue;let f=this._group(m,c),g=this._scoreGroup(f,i[m],!1);for(let M of n[m])for(let L of g){let v=this._closedScore(f,L);if(v===-1/0)continue;let O=this._next(M.node,L),S=M.score+v+o.lmW*O.lm,b=M.text+this.A[L],E=O.node?O.node.id:"off:"+b,_=p.get(E);(!_||_.score<S)&&p.set(E,{score:S,node:O.node,text:b,beam:M.beam,back:{i:m,st:M,L,sh:v},pos:c})}}n[c]=[...p.values()].sort((m,f)=>f.score-m.score).slice(0,o.beamK),i[c]=this._allowed(n[c])}let l=[];for(let c=Math.max(0,e-o.maxStrokes);c<e;c++){if(!n[c].length)continue;let p=this._group(c,e),m=this._scoreGroup(p,i[c],!0);for(let f of n[c])for(let g of m){let{full:M,part:L,best:v}=this._openScore(p,g);if(v===-1/0)continue;let O=this._next(f.node,g);l.push({score:f.score+v+o.lmW*O.lm,i:c,st:f,L:g,node:O.node,text:f.text+this.A[g],partial:L>M,shape:v,shapeFull:M,shapePart:L,lm:O.lm})}}return l.sort((c,p)=>p.score-c.score),{states:n,hyps:l}}_path(t){let s=[],e=t.st;for(;e.back;)s.push(this._mkGroup(e.back.i,e.pos,e.back.L,e.back.sh)),e=e.back.st;return s.reverse(),{beam:e.beam,groups:s,bounds:s.map(o=>o.j)}}_mkGroupOf(t,s,e,o,n=null){let i=t.slice(s,e);return{ch:this.A[o],ids:i.map(l=>l.id),strokes:i.map(l=>l.pts),sh:n,j:e,dim:this._groupOf(t,s,e).dim}}_mkGroup(t,s,e,o=null){return this._mkGroupOf(this.strokes,t,s,e,o)}_step(){let t=tt();this._ref=null;let{hyps:s}=this._dp(),e=null;if(s.length){let o=s[0],n=this._path(o),i=[o.i,...n.bounds.slice().reverse()].filter((l,c,p)=>l>0&&p.indexOf(l)===c);for(let l of i){let c=this._dp(l),p=c.hyps.length?c.hyps[0].score:-1/0,m=o.score-p;if(m>=this.opts.commitMargin){e={b:l,margin:m};break}}}return e&&(e.erased=this._commit(e.b,s),this._ref=null,{hyps:s}=this._dp()),this.last=this._state(s,e,tt()-t),this.last}_commit(t,s){let e=this.opts,o=s[0].score,n=new Map;for(let m of s){if(m.score<o-e.beamMargin)break;let f=m.st;if(m.i<t)continue;for(;f&&f.pos>t;)f=f.back?f.back.st:null;if(!f||f.pos!==t)continue;let g=f.node?f.node.id:"off:"+f.text,M=n.get(g);(!M||M.total<m.score)&&n.set(g,{st:f,total:m.score})}let i=[...n.values()].sort((m,f)=>f.total-m.total).slice(0,e.beamK),l=this.beam,c=this.strokes.slice(0,t),p=i[0].st.score;return this.beam=i.map(({st:m})=>{let f=[],g=m;for(;g.back;)f.push(this._mkGroup(g.back.i,g.pos,g.back.L,g.back.sh)),g=g.back.st;return f.reverse(),{text:m.text,node:m.node,score:m.score-p,groups:l[g.beam].groups.concat(f)}}),this.erased=this.erased.concat(c),this.strokes=this.strokes.slice(t),c}_report(t){this._ref=null;let{hyps:s}=this._dp();return this.last=this._state(s,t,0),this.last}_candidates(t){let s=this.opts,e=new Map,o=(l,c,p)=>{let m=e.get(l);(!m||m.score<c)&&e.set(l,{word:l,score:c,kind:p,complete:p==="done"})},n=t.length?t:this.beam.map(l=>({score:l.score,node:l.node,text:l.text})),i=n.length?n[0].score:0;for(let l of n){if(l.score<i-s.beamMargin)break;if(l.node===null){l.text&&o(l.text,l.score-(this.free?0:s.oovPen),this.free?"free":"oov");continue}if(l.node.mark){o(l.text,l.score+s.doneBoost,"done");continue}l.node.end&&o(l.text,l.score+s.lmW*(Math.log(l.node.end)-l.node.logMass)+s.doneBoost,"done");for(let c of l.node.top)o(c.word,l.score+s.lmW*(Math.log(c.wt)-l.node.logMass),c.word===l.text?"done":"more")}return[...e.values()].sort((l,c)=>c.score-l.score).slice(0,8)}_state(t,s,e,o={}){let n=t[0]||null,i=[];n?i=this._path(n).groups.map(p=>({ch:p.ch,ids:p.ids,strokes:p.strokes,open:!1})).concat([{ch:this.A[n.L],ids:this.strokes.slice(n.i).map(p=>p.id),strokes:this.strokes.slice(n.i).map(p=>p.pts),open:!0,partial:n.partial}]):this.strokes.length&&(i=[{ch:"",ids:this.strokes.map(c=>c.id),strokes:this.strokes.map(c=>c.pts),open:!0,partial:!0}]);let l=c=>{let p=this._path(c);return{text:c.text,score:c.score,i:c.i,partial:c.partial,shape:c.shape,lm:c.lm,groups:p.groups.map(m=>m.ch+"("+m.ids.length+")").concat([c.partial?c.text.slice(-1)+"\u2026":c.text.slice(-1)]),beam:p.beam}};return{n:this.strokes.length,text:n?n.text:this.beam[0].text,committed:this.beam[0].text,pending:n?n.text.slice(this.beam[0].text.length):"",ambiguous:this.beam.length>1,beam:this.beam.map(c=>({text:c.text,score:c.score,oov:c.node===null&&!this.free})),groups:this.beam[0].groups,hyps:t.slice(0,10).map(l),assignment:i,candidates:this._candidates(t),commit:s?{b:s.b,margin:s.margin,erased:s.erased,selected:s.selected||null}:null,words:this.words,strokes:this.strokes,alphabet:this.A,free:this.free,sizeRef:this._ref||this._sizeRef(),ms:e,...o}}},tt=()=>typeof performance<"u"?performance.now():Date.now();var Je="1.0.0",It="__MILLIREC_BASE_URL__",de=!It.startsWith("__"),Ve=(()=>{let u=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return u?u.slice(0,u.lastIndexOf("/")+1):""})(),Mt=typeof window<"u"?window:globalThis,gt=()=>Mt.MILLIREC_OVERLAP||{},yt=u=>u.assetBase||gt().assetBase||(de?It+"/overlap/":Ve),qe=u=>(u.apiBase||gt().apiBase||(de?It:"")).replace(/\/$/,""),mt=new Map;function Et(u,t){let s=et(t),o=`training.${it(s)||"all"}.json`,n=u+"|"+s.join("");return mt.has(n)||mt.set(n,(async()=>{let i=await fetch(u+o);if(!i.ok)throw new Error(`MillirecOverlap: could not load ${u}${o} (${i.status})`);let l=await i.json(),c=await ce(Yt,l,{locateFile:p=>u+p,alphabet:s});return{training:l,matcher:c,alphabet:s}})().catch(i=>{throw mt.delete(n),i})),mt.get(n)}async function le(u){if(Array.isArray(u.words))return{words:u.words,source:"words"};if(typeof u.words=="string"&&u.words.trim())return{words:rt(u.words),source:"words"};if(u.list){let s=qe(u);if(!s)throw new Error("MillirecOverlap: a hosted list (data-list) needs apiBase \u2014 the millirec server this list lives on");let e=await fetch(`${s}/api/overlap/lists/${encodeURIComponent(u.list)}`);if(!e.ok)throw new Error(`MillirecOverlap: word list ${u.list} not found (${e.status})`);let o=await e.json();return{words:o.words,source:"list",list:u.list,name:o.name}}if(u.wordsSrc){let s=await fetch(u.wordsSrc);if(!s.ok)throw new Error(`MillirecOverlap: could not load ${u.wordsSrc} (${s.status})`);let e=await s.text(),o;try{let n=JSON.parse(e);o=Array.isArray(n)?n:n.words}catch{o=rt(e)}return{words:o,source:"src"}}if(Array.isArray(gt().words))return{words:gt().words,source:"global"};if(Array.isArray(Mt.MILLIREC_WORDS))return{words:Mt.MILLIREC_WORDS,source:"global"};let t=await fetch(yt(u)+"words.json");if(!t.ok)throw new Error("MillirecOverlap: no word list given and the default words.json is missing");return{words:await t.json(),source:"default"}}var Xe=`
10
+ `),A=new Function(_t,B+`}
11
+ `)(...U),$=Object.defineProperty(A,"name",{value:$}),A=c-1,!e.hasOwnProperty(I))throw new Ft("Replacing nonexistent public symbol");return e[I].C!==void 0&&A!==void 0?e[I].C[A]=$:(e[I]=$,e[I].H=A),[]})},b:(r,c,h,p,g)=>{c=D(c);let y=x=>x;if(p===0){var C=32-8*h;y=x=>x<<C>>>C,g=y(g)}K(r,{name:c,A:y,D:(x,I)=>I,F:Dt(c,h,p!==0),B:null})},a:(r,c,h)=>{function p(y){return new g(b.buffer,T[y+4>>2],T[y>>2])}var g=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][c];h=D(h),K(r,{name:h,A:p,F:p},{L:!0})},j:(r,c)=>{c=D(c),K(r,{name:c,A(h){var p=(p=h+4)?Re.decode(E.subarray(p,Ht(E,p,T[h>>2],!0))):"";return V(h),p},D(h,p){p instanceof ArrayBuffer&&(p=new Uint8Array(p));var g,y=typeof p=="string";if(!(y||ArrayBuffer.isView(p)&&p.BYTES_PER_ELEMENT==1))throw new j("Cannot pass non-string to std::string");var C;if(y)for(g=C=0;g<p.length;++g){var x=p.charCodeAt(g);127>=x?C++:2047>=x?C+=2:55296<=x&&57343>=x?(C+=4,++g):C+=3}else C=p.length;if(g=C,C=bt(4+g+1),x=C+4,T[C>>2]=g,y){if(y=x,x=g+1,g=E,0<x){x=y+x-1;for(var I=0;I<p.length;++I){var A=p.codePointAt(I);if(127>=A){if(y>=x)break;g[y++]=A}else if(2047>=A){if(y+1>=x)break;g[y++]=192|A>>6,g[y++]=128|A&63}else if(65535>=A){if(y+2>=x)break;g[y++]=224|A>>12,g[y++]=128|A>>6&63,g[y++]=128|A&63}else{if(y+3>=x)break;g[y++]=240|A>>18,g[y++]=128|A>>12&63,g[y++]=128|A>>6&63,g[y++]=128|A&63,I++}}g[y]=0}}else E.set(p,x);return h!==null&&h.push(V,C),C},F:lt,B(h){V(h)}})},d:(r,c,h)=>{if(h=D(h),c===2)var p=We,g=Ne,y=$e;else p=Be,g=Fe,y=Ge;K(r,{name:h,A:C=>{var x=p(C+4,T[C>>2]*c,!0);return V(C),x},D:(C,x)=>{if(typeof x!="string")throw new j(`Cannot pass non-string to C++ string type ${h}`);var I=y(x),A=bt(4+I+c);return T[A>>2]=I/c,g(x,A+4,I+c),C!==null&&C.push(V,A),A},F:lt,B(C){V(C)}})},o:(r,c,h,p,g,y)=>{ct[r]={name:D(c),N:nt(h,p),O:nt(g,y),elements:[]}},g:(r,c,h,p,g,y,C,x,I)=>{ct[r].elements.push({K:c,I:nt(h,p),J:g,R:y,P:nt(C,x),S:I})},l:(r,c)=>{c=D(c),K(r,{M:!0,name:c,A:()=>{},D:()=>{}})},n:r=>{var c=E.length;if(r>>>=0,2147483648<r)return!1;for(var h=1;4>=h;h*=2){var p=c*(1+.2/h);p=Math.min(p,r+100663296);t:{p=(Math.min(2147483648,65536*Math.ceil(Math.max(r,p)/65536))-ut.buffer.byteLength+65535)/65536|0;try{ut.grow(p),Tt();var g=1;break t}catch{}g=void 0}if(g)return!0}return!1}},dt;return dt=await(async function(){function r(h){return h=dt=h.exports,Kt=h.s,Jt=e._main=h.u,bt=h.v,V=h.w,ut=h.q,Vt=h.t,Tt(),dt}var c={a:De};return e.instantiateWasm?new Promise(h=>{e.instantiateWasm(c,(p,g)=>{h(r(p,g))})}):(vt??(vt=e.locateFile?e.locateFile("millirec.wasm",a):a+"millirec.wasm"),r((await ye(c)).instance))})(),(function(){function r(){if(e.calledRun=!0,!L){if(Lt=!0,dt.r(),O?.(e),e.onRuntimeInitialized?.(),!e.noInitialRun){var c=Jt;try{var h=c(0,0);Nt||(e.onExit?.(h),L=!0),l(h,new Pt(h))}catch(p){p instanceof Pt||p=="unwind"||l(1,p)}}if(e.postRun)for(typeof e.postRun=="function"&&(e.postRun=[e.postRun]);e.postRun.length;)c=e.postRun.shift(),zt.push(c);Rt(zt)}}if(e.preRun)for(typeof e.preRun=="function"&&(e.preRun=[e.preRun]);e.preRun.length;)xe();Rt(Wt),e.setStatus?(e.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>e.setStatus(""),1),r()},1)):r()})(),Lt?s=e:s=new Promise((r,c)=>{O=r,S=c}),s}})();typeof exports=="object"&&typeof module=="object"?(module.exports=ft,module.exports.default=ft):typeof define=="function"&&define.amd&&define([],()=>ft);var Yt=ft;var Qt={stroke:{alpha:1,beta:.003,maxCost:30,divi:1,outliersMul:1,outlierCost:0,scoreMode:0,kappaGamma:0,gateScale:1},image:{alpha:5,beta:.002,maxCost:90,divi:1,outliersMul:2,outlierCost:0,scoreMode:0,kappaGamma:3,gateScale:.6}};function te(u){let t=[],s=0,e=0;for(let i=0;i<u.x.length;i++)s+=u.x[i],e+=u.y[i],t.push({x:s,y:e});return t}function kt(u){let t=u.length,s=[0,0],e=[0,0],i=[];for(let m=0;m<t;m++){let f=u[m];s[0]+=f.x,s[1]+=f.y;let w={x:f.x,y:f.y,a:1.570795};m>0&&f.x!==e[0]&&(w.a=Math.atan2(f.y-e[1],f.x-e[0])),w.s=Math.sin(w.a),w.c=Math.cos(w.a),m===1&&(i[0].s=w.s,i[0].c=w.c),e=[f.x,f.y],i.push(w)}s[0]/=t,s[1]/=t;let n=[0,0],o=[0,0],l=[0,0],a=[0,0];for(let m of i)m.x<s[0]?(l[0]+=m.x-s[0],l[1]++):(a[0]+=m.x-s[0],a[1]++),m.y<s[1]?(n[0]+=m.y-s[1],n[1]++):(o[0]+=m.y-s[1],o[1]++),m.x-=s[0],m.y-=s[1];n[1]>0&&(n[0]/=n[1]),o[1]>0&&(o[0]/=o[1]),l[1]>0&&(l[0]/=l[1]),a[1]>0&&(a[0]/=a[1]);let d=o[0]-n[0]<a[0]-l[0]?100/(a[0]-l[0]):n[0]<o[0]?100/(o[0]-n[0]):1;return{points:i,scale:d}}function ee(u,t=50){let s=[],e=0;for(let o of u){let l=o.length===1?[{x:o[0].x-.5,y:o[0].y},{x:o[0].x+.5,y:o[0].y}]:o;for(let a=1;a<l.length;a++){let d=l[a].x-l[a-1].x,m=l[a].y-l[a-1].y,f=Math.sqrt(d*d+m*m);s.push({ax:l[a-1].x,ay:l[a-1].y,bx:l[a].x,by:l[a].y,cumStart:e,cumEnd:e+f}),e+=f}}if(!e||!s.length)return null;let i=[],n=0;for(let o=0;o<t;o++){let l=o*e/(t-1);for(;n<s.length-1&&s[n].cumEnd<l;)n++;let a=s[n],d=a.cumEnd-a.cumStart,m=d?Math.min(1,Math.max(0,(l-a.cumStart)/d)):0;i.push({x:a.ax+(a.bx-a.ax)*m,y:a.ay+(a.by-a.ay)*m})}return i}var F={capitals:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowercase:"abcdefghijklmnopqrstuvwxyz",digits:"0123456789",punctuation:",.:/'-%$"};F.all=F.capitals+F.lowercase+F.digits+F.punctuation;var At=["capitals","lowercase","digits","punctuation","all"],re=",.:",ms="don't can't won't isn't aren't wasn't weren't hasn't haven't hadn't doesn't didn't wouldn't couldn't shouldn't i'm i've i'll i'd you're you've you'll you'd he's he'll he'd she's she'll she'd it's we're we've we'll we'd they're they've they'll they'd that's there's here's what's who's where's when's how's let's o'clock ain't y'all ma'am".split(" "),ne=F.capitals;function et(u="capitals"){if(Array.isArray(u))return[...new Set(u.map(e=>String(e)).filter(e=>e.length===1))];let t=String(u??"capitals").trim();if(!t)return[...F.capitals];let s=t.split(/[,+\s]+/).filter(Boolean);return s.every(e=>F[e])?[...new Set(s.flatMap(e=>[...F[e]]))]:[...new Set([...t.replace(/\s+/g,"")])]}function ot(u){let t=[...u].join("");for(let s of At)if([...new Set([...F[s]])].join("")===t)return s;return null}var ie=u=>u.some(t=>t!==t.toLowerCase()),oe=u=>u.some(t=>t!==t.toUpperCase());function ae(u,t,s=null){let e=t,i=s||new Map(e.map((a,d)=>[a,d])),n=String(u??"").trim();if(!n)return null;let o=ie(e),l=oe(e);o&&!l?n=n.toUpperCase():l&&!o&&(n=n.toLowerCase());for(let a of n)if(!i.has(a))return null;return n}function st(u,{alphabet:t="capitals",weightOf:s=n=>1/(n+1),topK:e=8,variants:i="auto"}={}){let n=et(t),o=new Map(n.map((_,k)=>[_,k])),l=n.length,a=0,d=_=>({id:a++,ch:new Array(l).fill(null),mass:0,end:0,depth:_,word:null,top:[],logMass:0}),m=d(0),f=new Set,w=[],M=0,L=ie(n)&&oe(n),v=i===!0||i==="auto"&&L,O=(_,k)=>{if(f.has(_))return;f.add(_),w.push(_);let P=m,T=[m];for(let R of _){let z=o.get(R);P=P.ch[z]||(P.ch[z]=d(T.length)),T.push(P)}P.end+=k,P.word=_;for(let R of T){R.mass+=k;let z=R.top;if(z.length<e||k>z[z.length-1].wt){let H=z.length;for(;H>0&&z[H-1].wt<k;)H--;z.splice(H,0,{word:_,wt:k}),z.length>e&&z.pop()}}};for(let _ of u||[]){let k=ae(_,n,o);if(!k)continue;let P=s(M,k);if(M++,O(k,P),v&&k===k.toLowerCase()&&k!==k.toUpperCase()){let T=k[0].toUpperCase()+k.slice(1);[...T].every(z=>o.has(z))&&O(T,P/3);let R=k.toUpperCase();[...R].every(z=>o.has(z))&&O(R,P/10)}}let S=[m];for(;S.length;){let _=S.pop();_.logMass=_.mass>0?Math.log(_.mass):-1/0;for(let k of _.ch)k&&S.push(k)}let b={id:-2,ch:new Array(l).fill(null),mass:1,end:1,depth:-1,word:null,top:[],logMass:0,mark:!0},E=_=>{let k=m,P=String(_);for(let T=0;T<P.length;T++){let R=P[T],z=o.get(R),H=z==null?null:k.ch[z];if(!H)return T===P.length-1&&re.includes(R)&&k.end>0?b:null;k=H}return k};return{root:m,size:w.length,words:w,lookup:E,alphabet:n,idx:o,free:w.length===0,markNode:b}}function rt(u){return String(u||"").split(/[\s,;]+/).map(t=>t.trim()).filter(Boolean)}async function ce(u,t,{params:s=null,locateFile:e=null,alphabet:i=null}={}){let n={...Qt.stroke,...s||{}},o=await u(e?{locateFile:e}:{}),l=i?new Set(et(i)):null,a=Object.keys(t.classes).filter(b=>!l||l.has(b[0]));if(!a.length)throw new Error("createMatcher: no template class matches the alphabet");let d=new Map(a.map((b,E)=>[b,E])),m=Math.max(1,...a.map(b=>t.classes[b].length)),f=t.pointsPerShape;o.firstCall(n.alpha,n.beta,n.maxCost,n.divi,f,m,a.length),n.outlierCost&&o.setOutlierCost(n.outlierCost),n.scoreMode&&o.setScoreMode(n.scoreMode),n.kappaGamma&&o.setKappaGamma&&o.setKappaGamma(n.kappaGamma),n.gateMode!=null&&o.setGateMode&&o.setGateMode(n.gateMode),n.gateScale!=null&&o.setGateScale&&o.setGateScale(n.gateScale);let w=0,M=new Map,L=1;a.forEach((b,E)=>t.classes[b].forEach((_,k)=>{let{points:P,scale:T}=kt(te(_));if(P.forEach((R,z)=>o.addPoint(E*m+k,z,R.x*T,R.y*T,R.s,R.c)),w++,b.length===1&&_.strokes>0){M.has(b)||M.set(b,{n:0,hist:new Map});let R=M.get(b);R.n++,R.hist.set(_.strokes,(R.hist.get(_.strokes)||0)+1),_.strokes>L&&(L=_.strokes)}}));let v=L+2,O=.5,S=0;return{pps:f,keys:a,spc:m,training:t,params:n,templates:w,current:null,alphabet:[...new Set(a.map(b=>b[0]))],has:b=>d.has(b),strokeLogP(b,E){let _=M.get(b);if(!_)return 0;let k=Math.min(Math.max(1,E),v),P=((_.hist.get(k)||0)+O)/(_.n+O*v);return Math.log(P*v)},get calls(){return S},upload(b,E=null){this.current=E;let _=ee(b,f);if(!_)return!1;let{points:k,scale:P}=kt(_);for(let T=0;T<k.length;T++){let R=k[T];o.addPoint(-1,T,R.x*P,R.y*P,R.s,R.c)}return!0},costs(b){let E=d.get(b),_=new Array(t.classes[b].length);for(let k=0;k<_.length;k++)_[k]=o.getTestScore(E,k,f,n.outliersMul),S++;return _}}}function se(u,t="prod"){let s=1/0,e=1/0;for(let i of u)i<s?(e=s,s=i):i<e&&(e=i);return t==="min"||s===1/0?s:e===1/0?Math.cbrt(.9)*s:Math.cbrt(s*s*e)}var St={maxStrokes:5,costRef:.5,costEps:.02,temp:.4,shMax:4,lmW:1,commitMargin:5,beamMargin:12,beamK:32,oovPen:15,endFloor:-10,doneBoost:1,combine:"prod",combinePart:"min",pruneClasses:!0,oovTrigger:0,sizeW:1,sizeCap:8,tinyShape:1,freeMarkShare:.15,sizeRef0:160,sizeSd0:.35,sizeSd:.15,markP:.3,tinyRatio:.5,tinyPen:8,strokeCountW:"auto"},it=class{constructor({matcher:t,lexicon:s,opts:e={}}){this.m=t,this.opts={...St,...e},this._useLexicon(s),this.reset()}_useLexicon(t){this.lex=t,this.A=t.alphabet,this.idx=t.idx,this.NA=this.A.length,this.LOGA=-Math.log(this.NA),this.ALL=Array.from({length:this.NA},(a,d)=>d),this.markIdx=[...re].map(a=>this.idx.get(a)).filter(a=>a!=null);let s=this.m.training&&this.m.training.sizes||{},e=this.m.training&&this.m.training.capRef||84;this.capRef=e,this.sizes=this.A.map(a=>s[a]?{mu:s[a].mu,sd:Math.max(.15,s[a].sd||0),eligible:Math.exp(s[a].mu)>=.4*e,minStroke:s[a].minStroke||0,tiny:Math.exp(s[a].mu)<.2*e}:null);let i=this.A.map(a=>F.punctuation.includes(a)),n=i.filter(Boolean).length,o=this.NA-n;this.freeLogP=this.A.map((a,d)=>n&&o?Math.log(i[d]?this.opts.freeMarkShare/n:(1-this.opts.freeMarkShare)/o):this.LOGA);let l=this.A.filter(a=>!this.m.has(a));l.length&&console.warn("OverlapRecognizer: no templates for "+JSON.stringify(l.join("")))}_sizeRef(){let t=[],s=i=>{for(let n of i){let o=this.idx.get(n.ch),l=o==null?null:this.sizes[o];!l||!l.eligible||!n.dim||t.push(n.dim/Math.exp(l.mu))}};for(let i of this.words)s(i.groups);s(this.beam[0].groups);let e=t.slice(-12).sort((i,n)=>i-n);return e.length?{scale:e[Math.floor(e.length/2)],known:!0}:{scale:this.opts.sizeRef0/this.capRef,known:!1}}_sizeScore(t,s){let e=this.sizes[s];if(!e||!t.dim)return 0;let i=0;if(this.opts.sizeW){let n=this._sizeZ(t,s);i-=this.opts.sizeW*Math.min(this.opts.sizeCap,.5*n*n)}return t.k>1&&e.minStroke&&t.minFrac<this.opts.tinyRatio*e.minStroke&&(i-=this.opts.tinyPen),i}get free(){return this.lex.size===0}get scw(){let t=this.opts.strokeCountW;return t==="auto"||t==null?this.free?1:.25:Number(t)}reset(){return this.strokes=[],this.erased=[],this.beam=[this._rootEntry()],this.words=[],this.cache=new Map,this.history=[],this.nextId=1,this.last=this._state([],null,0),this.last}setLexicon(t){this._snapshot();let s=this.beam[0].text,e=t.alphabet.join("")===this.A.join("");this._useLexicon(t),e||this.cache.clear();let i=t.size?t.lookup(s):null;return this.beam=[{text:s,node:t.size?i:null,score:0,groups:this.beam[0].groups}],this._report(null)}setOpts(t){return this.opts={...this.opts,...t},this._report(null)}_rootEntry(){return{text:"",node:this.lex.size?this.lex.root:null,score:0,groups:[]}}_snapshot(){this.history.push({strokes:this.strokes.slice(),erased:this.erased.slice(),beam:this.beam.slice(),words:this.words.slice()}),this.history.length>200&&this.history.shift()}clearWord(){return this._snapshot(),this.strokes=[],this.erased=[],this.beam=[this._rootEntry()],this._report(null)}undo(){let t=this.history.pop();return t?(this.strokes=t.strokes,this.erased=t.erased,this.beam=t.beam,this.words=t.words,this._report(null)):this.last}addStroke(t,{t0:s=0,t1:e=0}={}){return!t||t.length<2?this.last:(this._snapshot(),this.strokes.push({id:this.nextId++,pts:t.map(i=>({x:i.x,y:i.y})),t0:s,t1:e}),this._step())}finishWord({word:t=null}={}){if(t)return this.selectWord(t,{finish:!0});this._snapshot();let s=tt(),e=this.opts,i=null,n=new Map,o=(d,m,f,w)=>{let M=m+e.lmW*this._endLogP(f);(!n.has(d)||n.get(d).score<M)&&n.set(d,{text:d,score:M,groups:w,inList:!!(f&&f.end)}),(!i||M>i.score)&&(i=n.get(d))};if(this.strokes.length===0)for(let d of this.beam)o(d.text,d.score,d.node,d.groups);else{let{hyps:d}=this._dp(),m=(f,w)=>this.beam[w.beam].groups.concat(w.groups,[this._mkGroup(f.i,this.strokes.length,f.L,f.shapeFull)]);for(let f of d){if(f.shapeFull===-1/0)continue;let w=this._path(f);o(f.text,f.score-f.shape+f.shapeFull,f.node,m(f,w))}if(!i)for(let f of d){let w=this._path(f);o(f.text,f.score,f.node,m(f,w))}}i||(i={text:this.beam[0].text,score:0,groups:this.beam[0].groups,inList:!1});let l=[...n.values()].sort((d,m)=>m.score-d.score).slice(0,6).map(d=>({text:d.text,score:d.score,inList:d.inList})),a={word:i.text,groups:i.groups,alternatives:l,inList:i.inList,selected:!1};return this._finish(a,tt()-s)}_finish(t,s){return t.word&&this.words.push(t),this._ref=null,this.strokes=[],this.erased=[],this.beam=[this._rootEntry()],this.cache.clear(),this.last=this._state([],null,s,{finished:t}),this.last}fitToWord(t){let s=ae(t,this.A,this.idx),e=this.erased.concat(this.strokes),i=e.length;if(!s||!i)return null;let n=[...s].map(v=>this.idx.get(v)),o=this.opts,l=Math.min(n.length,i),a=-1/0,d=Array.from({length:l+1},()=>new Float64Array(i+1).fill(a)),m=Array.from({length:l+1},()=>new Int32Array(i+1).fill(-1));d[0][0]=0;for(let v=1;v<=l;v++){let O=n[v-1];for(let S=v;S<i;S++)for(let b=Math.max(v-1,S-o.maxStrokes);b<S;b++){if(d[v-1][b]===a)continue;let E=this._groupOf(e,b,S);this._cost(E,O);let _=this._closedScore(E,O);if(_===a)continue;let k=d[v-1][b]+_;k>d[v][S]&&(d[v][S]=k,m[v][S]=b)}}let f=null;for(let v=1;v<=l;v++){let O=n[v-1];for(let S=Math.max(v-1,i-o.maxStrokes);S<i;S++){if(d[v-1][S]===a)continue;let b=this._groupOf(e,S,i);this._cost(b,O);let{full:E,part:_,best:k}=this._openScore(b,O);if(k===a)continue;let P=d[v-1][S]+k;(!f||P>f.score)&&(f={score:P,m:v,i:S,partial:_>E,sF:E})}}if(!f)return null;let w=[],M=f.i;for(let v=f.m-1;v>=1;v--){let O=m[v][M];w.push(this._mkGroupOf(e,O,M,n[v-1])),M=O}return w.reverse(),w.push({...this._mkGroupOf(e,f.i,i,n[f.m-1],f.sF),open:!0,partial:f.partial}),{text:s.slice(0,f.m),groups:w,m:f.m,complete:f.m===n.length&&!f.partial,score:f.score,word:s}}selectWord(t,{finish:s=!0}={}){let e=this.fitToWord(t);if(!e)return this.last;this._snapshot();let i=tt();if(s){let d=e.groups.map(w=>({ch:w.ch,ids:w.ids,strokes:w.strokes,sh:w.sh}));for(let w=e.m;w<e.word.length;w++)d.push({ch:e.word[w],ids:[],strokes:[],sh:null});let m=this.lex.size?this.lex.lookup(e.word):null,f={word:e.word,groups:d,alternatives:[],inList:!!(m&&m.end),selected:!0,complete:e.complete};return this._finish(f,tt()-i)}let n=e.groups.slice(0,-1),o=e.groups[e.groups.length-1],l=n.map(d=>d.ch).join("");this.beam=[{text:l,node:this.lex.size?this.lex.lookup(l):null,score:0,groups:n.map(d=>({ch:d.ch,ids:d.ids,strokes:d.strokes,sh:d.sh}))}];let a=this.erased.concat(this.strokes);return this.erased=a.slice(0,a.length-o.ids.length),this.strokes=a.slice(a.length-o.ids.length),this._report({b:0,margin:1/0,erased:[],selected:e.word})}_sh(t){if(t===1/0)return-1/0;let s=(Math.log(this.opts.costRef)-Math.log(t+this.opts.costEps))/this.opts.temp,e=this.opts.shMax;return s>0&&e>0?e*Math.tanh(s/e):s}_next(t,s){if(t===null)return{node:null,lm:this.free?this.freeLogP[s]:this.LOGA};let e=t.ch[s];return e?{node:e,lm:e.logMass-t.logMass}:t.end>0&&!t.mark&&this.markIdx.includes(s)?{node:this.lex.markNode,lm:Math.log(t.end)-t.logMass+Math.log(this.opts.markP)}:{node:null,lm:this.LOGA-this.opts.oovPen}}_endLogP(t){return t===null?this.free?0:-this.opts.oovPen:t.end?Math.log(t.end)-t.logMass:this.opts.endFloor}_groupOf(t,s,e){let i=t.slice(s,e).map(M=>M.id).join(","),n=this.cache.get(i);if(n)return n;let o=t.slice(s,e).map(M=>M.pts),l=1/0,a=1/0,d=-1/0,m=-1/0;for(let M of o)for(let L of M)L.x<l&&(l=L.x),L.y<a&&(a=L.y),L.x>d&&(d=L.x),L.y>m&&(m=L.y);let f=Math.max(d-l,m-a,1),w=1/0;for(let M of o){let L=1/0,v=1/0,O=-1/0,S=-1/0;for(let E of M)E.x<L&&(L=E.x),E.y<v&&(v=E.y),E.x>O&&(O=E.x),E.y>S&&(S=E.y);let b=Math.max(O-L,S-v,1);b<w&&(w=b)}return n={key:i,k:e-s,pts:o,dim:f,minFrac:w/f,full:new Float64Array(this.NA).fill(NaN),part:new Float64Array(this.NA).fill(NaN),scored:[],ok:null},this.cache.set(i,n),n}_cost(t,s){if(Number.isNaN(t.full[s])){(t.ok===null||this.m.current!==t.key)&&(t.ok=this.m.upload(t.pts,t.key));let e=this.A[s];t.full[s]=t.ok&&this.m.has(e)?se(this.m.costs(e),this.opts.combine):1/0;let i=e+"/"+t.k;t.part[s]=t.ok&&this.m.has(i)?se(this.m.costs(i),this.opts.combinePart):1/0,t.scored.push(s)}return{full:t.full[s],part:t.part[s]}}_sizeZ(t,s){let e=this.sizes[s];if(!e||!t.dim)return 0;this._ref||(this._ref=this._sizeRef());let i=Math.sqrt(e.sd*e.sd+(this._ref.known?this.opts.sizeSd:this.opts.sizeSd0)**2);return(Math.log(t.dim/this._ref.scale)-e.mu)/i}_shOf(t,s){if(t.full[s]===1/0)return-1/0;let e=this.sizes[s];return e&&e.tiny?this._sizeZ(t,s)<3?this.opts.tinyShape:-1/0:this._sh(t.full[s])}_closedScore(t,s){let e=this._shOf(t,s);return e===-1/0?-1/0:e*t.k+this.scw*this.m.strokeLogP(this.A[s],t.k)+this._sizeScore(t,s)}_openScore(t,s){let e=this._shOf(t,s),i=this._sh(t.part[s]),n=e===-1/0?-1/0:e*t.k+this.scw*this.m.strokeLogP(this.A[s],t.k)+this._sizeScore(t,s),o=i===-1/0?-1/0:i*t.k;return{full:n,part:o,best:Math.max(n,o)}}_scoreGroup(t,s,e){if(s===this.ALL||!this.opts.pruneClasses){for(let n of this.ALL)this._cost(t,n);return t.scored}let i=-1/0;for(let n of s){let o=this._cost(t,n),l=e?Math.max(this._sh(o.full),this._sh(o.part)):this._sh(o.full);l>i&&(i=l)}if(i<this.opts.oovTrigger)for(let n of this.ALL)this._cost(t,n);return t.scored}_allowed(t){if(!this.opts.pruneClasses)return this.ALL;let s=new Set;for(let e of t){if(e.node===null)return this.ALL;let i=e.node.ch;for(let n=0;n<this.NA;n++)i[n]&&s.add(n);if(e.node.end>0&&!e.node.mark)for(let n of this.markIdx)s.add(n)}return[...s]}_group(t,s){return this._groupOf(this.strokes,t,s)}_dp(t=-1){let s=this.strokes,e=s.length,i=this.opts,n=new Array(e+1);n[0]=this.beam.map((a,d)=>({score:a.score,node:a.node,text:a.text,beam:d,back:null,pos:0}));let o=new Array(e+1);o[0]=this._allowed(n[0]);for(let a=1;a<=e;a++){let d=new Map;if(a!==t&&a<e)for(let m=Math.max(0,a-i.maxStrokes);m<a;m++){if(!n[m].length)continue;let f=this._group(m,a),w=this._scoreGroup(f,o[m],!1);for(let M of n[m])for(let L of w){let v=this._closedScore(f,L);if(v===-1/0)continue;let O=this._next(M.node,L),S=M.score+v+i.lmW*O.lm,b=M.text+this.A[L],E=O.node?O.node.id:"off:"+b,_=d.get(E);(!_||_.score<S)&&d.set(E,{score:S,node:O.node,text:b,beam:M.beam,back:{i:m,st:M,L,sh:v},pos:a})}}n[a]=[...d.values()].sort((m,f)=>f.score-m.score).slice(0,i.beamK),o[a]=this._allowed(n[a])}let l=[];for(let a=Math.max(0,e-i.maxStrokes);a<e;a++){if(!n[a].length)continue;let d=this._group(a,e),m=this._scoreGroup(d,o[a],!0);for(let f of n[a])for(let w of m){let{full:M,part:L,best:v}=this._openScore(d,w);if(v===-1/0)continue;let O=this._next(f.node,w);l.push({score:f.score+v+i.lmW*O.lm,i:a,st:f,L:w,node:O.node,text:f.text+this.A[w],partial:L>M,shape:v,shapeFull:M,shapePart:L,lm:O.lm})}}return l.sort((a,d)=>d.score-a.score),{states:n,hyps:l}}_path(t){let s=[],e=t.st;for(;e.back;)s.push(this._mkGroup(e.back.i,e.pos,e.back.L,e.back.sh)),e=e.back.st;return s.reverse(),{beam:e.beam,groups:s,bounds:s.map(i=>i.j)}}_mkGroupOf(t,s,e,i,n=null){let o=t.slice(s,e);return{ch:this.A[i],ids:o.map(l=>l.id),strokes:o.map(l=>l.pts),sh:n,j:e,dim:this._groupOf(t,s,e).dim}}_mkGroup(t,s,e,i=null){return this._mkGroupOf(this.strokes,t,s,e,i)}_step(){let t=tt();this._ref=null;let{hyps:s}=this._dp(),e=null;if(s.length){let i=s[0],n=this._path(i),o=[i.i,...n.bounds.slice().reverse()].filter((l,a,d)=>l>0&&d.indexOf(l)===a);for(let l of o){let a=this._dp(l),d=a.hyps.length?a.hyps[0].score:-1/0,m=i.score-d;if(m>=this.opts.commitMargin){e={b:l,margin:m};break}}}return e&&(e.erased=this._commit(e.b,s),this._ref=null,{hyps:s}=this._dp()),this.last=this._state(s,e,tt()-t),this.last}_commit(t,s){let e=this.opts,i=s[0].score,n=new Map;for(let m of s){if(m.score<i-e.beamMargin)break;let f=m.st;if(m.i<t)continue;for(;f&&f.pos>t;)f=f.back?f.back.st:null;if(!f||f.pos!==t)continue;let w=f.node?f.node.id:"off:"+f.text,M=n.get(w);(!M||M.total<m.score)&&n.set(w,{st:f,total:m.score})}let o=[...n.values()].sort((m,f)=>f.total-m.total).slice(0,e.beamK),l=this.beam,a=this.strokes.slice(0,t),d=o[0].st.score;return this.beam=o.map(({st:m})=>{let f=[],w=m;for(;w.back;)f.push(this._mkGroup(w.back.i,w.pos,w.back.L,w.back.sh)),w=w.back.st;return f.reverse(),{text:m.text,node:m.node,score:m.score-d,groups:l[w.beam].groups.concat(f)}}),this.erased=this.erased.concat(a),this.strokes=this.strokes.slice(t),a}_report(t){this._ref=null;let{hyps:s}=this._dp();return this.last=this._state(s,t,0),this.last}_candidates(t){let s=this.opts,e=new Map,i=(l,a,d)=>{let m=e.get(l);(!m||m.score<a)&&e.set(l,{word:l,score:a,kind:d,complete:d==="done"})},n=t.length?t:this.beam.map(l=>({score:l.score,node:l.node,text:l.text})),o=n.length?n[0].score:0;for(let l of n){if(l.score<o-s.beamMargin)break;if(l.node===null){l.text&&i(l.text,l.score-(this.free?0:s.oovPen),this.free?"free":"oov");continue}if(l.node.mark){i(l.text,l.score+s.doneBoost,"done");continue}l.node.end&&i(l.text,l.score+s.lmW*(Math.log(l.node.end)-l.node.logMass)+s.doneBoost,"done");for(let a of l.node.top)i(a.word,l.score+s.lmW*(Math.log(a.wt)-l.node.logMass),a.word===l.text?"done":"more")}return[...e.values()].sort((l,a)=>a.score-l.score).slice(0,8)}_state(t,s,e,i={}){let n=t[0]||null,o=[];n?o=this._path(n).groups.map(d=>({ch:d.ch,ids:d.ids,strokes:d.strokes,open:!1})).concat([{ch:this.A[n.L],ids:this.strokes.slice(n.i).map(d=>d.id),strokes:this.strokes.slice(n.i).map(d=>d.pts),open:!0,partial:n.partial}]):this.strokes.length&&(o=[{ch:"",ids:this.strokes.map(a=>a.id),strokes:this.strokes.map(a=>a.pts),open:!0,partial:!0}]);let l=a=>{let d=this._path(a);return{text:a.text,score:a.score,i:a.i,partial:a.partial,shape:a.shape,lm:a.lm,groups:d.groups.map(m=>m.ch+"("+m.ids.length+")").concat([a.partial?a.text.slice(-1)+"\u2026":a.text.slice(-1)]),beam:d.beam}};return{n:this.strokes.length,text:n?n.text:this.beam[0].text,committed:this.beam[0].text,pending:n?n.text.slice(this.beam[0].text.length):"",ambiguous:this.beam.length>1,beam:this.beam.map(a=>({text:a.text,score:a.score,oov:a.node===null&&!this.free})),groups:this.beam[0].groups,hyps:t.slice(0,10).map(l),assignment:o,candidates:this._candidates(t),commit:s?{b:s.b,margin:s.margin,erased:s.erased,selected:s.selected||null}:null,words:this.words,strokes:this.strokes,alphabet:this.A,free:this.free,sizeRef:this._ref||this._sizeRef(),ms:e,...i}}},tt=()=>typeof performance<"u"?performance.now():Date.now();var Je="1.0.0",It="__MILLIREC_BASE_URL__",de=!It.startsWith("__"),Ve=(()=>{let u=typeof document<"u"&&document.currentScript&&document.currentScript.src||"";return u?u.slice(0,u.lastIndexOf("/")+1):""})(),Mt=typeof window<"u"?window:globalThis,yt=()=>Mt.MILLIREC_OVERLAP||{},qe=u=>u&&!u.endsWith("/")?u+"/":u,xt=u=>qe(u.assetBase||yt().assetBase||(de?It+"/overlap/":Ve)),Xe=u=>(u.apiBase||yt().apiBase||(de?It:"")).replace(/\/$/,""),mt=new Map;function Et(u,t){let s=et(t),i=`training.${ot(s)||"all"}.json`,n=u+"|"+s.join("");return mt.has(n)||mt.set(n,(async()=>{let o=await fetch(u+i);if(!o.ok)throw new Error(`MillirecOverlap: could not load ${u}${i} (${o.status})`);let l=await o.json(),a;try{a=await ce(Yt,l,{locateFile:d=>u+d,alphabet:s})}catch(d){throw new Error(`MillirecOverlap: could not start the matcher \u2014 is ${u}millirec.wasm served (as application/wasm)? (${String(d&&d.message||d).slice(0,160)})`)}return{training:l,matcher:a,alphabet:s}})().catch(o=>{throw mt.delete(n),o})),mt.get(n)}async function le(u){if(Array.isArray(u.words))return{words:u.words,source:"words"};if(typeof u.words=="string"&&u.words.trim())return{words:rt(u.words),source:"words"};if(u.list){let s=Xe(u);if(!s)throw new Error("MillirecOverlap: a hosted list (data-list) needs apiBase \u2014 the millirec server this list lives on");let e=await fetch(`${s}/api/overlap/lists/${encodeURIComponent(u.list)}`);if(!e.ok)throw new Error(`MillirecOverlap: word list ${u.list} not found (${e.status})`);let i=await e.json();return{words:i.words,source:"list",list:u.list,name:i.name}}if(u.wordsSrc){let s=await fetch(u.wordsSrc);if(!s.ok)throw new Error(`MillirecOverlap: could not load ${u.wordsSrc} (${s.status})`);let e=await s.text(),i;try{let n=JSON.parse(e);i=Array.isArray(n)?n:n.words}catch{i=rt(e)}return{words:i,source:"src"}}if(Array.isArray(yt().words))return{words:yt().words,source:"global"};if(Array.isArray(Mt.MILLIREC_WORDS))return{words:Mt.MILLIREC_WORDS,source:"global"};let t=await fetch(xt(u)+"words.json");if(!t.ok)throw new Error("MillirecOverlap: no word list given and the default words.json is missing");return{words:await t.json(),source:"default"}}var Ze=`
12
12
  :host { display: inline-block; box-sizing: border-box; font: 14px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; color: var(--mo-ink, #111827);
13
13
  --_ink: var(--mo-ink, #111827); --_bg: var(--mo-bg, #ffffff); --_line: var(--mo-line, #d4d4d8); --_muted: var(--mo-muted, #9ca3af);
14
14
  --_accent: var(--mo-accent, #2563eb); --_grey: var(--mo-suspect, #b6b6bb); --_chip: var(--mo-chip, #f3f4f6); --_radius: var(--mo-radius, 10px); }
@@ -42,4 +42,4 @@ return ret;
42
42
  .bar button:disabled { opacity: .4; cursor: default; }
43
43
  .err { color: #dc2626; font-size: 12px; }
44
44
  [hidden] { display: none !important; }
45
- `,Ze=["ready","stroke","change","word","select","error"],at=class u{constructor(t,s={}){let e=typeof t=="string"?document.querySelector(t):t;if(!e)throw new Error("MillirecOverlap: host element not found");this.el=e,this.opts={...Ye(e),...s},this.listeners=new Map;for(let o of Ze){let n=this.opts["on"+o[0].toUpperCase()+o.slice(1)];typeof n=="function"&&this.on(o,n)}this.rec=null,this.state=null,this.words=[],this.wordSource=null,this.fading=[],this.cur=null,this.activeId=null,this.idleTimer=0,this.raf=0,this.destroyed=!1,this._build(),e.__millirecOverlap=this,this.ready=this._boot()}static create(t,s={}){let e=new u(t,s);return e.ready.then(()=>e)}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>this.listeners.get(t).delete(s)}_emit(t,s){s={...s,widget:this};for(let e of this.listeners.get(t)||[])try{e(s)}catch(o){console.error(o)}this.el.dispatchEvent(new CustomEvent("millirec-overlap:"+t,{detail:s,bubbles:!0}))}_build(){let t=this.opts,s=Number(t.size)||240;this.size=s;let e=this.el.attachShadow?this.el.shadowRoot||this.el.attachShadow({mode:"open"}):this.el;this.root=e,this.el.setAttribute("data-theme",t.theme||"auto"),e.innerHTML="";let o=document.createElement("style");o.textContent=Xe,e.appendChild(o);let n=document.createElement("div");n.className="mo"+(t.layout==="row"?" row":""),n.setAttribute("part","root");let i=new Set(rt(t.hide||""));this.box=document.createElement("canvas"),this.box.className="box busy",this.box.setAttribute("part","box");let l=window.devicePixelRatio||1;this.dpr=l,this.box.width=s*l,this.box.height=s*l,this.box.style.width=this.box.style.height=s+"px",this.ctx=this.box.getContext("2d"),this.ctx.scale(l,l),n.appendChild(this.box);let c=document.createElement("div");c.className="side",this.textEl=document.createElement("div"),this.textEl.className="text",this.textEl.setAttribute("part","text"),this.textEl.hidden=i.has("text"),this.hwEl=document.createElement("div"),this.hwEl.className="hw",this.hwEl.setAttribute("part","handwriting"),this.hwEl.hidden=i.has("handwriting"),this.wordsEl=document.createElement("div"),this.wordsEl.className="words",this.wordsEl.setAttribute("part","words"),this.wordsEl.hidden=i.has("words"),this.barEl=document.createElement("div"),this.barEl.className="bar",this.barEl.setAttribute("part","buttons"),this.barEl.hidden=i.has("buttons"),this.barEl.innerHTML='<button class="primary" data-act="done" title="finish this word">done</button><button data-act="undo" title="undo the last stroke">undo</button><button data-act="clear" title="clear the box">clear</button>',this.errEl=document.createElement("div"),this.errEl.className="err",this.errEl.hidden=!0;for(let p of[this.textEl,this.hwEl,this.wordsEl,this.barEl,this.errEl])c.appendChild(p);n.appendChild(c),e.appendChild(n),this.wrap=n,this._bindPointer(),this.barEl.addEventListener("click",p=>{let m=p.target&&p.target.dataset&&p.target.dataset.act;m==="done"?this.finishWord():m==="undo"?this.undo():m==="clear"&&this.clearWord()}),this.wordsEl.addEventListener("click",p=>{let m=p.target.closest?p.target.closest(".chip"):null;m&&m.dataset.word&&this.selectWord(m.dataset.word)}),this._renderText()}_engineOpts(){return{sizeRef0:this.size*.55,...this.opts.engine||{}}}get alphabet(){return et(this.opts.alphabet||this.opts.set||"capitals")}async _boot(){try{let t=yt(this.opts),s=this.alphabet,[{matcher:e},o]=await Promise.all([Et(t,s),le(this.opts)]);if(this.destroyed)return;this.words=o.words,this.wordSource=o,this.lexicon=st(this.words,{alphabet:s}),this.rec=new ot({matcher:e,lexicon:this.lexicon,opts:this._engineOpts()}),this.state=this.rec.last,this.box.classList.remove("busy"),this._render(),this._emit("ready",{words:this.lexicon.size,source:o.source,list:o.list||null,alphabet:s.join(""),set:it(s),free:this.lexicon.size===0})}catch(t){throw this.errEl.textContent=String(t.message||t),this.errEl.hidden=!1,this._emit("error",{error:t}),t}}_bindPointer(){let t=this.box,s=this.size,e=n=>{let i=t.getBoundingClientRect();return{x:(n.clientX-i.left)*s/i.width,y:(n.clientY-i.top)*s/i.height}};t.addEventListener("pointerdown",n=>{if(!(n.button>0||!this.rec)&&!(this.activeId!==null&&n.pointerType!=="pen"&&this.activeId!==n.pointerId)){n.preventDefault(),this.activeId=n.pointerId;try{t.setPointerCapture(n.pointerId)}catch{}clearTimeout(this.idleTimer),this.cur=[e(n)],this.curT0=performance.now(),this._repaint()}},{passive:!1}),t.addEventListener("pointermove",n=>{if(this.activeId!==n.pointerId||!this.cur)return;n.preventDefault();let i=n.getCoalescedEvents?n.getCoalescedEvents():null;for(let l of i&&i.length?i:[n])this.cur.push(e(l));this._repaint()},{passive:!1});let o=n=>{if(this.activeId!==n.pointerId)return;try{t.releasePointerCapture(n.pointerId)}catch{}if(this.activeId=null,!this.cur)return;let i=this.cur;if(this.cur=null,i.length===1){let l=i[0];i=[{x:l.x-1,y:l.y},{x:l.x+1,y:l.y}]}this._apply(this.rec.addStroke(i,{t0:this.curT0,t1:performance.now()}),"stroke"),this._armIdle()};t.addEventListener("pointerup",o),t.addEventListener("pointercancel",o);for(let n of["touchstart","touchmove"])t.addEventListener(n,i=>i.preventDefault(),{passive:!1});t.addEventListener("contextmenu",n=>n.preventDefault())}_armIdle(){clearTimeout(this.idleTimer);let t=Number(this.opts.idleFinish)||0;!t||!this.rec||!this.rec.strokes.length||(this.idleTimer=setTimeout(()=>{this.rec&&this.rec.strokes.length&&this.finishWord()},t*1e3))}getText(){return this.rec?this.rec.words.map(t=>t.word).join(" "):""}getLiveText(){let t=this.getText(),s=this.state?this.state.text:"";return s?t?t+" "+s:s:t}getWords(){return this.rec?this.rec.words.map(ue):[]}getCandidates(){return this.state?this.state.candidates.map(he):[]}getState(){return this.state}getWordList(){return this.words.slice()}getHandwriting({scope:t="word",index:s=-1,capHeight:e=44}={}){if(!this.rec)return null;if(t==="word"&&s<0)return X(this._currentGroups(),e,this._colors());if(t==="word"){let i=this.rec.words[s];return i?X(i.groups,e,this._colors()):null}let o=this.rec.words.map(i=>i.groups),n=this._currentGroups();return n.length&&o.push(n),pe(o,e,this._colors())}setWords(t){return this.words=Array.isArray(t)?t.slice():rt(t),this.wordSource={source:"words"},this.lexicon=st(this.words,{alphabet:this.alphabet}),this.rec&&this._apply(this.rec.setLexicon(this.lexicon),"change"),this.lexicon.size}async loadList(t){let s=await le({...this.opts,list:t,words:void 0});return this.words=s.words,this.wordSource=s,this.lexicon=st(this.words,{alphabet:this.alphabet}),this.rec&&this._apply(this.rec.setLexicon(this.lexicon),"change"),this.lexicon.size}getLexiconSize(){return this.lexicon?this.lexicon.size:0}async setAlphabet(t){t&&F[t]?(this.opts.set=t,delete this.opts.alphabet):(this.opts.alphabet=t,delete this.opts.set);let s=this.alphabet,{matcher:e}=await Et(yt(this.opts),s);if(!this.destroyed)return this.lexicon=st(this.words,{alphabet:s}),this.rec=new ot({matcher:e,lexicon:this.lexicon,opts:this._engineOpts()}),this.fading=[],this.state=this.rec.last,this._render(),this._emit("change",this._detail(this.state)),this._pushTarget(),s.join("")}finishWord(t=null){this.rec&&this._apply(this.rec.finishWord({word:t}),"word")}selectWord(t,{finish:s=!0}={}){if(!this.rec)return;let e=this.rec.selectWord(t,{finish:s});this._emit("select",{word:String(t).toUpperCase(),finish:s}),this._apply(e,s?"word":"change")}undo(){this.rec&&this._apply(this.rec.undo(),"change")}clearWord(){this.rec&&(this.fading=[],this._apply(this.rec.clearWord(),"change"))}clear(){this.rec&&(this.fading=[],this._apply(this.rec.reset(),"change"))}setOptions(t){this.rec&&this._apply(this.rec.setOpts(t),"change")}destroy(){this.destroyed=!0,clearTimeout(this.idleTimer),cancelAnimationFrame(this.raf),this.root.innerHTML="",delete this.el.__millirecOverlap}_apply(t,s){this.state=t,t.commit&&t.commit.erased&&t.commit.erased.length&&this.fading.push({strokes:t.commit.erased,t0:performance.now()}),this._render();let e=this._detail(t);s==="stroke"&&this._emit("stroke",e),t.finished&&this._emit("word",{...e,...ue(t.finished),canvas:X(t.finished.groups,44,this._colors())}),this._emit("change",e),this._pushTarget()}_detail(t){return{text:this.getText(),live:this.getLiveText(),current:t.text,committed:t.committed,pending:t.pending,candidates:t.candidates.map(he),strokes:t.n,erased:t.commit?t.commit.erased.length:0,canvas:this.hwCanvas||null}}_pushTarget(){let t=this.opts.target;if(!t)return;let s=typeof t=="string"?document.querySelector(t):t;if(!s)return;let e=this.opts.targetMode==="words"?this.getText():this.getLiveText();"value"in s&&/^(INPUT|TEXTAREA)$/.test(s.tagName)?(s.value=e,s.dispatchEvent(new Event("input",{bubbles:!0}))):s.textContent=e}_colors(){let t=getComputedStyle(this.el),s=(n,i)=>(t.getPropertyValue(n)||"").trim()||i,e=this.wrap?getComputedStyle(this.wrap):t,o=(n,i)=>(e.getPropertyValue(n)||"").trim()||i;return{ink:o("--_ink",s("--mo-ink","#111827")),grey:o("--_grey","#b6b6bb"),accent:o("--_accent","#2563eb"),muted:o("--_muted","#9ca3af")}}_currentGroups(){let t=this.state;return t?(t.groups||[]).map(s=>({ch:s.ch,strokes:s.strokes,state:"done"})).concat((t.assignment||[]).map(s=>({ch:s.ch,strokes:s.strokes,state:s.open?"open":"closed"}))):[]}_render(){this._repaint(),this._renderText(),this._renderHandwriting(),this._renderWords()}_renderText(){let t=this.state,s=this.getText();if(!t||!s&&!t.text){let e={capitals:"a capital letter",lowercase:"a lowercase letter",digits:"a digit",punctuation:"a punctuation mark",all:"a character"}[it(this.alphabet)]||"a character";this.textEl.innerHTML=`<span class="ph">${wt(this.opts.placeholder||`write ${e}, then the next one over it`)}</span>`;return}this.textEl.innerHTML=(s?`<span class="done">${wt(s)}</span> `:"")+`<span class="cur">${wt(t.committed)}</span><span class="pend">${wt(t.pending)}</span>`}_renderHandwriting(){let t=this.hwEl;if(t.innerHTML="",!this.rec)return;let s=this._colors(),e=Math.max(0,Number(this.opts.history??1)),o=this.rec.words.slice(-e);for(let i of o){let l=X(i.groups,34,s);l.className="prev",l.title=i.word,t.appendChild(l)}let n=this._currentGroups();this.hwCanvas=n.length?X(n,44,s):null,this.hwCanvas&&t.appendChild(this.hwCanvas)}_renderWords(){let t=this.wordsEl;if(t.innerHTML="",!this.state)return;let s=Math.max(0,Number(this.opts.chips??6));this.state.candidates.slice(0,s).forEach((e,o)=>{let n=document.createElement("button");n.type="button",n.className="chip"+(o===0?" best":"")+(e.kind==="done"?" complete":"")+(e.kind==="oov"?" oov":"")+(e.kind==="free"?" free":""),n.dataset.word=e.word,n.textContent=e.word,n.title=e.kind==="done"?"a complete word \u2014 tap to accept it":e.kind==="oov"?"not in the word list":e.kind==="free"?"the reading so far \u2014 tap to accept it":"tap to accept this word",n.setAttribute("part","chip"),t.appendChild(n)})}_repaint(){let t=this.ctx,s=this.size;t.clearRect(0,0,s,s);let e=this._colors(),o=performance.now();this.fading=this.fading.filter(i=>o-i.t0<500);for(let i of this.fading){let l=1-(o-i.t0)/500;for(let c of i.strokes)St(t,c.pts,e.grey,3,.9*l)}let n=new Set;for(let i of this.state&&this.state.assignment||[])if(!i.open)for(let l of i.ids)n.add(l);for(let i of this.rec?this.rec.strokes:[])St(t,i.pts,n.has(i.id)?e.grey:e.ink,3,1);this.cur&&St(t,this.cur,e.ink,3,1),cancelAnimationFrame(this.raf),this.fading.length&&(this.raf=requestAnimationFrame(()=>this._repaint()))}},wt=u=>String(u).replace(/[&<>]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[t]),he=u=>({word:u.word,score:u.score,complete:u.kind==="done",inList:u.kind!=="oov"}),ue=u=>({word:u.word,letters:u.groups.map(t=>({ch:t.ch,strokes:t.strokes})),inList:!!u.inList,selected:!!u.selected,alternatives:(u.alternatives||[]).map(t=>({word:t.text,score:t.score,inList:t.inList}))});function Ye(u){let t={},s={"millirec-overlap":null,set:"set",alphabet:"alphabet",list:"list",words:"words","words-src":"wordsSrc",target:"target","target-mode":"targetMode",size:"size",layout:"layout",chips:"chips",history:"history","idle-finish":"idleFinish",theme:"theme",hide:"hide",placeholder:"placeholder","asset-base":"assetBase","api-base":"apiBase"};for(let[n,i]of Object.entries(s)){let l=u.getAttribute("data-"+n);l==null||!i||(t[i]=l)}let e=u.getAttribute("data-engine");if(e)try{t.engine=JSON.parse(e)}catch{console.warn("MillirecOverlap: data-engine is not JSON")}let o=u.getAttribute("data-millirec-overlap");return o&&!t.list&&!t.words&&(t.list=o),t}function St(u,t,s,e,o){if(!(!t||t.length<2)){u.globalAlpha=o,u.strokeStyle=s,u.lineWidth=e,u.lineCap="round",u.lineJoin="round",u.beginPath(),u.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n++)u.lineTo(t[n].x,t[n].y);u.stroke(),u.globalAlpha=1}}function Qe(u){let t=1/0,s=1/0,e=-1/0,o=-1/0;for(let n of u)for(let i of n)i.x<t&&(t=i.x),i.y<s&&(s=i.y),i.x>e&&(e=i.x),i.y>o&&(o=i.y);return t===1/0?null:{x0:t,y0:s,w:Math.max(1,e-t),h:Math.max(1,o-s)}}function X(u,t=44,s={},{gap:e=8,pad:o=6,dpr:n=window.devicePixelRatio||1}={}){let i=s.ink||"#111827",l=u.map(S=>Qe(S.strokes||[])),c=l.filter(Boolean).map(S=>S.h).sort((S,b)=>S-b),p=c.length?c[Math.floor(c.length/2)]:1,m=t/p,f=l.map(S=>S?S.w*m:t*.35),g=f.reduce((S,b)=>S+b,0)+e*Math.max(0,u.length-1)+2*o,M=Math.max(t,...l.filter(Boolean).map(S=>S.h*m))+2*o,L=document.createElement("canvas");L.width=Math.ceil(g*n),L.height=Math.ceil(M*n),L.style.width=Math.ceil(g)+"px",L.style.height=Math.ceil(M)+"px";let v=L.getContext("2d");v.scale(n,n),v.lineWidth=Math.max(1.6,t/18),v.lineCap=v.lineJoin="round";let O=o;return u.forEach((S,b)=>{let E=l[b];if(E){let _=M-o-E.h*m;v.strokeStyle=S.state==="open"&&s.openInk||i;for(let k of S.strokes)v.beginPath(),k.forEach((P,T)=>{let R=O+(P.x-E.x0)*m,z=_+(P.y-E.y0)*m;T?v.lineTo(R,z):v.moveTo(R,z)}),v.stroke()}O+=f[b]+e}),L}function pe(u,t=44,s={}){let e=u.map(f=>X(f,t,s)),o=window.devicePixelRatio||1,n=t*.6,i=e.reduce((f,g)=>f+g.width/o,0)+n*Math.max(0,e.length-1),l=Math.max(1,...e.map(f=>f.height/o)),c=document.createElement("canvas");c.width=Math.ceil(i*o),c.height=Math.ceil(l*o),c.style.width=Math.ceil(i)+"px",c.style.height=Math.ceil(l)+"px";let p=c.getContext("2d"),m=0;for(let f of e)p.drawImage(f,m*o,l*o-f.height),m+=f.width/o+n;return c}function fe(u=document){let t=u.querySelectorAll?u.querySelectorAll("[data-millirec-overlap]"):[],s=[];for(let e of t)e.__millirecOverlap||s.push(new at(e));return s}var me={version:Je,create:(u,t)=>at.create(u,t),scan:fe,Widget:at,buildLexicon:st,splitWords:rt,wordStrip:X,sentenceStrip:pe,alphabetOf:et,setNameOf:it,DEFAULTS:At,LETTERS:ne,SETS:F,SET_NAMES:kt,preload:(u="capitals",t)=>Et(t||yt({}),u)};if(typeof window<"u"&&!window.MillirecOverlap){window.MillirecOverlap=me;let u=()=>{try{fe(document)}catch(t){console.error(t)}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",u):u()}var ys=me;})();
45
+ `,Ye=["ready","stroke","change","word","select","error"],at=class u{constructor(t,s={}){let e=typeof t=="string"?document.querySelector(t):t;if(!e)throw new Error("MillirecOverlap: host element not found");this.el=e,this.opts={...Qe(e),...s},this.listeners=new Map;for(let i of Ye){let n=this.opts["on"+i[0].toUpperCase()+i.slice(1)];typeof n=="function"&&this.on(i,n)}this.rec=null,this.state=null,this.words=[],this.wordSource=null,this.fading=[],this.cur=null,this.activeId=null,this.activeType=null,this.idleTimer=0,this.raf=0,this.destroyed=!1,this._build(),e.__millirecOverlap=this,this.ready=this._boot()}static create(t,s={}){let e=new u(t,s);return e.ready.then(()=>e)}on(t,s){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(s),()=>this.listeners.get(t).delete(s)}_emit(t,s){s={...s,widget:this};for(let e of this.listeners.get(t)||[])try{e(s)}catch(i){console.error(i)}this.el.dispatchEvent(new CustomEvent("millirec-overlap:"+t,{detail:s,bubbles:!0}))}_build(){let t=this.opts,s=Number(t.size)||240;this.size=s;let e=this.el.attachShadow?this.el.shadowRoot||this.el.attachShadow({mode:"open"}):this.el;this.root=e,this.el.setAttribute("data-theme",t.theme||"auto"),e.innerHTML="";let i=document.createElement("style");i.textContent=Ze,e.appendChild(i);let n=document.createElement("div");n.className="mo"+(t.layout==="row"?" row":""),n.setAttribute("part","root");let o=new Set(rt(t.hide||""));this.box=document.createElement("canvas"),this.box.className="box busy",this.box.setAttribute("part","box");let l=window.devicePixelRatio||1;this.dpr=l,this.box.width=s*l,this.box.height=s*l,this.box.style.width=this.box.style.height=s+"px",this.ctx=this.box.getContext("2d"),this.ctx.scale(l,l),n.appendChild(this.box);let a=document.createElement("div");a.className="side",this.textEl=document.createElement("div"),this.textEl.className="text",this.textEl.setAttribute("part","text"),this.textEl.hidden=o.has("text"),this.hwEl=document.createElement("div"),this.hwEl.className="hw",this.hwEl.setAttribute("part","handwriting"),this.hwEl.hidden=o.has("handwriting"),this.wordsEl=document.createElement("div"),this.wordsEl.className="words",this.wordsEl.setAttribute("part","words"),this.wordsEl.hidden=o.has("words"),this.barEl=document.createElement("div"),this.barEl.className="bar",this.barEl.setAttribute("part","buttons"),this.barEl.hidden=o.has("buttons"),this.barEl.innerHTML='<button class="primary" data-act="done" title="finish this word">done</button><button data-act="undo" title="undo the last stroke">undo</button><button data-act="clear" title="clear the box">clear</button>',this.errEl=document.createElement("div"),this.errEl.className="err",this.errEl.hidden=!0;for(let d of[this.textEl,this.hwEl,this.wordsEl,this.barEl,this.errEl])a.appendChild(d);n.appendChild(a),e.appendChild(n),this.wrap=n,this._bindPointer(),this.barEl.addEventListener("click",d=>{let m=d.target&&d.target.dataset&&d.target.dataset.act;m==="done"?this.finishWord():m==="undo"?this.undo():m==="clear"&&this.clearWord()}),this.wordsEl.addEventListener("click",d=>{let m=d.target.closest?d.target.closest(".chip"):null;m&&m.dataset.word&&this.selectWord(m.dataset.word)}),this._renderText()}_engineOpts(){return{sizeRef0:this.size*.55,...this.opts.engine||{}}}get alphabet(){return et(this.opts.alphabet||this.opts.set||"capitals")}async _boot(){try{let t=xt(this.opts),s=this.alphabet,[{matcher:e},i]=await Promise.all([Et(t,s),le(this.opts)]);if(this.destroyed)return;this.words=i.words,this.wordSource=i,this.lexicon=st(this.words,{alphabet:s}),this.rec=new it({matcher:e,lexicon:this.lexicon,opts:this._engineOpts()}),this.state=this.rec.last,this.box.classList.remove("busy"),this._render(),this._emit("ready",{words:this.lexicon.size,source:i.source,list:i.list||null,alphabet:s.join(""),set:ot(s),free:this.lexicon.size===0})}catch(t){throw this.errEl.textContent=String(t.message||t),this.errEl.hidden=!1,this._emit("error",{error:t}),t}}_bindPointer(){let t=this.box,s=this.size,e=null,i=o=>{let l=e||(e=t.getBoundingClientRect());return{x:(o.clientX-l.left)*s/l.width,y:(o.clientY-l.top)*s/l.height}};t.addEventListener("pointerdown",o=>{if(!(o.button>0||!this.rec)){if(this.activeId!==null){if(this.activeType==="pen"&&o.pointerType!=="pen"&&o.pointerId!==this.activeId)return;n({pointerId:this.activeId},!1)}o.preventDefault(),e=t.getBoundingClientRect(),this.activeId=o.pointerId,this.activeType=o.pointerType;try{t.setPointerCapture(o.pointerId)}catch{}clearTimeout(this.idleTimer),this.cur=[i(o)],this.curT0=performance.now(),this.curInk=this._colors().ink,this._repaint()}},{passive:!1}),t.addEventListener("pointermove",o=>{if(this.activeId!==o.pointerId||!this.cur)return;o.preventDefault();let l=o.getCoalescedEvents?o.getCoalescedEvents():null,a=this.cur.length-1;for(let d of l&&l.length?l:[o])this.cur.push(i(d));this.fading.length?this._repaint():wt(this.ctx,this.cur.slice(a),this.curInk,3,1)},{passive:!1});let n=(o,l=!1)=>{if(this.activeId!==o.pointerId)return;try{t.releasePointerCapture(o.pointerId)}catch{}if(this.activeId=null,this.activeType=null,e=null,!this.cur)return;let a=this.cur;if(this.cur=null,l&&a.length===1){this._repaint();return}if(a.length===1){let d=a[0];a=[{x:d.x-1,y:d.y},{x:d.x+1,y:d.y}]}this._apply(this.rec.addStroke(a,{t0:this.curT0,t1:performance.now()}),"stroke"),this._armIdle()};t.addEventListener("pointerup",o=>{o.pointerId===this.activeId&&o.preventDefault(),n(o,!1)},{passive:!1}),t.addEventListener("pointercancel",o=>n(o,!0),{passive:!1}),t.addEventListener("lostpointercapture",o=>{(!t.hasPointerCapture||!t.hasPointerCapture(o.pointerId))&&n(o,!0)});for(let o of["touchstart","touchmove"])t.addEventListener(o,l=>l.preventDefault(),{passive:!1});t.addEventListener("contextmenu",o=>o.preventDefault())}_armIdle(){clearTimeout(this.idleTimer);let t=Number(this.opts.idleFinish)||0;!t||!this.rec||!this.rec.strokes.length||(this.idleTimer=setTimeout(()=>{this.rec&&this.rec.strokes.length&&this.finishWord()},t*1e3))}getText(){return this.rec?this.rec.words.map(t=>t.word).join(" "):""}getLiveText(){let t=this.getText(),s=this.state?this.state.text:"";return s?t?t+" "+s:s:t}getWords(){return this.rec?this.rec.words.map(ue):[]}getCandidates(){return this.state?this.state.candidates.map(he):[]}getState(){return this.state}getWordList(){return this.words.slice()}getHandwriting({scope:t="word",index:s=-1,capHeight:e=44}={}){if(!this.rec)return null;if(t==="word"&&s<0)return X(this._currentGroups(),e,this._colors());if(t==="word"){let o=this.rec.words[s];return o?X(o.groups,e,this._colors()):null}let i=this.rec.words.map(o=>o.groups),n=this._currentGroups();return n.length&&i.push(n),pe(i,e,this._colors())}setWords(t){return this.words=Array.isArray(t)?t.slice():rt(t),this.wordSource={source:"words"},this.lexicon=st(this.words,{alphabet:this.alphabet}),this.rec&&this._apply(this.rec.setLexicon(this.lexicon),"change"),this.lexicon.size}async loadList(t){let s=await le({...this.opts,list:t,words:void 0});return this.words=s.words,this.wordSource=s,this.lexicon=st(this.words,{alphabet:this.alphabet}),this.rec&&this._apply(this.rec.setLexicon(this.lexicon),"change"),this.lexicon.size}getLexiconSize(){return this.lexicon?this.lexicon.size:0}async setAlphabet(t){t&&F[t]?(this.opts.set=t,delete this.opts.alphabet):(this.opts.alphabet=t,delete this.opts.set);let s=this.alphabet,{matcher:e}=await Et(xt(this.opts),s);if(!this.destroyed)return this.lexicon=st(this.words,{alphabet:s}),this.rec=new it({matcher:e,lexicon:this.lexicon,opts:this._engineOpts()}),this.fading=[],this.state=this.rec.last,this._render(),this._emit("change",this._detail(this.state)),this._pushTarget(),s.join("")}finishWord(t=null){this.rec&&this._apply(this.rec.finishWord({word:t}),"word")}selectWord(t,{finish:s=!0}={}){if(!this.rec)return;let e=this.rec.selectWord(t,{finish:s});this._emit("select",{word:String(t).toUpperCase(),finish:s}),this._apply(e,s?"word":"change")}undo(){this.rec&&this._apply(this.rec.undo(),"change")}clearWord(){this.rec&&(this.fading=[],this._apply(this.rec.clearWord(),"change"))}clear(){this.rec&&(this.fading=[],this._apply(this.rec.reset(),"change"))}setOptions(t){this.rec&&this._apply(this.rec.setOpts(t),"change")}destroy(){this.destroyed=!0,clearTimeout(this.idleTimer),cancelAnimationFrame(this.raf),this.root.innerHTML="",delete this.el.__millirecOverlap}_apply(t,s){this.state=t,t.commit&&t.commit.erased&&t.commit.erased.length&&this.fading.push({strokes:t.commit.erased,t0:performance.now()}),this._render();let e=this._detail(t);s==="stroke"&&this._emit("stroke",e),t.finished&&this._emit("word",{...e,...ue(t.finished),canvas:X(t.finished.groups,44,this._colors())}),this._emit("change",e),this._pushTarget()}_detail(t){return{text:this.getText(),live:this.getLiveText(),current:t.text,committed:t.committed,pending:t.pending,candidates:t.candidates.map(he),strokes:t.n,erased:t.commit?t.commit.erased.length:0,canvas:this.hwCanvas||null}}_pushTarget(){let t=this.opts.target;if(!t)return;let s=typeof t=="string"?document.querySelector(t):t;if(!s)return;let e=this.opts.targetMode==="words"?this.getText():this.getLiveText();"value"in s&&/^(INPUT|TEXTAREA)$/.test(s.tagName)?(s.value=e,s.dispatchEvent(new Event("input",{bubbles:!0}))):s.textContent=e}_colors(){let t=getComputedStyle(this.el),s=(n,o)=>(t.getPropertyValue(n)||"").trim()||o,e=this.wrap?getComputedStyle(this.wrap):t,i=(n,o)=>(e.getPropertyValue(n)||"").trim()||o;return{ink:i("--_ink",s("--mo-ink","#111827")),grey:i("--_grey","#b6b6bb"),accent:i("--_accent","#2563eb"),muted:i("--_muted","#9ca3af")}}_currentGroups(){let t=this.state;return t?(t.groups||[]).map(s=>({ch:s.ch,strokes:s.strokes,state:"done"})).concat((t.assignment||[]).map(s=>({ch:s.ch,strokes:s.strokes,state:s.open?"open":"closed"}))):[]}_render(){this._repaint(),this._renderText(),this._renderHandwriting(),this._renderWords()}_renderText(){let t=this.state,s=this.getText();if(!t||!s&&!t.text){let e={capitals:"a capital letter",lowercase:"a lowercase letter",digits:"a digit",punctuation:"a punctuation mark",all:"a character"}[ot(this.alphabet)]||"a character";this.textEl.innerHTML=`<span class="ph">${gt(this.opts.placeholder||`write ${e}, then the next one over it`)}</span>`;return}this.textEl.innerHTML=(s?`<span class="done">${gt(s)}</span> `:"")+`<span class="cur">${gt(t.committed)}</span><span class="pend">${gt(t.pending)}</span>`}_renderHandwriting(){let t=this.hwEl;if(t.innerHTML="",!this.rec)return;let s=this._colors(),e=Math.max(0,Number(this.opts.history??1)),i=this.rec.words.slice(-e);for(let o of i){let l=X(o.groups,34,s);l.className="prev",l.title=o.word,t.appendChild(l)}let n=this._currentGroups();this.hwCanvas=n.length?X(n,44,s):null,this.hwCanvas&&t.appendChild(this.hwCanvas)}_renderWords(){let t=this.wordsEl;if(t.innerHTML="",!this.state)return;let s=Math.max(0,Number(this.opts.chips??6));this.state.candidates.slice(0,s).forEach((e,i)=>{let n=document.createElement("button");n.type="button",n.className="chip"+(i===0?" best":"")+(e.kind==="done"?" complete":"")+(e.kind==="oov"?" oov":"")+(e.kind==="free"?" free":""),n.dataset.word=e.word,n.textContent=e.word,n.title=e.kind==="done"?"a complete word \u2014 tap to accept it":e.kind==="oov"?"not in the word list":e.kind==="free"?"the reading so far \u2014 tap to accept it":"tap to accept this word",n.setAttribute("part","chip"),t.appendChild(n)})}_repaint(){let t=this.ctx,s=this.size;t.clearRect(0,0,s,s);let e=this._colors(),i=performance.now();this.fading=this.fading.filter(o=>i-o.t0<500);for(let o of this.fading){let l=1-(i-o.t0)/500;for(let a of o.strokes)wt(t,a.pts,e.grey,3,.9*l)}let n=new Set;for(let o of this.state&&this.state.assignment||[])if(!o.open)for(let l of o.ids)n.add(l);for(let o of this.rec?this.rec.strokes:[])wt(t,o.pts,n.has(o.id)?e.grey:e.ink,3,1);this.cur&&wt(t,this.cur,e.ink,3,1),cancelAnimationFrame(this.raf),this.fading.length&&(this.raf=requestAnimationFrame(()=>this._repaint()))}},gt=u=>String(u).replace(/[&<>]/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[t]),he=u=>({word:u.word,score:u.score,complete:u.kind==="done",inList:u.kind!=="oov"}),ue=u=>({word:u.word,letters:u.groups.map(t=>({ch:t.ch,strokes:t.strokes})),inList:!!u.inList,selected:!!u.selected,alternatives:(u.alternatives||[]).map(t=>({word:t.text,score:t.score,inList:t.inList}))});function Qe(u){let t={},s={"millirec-overlap":null,set:"set",alphabet:"alphabet",list:"list",words:"words","words-src":"wordsSrc",target:"target","target-mode":"targetMode",size:"size",layout:"layout",chips:"chips",history:"history","idle-finish":"idleFinish",theme:"theme",hide:"hide",placeholder:"placeholder","asset-base":"assetBase","api-base":"apiBase"};for(let[n,o]of Object.entries(s)){let l=u.getAttribute("data-"+n);l==null||!o||(t[o]=l)}let e=u.getAttribute("data-engine");if(e)try{t.engine=JSON.parse(e)}catch{console.warn("MillirecOverlap: data-engine is not JSON")}let i=u.getAttribute("data-millirec-overlap");return i&&!t.list&&!t.words&&(t.list=i),t}function wt(u,t,s,e,i){if(!(!t||t.length<2)){u.globalAlpha=i,u.strokeStyle=s,u.lineWidth=e,u.lineCap="round",u.lineJoin="round",u.beginPath(),u.moveTo(t[0].x,t[0].y);for(let n=1;n<t.length;n++)u.lineTo(t[n].x,t[n].y);u.stroke(),u.globalAlpha=1}}function ts(u){let t=1/0,s=1/0,e=-1/0,i=-1/0;for(let n of u)for(let o of n)o.x<t&&(t=o.x),o.y<s&&(s=o.y),o.x>e&&(e=o.x),o.y>i&&(i=o.y);return t===1/0?null:{x0:t,y0:s,w:Math.max(1,e-t),h:Math.max(1,i-s)}}function X(u,t=44,s={},{gap:e=8,pad:i=6,dpr:n=window.devicePixelRatio||1}={}){let o=s.ink||"#111827",l=u.map(S=>ts(S.strokes||[])),a=l.filter(Boolean).map(S=>S.h).sort((S,b)=>S-b),d=a.length?a[Math.floor(a.length/2)]:1,m=t/d,f=l.map(S=>S?S.w*m:t*.35),w=f.reduce((S,b)=>S+b,0)+e*Math.max(0,u.length-1)+2*i,M=Math.max(t,...l.filter(Boolean).map(S=>S.h*m))+2*i,L=document.createElement("canvas");L.width=Math.ceil(w*n),L.height=Math.ceil(M*n),L.style.width=Math.ceil(w)+"px",L.style.height=Math.ceil(M)+"px";let v=L.getContext("2d");v.scale(n,n),v.lineWidth=Math.max(1.6,t/18),v.lineCap=v.lineJoin="round";let O=i;return u.forEach((S,b)=>{let E=l[b];if(E){let _=M-i-E.h*m;v.strokeStyle=S.state==="open"&&s.openInk||o;for(let k of S.strokes)v.beginPath(),k.forEach((P,T)=>{let R=O+(P.x-E.x0)*m,z=_+(P.y-E.y0)*m;T?v.lineTo(R,z):v.moveTo(R,z)}),v.stroke()}O+=f[b]+e}),L}function pe(u,t=44,s={}){let e=u.map(f=>X(f,t,s)),i=window.devicePixelRatio||1,n=t*.6,o=e.reduce((f,w)=>f+w.width/i,0)+n*Math.max(0,e.length-1),l=Math.max(1,...e.map(f=>f.height/i)),a=document.createElement("canvas");a.width=Math.ceil(o*i),a.height=Math.ceil(l*i),a.style.width=Math.ceil(o)+"px",a.style.height=Math.ceil(l)+"px";let d=a.getContext("2d"),m=0;for(let f of e)d.drawImage(f,m*i,l*i-f.height),m+=f.width/i+n;return a}function fe(u=document){let t=u.querySelectorAll?u.querySelectorAll("[data-millirec-overlap]"):[],s=[];for(let e of t)if(!e.__millirecOverlap){let i=new at(e);i.ready&&typeof i.ready.catch=="function"&&i.ready.catch(()=>{}),s.push(i)}return s}var me={version:Je,create:(u,t)=>at.create(u,t),scan:fe,Widget:at,buildLexicon:st,splitWords:rt,wordStrip:X,sentenceStrip:pe,alphabetOf:et,setNameOf:ot,DEFAULTS:St,LETTERS:ne,SETS:F,SET_NAMES:At,preload:(u="capitals",t)=>Et(t||xt({}),u)};if(typeof window<"u"&&!window.MillirecOverlap){window.MillirecOverlap=me;let u=()=>{try{fe(document)}catch(t){console.error(t)}};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",u):u()}var xs=me;})();