UNPKG

@wayrisignals/kicad-webview

Version:

Interactive KiCad schematic, PCB and 3D viewer for the web, with Gerber, Excellon, linked views and offline HTML exports

3 lines (2 loc) • 28.3 kB
/*! KiCad WebView 1.2.1 | Copyright (c) 2026 wayri | SPDX-License-Identifier: MPL-2.0 | Source: https://github.com/wayri/kicad-webview/tree/v1.2.1 | Keep LICENSE and THIRD-PARTY-NOTICES.md; bundled dependencies retain their licenses. */ var R=Object.freeze({bytes:16777216,commands:2e5,operations:2e5,segments:5e5,apertures:1024,repeats:1e4}),P=t=>{let e=Number(t);if(!Number.isFinite(e)||Math.abs(e)>1e6)throw new Error("CAM numeric value is invalid or exceeds the 1,000,000 mm coordinate bound.");return e},p=t=>String(Math.round(P(t)*1e9)/1e9);function ie(t){if(typeof t!="string")throw new TypeError("Manufacturing source must be text.");if(t.length>R.bytes)throw new Error("Manufacturing source exceeds 16 MiB.");let e=0;for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);if(o===0)throw new Error("Binary manufacturing files are unsupported.");if(o<128?e++:o<2048?e+=2:o>=55296&&o<=56319&&t.charCodeAt(r+1)>=56320&&t.charCodeAt(r+1)<=57343?(e+=4,r++):e+=3,e>R.bytes)throw new Error("Manufacturing source exceeds 16 MiB.")}}function B(t,e=0){let r=1/0,o=1/0,i=-1/0,a=-1/0;for(let c of t){let f=P(c.x),w=P(c.y);r=Math.min(r,f-e),o=Math.min(o,w-e),i=Math.max(i,f+e),a=Math.max(a,w+e)}return r===1/0?null:{x:r,y:o,w:i-r,h:a-o}}function ae(t){return B(t.filter(Boolean).flatMap(e=>[{x:e.x,y:e.y},{x:e.x+e.w,y:e.y+e.h}]))}function V(t,e,r){if(!(r>0))throw new Error("Aperture/tool dimensions must be positive.");return`M${p(t+r)} ${p(e)}A${p(r)} ${p(r)} 0 1 1 ${p(t-r)} ${p(e)}A${p(r)} ${p(r)} 0 1 1 ${p(t+r)} ${p(e)}Z`}var se=t=>t.map((e,r)=>`${r?"L":"M"}${p(e.x)} ${p(e.y)}`).join("")+"Z";function fe(t,e,r){let o=e.x-t.x,i=e.y-t.y,a=Math.hypot(o,i);if(a<1e-12)return V(t.x,t.y,r);let c=-i/a*r,f=o/a*r;return`M${p(t.x+c)} ${p(t.y+f)}L${p(e.x+c)} ${p(e.y+f)}A${p(r)} ${p(r)} 0 0 0 ${p(e.x-c)} ${p(e.y-f)}L${p(t.x-c)} ${p(t.y-f)}A${p(r)} ${p(r)} 0 0 0 ${p(t.x+c)} ${p(t.y+f)}Z`}var oe=Math.PI*2,de=t=>(t%oe+oe)%oe;function ee(t,e,r,o){let i=Math.hypot(t.x-r.x,t.y-r.y),a=Math.hypot(e.x-r.x,e.y-r.y);if(!(i>0)||Math.abs(i-a)>Math.max(.005,i*1e-6))throw new Error("Circular interpolation has inconsistent endpoint radii.");let c=Math.atan2(t.y-r.y,t.x-r.x),f=Math.atan2(e.y-r.y,e.x-r.x),w=Math.hypot(t.x-e.x,t.y-e.y)<1e-9,m=w?oe:de(o?c-f:f-c),u=o?0:1,s;if(w){let $={x:r.x*2-t.x,y:r.y*2-t.y};s=`A${p(i)} ${p(i)} 0 1 ${u} ${p($.x)} ${p($.y)}A${p(i)} ${p(i)} 0 1 ${u} ${p(e.x)} ${p(e.y)}`}else s=`A${p(i)} ${p(i)} 0 ${m>Math.PI?1:0} ${u} ${p(e.x)} ${p(e.y)}`;let h=[t,e];for(let $ of[0,Math.PI/2,Math.PI,Math.PI*1.5])(w||de(o?c-$:$-c)<=m+1e-10)&&h.push({x:r.x+i*Math.cos($),y:r.y+i*Math.sin($)});return{segment:s,bounds:B(h),radius:i,sweep:m,center:r}}function he(t,e,r,o){let i=e.x-t.x,a=e.y-t.y,c=Math.hypot(i,a);if(!(r>0)||c<1e-12||c>r*2+1e-8)throw new Error("Invalid or ambiguous radius-defined route arc.");let f=Math.sqrt(Math.max(0,r*r-c*c/4)),w=o?-1:1;return{x:(t.x+e.x)/2-w*a/c*f,y:(t.y+e.y)/2+w*i/c*f}}function L(t,{rotation:e=0,mirrorX:r=!1,mirrorY:o=!1,scale:i=1,x:a=0,y:c=0}={}){let f=e*Math.PI/180,w=t.x*(r?-1:1)*i,m=t.y*(o?-1:1)*i;return{x:P(a+w*Math.cos(f)-m*Math.sin(f)),y:P(c+w*Math.sin(f)+m*Math.cos(f))}}function J(t,e={}){let r=t.match(/[MLAZ]|[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi)||[],o=[],i=e.scale??1,a=!!e.mirrorX!=!!e.mirrorY;for(let c=0;c<r.length;){let f=r[c++];if(f==="Z"){o.push("Z");continue}if(f==="M"||f==="L"){let w=L({x:Number(r[c++]),y:Number(r[c++])},e);o.push(`${f}${p(w.x)} ${p(w.y)}`)}else if(f==="A"){let w=Number(r[c++])*i,m=Number(r[c++])*i;c++;let u=r[c++],s=Number(r[c++]),h=L({x:Number(r[c++]),y:Number(r[c++])},e);o.push(`A${p(w)} ${p(m)} 0 ${u} ${a?1-s:s} ${p(h.x)} ${p(h.y)}`)}else throw new Error("Unexpected internal CAM path command.")}return o.join("")}function pe(t){let e=[...t].sort((i,a)=>i.x-a.x||i.y-a.y),r=(i,a,c)=>(a.x-i.x)*(c.y-i.y)-(a.y-i.y)*(c.x-i.x),o=i=>{let a=[];for(let c of i){for(;a.length>1&&r(a.at(-2),a.at(-1),c)<=0;)a.pop();a.push(c)}return a};return[...o(e).slice(0,-1),...o(e.reverse()).slice(0,-1)]}function re(t,e){let r=[],o=[],i=new Set,a=0,c=0;return{operations:r,warnings:o,warn:u=>{i.has(u)||(i.add(u),o.length<100&&o.push(u))},add:u=>{if(r.length>=R.operations)throw new Error("Manufacturing geometry exceeds 200,000 operations.");if(a+=u.path.length,a>32*1024*1024)throw new Error("Manufacturing SVG geometry exceeds 32 MiB.");if(c+=JSON.stringify(u.metadata||{}).length,c>8*1024*1024)throw new Error("Manufacturing operation metadata exceeds 8 Mi characters.");let s={id:`${e||t}:${r.length+1}`,polarity:"dark",fill:!0,...u};return r.push(s),s},finish:(u={})=>({format:t,path:e,units:"mm",layers:[{id:e||t,name:u.fileFunction||e||t,operations:r}],warnings:o,bounds:ae(r.map(s=>s.bounds)),metadata:u})}}var ce=Object.freeze({parts:16384,points:131072,pathBytes:8*1024*1024,macroCommands:32768,expressionTokens:524288});function le(){return Object.fromEntries(Object.keys(ce).map(t=>[t,0]))}function U(t,e,r){if(t[e]+=r,t[e]>ce[e]){let o=new Error(`Gerber compiled aperture ${e} budget exceeded.`);throw o.code="CAM_RESOURCE_LIMIT",o}}var W=t=>{let e=P(t);if(!(e>0))throw new Error("Aperture dimensions must be positive.");return e},we=(t,e,r)=>({path:V(t,e,r),bounds:{x:t-r,y:e-r,w:r*2,h:r*2},circle:{x:t,y:e,radius:r}}),K=t=>({path:se(t),bounds:B(t),points:t}),xe=(t,e,r=0,o=0)=>[{x:r-t/2,y:o-e/2},{x:r+t/2,y:o-e/2},{x:r+t/2,y:o+e/2},{x:r-t/2,y:o+e/2}];function ye(t,e,r=0,o=0,i=0){if(!Number.isInteger(e)||e<3||e>12)throw new Error("Polygon apertures require 3 to 12 vertices.");return Array.from({length:e},(a,c)=>{let f=(i+c*360/e)*Math.PI/180;return{x:r+t/2*Math.cos(f),y:o+t/2*Math.sin(f)}})}function me(t,e,r){if(t.length>256)throw new Error("Aperture macro expression exceeds 256 characters.");let o=t.match(/\$\d+|(?:\d+(?:\.\d*)?|\.\d+)|[()+\-/xX]/g)||[];if(U(r,"expressionTokens",o.length),o.join("")!==t.replace(/\s/g,"")||o.length>128)throw new Error("Unsupported aperture macro expression.");let i=0,a=0;function c(){if(++a>32)throw new Error("Aperture macro expression nesting exceeds 32.");let u=o[i++],s;if(u==="+"||u==="-")s=(u==="-"?-1:1)*c();else if(u==="("){if(s=w(),o[i++]!==")")throw new Error("Unclosed aperture macro expression.")}else if(u?.startsWith("$")){let h=Number(u.slice(1));if(h>500)throw new Error("Aperture macro variable limit exceeded.");s=e.get(h)||0}else if(u!==void 0&&/^\d|^\./.test(u))s=Number(u);else throw new Error("Invalid aperture macro expression.");return a--,P(s)}function f(){let u=c();for(;["x","X","/"].includes(o[i]);){let s=o[i++],h=c();if(s==="/"&&h===0)throw new Error("Aperture macro division by zero.");u=P(s==="/"?u/h:u*h)}return u}function w(){let u=f();for(;["+","-"].includes(o[i]);){let s=o[i++],h=f();u=P(s==="+"?u+h:u-h)}return u}let m=w();if(i!==o.length)throw new Error("Invalid aperture macro expression tail.");return m}function Me(t,e,r,o){if(t.length>512)throw new Error("Aperture macro exceeds 512 commands.");let i=new Map(e.map((c,f)=>[f+1,P(c)])),a=[];for(let c of t){if(U(o,"macroCommands",1),!c||/^0(?:\s|,|$)/.test(c))continue;c.length>128*1024&&U(o,"expressionTokens",ce.expressionTokens+1);let f=0;for(let g=0;g<c.length;g++)c[g]===","&&++f>4100&&U(o,"expressionTokens",ce.expressionTokens+1);let w=/^\$(\d+)=(.+)$/.exec(c);if(w){let g=Number(w[1]);if(g>500)throw new Error("Aperture macro variable limit exceeded.");i.set(g,me(w[2],i,o));continue}let m=c.split(","),u=Number(m.shift()),s=m.map(g=>me(g,i,o));if(![1,4,5,20,21,22].includes(u))throw new Error(`Aperture macro primitive ${u} is unsupported.`);if(s[0]!==1)throw new Error("Aperture macros with clear exposure are unsupported.");let h,$=0,M=g=>P(g*r);if(u===1){if(s.length!==4&&s.length!==5)throw new Error("Invalid macro circle.");let g=W(M(s[1]))/2;$=s[4]||0;let N=L({x:M(s[2]),y:M(s[3])},{rotation:$});h=we(N.x,N.y,g)}else if(u===20){if(s.length!==7)throw new Error("Invalid macro vector line.");let g=W(M(s[1])),N={x:M(s[2]),y:M(s[3])},E={x:M(s[4]),y:M(s[5])},I=Math.hypot(E.x-N.x,E.y-N.y);if(!I)throw new Error("A zero-length macro vector line is unsupported.");let b=-(E.y-N.y)/I*g/2,D=(E.x-N.x)/I*g/2;$=s[6],h=K([{x:N.x+b,y:N.y+D},{x:E.x+b,y:E.y+D},{x:E.x-b,y:E.y-D},{x:N.x-b,y:N.y-D}].map(Z=>L(Z,{rotation:$})))}else if(u===21||u===22){if(s.length!==6)throw new Error("Invalid macro rectangle.");let g=W(M(s[1])),N=W(M(s[2]));$=s[5];let E=M(s[3])+(u===22?g/2:0),I=M(s[4])+(u===22?N/2:0);h=K(xe(g,N,E,I).map(b=>L(b,{rotation:$})))}else if(u===5){if(s.length!==6)throw new Error("Invalid macro polygon.");h=K(ye(W(M(s[4])),s[1],M(s[2]),M(s[3])).map(g=>L(g,{rotation:s[5]})))}else{let g=s[1];if(!Number.isInteger(g)||g<3||g>2e3||s.length!==g*2+5)throw new Error("Invalid macro outline.");U(o,"points",g+1);let N=Array.from({length:g+1},(E,I)=>({x:M(s[2+I*2]),y:M(s[3+I*2])}));if(Math.hypot(N[0].x-N.at(-1).x,N[0].y-N.at(-1).y)>1e-9)throw new Error("Macro outline is not closed.");h=K(N.slice(0,-1).map(E=>L(E,{rotation:s.at(-1)})))}if(U(o,"parts",1),u!==4&&U(o,"points",h.points?.length||1),U(o,"pathBytes",h.path.length),a.push(h),a.length>256)throw new Error("Aperture macro exceeds 256 primitives.")}if(!a.length)throw new Error("Aperture macro contains no drawable primitives.");return a}function ge(t,e,r,o,i=le()){if(e.length>500)throw new Error("Aperture exceeds 500 parameters.");let a=e.map(P),c=h=>W(a[h]*r),f,w,m;if(t==="C"){if(a.length<1||a.length>2)throw new Error("Invalid circular aperture parameters.");let h=c(0)/2;f=[we(0,0,h)],w={type:"circle",radius:h},m=h*2}else if(t==="R"||t==="O"){if(a.length<2||a.length>3)throw new Error("Invalid rectangular/obround aperture parameters.");let h=c(0),$=c(1);if(m=Math.min(h,$),t==="R"){let M=xe(h,$);f=[K(M)],w={type:"polygon",points:M}}else{let M=m/2,g={x:-(h-m)/2,y:-($-m)/2},N={x:-g.x,y:-g.y};f=[{path:fe(g,N,M),bounds:{x:-h/2,y:-$/2,w:h,h:$},capsule:{a:g,b:N,radius:M}}],Math.abs(h-$)<1e-12&&(w={type:"circle",radius:M})}}else if(t==="P"){if(a.length<2||a.length>4)throw new Error("Invalid polygon aperture parameters.");let h=ye(c(0),a[1],0,0,a[2]||0);f=[K(h)],w={type:"polygon",points:h},m=c(0)*Math.cos(Math.PI/a[1])}else{if(!o.has(t))throw new Error(`Aperture macro ${t} is not defined.`);return{template:t,parts:Me(o.get(t),e,r,i)}}let u=t==="C"?1:t==="P"?3:2,s=a[u]?W(a[u]*r):0;if(s){if(s>=m)throw new Error("Aperture hole is not contained inside its outer shape.");f[0].path+=V(0,0,s/2)}U(i,"parts",f.length);for(let h of f)U(i,"points",h.points?.length||1),U(i,"pathBytes",h.path.length);return{template:t,parts:f,stroke:s?null:w,hole:s}}function be(t,e){return t.parts.map(r=>{if(r.circle){let i=L(r.circle,e),a=r.circle.radius*e.scale;return{path:J(r.path,e),bounds:{x:i.x-a,y:i.y-a,w:a*2,h:a*2}}}if(r.points)return{path:J(r.path,e),bounds:B(r.points.map(i=>L(i,e)))};if(r.capsule)return{path:J(r.path,e),bounds:B([r.capsule.a,r.capsule.b].map(i=>L(i,e)),r.capsule.radius*e.scale)};let o=[{x:r.bounds.x,y:r.bounds.y},{x:r.bounds.x+r.bounds.w,y:r.bounds.y},{x:r.bounds.x+r.bounds.w,y:r.bounds.y+r.bounds.h},{x:r.bounds.x,y:r.bounds.y+r.bounds.h}].map(i=>L(i,e));return{path:J(r.path,e),bounds:B(o)}})}function*Ae(t){let e=0,r=0;for(;e<t.length;){if(/\s/.test(t[e])){e++;continue}let o=t[e]==="%",i=t.indexOf(o?"%":"*",e+(o?1:0));if(i<0)throw new Error("Unterminated Gerber command.");let a=t.slice(e+(o?1:0),i).trim();if(e=i+1,o&&a.startsWith("AM")){if(++r>R.commands)throw new Error("Gerber command limit exceeded.");yield{extended:o,body:a};continue}let c=0;for(;c<a.length;){let f=o?a.indexOf("*",c):-1,w=a.slice(c,f<0?a.length:f).trim();if(c=f<0?a.length:f+1,!!w){if(++r>R.commands)throw new Error("Gerber command limit exceeded.");yield{extended:o,body:w}}}}}function Ee(t,{path:e=""}={}){ie(t);let r=re("gerber",e),o=new Map,i=new Map,a=le(),c=Object.create(null),f=Object.create(null),w=Object.create(null),m=null,u=null,s=null,h=null,$=null,M="linear",g=null,N="dark",E={rotation:0,scale:1,mirrorX:!1,mirrorY:!1},I=null,b=null,D=!1,Z=0,q=(A,O)=>{if(!m||!u)throw new Error("Gerber units and coordinate format must be declared before coordinates.");if(/^[+-]?(?:\d+\.\d*|\.\d+)$/.test(A))return P(Number(A)*m);if(!/^[+-]?\d+$/.test(A))throw new Error("Invalid Gerber coordinate.");let x=A.startsWith("-")?-1:1,C=A.replace(/^[+-]/,""),F=u[O];if(C.length>F.integer+F.decimal)throw new Error("Gerber coordinate exceeds its declared digit format.");let T=u.zeros==="T"?C.padEnd(F.integer+F.decimal,"0"):C.padStart(F.integer+F.decimal,"0");return P(x*Number(T)/10**F.decimal*m)},H=(A,O,x={})=>{let C={...A,kind:O,polarity:N,metadata:{aperture:h,apertureAttributes:{...o.get(h)?.attributes},objectAttributes:{...w},...x}};(I?I.buffer:r).add(C)};function te(){if(I){for(let A=0;A<I.x;A++)for(let O=0;O<I.y;O++)for(let x of I.buffer.operations){let{id:C,...F}=x,T=A*I.i,z=O*I.j;r.add({...F,path:T||z?J(F.path,{x:T,y:z}):F.path,bounds:{...F.bounds,x:F.bounds.x+T,y:F.bounds.y+z},metadata:{...F.metadata,repeat:{x:A,y:O}}})}I=null}}function Q(){if(!b?.contour)return;let A=b.contour;if(A.edges&&Math.hypot(A.start.x-s.x,A.start.y-s.y)>1e-7)throw new Error("Gerber region contour is not closed.");A.edges&&(b.paths.push(A.path+"Z"),b.bounds.push(...A.bounds)),b.contour=null}function ne(A,O,x){if(!g)throw new Error("Gerber circular interpolation requires G74 or G75 quadrant mode.");let C=x.I===void 0?0:q(x.I,"x"),F=x.J===void 0?0:q(x.J,"y"),T=M==="clockwise";if(g==="multi")return ee(A,O,{x:A.x+C,y:A.y+F},T);let z=[];for(let j of[-1,1])for(let l of[-1,1])try{let y=ee(A,O,{x:A.x+Math.abs(C)*j,y:A.y+Math.abs(F)*l},T);y.sweep<=Math.PI/2+1e-6&&!z.some(n=>Math.hypot(n.center.x-y.center.x,n.center.y-y.center.y)<1e-8)&&z.push(y)}catch{}if(z.length!==1)throw new Error("Gerber single-quadrant arc has no unique valid center.");return z[0]}for(let A of Ae(t)){let O=A.body;if(D)throw new Error("Gerber commands appear after M02.");if(!A.extended&&/^G0?4/.test(O))continue;if(A.extended&&O.startsWith("AM")){let n=0;for(let k=0;k<O.length;k++)if(O[k]==="*"&&++n>513)throw new Error("Aperture macro exceeds 512 commands.");let d=O.split("*").map(k=>k.trim()).filter(Boolean),G=d.shift().slice(2);if(!/^[A-Za-z_.$][A-Za-z0-9_.$]{0,99}$/.test(G)||i.has(G)||i.size>=R.apertures)throw new Error("Invalid, duplicate or excessive Gerber aperture macro.");i.set(G,d);continue}let x=O.replace(/\s/g,"");if(A.extended){let n;if(n=/^FS([LT])([AI])X(\d)(\d)Y(\d)(\d)$/.exec(x)){if(u||n[2]!=="A")throw new Error("Repeated or incremental Gerber format declarations are unsupported.");let d={integer:Number(n[3]),decimal:Number(n[4])},G={integer:Number(n[5]),decimal:Number(n[6])};if([d,G].some(k=>k.integer<1||k.integer>6||k.decimal<1||k.decimal>7))throw new Error("Invalid Gerber digit format.");u={zeros:n[1],x:d,y:G};continue}if(/^MO(MM|IN)$/.test(x)){let d=x==="MOMM"?1:25.4;if(m&&m!==d)throw new Error("Gerber unit changes within a file are unsupported.");m=d;continue}if(n=/^ADD(\d+)([A-Za-z_.$][A-Za-z0-9_.$]*)(?:,(.*))?$/.exec(x)){if(!m)throw new Error("Gerber aperture declaration needs explicit units.");let d=Number(n[1]);if(d<10||o.has(d)||o.size>=R.apertures)throw new Error("Invalid, duplicate or excessive Gerber aperture.");if(n[3]){let G=0;for(let k=0;k<n[3].length;k++)if(n[3][k]==="X"&&++G>=500)throw new Error("Aperture exceeds 500 parameters.")}try{o.set(d,{...ge(n[2],n[3]?n[3].split("X"):[],m,i,a),attributes:{...f}})}catch(G){if(G.code==="CAM_RESOURCE_LIMIT")throw G;o.set(d,{unsupported:G.message,attributes:{...f}})}continue}if(n=/^(TF|TA|TO)([^,]+)(?:,(.*))?$/.exec(O)){let d=n[1]==="TF"?c:n[1]==="TA"?f:w;if(Object.keys(d).length>=128||O.length>4096)throw new Error("Gerber attributes exceed metadata limits.");d[n[2]]=n[3]===void 0?[]:n[3].split(",");continue}if(n=/^TD(.*)$/.exec(x)){for(let d of[f,w])for(let G of Object.keys(d))(!n[1]||G===n[1])&&delete d[G];continue}if(/^LP[DC]$/.test(x)){if(b)throw new Error("Polarity changes inside a Gerber region are unsupported.");N=x==="LPD"?"dark":"clear";continue}if(n=/^LM(N|X|Y|XY)$/.exec(x)){E={...E,mirrorX:n[1].includes("X"),mirrorY:n[1].includes("Y")};continue}if(n=/^LR([+-]?(?:\d+(?:\.\d*)?|\.\d+))$/.exec(x)){E={...E,rotation:P(n[1])};continue}if(n=/^LS([+]?(?:\d+(?:\.\d*)?|\.\d+))$/.exec(x)){let d=P(n[1]);if(!(d>0))throw new Error("Invalid aperture scale.");E={...E,scale:d};continue}if(x==="SR"){if(b)throw new Error("Step-repeat changes inside a region are unsupported.");te();continue}if(n=/^SRX(\d+)Y(\d+)I([+-]?(?:\d+(?:\.\d*)?|\.\d+))J([+-]?(?:\d+(?:\.\d*)?|\.\d+))$/.exec(x)){if(b||I||!m)throw new Error("Nested or invalid Gerber step-repeat state.");if(I={x:Number(n[1]),y:Number(n[2]),i:P(Number(n[3])*m),j:P(Number(n[4])*m),buffer:re("gerber-repeat",e)},I.x<1||I.y<1||I.x*I.y>R.repeats)throw new Error("Gerber step-repeat exceeds 10,000 copies.");continue}if(/^LN/.test(x)){c.LayerName=[O.slice(2)];continue}if(x==="IPPOS")continue;throw new Error(`Unsupported Gerber state command: ${x.slice(0,80)}.`)}if(/^M0?2$/.test(x)){if(b||I)throw new Error("Gerber ended inside a region or step-repeat block.");D=!0;continue}if(/^G0?36$/.test(x)){if(b)throw new Error("Nested Gerber regions are unsupported.");b={paths:[],bounds:[],contour:null};continue}if(/^G0?37$/.test(x)){if(!b)throw new Error("Gerber region end without a start.");Q(),b.paths.length&&H({path:b.paths.join(""),bounds:ae(b.bounds)},"region"),b=null;continue}if(/^G0?74$/.test(x)){g="single";continue}if(/^G0?75$/.test(x)){g="multi";continue}if(/^G0?90$/.test(x))continue;if(/^G0?91$/.test(x))throw new Error("Incremental Gerber coordinates are unsupported.");let C=x.replace(/^G0?54/,""),F=[...C.matchAll(/([XYIJDG])([+-]?(?:\d+(?:\.\d*)?|\.\d+))/g)];if(!F.length||F.map(n=>n[0]).join("")!==C)throw new Error(`Unsupported Gerber command: ${x.slice(0,80)}.`);let T=Object.create(null);for(let n of F){if(T[n[1]]!==void 0)throw new Error("Duplicate Gerber coordinate/code word.");T[n[1]]=n[2]}if(T.G!==void 0){let n=Number(T.G);if(![1,2,3].includes(n))throw new Error(`Unsupported Gerber interpolation G${n}.`);M=n===1?"linear":n===2?"clockwise":"counterclockwise"}if(T.D!==void 0&&Number(T.D)>=10){if(["X","Y","I","J"].some(n=>T[n]!==void 0))throw new Error("Aperture selection cannot carry coordinates.");if(h=Number(T.D),!o.has(h))throw new Error("Selected Gerber aperture is undefined.");continue}if(T.D!==void 0&&($=Number(T.D),![1,2,3].includes($)))throw new Error("Invalid Gerber operation code.");if(!["X","Y"].some(n=>T[n]!==void 0)&&T.D===void 0)continue;if(!$)throw new Error("Gerber coordinates have no operation code.");let j={x:T.X===void 0?s?.x:q(T.X,"x"),y:T.Y===void 0?s?.y:q(T.Y,"y")};if(!Number.isFinite(j.x)||!Number.isFinite(j.y))throw new Error("The first Gerber position must define both axes.");if(++Z>R.segments)throw new Error("Gerber geometry segment limit exceeded.");if($===2){b&&(Q(),b.contour={start:j,path:`M${p(j.x)} ${p(j.y)}`,bounds:[],edges:0}),s=j;continue}let l=o.get(h);if($===3){if(b)throw new Error("A flash is not valid inside a Gerber region.");if(!l)throw new Error("Gerber flash needs a selected aperture.");if(l.unsupported)r.warn(`D${h} omitted: ${l.unsupported}`);else for(let n of be(l,{...E,x:j.x,y:j.y}))H(n,"flash");s=j;continue}if(!s)throw new Error("Gerber draw needs a starting position.");let y=M==="linear"?{segment:`L${p(j.x)} ${p(j.y)}`,bounds:B([s,j])}:ne(s,j,T);if(b){if(!b.contour)throw new Error("A region contour needs an initial D02 move.");b.contour.path+=y.segment,b.contour.bounds.push(y.bounds),b.contour.edges++}else{if(!l)throw new Error("Gerber draw needs a selected aperture.");if(l.unsupported||!l.stroke)r.warn(`D${h} draw omitted: ${l.unsupported||"unsupported swept aperture or aperture hole"}.`);else if(l.stroke.type==="circle"){let n=l.stroke.radius*2*E.scale,d=y.bounds;H({path:`M${p(s.x)} ${p(s.y)}`+y.segment,fill:!1,width:n,bounds:{x:d.x-n/2,y:d.y-n/2,w:d.w+n,h:d.h+n}},"stroke")}else if(M==="linear"){let n=l.stroke.points.map(G=>L(G,E)),d=pe(n.flatMap(G=>[{x:G.x+s.x,y:G.y+s.y},{x:G.x+j.x,y:G.y+j.y}]));H({path:se(d),bounds:B(d)},"stroke")}else r.warn(`D${h} circular draw omitted: non-circular swept apertures are unsupported.`)}s=j}if(b)throw new Error("Unclosed Gerber region.");if(I)throw new Error("Unclosed Gerber step-repeat block.");if(!m||!u)throw new Error("Gerber units/format are missing; RS-274D without embedded apertures is unsupported.");return D||r.warn("Gerber M02 end marker is missing."),r.finish({inputUnits:m===1?"mm":"inch",coordinateFormat:u,attributes:{...c},fileFunction:c[".FileFunction"]?.join(",")||c.LayerName?.join(",")})}function ue(t){if(t==null)return null;let e=Array.isArray(t)?t:typeof t=="string"?t.split(":").map(Number):[t.integer,t.decimal];if(e.length!==2||e.some(r=>!Number.isInteger(r))||e[0]<1||e[0]>6||e[1]<1||e[1]>7)throw new TypeError("Excellon formatDigits must specify integer and decimal digit counts.");return{integer:e[0],decimal:e[1]}}function $e(t,e={}){ie(t);let{path:r=""}=e,o=re("excellon",r),i=new Map,a=Object.create(null),c=Object.create(null),f=Object.create(null),w=e.units===void 0?null:e.units==="mm"?1:e.units==="inch"?25.4:NaN;if(Number.isNaN(w))throw new TypeError("Excellon units must be mm or inch.");let m=w,u=ue(e.formatDigits),s=e.zeroSuppression||null;if(s&&!["leading","trailing","none"].includes(s))throw new TypeError("Excellon zeroSuppression must be leading, trailing or none.");let h=e.decimal===!0||e.coordinateFormat==="decimal"||/\.xnc$/i.test(r),$=!1,M=!1,g=!1,N=!1,E=null,I=null,b="drill",D=!1,Z="linear",q=null,H=1;for(let l=0;l<t.length;l++)if(t.charCodeAt(l)===10&&++H>R.commands)throw new Error("Excellon command limit exceeded.");let te=t.split(/\r?\n/),Q=l=>{if(m&&m!==l)throw new Error("Excellon units conflict with the header/options.");m=l},ne=l=>{if(u&&(u.integer!==l.integer||u.decimal!==l.decimal))throw new Error("Excellon digit format conflicts with the header/options.");u=l},A=l=>{if(s&&s!==l)throw new Error("Excellon zero suppression conflicts with the header/options.");s=l},O=l=>{if(!m)throw new Error("Excellon units are missing; specify units explicitly.");if(/^[+-]?(?:\d+\.\d*|\.\d+)$/.test(l)||h)return P(Number(l)*m);if(!/^[+-]?\d+$/.test(l))throw new Error("Invalid Excellon coordinate.");if(Number(l)===0)return 0;if(!u)throw new Error("Ambiguous Excellon integer coordinates: specify formatDigits or use a declared decimal format.");let y=l.startsWith("-")?-1:1,n=l.replace(/^[+-]/,""),d=u.integer+u.decimal;if(n.length>d)throw new Error("Excellon coordinate exceeds its declared digit format.");if(n.length<d&&(!s||s==="none"))throw new Error("Ambiguous Excellon omitted zeros: specify zeroSuppression.");let G=s==="trailing"?n.padEnd(d,"0"):n.padStart(d,"0");return P(y*Number(G)/10**u.decimal*m)};function x(l){let y=[...l.matchAll(/([XYIJA])([+-]?(?:\d+(?:\.\d*)?|\.\d+))/g)];if(!y.length||y.map(d=>d[0]).join("")!==l)throw new Error(`Unsupported Excellon coordinate command: ${l.slice(0,80)}.`);let n=Object.create(null);for(let d of y){if(n[d[1]]!==void 0)throw new Error("Duplicate Excellon coordinate word.");n[d[1]]=O(d[2])}return n}function C(l,y=E){let n={x:l.X??y?.x,y:l.Y??y?.y};if(!Number.isFinite(n.x)||!Number.isFinite(n.y))throw new Error("The first Excellon position must define both axes.");return n}function F(){let l=i.get(I);if(!l)throw new Error("Excellon geometry requires a defined selected tool.");return l}function T(l,y,n){let d=F();o.add({...l,kind:y,metadata:{tool:I,diameter:d.diameter,line:n,toolAttributes:{...d.attributes},objectAttributes:{...f}}}),d.operations++}function z(l,y){let n=F().diameter/2;T({path:V(l.x,l.y,n),bounds:{x:l.x-n,y:l.y-n,w:n*2,h:n*2}},"drill",y)}function j(l,y,n,d,G="route"){let k=F().diameter,_,Y;if(Z==="linear"||G==="slot")_=`L${p(y.x)} ${p(y.y)}`,Y=B([l,y]);else{let v=Z==="clockwise",S;if(n.I!==void 0||n.J!==void 0)S={x:l.x+(n.I||0),y:l.y+(n.J||0)};else{let X=n.A??q;if(!X)throw new Error("Excellon circular routing requires I/J offsets or an explicit A radius.");q=X,S=he(l,y,X,v)}({segment:_,bounds:Y}=ee(l,y,S,v))}T({path:`M${p(l.x)} ${p(l.y)}`+_,fill:!1,width:k,bounds:{x:Y.x-k/2,y:Y.y-k/2,w:Y.w+k,h:Y.h+k}},G,d)}for(let l=0;l<te.length;l++){let y=te[l].trim();if(!y)continue;if(y.startsWith(";")){let v;if((v=/FILE_FORMAT\s*=\s*(\d+)\s*:\s*(\d+)/i.exec(y))&&ne(ue([Number(v[1]),Number(v[2])])),/FORMAT=.*\/\s*decimal\s*\}/i.test(y)&&(h=!0),v=/#@!\s*(TF|TA|TO)([^,\s]+)(?:,(.*))?/.exec(y)){let S=v[1]==="TF"?a:v[1]==="TA"?c:f;if(Object.keys(S).length>128||y.length>4096)throw new Error("Excellon attributes exceed metadata limits.");S[v[2]]=v[3]?.split(",")||[]}if(/#@!\s*TD/.test(y))for(let S of[c,f])for(let X of Object.keys(S))delete S[X];continue}if(N)throw new Error("Excellon commands appear after M30.");let n=y.replace(/\s/g,""),d;if(n==="M48"){if(M)throw new Error("Repeated Excellon header.");M=$=!0;continue}if(!M)throw new Error("An Excellon M48 header is required in this beta.");if(n==="%"||n==="M95"){if(!$)throw new Error("Unexpected Excellon header end.");$=!1,g=!0;continue}if(d=/^(METRIC|INCH)(?:,(LZ|TZ))?(?:,(0+)\.(0+))?$/.exec(n)){if(!$)throw new Error("Excellon unit declaration must be in its header.");Q(d[1]==="METRIC"?1:25.4),d[2]&&A(d[2]==="LZ"?"trailing":"leading"),d[3]&&ne(ue([d[3].length,d[4].length]));continue}if(n==="M71"||n==="M72"){Q(n==="M71"?1:25.4);continue}if(n==="FMAT,2"||n==="VER,1"||n==="ICI,OFF"||n==="G90")continue;if(n==="G91"||n==="ICI,ON")throw new Error("Incremental Excellon coordinates are unsupported.");if(d=/^T(\d+)C((?:\d+(?:\.\d*)?|\.\d+))(?:F[\d.]+)?(?:S[\d.]+)?$/.exec(n)){if(!$||!m)throw new Error("Excellon tools must be declared in a header with explicit units.");let v=Number(d[1]),S=P(Number(d[2])*m);if(v<1||v>9999||i.has(v)||i.size>=R.apertures||!(S>0))throw new Error("Invalid, duplicate or excessive Excellon tool.");i.set(v,{diameter:S,attributes:{...c},operations:0});continue}if($)throw new Error(`Unsupported Excellon header command: ${n.slice(0,80)}.`);if(n==="M30"){if(D)throw new Error("Excellon ended with the route tool down.");N=!0;continue}if(d=/^T(\d+)$/.exec(n)){if(I=Number(d[1])||null,I&&!i.has(I))throw new Error("Undefined Excellon tool selected.");continue}if(/^G0?5$/.test(n)){b="drill",D=!1,Z="linear";continue}if(n==="M15"){if(b!=="rout"||!E)throw new Error("Excellon tool down requires a route start.");F(),D=!0;continue}if(n==="M16"||n==="M17"){D=!1;continue}if(n.includes("G85")){if(D)throw new Error("G85 slot encountered while routing.");let v=n.split("G85");if(v.length!==2||!v[1])throw new Error("Invalid Excellon G85 slot.");let S=v[0]?C(x(v[0])):E;if(!S)throw new Error("Excellon slot start is undefined.");let X=C(x(v[1]),S);j(S,X,{},l+1,"slot"),E=X;continue}if(d=/^R(\d+)(.*)$/.exec(n)){let v=Number(d[1]);if(b!=="drill"||!E||v<1||v>R.repeats)throw new Error("Invalid or excessive Excellon repeat drill pattern.");let S=x(d[2]);if(Object.keys(S).some(X=>!["X","Y"].includes(X)))throw new Error("Unsupported Excellon repeat fields.");for(let X=0;X<v;X++)E={x:P(E.x+(S.X||0)),y:P(E.y+(S.Y||0))},z(E,l+1);continue}let G=n,k=null;if((d=/^G(0?[0123])(.*)$/.exec(n))&&(k=Number(d[1]),G=d[2]),k===0){if(b="rout",D)throw new Error("Rapid route movement with tool down is unsupported.");G&&(E=C(x(G)));continue}k!==null&&(b="rout",Z=k===1?"linear":k===2?"clockwise":"counterclockwise");let _=x(G),Y=C(_);if(b==="drill"){if(["I","J","A"].some(v=>_[v]!==void 0))throw new Error("Unexpected arc fields in drill mode.");z(Y,l+1)}else{if(!D||!E)throw new Error("Excellon route segment requires tool down and a starting point.");j(E,Y,_,l+1)}E=Y}if(!g||$)throw new Error("Excellon header is incomplete.");if(!m)throw new Error("Excellon units are missing.");return N||o.warn("Excellon M30 end marker is missing."),o.finish({inputUnits:m===1?"mm":"inch",coordinateFormat:h?"decimal":u,zeroSuppression:s,attributes:{...a},fileFunction:a[".FileFunction"]?.join(","),tools:[...i].map(([l,y])=>({id:l,diameter:y.diameter,operations:y.operations,attributes:{...y.attributes}}))})}function Ie(t,e=""){if(typeof t!="string")return null;let r=t.slice(0,65536).replace(/^\uFEFF/,"");return/%\s*(?:FS[LT][AI]X\d\dY\d\d|MO(?:MM|IN)|ADD\d+)/.test(r)?"gerber":/(?:^|\n)\s*M48\s*(?:\r?\n|$)/.test(r)?"excellon":null}function Ce(t,e={}){let r=e.format||Ie(t,e.path);if(r==="gerber")return Ee(t.replace(/^\uFEFF/,""),e);if(r==="excellon"||r==="xnc")return $e(t.replace(/^\uFEFF/,""),e);throw new Error("Source is not a recognized Gerber RS-274X or Excellon/XNC file.")}export{Ie as a,Ce as b};