);function YCt(t){let e=\"[0-5]\\\\d\";return t.precision?e=`${e}\\\\.\\\\d{${t.precision}}`:t.precision==null\u0026\u0026(e=`${e}(\\\\.\\\\d+)?`),`([01]\\\\d|2[0-3]):[0-5]\\\\d(:${e})${t.precision?\"+\":\"?\"}`}function Qoo(t){return new RegExp(`^${YCt(t)} dist/viewer-part-02.txt - astra/am3352-sbc - tscircuit )}function UCt(t){let e=`${GCt}T${YCt(t)}`;const n=[];return n.push(t.local?\"Z?\":\"Z\"),t.offset\u0026\u0026n.push(\"([+-]\\\\d{2}:?\\\\d{2})\"),e=`${e}(${n.join(\"|\")})`,new RegExp(`^${e} dist/viewer-part-02.txt - astra/am3352-sbc - tscircuit )}function voo(t,e){return!(e!==\"v4\"\u0026\u0026e||!Coo.test(t))||!(e!==\"v6\"\u0026\u0026e||!xoo.test(t))}function woo(t,e){if(!_oo.test(t))return!1;try{const[n]=t.split(\".\");if(!n)return!1;const o=n.replace(/-/g,\"+\").replace(/_/g,\"/\").padEnd(n.length+(4-n.length%4)%4,\"=\"),i=JSON.parse(atob(o));return typeof i==\"object\"\u0026\u0026i!==null\u0026\u0026(!(\"typ\"in i)||i?.typ===\"JWT\")\u0026\u0026!!i.alg\u0026\u0026(!e||i.alg===e)}catch{return!1}}function Poo(t,e){return!(e!==\"v4\"\u0026\u0026e||!yoo.test(t))||!(e!==\"v6\"\u0026\u0026e||!Eoo.test(t))}var BL=class jte extends JA{_parse(e){if(this._def.coerce\u0026\u0026(e.data=String(e.data)),this._getType(e)!==xr.string){const i=this._getOrReturnCtx(e);return nr(i,{code:hi.invalid_type,expected:xr.string,received:i.parsedType}),ea}const n=new Cx;let o;for(const i of this._def.checks)if(i.kind===\"min\")e.data.length\u003ci.value\u0026\u0026(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.too_small,minimum:i.value,type:\"string\",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind===\"max\")e.data.length\u003ei.value\u0026\u0026(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.too_big,maximum:i.value,type:\"string\",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind===\"length\"){const r=e.data.length\u003ei.value,s=e.data.length\u003ci.value;(r||s)\u0026\u0026(o=this._getOrReturnCtx(e,o),r?nr(o,{code:hi.too_big,maximum:i.value,type:\"string\",inclusive:!0,exact:!0,message:i.message}):s\u0026\u0026nr(o,{code:hi.too_small,minimum:i.value,type:\"string\",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind===\"email\")Ioo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"email\",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind===\"emoji\")p8e||(p8e=new RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\",\"u\")),p8e.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"emoji\",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind===\"uuid\")poo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"uuid\",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind===\"nanoid\")moo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"nanoid\",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind===\"cuid\")goo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"cuid\",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind===\"cuid2\")doo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"cuid2\",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind===\"ulid\")hoo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"ulid\",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind===\"url\")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),nr(o,{validation:\"url\",code:hi.invalid_string,message:i.message}),n.dirty()}else i.kind===\"regex\"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"regex\",code:hi.invalid_string,message:i.message}),n.dirty())):i.kind===\"trim\"?e.data=e.data.trim():i.kind===\"includes\"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind===\"toLowerCase\"?e.data=e.data.toLowerCase():i.kind===\"toUpperCase\"?e.data=e.data.toUpperCase():i.kind===\"startsWith\"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind===\"endsWith\"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind===\"datetime\"?UCt(i).test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:\"datetime\",message:i.message}),n.dirty()):i.kind===\"date\"?Soo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:\"date\",message:i.message}),n.dirty()):i.kind===\"time\"?Qoo(i).test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:\"time\",message:i.message}),n.dirty()):i.kind===\"duration\"?foo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"duration\",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind===\"ip\"?voo(e.data,i.version)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"ip\",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind===\"jwt\"?woo(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"jwt\",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind===\"cidr\"?Poo(e.data,i.version)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"cidr\",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind===\"base64\"?Boo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"base64\",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind===\"base64url\"?boo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:\"base64url\",code:hi.invalid_string,message:i.message}),n.dirty()):Cl.assertNever(i);return{status:n.value,value:e.data}}_regex(e,n,o){return this.refinement(i=\u003ee.test(i),{validation:n,code:hi.invalid_string,...rs.errToObj(o)})}_addCheck(e){return new jte({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:\"email\",...rs.errToObj(e)})}url(e){return this._addCheck({kind:\"url\",...rs.errToObj(e)})}emoji(e){return this._addCheck({kind:\"emoji\",...rs.errToObj(e)})}uuid(e){return this._addCheck({kind:\"uuid\",...rs.errToObj(e)})}nanoid(e){return this._addCheck({kind:\"nanoid\",...rs.errToObj(e)})}cuid(e){return this._addCheck({kind:\"cuid\",...rs.errToObj(e)})}cuid2(e){return this._addCheck({kind:\"cuid2\",...rs.errToObj(e)})}ulid(e){return this._addCheck({kind:\"ulid\",...rs.errToObj(e)})}base64(e){return this._addCheck({kind:\"base64\",...rs.errToObj(e)})}base64url(e){return this._addCheck({kind:\"base64url\",...rs.errToObj(e)})}jwt(e){return this._addCheck({kind:\"jwt\",...rs.errToObj(e)})}ip(e){return this._addCheck({kind:\"ip\",...rs.errToObj(e)})}cidr(e){return this._addCheck({kind:\"cidr\",...rs.errToObj(e)})}datetime(e){return typeof e==\"string\"?this._addCheck({kind:\"datetime\",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:\"datetime\",precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...rs.errToObj(e?.message)})}date(e){return this._addCheck({kind:\"date\",message:e})}time(e){return typeof e==\"string\"?this._addCheck({kind:\"time\",precision:null,message:e}):this._addCheck({kind:\"time\",precision:e?.precision===void 0?null:e?.precision,...rs.errToObj(e?.message)})}duration(e){return this._addCheck({kind:\"duration\",...rs.errToObj(e)})}regex(e,n){return this._addCheck({kind:\"regex\",regex:e,...rs.errToObj(n)})}includes(e,n){return this._addCheck({kind:\"includes\",value:e,position:n?.position,...rs.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:\"startsWith\",value:e,...rs.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:\"endsWith\",value:e,...rs.errToObj(n)})}min(e,n){return this._addCheck({kind:\"min\",value:e,...rs.errToObj(n)})}max(e,n){return this._addCheck({kind:\"max\",value:e,...rs.errToObj(n)})}length(e,n){return this._addCheck({kind:\"length\",value:e,...rs.errToObj(n)})}nonempty(e){return this.min(1,rs.errToObj(e))}trim(){return new jte({...this._def,checks:[...this._def.checks,{kind:\"trim\"}]})}toLowerCase(){return new jte({...this._def,checks:[...this._def.checks,{kind:\"toLowerCase\"}]})}toUpperCase(){return new jte({...this._def,checks:[...this._def.checks,{kind:\"toUpperCase\"}]})}get isDatetime(){return!!this._def.checks.find(e=\u003ee.kind===\"datetime\")}get isDate(){return!!this._def.checks.find(e=\u003ee.kind===\"date\")}get isTime(){return!!this._def.checks.find(e=\u003ee.kind===\"time\")}get isDuration(){return!!this._def.checks.find(e=\u003ee.kind===\"duration\")}get isEmail(){return!!this._def.checks.find(e=\u003ee.kind===\"email\")}get isURL(){return!!this._def.checks.find(e=\u003ee.kind===\"url\")}get isEmoji(){return!!this._def.checks.find(e=\u003ee.kind===\"emoji\")}get isUUID(){return!!this._def.checks.find(e=\u003ee.kind===\"uuid\")}get isNANOID(){return!!this._def.checks.find(e=\u003ee.kind===\"nanoid\")}get isCUID(){return!!this._def.checks.find(e=\u003ee.kind===\"cuid\")}get isCUID2(){return!!this._def.checks.find(e=\u003ee.kind===\"cuid2\")}get isULID(){return!!this._def.checks.find(e=\u003ee.kind===\"ulid\")}get isIP(){return!!this._def.checks.find(e=\u003ee.kind===\"ip\")}get isCIDR(){return!!this._def.checks.find(e=\u003ee.kind===\"cidr\")}get isBase64(){return!!this._def.checks.find(e=\u003ee.kind===\"base64\")}get isBase64url(){return!!this._def.checks.find(e=\u003ee.kind===\"base64url\")}get minLength(){let e=null;for(const n of this._def.checks)n.kind===\"min\"\u0026\u0026(e===null||n.value\u003ee)\u0026\u0026(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind===\"max\"\u0026\u0026(e===null||n.value\u003ce)\u0026\u0026(e=n.value);return e}};function Moo(t,e){const n=(t.toString().split(\".\")[1]||\"\").length,o=(e.toString().split(\".\")[1]||\"\").length,i=n\u003eo?n:o;return Number.parseInt(t.toFixed(i).replace(\".\",\"\"))%Number.parseInt(e.toFixed(i).replace(\".\",\"\"))/10**i}BL.create=t=\u003enew BL({checks:[],typeName:aa.ZodString,coerce:t?.coerce??!1,...SA(t)});var xJ=class hit extends JA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce\u0026\u0026(e.data=Number(e.data)),this._getType(e)!==xr.number){const i=this._getOrReturnCtx(e);return nr(i,{code:hi.invalid_type,expected:xr.number,received:i.parsedType}),ea}let n;const o=new Cx;for(const i of this._def.checks)i.kind===\"int\"?Cl.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.invalid_type,expected:\"integer\",received:\"float\",message:i.message}),o.dirty()):i.kind===\"min\"?(i.inclusive?e.data\u003ci.value:e.data\u003c=i.value)\u0026\u0026(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.too_small,minimum:i.value,type:\"number\",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind===\"max\"?(i.inclusive?e.data\u003ei.value:e.data\u003e=i.value)\u0026\u0026(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.too_big,maximum:i.value,type:\"number\",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind===\"multipleOf\"?Moo(e.data,i.value)!==0\u0026\u0026(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind===\"finite\"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.not_finite,message:i.message}),o.dirty()):Cl.assertNever(i);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit(\"min\",e,!0,rs.toString(n))}gt(e,n){return this.setLimit(\"min\",e,!1,rs.toString(n))}lte(e,n){return this.setLimit(\"max\",e,!0,rs.toString(n))}lt(e,n){return this.setLimit(\"max\",e,!1,rs.toString(n))}setLimit(e,n,o,i){return new hit({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:o,message:rs.toString(i)}]})}_addCheck(e){return new hit({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:\"int\",message:rs.toString(e)})}positive(e){return this._addCheck({kind:\"min\",value:0,inclusive:!1,message:rs.toString(e)})}negative(e){return this._addCheck({kind:\"max\",value:0,inclusive:!1,message:rs.toString(e)})}nonpositive(e){return this._addCheck({kind:\"max\",value:0,inclusive:!0,message:rs.toString(e)})}nonnegative(e){return this._addCheck({kind:\"min\",value:0,inclusive:!0,message:rs.toString(e)})}multipleOf(e,n){return this._addCheck({kind:\"multipleOf\",value:e,message:rs.toString(n)})}finite(e){return this._addCheck({kind:\"finite\",message:rs.toString(e)})}safe(e){return this._addCheck({kind:\"min\",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:rs.toString(e)})._addCheck({kind:\"max\",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:rs.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind===\"min\"\u0026\u0026(e===null||n.value\u003ee)\u0026\u0026(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind===\"max\"\u0026\u0026(e===null||n.value\u003ce)\u0026\u0026(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=\u003ee.kind===\"int\"||e.kind===\"multipleOf\"\u0026\u0026Cl.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const o of this._def.checks){if(o.kind===\"finite\"||o.kind===\"int\"||o.kind===\"multipleOf\")return!0;o.kind===\"min\"?(n===null||o.value\u003en)\u0026\u0026(n=o.value):o.kind===\"max\"\u0026\u0026(e===null||o.value\u003ce)\u0026\u0026(e=o.value)}return Number.isFinite(n)\u0026\u0026Number.isFinite(e)}};xJ.create=t=\u003enew xJ({checks:[],typeName:aa.ZodNumber,coerce:t?.coerce||!1,...SA(t)});var EJ=class pit extends JA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==xr.bigint)return this._getInvalidInput(e);let n;const o=new Cx;for(const i of this._def.checks)i.kind===\"min\"?(i.inclusive?e.data\u003ci.value:e.data\u003c=i.value)\u0026\u0026(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.too_small,type:\"bigint\",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind===\"max\"?(i.inclusive?e.data\u003ei.value:e.data\u003e=i.value)\u0026\u0026(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.too_big,type:\"bigint\",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind===\"multipleOf\"?e.data%i.value!==BigInt(0)\u0026\u0026(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):Cl.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return nr(n,{code:hi.invalid_type,expected:xr.bigint,received:n.parsedType}),ea}gte(e,n){return this.setLimit(\"min\",e,!0,rs.toString(n))}gt(e,n){return this.setLimit(\"min\",e,!1,rs.toString(n))}lte(e,n){return this.setLimit(\"max\",e,!0,rs.toString(n))}lt(e,n){return this.setLimit(\"max\",e,!1,rs.toString(n))}setLimit(e,n,o,i){return new pit({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:o,message:rs.toString(i)}]})}_addCheck(e){return new pit({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:\"min\",value:BigInt(0),inclusive:!1,message:rs.toString(e)})}negative(e){return this._addCheck({kind:\"max\",value:BigInt(0),inclusive:!1,message:rs.toString(e)})}nonpositive(e){return this._addCheck({kind:\"max\",value:BigInt(0),inclusive:!0,message:rs.toString(e)})}nonnegative(e){return this._addCheck({kind:\"min\",value:BigInt(0),inclusive:!0,message:rs.toString(e)})}multipleOf(e,n){return this._addCheck({kind:\"multipleOf\",value:e,message:rs.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind===\"min\"\u0026\u0026(e===null||n.value\u003ee)\u0026\u0026(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind===\"max\"\u0026\u0026(e===null||n.value\u003ce)\u0026\u0026(e=n.value);return e}};EJ.create=t=\u003enew EJ({checks:[],typeName:aa.ZodBigInt,coerce:t?.coerce??!1,...SA(t)});var BJ=class extends JA{_parse(t){if(this._def.coerce\u0026\u0026(t.data=!!t.data),this._getType(t)!==xr.boolean){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.boolean,received:e.parsedType}),ea}return Dy(t.data)}};BJ.create=t=\u003enew BJ({typeName:aa.ZodBoolean,coerce:t?.coerce||!1,...SA(t)});var bJ=class A5n extends JA{_parse(e){if(this._def.coerce\u0026\u0026(e.data=new Date(e.data)),this._getType(e)!==xr.date){const i=this._getOrReturnCtx(e);return nr(i,{code:hi.invalid_type,expected:xr.date,received:i.parsedType}),ea}if(Number.isNaN(e.data.getTime()))return nr(this._getOrReturnCtx(e),{code:hi.invalid_date}),ea;const n=new Cx;let o;for(const i of this._def.checks)i.kind===\"min\"?e.data.getTime()\u003ci.value\u0026\u0026(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:\"date\"}),n.dirty()):i.kind===\"max\"?e.data.getTime()\u003ei.value\u0026\u0026(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:\"date\"}),n.dirty()):Cl.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new A5n({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:\"min\",value:e.getTime(),message:rs.toString(n)})}max(e,n){return this._addCheck({kind:\"max\",value:e.getTime(),message:rs.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind===\"min\"\u0026\u0026(e===null||n.value\u003ee)\u0026\u0026(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind===\"max\"\u0026\u0026(e===null||n.value\u003ce)\u0026\u0026(e=n.value);return e!=null?new Date(e):null}};bJ.create=t=\u003enew bJ({checks:[],coerce:t?.coerce||!1,typeName:aa.ZodDate,...SA(t)});var $ae=class extends JA{_parse(t){if(this._getType(t)!==xr.symbol){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.symbol,received:e.parsedType}),ea}return Dy(t.data)}};$ae.create=t=\u003enew $ae({typeName:aa.ZodSymbol,...SA(t)});var SJ=class extends JA{_parse(t){if(this._getType(t)!==xr.undefined){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.undefined,received:e.parsedType}),ea}return Dy(t.data)}};SJ.create=t=\u003enew SJ({typeName:aa.ZodUndefined,...SA(t)});var QJ=class extends JA{_parse(t){if(this._getType(t)!==xr.null){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.null,received:e.parsedType}),ea}return Dy(t.data)}};QJ.create=t=\u003enew QJ({typeName:aa.ZodNull,...SA(t)});var bL=class extends JA{constructor(){super(...arguments),this._any=!0}_parse(t){return Dy(t.data)}};bL.create=t=\u003enew bL({typeName:aa.ZodAny,...SA(t)});var ZD=class extends JA{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Dy(t.data)}};ZD.create=t=\u003enew ZD({typeName:aa.ZodUnknown,...SA(t)});var eb=class extends JA{_parse(t){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.never,received:e.parsedType}),ea}};eb.create=t=\u003enew eb({typeName:aa.ZodNever,...SA(t)});var qae=class extends JA{_parse(t){if(this._getType(t)!==xr.undefined){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.void,received:e.parsedType}),ea}return Dy(t.data)}};qae.create=t=\u003enew qae({typeName:aa.ZodVoid,...SA(t)});var eN=class Vye extends JA{_parse(e){const{ctx:n,status:o}=this._processInputParams(e),i=this._def;if(n.parsedType!==xr.array)return nr(n,{code:hi.invalid_type,expected:xr.array,received:n.parsedType}),ea;if(i.exactLength!==null){const s=n.data.length\u003ei.exactLength.value,a=n.data.length\u003ci.exactLength.value;(s||a)\u0026\u0026(nr(n,{code:s?hi.too_big:hi.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:\"array\",inclusive:!0,exact:!0,message:i.exactLength.message}),o.dirty())}if(i.minLength!==null\u0026\u0026n.data.length\u003ci.minLength.value\u0026\u0026(nr(n,{code:hi.too_small,minimum:i.minLength.value,type:\"array\",inclusive:!0,exact:!1,message:i.minLength.message}),o.dirty()),i.maxLength!==null\u0026\u0026n.data.length\u003ei.maxLength.value\u0026\u0026(nr(n,{code:hi.too_big,maximum:i.maxLength.value,type:\"array\",inclusive:!0,exact:!1,message:i.maxLength.message}),o.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=\u003ei.type._parseAsync(new p7(n,s,n.path,a)))).then(s=\u003eCx.mergeArray(o,s));const r=[...n.data].map((s,a)=\u003ei.type._parseSync(new p7(n,s,n.path,a)));return Cx.mergeArray(o,r)}get element(){return this._def.type}min(e,n){return new Vye({...this._def,minLength:{value:e,message:rs.toString(n)}})}max(e,n){return new Vye({...this._def,maxLength:{value:e,message:rs.toString(n)}})}length(e,n){return new Vye({...this._def,exactLength:{value:e,message:rs.toString(n)}})}nonempty(e){return this.min(1,e)}};function SL(t){if(t instanceof H5){const e={};for(const n in t.shape){const o=t.shape[n];e[n]=m7.create(SL(o))}return new H5({...t._def,shape:()=\u003ee})}return t instanceof eN?new eN({...t._def,type:SL(t.element)}):t instanceof m7?m7.create(SL(t.unwrap())):t instanceof lv?lv.create(SL(t.unwrap())):t instanceof cv?cv.create(t.items.map(e=\u003eSL(e))):t}eN.create=(t,e)=\u003enew eN({type:t,minLength:null,maxLength:null,exactLength:null,typeName:aa.ZodArray,...SA(e)});var H5=class v9 extends JA{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Cl.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==xr.object){const A=this._getOrReturnCtx(e);return nr(A,{code:hi.invalid_type,expected:xr.object,received:A.parsedType}),ea}const{status:n,ctx:o}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),s=[];if(!(this._def.catchall instanceof eb\u0026\u0026this._def.unknownKeys===\"strip\"))for(const A in o.data)r.includes(A)||s.push(A);const a=[];for(const A of r){const c=i[A],l=o.data[A];a.push({key:{status:\"valid\",value:A},value:c._parse(new p7(o,l,o.path,A)),alwaysSet:A in o.data})}if(this._def.catchall instanceof eb){const A=this._def.unknownKeys;if(A===\"passthrough\")for(const c of s)a.push({key:{status:\"valid\",value:c},value:{status:\"valid\",value:o.data[c]}});else if(A===\"strict\")s.length\u003e0\u0026\u0026(nr(o,{code:hi.unrecognized_keys,keys:s}),n.dirty());else if(A!==\"strip\")throw new Error(\"Internal ZodObject error: invalid unknownKeys value.\")}else{const A=this._def.catchall;for(const c of s){const l=o.data[c];a.push({key:{status:\"valid\",value:c},value:A._parse(new p7(o,l,o.path,c)),alwaysSet:c in o.data})}}return o.common.async?Promise.resolve().then(async()=\u003e{const A=[];for(const c of a){const l=await c.key,u=await c.value;A.push({key:l,value:u,alwaysSet:c.alwaysSet})}return A}).then(A=\u003eCx.mergeObjectSync(n,A)):Cx.mergeObjectSync(n,a)}get shape(){return this._def.shape()}strict(e){return rs.errToObj,new v9({...this._def,unknownKeys:\"strict\",...e!==void 0?{errorMap:(n,o)=\u003e{const i=this._def.errorMap?.(n,o).message??o.defaultError;return n.code===\"unrecognized_keys\"?{message:rs.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new v9({...this._def,unknownKeys:\"strip\"})}passthrough(){return new v9({...this._def,unknownKeys:\"passthrough\"})}extend(e){return new v9({...this._def,shape:()=\u003e({...this._def.shape(),...e})})}merge(e){return new v9({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=\u003e({...this._def.shape(),...e._def.shape()}),typeName:aa.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new v9({...this._def,catchall:e})}pick(e){const n={};for(const o of Cl.objectKeys(e))e[o]\u0026\u0026this.shape[o]\u0026\u0026(n[o]=this.shape[o]);return new v9({...this._def,shape:()=\u003en})}omit(e){const n={};for(const o of Cl.objectKeys(this.shape))e[o]||(n[o]=this.shape[o]);return new v9({...this._def,shape:()=\u003en})}deepPartial(){return SL(this)}partial(e){const n={};for(const o of Cl.objectKeys(this.shape)){const i=this.shape[o];e\u0026\u0026!e[o]?n[o]=i:n[o]=i.optional()}return new v9({...this._def,shape:()=\u003en})}required(e){const n={};for(const o of Cl.objectKeys(this.shape))if(e\u0026\u0026!e[o])n[o]=this.shape[o];else{let i=this.shape[o];for(;i instanceof m7;)i=i._def.innerType;n[o]=i}return new v9({...this._def,shape:()=\u003en})}keyof(){return JCt(Cl.objectKeys(this.shape))}};H5.create=(t,e)=\u003enew H5({shape:()=\u003et,unknownKeys:\"strip\",catchall:eb.create(),typeName:aa.ZodObject,...SA(e)}),H5.strictCreate=(t,e)=\u003enew H5({shape:()=\u003et,unknownKeys:\"strict\",catchall:eb.create(),typeName:aa.ZodObject,...SA(e)}),H5.lazycreate=(t,e)=\u003enew H5({shape:t,unknownKeys:\"strip\",catchall:eb.create(),typeName:aa.ZodObject,...SA(e)});var vJ=class extends JA{_parse(t){const{ctx:e}=this._processInputParams(t),n=this._def.options;if(e.common.async)return Promise.all(n.map(async o=\u003e{const i={...e,common:{...e.common,issues:[]},parent:null};return{result:await o._parseAsync({data:e.data,path:e.path,parent:i}),ctx:i}})).then(function(o){for(const r of o)if(r.result.status===\"valid\")return r.result;for(const r of o)if(r.result.status===\"dirty\")return e.common.issues.push(...r.ctx.common.issues),r.result;const i=o.map(r=\u003enew iB(r.ctx.common.issues));return nr(e,{code:hi.invalid_union,unionErrors:i}),ea});{let o;const i=[];for(const s of n){const a={...e,common:{...e.common,issues:[]},parent:null},A=s._parseSync({data:e.data,path:e.path,parent:a});if(A.status===\"valid\")return A;A.status!==\"dirty\"||o||(o={result:A,ctx:a}),a.common.issues.length\u0026\u0026i.push(a.common.issues)}if(o)return e.common.issues.push(...o.ctx.common.issues),o.result;const r=i.map(s=\u003enew iB(s));return nr(e,{code:hi.invalid_union,unionErrors:r}),ea}}get options(){return this._def.options}};vJ.create=(t,e)=\u003enew vJ({options:t,typeName:aa.ZodUnion,...SA(e)});var Av=t=\u003et instanceof PJ?Av(t.schema):t instanceof rB?Av(t.innerType()):t instanceof MJ?[t.value]:t instanceof DJ?t.options:t instanceof NJ?Cl.objectValues(t.enum):t instanceof RJ?Av(t._def.innerType):t instanceof SJ?[void 0]:t instanceof QJ?[null]:t instanceof m7?[void 0,...Av(t.unwrap())]:t instanceof lv?[null,...Av(t.unwrap())]:t instanceof _8e||t instanceof kJ?Av(t.unwrap()):t instanceof TJ?Av(t._def.innerType):[],KCt=class c5n extends JA{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==xr.object)return nr(n,{code:hi.invalid_type,expected:xr.object,received:n.parsedType}),ea;const o=this.discriminator,i=n.data[o],r=this.optionsMap.get(i);return r?n.common.async?r._parseAsync({data:n.data,path:n.path,parent:n}):r._parseSync({data:n.data,path:n.path,parent:n}):(nr(n,{code:hi.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),ea)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,o){const i=new Map;for(const r of n){const s=Av(r.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \\`${e}\\` could not be extracted from all schema options`);for(const a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,r)}}return new c5n({typeName:aa.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...SA(o)})}};function m8e(t,e){const n=Z8(t),o=Z8(e);if(t===e)return{valid:!0,data:t};if(n===xr.object\u0026\u0026o===xr.object){const i=Cl.objectKeys(e),r=Cl.objectKeys(t).filter(a=\u003ei.indexOf(a)!==-1),s={...t,...e};for(const a of r){const A=m8e(t[a],e[a]);if(!A.valid)return{valid:!1};s[a]=A.data}return{valid:!0,data:s}}if(n===xr.array\u0026\u0026o===xr.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let r=0;r\u003ct.length;r++){const s=m8e(t[r],e[r]);if(!s.valid)return{valid:!1};i.push(s.data)}return{valid:!0,data:i}}return n===xr.date\u0026\u0026o===xr.date\u0026\u0026+t==+e?{valid:!0,data:t}:{valid:!1}}var wJ=class extends JA{_parse(t){const{status:e,ctx:n}=this._processInputParams(t),o=(i,r)=\u003e{if(d8e(i)||d8e(r))return ea;const s=m8e(i.value,r.value);return s.valid?((h8e(i)||h8e(r))\u0026\u0026e.dirty(),{status:e.value,value:s.data}):(nr(n,{code:hi.invalid_intersection_types}),ea)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,r])=\u003eo(i,r)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};wJ.create=(t,e,n)=\u003enew wJ({left:t,right:e,typeName:aa.ZodIntersection,...SA(n)});var cv=class l5n extends JA{_parse(e){const{status:n,ctx:o}=this._processInputParams(e);if(o.parsedType!==xr.array)return nr(o,{code:hi.invalid_type,expected:xr.array,received:o.parsedType}),ea;if(o.data.length\u003cthis._def.items.length)return nr(o,{code:hi.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:\"array\"}),ea;!this._def.rest\u0026\u0026o.data.length\u003ethis._def.items.length\u0026\u0026(nr(o,{code:hi.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:\"array\"}),n.dirty());const i=[...o.data].map((r,s)=\u003e{const a=this._def.items[s]||this._def.rest;return a?a._parse(new p7(o,r,o.path,s)):null}).filter(r=\u003e!!r);return o.common.async?Promise.all(i).then(r=\u003eCx.mergeArray(n,r)):Cx.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new l5n({...this._def,rest:e})}};cv.create=(t,e)=\u003e{if(!Array.isArray(t))throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");return new cv({items:t,typeName:aa.ZodTuple,rest:null,...SA(e)})};var VCt=class u5n extends JA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:o}=this._processInputParams(e);if(o.parsedType!==xr.object)return nr(o,{code:hi.invalid_type,expected:xr.object,received:o.parsedType}),ea;const i=[],r=this._def.keyType,s=this._def.valueType;for(const a in o.data)i.push({key:r._parse(new p7(o,a,o.path,a)),value:s._parse(new p7(o,o.data[a],o.path,a)),alwaysSet:a in o.data});return o.common.async?Cx.mergeObjectAsync(n,i):Cx.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,o){return new u5n(n instanceof JA?{keyType:e,valueType:n,typeName:aa.ZodRecord,...SA(o)}:{keyType:BL.create(),valueType:e,typeName:aa.ZodRecord,...SA(n)})}},Xae=class extends JA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:n}=this._processInputParams(t);if(n.parsedType!==xr.map)return nr(n,{code:hi.invalid_type,expected:xr.map,received:n.parsedType}),ea;const o=this._def.keyType,i=this._def.valueType,r=[...n.data.entries()].map(([s,a],A)=\u003e({key:o._parse(new p7(n,s,n.path,[A,\"key\"])),value:i._parse(new p7(n,a,n.path,[A,\"value\"]))}));if(n.common.async){const s=new Map;return Promise.resolve().then(async()=\u003e{for(const a of r){const A=await a.key,c=await a.value;if(A.status===\"aborted\"||c.status===\"aborted\")return ea;A.status!==\"dirty\"\u0026\u0026c.status!==\"dirty\"||e.dirty(),s.set(A.value,c.value)}return{status:e.value,value:s}})}{const s=new Map;for(const a of r){const A=a.key,c=a.value;if(A.status===\"aborted\"||c.status===\"aborted\")return ea;A.status!==\"dirty\"\u0026\u0026c.status!==\"dirty\"||e.dirty(),s.set(A.value,c.value)}return{status:e.value,value:s}}}};Xae.create=(t,e,n)=\u003enew Xae({valueType:e,keyType:t,typeName:aa.ZodMap,...SA(n)});var Zae=class mit extends JA{_parse(e){const{status:n,ctx:o}=this._processInputParams(e);if(o.parsedType!==xr.set)return nr(o,{code:hi.invalid_type,expected:xr.set,received:o.parsedType}),ea;const i=this._def;i.minSize!==null\u0026\u0026o.data.size\u003ci.minSize.value\u0026\u0026(nr(o,{code:hi.too_small,minimum:i.minSize.value,type:\"set\",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null\u0026\u0026o.data.size\u003ei.maxSize.value\u0026\u0026(nr(o,{code:hi.too_big,maximum:i.maxSize.value,type:\"set\",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const r=this._def.valueType;function s(A){const c=new Set;for(const l of A){if(l.status===\"aborted\")return ea;l.status===\"dirty\"\u0026\u0026n.dirty(),c.add(l.value)}return{status:n.value,value:c}}const a=[...o.data.values()].map((A,c)=\u003er._parse(new p7(o,A,o.path,c)));return o.common.async?Promise.all(a).then(A=\u003es(A)):s(a)}min(e,n){return new mit({...this._def,minSize:{value:e,message:rs.toString(n)}})}max(e,n){return new mit({...this._def,maxSize:{value:e,message:rs.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Zae.create=(t,e)=\u003enew Zae({valueType:t,minSize:null,maxSize:null,typeName:aa.ZodSet,...SA(e)});var zCt=class zye extends JA{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==xr.function)return nr(n,{code:hi.invalid_type,expected:xr.function,received:n.parsedType}),ea;function o(a,A){return Wae({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Jae(),EL].filter(c=\u003e!!c),issueData:{code:hi.invalid_arguments,argumentsError:A}})}function i(a,A){return Wae({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Jae(),EL].filter(c=\u003e!!c),issueData:{code:hi.invalid_return_type,returnTypeError:A}})}const r={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof QL){const a=this;return Dy(async function(...A){const c=new iB([]),l=await a._def.args.parseAsync(A,r).catch(g=\u003e{throw c.addIssue(o(A,g)),c}),u=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(u,r).catch(g=\u003e{throw c.addIssue(i(u,g)),c})})}{const a=this;return Dy(function(...A){const c=a._def.args.safeParse(A,r);if(!c.success)throw new iB([o(A,c.error)]);const l=Reflect.apply(s,this,c.data),u=a._def.returns.safeParse(l,r);if(!u.success)throw new iB([i(l,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new zye({...this._def,args:cv.create(e).rest(ZD.create())})}returns(e){return new zye({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,o){return new zye({args:e||cv.create([]).rest(ZD.create()),returns:n||ZD.create(),typeName:aa.ZodFunction,...SA(o)})}},PJ=class extends JA{get schema(){return this._def.getter()}_parse(t){const{ctx:e}=this._processInputParams(t);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}};PJ.create=(t,e)=\u003enew PJ({getter:t,typeName:aa.ZodLazy,...SA(e)});var MJ=class extends JA{_parse(t){if(t.data!==this._def.value){const e=this._getOrReturnCtx(t);return nr(e,{received:e.data,code:hi.invalid_literal,expected:this._def.value}),ea}return{status:\"valid\",value:t.data}}get value(){return this._def.value}};function JCt(t,e){return new DJ({values:t,typeName:aa.ZodEnum,...SA(e)})}MJ.create=(t,e)=\u003enew MJ({value:t,typeName:aa.ZodLiteral,...SA(e)});var DJ=class _it extends JA{_parse(e){if(typeof e.data!=\"string\"){const n=this._getOrReturnCtx(e),o=this._def.values;return nr(n,{expected:Cl.joinValues(o),received:n.parsedType,code:hi.invalid_type}),ea}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),o=this._def.values;return nr(n,{received:n.data,code:hi.invalid_enum_value,options:o}),ea}return Dy(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return _it.create(e,{...this._def,...n})}exclude(e,n=this._def){return _it.create(this.options.filter(o=\u003e!e.includes(o)),{...this._def,...n})}};DJ.create=JCt;var NJ=class extends JA{_parse(t){const e=Cl.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==xr.string\u0026\u0026n.parsedType!==xr.number){const o=Cl.objectValues(e);return nr(n,{expected:Cl.joinValues(o),received:n.parsedType,code:hi.invalid_type}),ea}if(this._cache||(this._cache=new Set(Cl.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Cl.objectValues(e);return nr(n,{received:n.data,code:hi.invalid_enum_value,options:o}),ea}return Dy(t.data)}get enum(){return this._def.values}};NJ.create=(t,e)=\u003enew NJ({values:t,typeName:aa.ZodNativeEnum,...SA(e)});var QL=class extends JA{unwrap(){return this._def.type}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==xr.promise\u0026\u0026e.common.async===!1)return nr(e,{code:hi.invalid_type,expected:xr.promise,received:e.parsedType}),ea;const n=e.parsedType===xr.promise?e.data:Promise.resolve(e.data);return Dy(n.then(o=\u003ethis._def.type.parseAsync(o,{path:e.path,errorMap:e.common.contextualErrorMap})))}};QL.create=(t,e)=\u003enew QL({type:t,typeName:aa.ZodPromise,...SA(e)});var rB=class extends JA{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===aa.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:e,ctx:n}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:r=\u003e{nr(n,r),r.fatal?e.abort():e.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type===\"preprocess\"){const r=o.transform(n.data,i);if(n.common.async)return Promise.resolve(r).then(async s=\u003e{if(e.value===\"aborted\")return ea;const a=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return a.status===\"aborted\"?ea:a.status===\"dirty\"||e.value===\"dirty\"?jae(a.value):a});{if(e.value===\"aborted\")return ea;const s=this._def.schema._parseSync({data:r,path:n.path,parent:n});return s.status===\"aborted\"?ea:s.status===\"dirty\"||e.value===\"dirty\"?jae(s.value):s}}if(o.type===\"refinement\"){const r=s=\u003e{const a=o.refinement(s,i);if(n.common.async)return Promise.resolve(a);if(a instanceof Promise)throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");return s};if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status===\"aborted\"?ea:(s.status===\"dirty\"\u0026\u0026e.dirty(),r(s.value),{status:e.value,value:s.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=\u003es.status===\"aborted\"?ea:(s.status===\"dirty\"\u0026\u0026e.dirty(),r(s.value).then(()=\u003e({status:e.value,value:s.value}))))}if(o.type===\"transform\"){if(n.common.async===!1){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!XD(r))return ea;const s=o.transform(r.value,i);if(s instanceof Promise)throw new Error(\"Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.\");return{status:e.value,value:s}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(r=\u003eXD(r)?Promise.resolve(o.transform(r.value,i)).then(s=\u003e({status:e.value,value:s})):ea)}Cl.assertNever(o)}};rB.create=(t,e,n)=\u003enew rB({schema:t,typeName:aa.ZodEffects,effect:e,...SA(n)}),rB.createWithPreprocess=(t,e,n)=\u003enew rB({schema:e,effect:{type:\"preprocess\",transform:t},typeName:aa.ZodEffects,...SA(n)});var m7=class extends JA{_parse(t){return this._getType(t)===xr.undefined?Dy(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};m7.create=(t,e)=\u003enew m7({innerType:t,typeName:aa.ZodOptional,...SA(e)});var lv=class extends JA{_parse(t){return this._getType(t)===xr.null?Dy(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};lv.create=(t,e)=\u003enew lv({innerType:t,typeName:aa.ZodNullable,...SA(e)});var RJ=class extends JA{_parse(t){const{ctx:e}=this._processInputParams(t);let n=e.data;return e.parsedType===xr.undefined\u0026\u0026(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:e.path,parent:e})}removeDefault(){return this._def.innerType}};RJ.create=(t,e)=\u003enew RJ({innerType:t,typeName:aa.ZodDefault,defaultValue:typeof e.default==\"function\"?e.default:()=\u003ee.default,...SA(e)});var TJ=class extends JA{_parse(e){const{ctx:n}=this._processInputParams(e),o={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});return yJ(i)?i.then(r=\u003e({status:\"valid\",value:r.status===\"valid\"?r.value:this._def.catchValue({get error(){return new iB(o.common.issues)},input:o.data})})):{status:\"valid\",value:i.status===\"valid\"?i.value:this._def.catchValue({get error(){return new iB(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}};TJ.create=(t,e)=\u003enew TJ({innerType:t,typeName:aa.ZodCatch,catchValue:typeof e.catch==\"function\"?e.catch:()=\u003ee.catch,...SA(e)});var eAe=class extends JA{_parse(e){if(this._getType(e)!==xr.nan){const n=this._getOrReturnCtx(e);return nr(n,{code:hi.invalid_type,expected:xr.nan,received:n.parsedType}),ea}return{status:\"valid\",value:e.data}}};eAe.create=t=\u003enew eAe({typeName:aa.ZodNaN,...SA(t)});var Doo=Symbol(\"zod_brand\"),_8e=class extends JA{_parse(e){const{ctx:n}=this._processInputParams(e),o=n.data;return this._def.type._parse({data:o,path:n.path,parent:n})}unwrap(){return this._def.type}},f8e=class g5n extends JA{_parse(e){const{status:n,ctx:o}=this._processInputParams(e);if(o.common.async)return(async()=\u003e{const i=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});return i.status===\"aborted\"?ea:i.status===\"dirty\"?(n.dirty(),jae(i.value)):this._def.out._parseAsync({data:i.value,path:o.path,parent:o})})();{const i=this._def.in._parseSync({data:o.data,path:o.path,parent:o});return i.status===\"aborted\"?ea:i.status===\"dirty\"?(n.dirty(),{status:\"dirty\",value:i.value}):this._def.out._parseSync({data:i.value,path:o.path,parent:o})}}static create(e,n){return new g5n({in:e,out:n,typeName:aa.ZodPipeline})}},kJ=class extends JA{_parse(e){const n=this._def.innerType._parse(e),o=i=\u003e(XD(i)\u0026\u0026(i.value=Object.freeze(i.value)),i);return yJ(n)?n.then(i=\u003eo(i)):o(n)}unwrap(){return this._def.innerType}};function WCt(t,e){const n=typeof t==\"function\"?t(e):typeof t==\"string\"?{message:t}:t;return typeof n==\"string\"?{message:n}:n}function jCt(t,e={},n){return t?bL.create().superRefine((o,i)=\u003e{const r=t(o);if(r instanceof Promise)return r.then(s=\u003e{if(!s){const a=WCt(e,o),A=a.fatal??n??!0;i.addIssue({code:\"custom\",...a,fatal:A})}});if(!r){const s=WCt(e,o),a=s.fatal??n??!0;i.addIssue({code:\"custom\",...s,fatal:a})}}):bL.create()}kJ.create=(t,e)=\u003enew kJ({innerType:t,typeName:aa.ZodReadonly,...SA(e)});var aa,Yc,Noo={object:H5.lazycreate};(Yc=aa||(aa={})).ZodString=\"ZodString\",Yc.ZodNumber=\"ZodNumber\",Yc.ZodNaN=\"ZodNaN\",Yc.ZodBigInt=\"ZodBigInt\",Yc.ZodBoolean=\"ZodBoolean\",Yc.ZodDate=\"ZodDate\",Yc.ZodSymbol=\"ZodSymbol\",Yc.ZodUndefined=\"ZodUndefined\",Yc.ZodNull=\"ZodNull\",Yc.ZodAny=\"ZodAny\",Yc.ZodUnknown=\"ZodUnknown\",Yc.ZodNever=\"ZodNever\",Yc.ZodVoid=\"ZodVoid\",Yc.ZodArray=\"ZodArray\",Yc.ZodObject=\"ZodObject\",Yc.ZodUnion=\"ZodUnion\",Yc.ZodDiscriminatedUnion=\"ZodDiscriminatedUnion\",Yc.ZodIntersection=\"ZodIntersection\",Yc.ZodTuple=\"ZodTuple\",Yc.ZodRecord=\"ZodRecord\",Yc.ZodMap=\"ZodMap\",Yc.ZodSet=\"ZodSet\",Yc.ZodFunction=\"ZodFunction\",Yc.ZodLazy=\"ZodLazy\",Yc.ZodLiteral=\"ZodLiteral\",Yc.ZodEnum=\"ZodEnum\",Yc.ZodEffects=\"ZodEffects\",Yc.ZodNativeEnum=\"ZodNativeEnum\",Yc.ZodOptional=\"ZodOptional\",Yc.ZodNullable=\"ZodNullable\",Yc.ZodDefault=\"ZodDefault\",Yc.ZodCatch=\"ZodCatch\",Yc.ZodPromise=\"ZodPromise\",Yc.ZodBranded=\"ZodBranded\",Yc.ZodPipeline=\"ZodPipeline\",Yc.ZodReadonly=\"ZodReadonly\";var Roo=(t,e={message:`Input not instance of ${t.name}`})=\u003ejCt(n=\u003en instanceof t,e),$Ct=BL.create,qCt=xJ.create,Too=eAe.create,koo=EJ.create,XCt=BJ.create,Foo=bJ.create,Loo=$ae.create,Hoo=SJ.create,Ooo=QJ.create,Goo=bL.create,Yoo=ZD.create,Uoo=eb.create,Koo=qae.create,Voo=eN.create,zoo=H5.create,Joo=H5.strictCreate,Woo=vJ.create,joo=KCt.create,$oo=wJ.create,qoo=cv.create,Xoo=VCt.create,Zoo=Xae.create,eio=Zae.create,tio=zCt.create,nio=PJ.create,oio=MJ.create,iio=DJ.create,rio=NJ.create,sio=QL.create,ZCt=rB.create,aio=m7.create,Aio=lv.create,cio=rB.createWithPreprocess,lio=f8e.create,uio=()=\u003e$Ct().optional(),gio=()=\u003eqCt().optional(),dio=()=\u003eXCt().optional(),hio={string:t=\u003eBL.create({...t,coerce:!0}),number:t=\u003exJ.create({...t,coerce:!0}),boolean:t=\u003eBJ.create({...t,coerce:!0}),bigint:t=\u003eEJ.create({...t,coerce:!0}),date:t=\u003ebJ.create({...t,coerce:!0})},pio=ea,tAe=N.string().or(N.number()).transform(t=\u003eL5(t,\"Ω\").value),I8e=N.string().or(N.number()).transform(t=\u003eL5(t,\"F\").value).transform(t=\u003eNumber.parseFloat(t.toPrecision(12))),eyt=N.string().or(N.number()).transform(t=\u003eL5(t,\"H\").value),tb=N.string().or(N.number()).transform(t=\u003eL5(t,\"V\").value),Di=N.string().or(N.number()).transform(t=\u003eL5(t).value),tN=N.string().or(N.number()).transform(t=\u003eL5(t,\"Hz\").value),ao=Di,vL=N.string().or(N.number()).transform(t=\u003eL5(t,\"A\").value),wL=N.string().or(N.number()).transform(t=\u003eL5(t).value),mio=wL,J_=wL,tyt=N.string().datetime(),im=N.string().or(N.number()).transform(t=\u003etypeof t==\"number\"?t:t.endsWith(\"deg\")?Number.parseFloat(t.split(\"deg\")[0]):t.endsWith(\"rad\")?180*Number.parseFloat(t.split(\"rad\")[0])/Math.PI:Number.parseFloat(t)),nyt=N.number().or(N.string().endsWith(\"mAh\")).transform(t=\u003e{if(typeof t==\"string\"){const e=t.replace(\"mAh\",\"\"),n=Number.parseFloat(e);if(Number.isNaN(n))throw new Error(\"Invalid capacity\");return n}return t}).describe(\"Battery capacity in mAh\"),_r=N.object({x:ao,y:ao}),_io=_r,nb=N.object({x:ao,y:ao,z:ao}),fio=nb,C8e=N.object({width:N.number(),height:N.number()}),So=t=\u003eN.string().optional().default(()=\u003e`${t}_${(e=\u003e{const n=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";return Array.from({length:e},()=\u003en[Math.floor(62*Math.random())]).join(\"\")})(10)}`),ob=N.enum([\"top_left\",\"top_center\",\"top_right\",\"center_left\",\"center\",\"center_right\",\"bottom_left\",\"bottom_center\",\"bottom_right\"]),Iio=N.enum([\"top_silkscreen\",\"bottom_silkscreen\",\"top_copper\",\"bottom_copper\",\"top_soldermask\",\"bottom_soldermask\",\"top_fabrication_note\",\"bottom_fabrication_note\",\"top_user_note\",\"bottom_user_note\",\"top_courtyard\",\"bottom_courtyard\",\"inner1_copper\",\"inner2_copper\",\"inner3_copper\",\"inner4_copper\",\"inner5_copper\",\"inner6_copper\",\"inner7_copper\",\"inner8_copper\",\"edge_cuts\",\"drill\"]),y8e=N.object({project_relative_path:N.string(),url:N.string(),mimetype:N.string()}),nAe=_r.extend({rotation:im.optional()}),x8e=N.object({size:_r.optional(),thickness:ao.optional()}),oyt=N.object({font:x8e.optional()}),FJ=N.object({value:N.string(),at:nAe.optional(),layer:N.string().optional(),uuid:N.string().optional(),hide:N.boolean().optional(),effects:oyt.optional()}),iyt=N.object({Reference:FJ.optional(),Value:FJ.optional(),Datasheet:FJ.optional(),Description:FJ.optional()}),ryt=N.object({through_hole:N.boolean().optional(),smd:N.boolean().optional(),exclude_from_pos_files:N.boolean().optional(),exclude_from_bom:N.boolean().optional()}),syt=N.object({name:N.string(),type:N.string(),shape:N.string().optional(),at:nAe.optional(),size:_r.optional(),drill:ao.optional(),layers:N.array(N.string()).optional(),removeUnusedLayers:N.boolean().optional(),uuid:N.string().optional()}),ayt=N.object({path:N.string(),offset:nb.optional(),scale:nb.optional(),rotate:nb.optional()}),Ayt=N.object({footprintName:N.string().optional(),version:N.union([N.number(),N.string()]).optional(),generator:N.string().optional(),generatorVersion:N.union([N.number(),N.string()]).optional(),layer:N.string().optional(),properties:iyt.optional(),attributes:ryt.optional(),pads:N.array(syt).optional(),embeddedFonts:N.boolean().optional(),model:ayt.optional()}),cyt=N.object({hide:N.boolean().optional()}),lyt=N.object({offset:ao.optional(),hide:N.boolean().optional()}),uyt=N.object({font:x8e.optional(),justify:N.union([N.string(),N.array(N.string())]).optional(),hide:N.boolean().optional()}),uv=N.object({value:N.string(),id:N.union([N.number(),N.string()]).optional(),at:nAe.optional(),effects:uyt.optional()}),gyt=N.object({Reference:uv.optional(),Value:uv.optional(),Footprint:uv.optional(),Datasheet:uv.optional(),Description:uv.optional(),ki_keywords:uv.optional(),ki_fp_filters:uv.optional()}),dyt=N.object({symbolName:N.string().optional(),extends:N.string().optional(),pinNumbers:cyt.optional(),pinNames:lyt.optional(),excludeFromSim:N.boolean().optional(),inBom:N.boolean().optional(),onBoard:N.boolean().optional(),properties:gyt.optional(),embeddedFonts:N.boolean().optional()}),Wl=N.object({error_type:N.string(),message:N.string(),is_fatal:N.boolean().optional()}),oAe=N.enum([\"jlcpcb\",\"macrofab\",\"pcbway\",\"digikey\",\"mouser\",\"lcsc\"]),vu=N.object({type:N.literal(\"source_component\"),ftype:N.string().optional(),source_component_id:N.string(),name:N.string(),manufacturer_part_number:N.string().optional(),supplier_part_numbers:N.record(oAe,N.array(N.string())).optional(),display_value:N.string().optional(),display_name:N.string().optional(),are_pins_interchangeable:N.boolean().optional(),internally_connected_source_port_ids:N.array(N.array(N.string())).optional(),source_group_id:N.string().optional(),subcircuit_id:N.string().optional()}),E8e=vu.extend({ftype:N.literal(\"simple_capacitor\"),capacitance:I8e,max_voltage_rating:tb.optional(),display_capacitance:N.string().optional(),max_decoupling_trace_length:ao.optional()}),B8e=vu.extend({ftype:N.literal(\"simple_resistor\"),resistance:tAe,display_resistance:N.string().optional()}),iAe=vu.extend({ftype:N.literal(\"simple_diode\")}),hyt=vu.extend({ftype:N.literal(\"simple_fiducial\")}),b8e=iAe.extend({ftype:N.literal(\"simple_led\"),color:N.string().optional(),wavelength:N.string().optional()}),pyt=vu.extend({ftype:N.literal(\"simple_ground\")}),S8e=vu.extend({ftype:N.literal(\"simple_chip\")}),Q8e=vu.extend({ftype:N.literal(\"simple_power_source\"),voltage:tb}),myt=vu.extend({ftype:N.literal(\"simple_current_source\"),current:vL,frequency:tN.optional(),peak_to_peak_current:vL.optional(),wave_shape:N.enum([\"sine\",\"square\",\"triangle\",\"sawtooth\",\"dc\"]).optional().default(\"dc\"),phase:N.number().optional(),duty_cycle:N.number().min(0).max(1).optional()}),_yt=vu.extend({ftype:N.literal(\"simple_fuse\"),current_rating_amps:N.number().describe(\"Nominal current in amps the fuse is rated for\"),voltage_rating_volts:N.number().describe(\"Voltage rating in volts, e.g. ±5V would be 5\")}),fyt=vu.extend({ftype:N.literal(\"simple_ammeter\")}),Iyt=N.object({must_be_connected:N.boolean().optional(),provides_power:N.boolean().optional(),requires_power:N.boolean().optional(),provides_ground:N.boolean().optional(),requires_ground:N.boolean().optional(),provides_voltage:N.union([N.string(),N.number()]).optional(),requires_voltage:N.union([N.string(),N.number()]).optional(),do_not_connect:N.boolean().optional(),include_in_board_pinout:N.boolean().optional(),can_use_internal_pullup:N.boolean().optional(),is_using_internal_pullup:N.boolean().optional(),needs_external_pullup:N.boolean().optional(),can_use_internal_pulldown:N.boolean().optional(),is_using_internal_pulldown:N.boolean().optional(),needs_external_pulldown:N.boolean().optional(),can_use_open_drain:N.boolean().optional(),is_using_open_drain:N.boolean().optional(),can_use_push_pull:N.boolean().optional(),is_using_push_pull:N.boolean().optional(),should_have_decoupling_capacitor:N.boolean().optional(),recommended_decoupling_capacitor_capacitance:N.union([N.string(),N.number()]).optional(),is_configured_for_i2c_sda:N.boolean().optional(),is_configured_for_i2c_scl:N.boolean().optional(),is_configured_for_spi_mosi:N.boolean().optional(),is_configured_for_spi_miso:N.boolean().optional(),is_configured_for_spi_sck:N.boolean().optional(),is_configured_for_spi_cs:N.boolean().optional(),is_configured_for_uart_tx:N.boolean().optional(),is_configured_for_uart_rx:N.boolean().optional(),supports_i2c_sda:N.boolean().optional(),supports_i2c_scl:N.boolean().optional(),supports_spi_mosi:N.boolean().optional(),supports_spi_miso:N.boolean().optional(),supports_spi_sck:N.boolean().optional(),supports_spi_cs:N.boolean().optional(),supports_uart_tx:N.boolean().optional(),supports_uart_rx:N.boolean().optional()}),v8e=vu.extend({ftype:N.literal(\"simple_battery\"),capacity:nyt}),w8e=vu.extend({ftype:N.literal(\"simple_inductor\"),inductance:eyt,display_inductance:N.string().optional(),max_current_rating:N.number().optional()}),P8e=vu.extend({ftype:N.literal(\"simple_push_button\")}),M8e=vu.extend({ftype:N.literal(\"simple_potentiometer\"),max_resistance:tAe,display_max_resistance:N.string().optional()}),Cyt=vu.extend({ftype:N.literal(\"simple_crystal\"),frequency:N.number().describe(\"Frequency in Hz\"),load_capacitance:N.number().optional().describe(\"Load capacitance in pF\"),pin_variant:N.enum([\"two_pin\",\"four_pin\"]).optional()}),D8e=vu.extend({ftype:N.literal(\"simple_pin_header\"),pin_count:N.number(),gender:N.enum([\"male\",\"female\"]).optional().default(\"male\")}),yyt=vu.extend({ftype:N.literal(\"simple_connector\"),standard:N.enum([\"usb_c\",\"m2\"]).optional()}),N8e=vu.extend({ftype:N.literal(\"simple_pinout\")}),R8e=vu.extend({ftype:N.literal(\"simple_resonator\"),load_capacitance:I8e,equivalent_series_resistance:tAe.optional(),frequency:tN}),T8e=vu.extend({ftype:N.literal(\"simple_transistor\"),transistor_type:N.enum([\"npn\",\"pnp\"])}),k8e=vu.extend({ftype:N.literal(\"simple_test_point\"),footprint_variant:N.enum([\"pad\",\"through_hole\"]).optional(),pad_shape:N.enum([\"rect\",\"circle\"]).optional(),pad_diameter:N.union([N.number(),N.string()]).optional(),hole_diameter:N.union([N.number(),N.string()]).optional(),width:N.union([N.number(),N.string()]).optional(),height:N.union([N.number(),N.string()]).optional()}),F8e=vu.extend({ftype:N.literal(\"simple_mosfet\"),channel_type:N.enum([\"n\",\"p\"]),mosfet_mode:N.enum([\"enhancement\",\"depletion\"])}),L8e=vu.extend({ftype:N.literal(\"simple_op_amp\")}),H8e=vu.extend({ftype:N.literal(\"simple_switch\")}),O8e=N.object({type:N.literal(\"source_project_metadata\"),name:N.string().optional(),software_used_string:N.string().optional(),project_url:N.string().optional(),source_filesystem_md5_hash:N.string().optional(),created_at:tyt.optional()}),xyt=Wl.extend({type:N.literal(\"source_missing_property_error\"),source_missing_property_error_id:So(\"source_missing_property_error\"),source_component_id:N.string(),property_name:N.string(),subcircuit_id:N.string().optional(),error_type:N.literal(\"source_missing_property_error\").default(\"source_missing_property_error\")}).describe(\"The source code is missing a property\"),Eyt=Wl.extend({type:N.literal(\"source_failed_to_create_component_error\"),source_failed_to_create_component_error_id:So(\"source_failed_to_create_component_error\"),error_type:N.literal(\"source_failed_to_create_component_error\").default(\"source_failed_to_create_component_error\"),component_name:N.string().optional(),subcircuit_id:N.string().optional(),parent_source_component_id:N.string().optional(),pcb_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),schematic_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional()}).describe(\"Error emitted when a component fails to be constructed\"),G8e=Wl.extend({type:N.literal(\"source_invalid_component_property_error\"),source_invalid_component_property_error_id:So(\"source_invalid_component_property_error\"),source_component_id:N.string(),property_name:N.string(),property_value:N.unknown().optional(),expected_format:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal(\"source_invalid_component_property_error\").default(\"source_invalid_component_property_error\")}).describe(\"The source component property is invalid\"),Y8e=Wl.extend({type:N.literal(\"source_trace_not_connected_error\"),source_trace_not_connected_error_id:So(\"source_trace_not_connected_error\"),error_type:N.literal(\"source_trace_not_connected_error\").default(\"source_trace_not_connected_error\"),subcircuit_id:N.string().optional(),source_group_id:N.string().optional(),source_trace_id:N.string().optional(),connected_source_port_ids:N.array(N.string()).optional(),selectors_not_found:N.array(N.string()).optional()}).describe(\"Occurs when a source trace selector does not match any ports\"),Byt=N.object({type:N.literal(\"source_property_ignored_warning\"),source_property_ignored_warning_id:So(\"source_property_ignored_warning\"),source_component_id:N.string(),property_name:N.string(),subcircuit_id:N.string().optional(),error_type:N.literal(\"source_property_ignored_warning\").default(\"source_property_ignored_warning\"),message:N.string()}).describe(\"The source property was ignored\"),U8e=N.object({type:N.literal(\"source_pin_missing_trace_warning\"),source_pin_missing_trace_warning_id:So(\"source_pin_missing_trace_warning\"),warning_type:N.literal(\"source_pin_missing_trace_warning\").default(\"source_pin_missing_trace_warning\"),message:N.string(),source_component_id:N.string(),source_port_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a source component pin is missing a trace connection\"),K8e=N.object({type:N.literal(\"source_missing_manufacturer_part_number_warning\"),source_missing_manufacturer_part_number_warning_id:So(\"source_missing_manufacturer_part_number_warning\"),warning_type:N.literal(\"source_missing_manufacturer_part_number_warning\").default(\"source_missing_manufacturer_part_number_warning\"),message:N.string(),source_component_id:N.string(),standard:N.string(),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a standard connector is missing manufacturer part number\"),V8e=N.object({type:N.literal(\"source_refdes_convention_warning\"),source_refdes_convention_warning_id:So(\"source_refdes_convention_warning\"),warning_type:N.literal(\"source_refdes_convention_warning\").default(\"source_refdes_convention_warning\"),message:N.string(),source_component_id:N.string(),refdes:N.string(),source_component_ftype:N.string(),expected_prefixes:N.array(N.string()),actual_prefix:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a source component reference designator does not match the component type convention\"),byt=vu.extend({ftype:N.literal(\"simple_voltage_probe\")}),Syt=vu.extend({ftype:N.literal(\"interconnect\")}),z8e=Wl.extend({type:N.literal(\"source_i2c_misconfigured_error\"),source_i2c_misconfigured_error_id:So(\"source_i2c_misconfigured_error\"),error_type:N.literal(\"source_i2c_misconfigured_error\").default(\"source_i2c_misconfigured_error\"),source_port_ids:N.array(N.string())}).describe(\"Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net\"),J8e=Wl.extend({type:N.literal(\"source_component_misconfigured_error\"),source_component_misconfigured_error_id:So(\"source_component_misconfigured_error\"),error_type:N.literal(\"source_component_misconfigured_error\").default(\"source_component_misconfigured_error\"),source_component_ids:N.array(N.string()),source_port_ids:N.array(N.string()).optional()}).describe(\"Error emitted when one or more source components have an invalid or conflicting configuration\"),Qyt=vu.extend({ftype:N.literal(\"simple_voltage_source\"),voltage:tb,frequency:tN.optional(),peak_to_peak_voltage:tb.optional(),wave_shape:N.enum([\"sinewave\",\"square\",\"triangle\",\"sawtooth\"]).optional(),phase:im.optional(),duty_cycle:N.number().optional().describe(\"Duty cycle as a fraction (0 to 1)\"),pulse_delay:J_.optional(),rise_time:J_.optional(),fall_time:J_.optional(),pulse_width:J_.optional(),period:J_.optional()}),vyt=N.union([B8e,E8e,iAe,hyt,b8e,pyt,S8e,Q8e,myt,fyt,v8e,w8e,P8e,M8e,Cyt,D8e,yyt,N8e,R8e,H8e,T8e,k8e,F8e,L8e,_yt,byt,Syt,Qyt,O8e,xyt,G8e,Eyt,Y8e,Byt,U8e,K8e,V8e,z8e,J8e]),wyt=N.object({type:N.literal(\"source_port\"),pin_number:N.number().optional(),port_hints:N.array(N.string()).optional(),name:N.string(),source_port_id:N.string(),source_component_id:N.string().optional(),source_group_id:N.string().optional(),most_frequently_referenced_by_name:N.string().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}).merge(Iyt),Pyt=N.object({type:N.literal(\"source_component_internal_connection\"),source_component_internal_connection_id:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}),Myt=N.object({type:N.literal(\"source_trace\"),source_trace_id:N.string(),connected_source_port_ids:N.array(N.string()),connected_source_net_ids:N.array(N.string()),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),max_length:N.number().optional(),name:N.string().optional(),min_trace_thickness:N.number().optional(),display_name:N.string().optional()}),Dyt=N.object({type:N.literal(\"source_group\"),source_group_id:N.string(),subcircuit_id:N.string().optional(),parent_subcircuit_id:N.string().optional(),parent_source_group_id:N.string().optional(),is_subcircuit:N.boolean().optional(),show_as_schematic_box:N.boolean().optional(),name:N.string().optional(),was_automatically_named:N.boolean().optional()}),Nyt=N.object({type:N.literal(\"source_net\"),source_net_id:N.string(),name:N.string(),member_source_group_ids:N.array(N.string()),is_power:N.boolean().optional(),is_ground:N.boolean().optional(),is_digital_signal:N.boolean().optional(),is_analog_signal:N.boolean().optional(),is_positive_voltage_source:N.boolean().optional(),trace_width:N.number().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}),Ryt=N.object({type:N.literal(\"source_board\"),source_board_id:N.string(),source_group_id:N.string(),title:N.string().optional()}).describe(\"Defines a board in the source domain\"),Tyt=Wl.extend({type:N.literal(\"source_ambiguous_port_reference\"),source_ambiguous_port_reference_id:So(\"source_ambiguous_port_reference\"),error_type:N.literal(\"source_ambiguous_port_reference\").default(\"source_ambiguous_port_reference\"),source_port_id:N.string().optional(),source_component_id:N.string().optional()}).describe(\"Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous\"),kyt=N.object({type:N.literal(\"source_pcb_ground_plane\"),source_pcb_ground_plane_id:N.string(),source_group_id:N.string(),source_net_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Defines a ground plane in the source domain\"),LJ=[\"top\",\"bottom\",\"inner1\",\"inner2\",\"inner3\",\"inner4\",\"inner5\",\"inner6\",\"inner7\",\"inner8\"],W8e=N.enum(LJ),WA=W8e.or(N.object({name:W8e})).transform(t=\u003etypeof t==\"string\"?t:t.name),W_=N.enum([\"top\",\"bottom\"]),Fyt=N.object({type:N.literal(\"source_manually_placed_via\"),source_manually_placed_via_id:N.string(),source_group_id:N.string(),source_net_id:N.string(),subcircuit_id:N.string().optional(),source_trace_id:N.string().optional()}).describe(\"Defines a via that is manually placed in the source domain\"),Lyt=N.object({type:N.literal(\"source_unnamed_trace_warning\"),source_unnamed_trace_warning_id:So(\"source_unnamed_trace_warning\"),warning_type:N.literal(\"source_unnamed_trace_warning\").default(\"source_unnamed_trace_warning\"),message:N.string(),source_trace_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a source trace is missing a name\"),Hyt=N.object({type:N.literal(\"source_no_power_pin_defined_warning\"),source_no_power_pin_defined_warning_id:So(\"source_no_power_pin_defined_warning\"),warning_type:N.literal(\"source_no_power_pin_defined_warning\").default(\"source_no_power_pin_defined_warning\"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a chip has no source ports with requires_power=true\"),Oyt=N.object({type:N.literal(\"source_no_ground_pin_defined_warning\"),source_no_ground_pin_defined_warning_id:So(\"source_no_ground_pin_defined_warning\"),warning_type:N.literal(\"source_no_ground_pin_defined_warning\").default(\"source_no_ground_pin_defined_warning\"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a chip has no source ports marked as ground pins\"),Gyt=N.object({type:N.literal(\"source_component_pins_underspecified_warning\"),source_component_pins_underspecified_warning_id:So(\"source_component_pins_underspecified_warning\"),warning_type:N.literal(\"source_component_pins_underspecified_warning\").default(\"source_component_pins_underspecified_warning\"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when all ports on a source component are underspecified\"),Yyt=Wl.extend({type:N.literal(\"source_pin_must_be_connected_error\"),source_pin_must_be_connected_error_id:So(\"source_pin_must_be_connected_error\"),error_type:N.literal(\"source_pin_must_be_connected_error\").default(\"source_pin_must_be_connected_error\"),source_component_id:N.string(),source_port_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when a pin with mustBeConnected attribute is not connected to any trace\"),Uyt=Wl.extend({type:N.literal(\"unknown_error_finding_part\"),unknown_error_finding_part_id:So(\"unknown_error_finding_part\"),error_type:N.literal(\"unknown_error_finding_part\").default(\"unknown_error_finding_part\"),source_component_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when an unexpected error occurs while finding a part\"),Kyt=N.object({type:N.literal(\"source_part_not_found_warning\"),source_part_not_found_warning_id:So(\"source_part_not_found_warning\"),warning_type:N.literal(\"source_part_not_found_warning\").default(\"source_part_not_found_warning\"),message:N.string(),source_component_id:N.string().optional(),subcircuit_id:N.string().optional(),supplier_name:oAe.optional(),manufacturer_part_number:N.string().optional(),supplier_part_number:N.string().optional(),part_name:N.string().optional()}).describe(\"Warning emitted when a requested part can not be found\"),Vyt=N.object({type:N.literal(\"schematic_box\"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),width:ao,height:ao,is_dashed:N.boolean().default(!1),x:ao,y:ao,subcircuit_id:N.string().optional()}).describe(\"Draws a box on the schematic\"),zyt=N.object({type:N.literal(\"schematic_path\"),schematic_path_id:So(\"schematic_path\"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),fill_color:N.string().optional(),is_filled:N.boolean().optional(),is_dashed:N.boolean().default(!1),stroke_width:ao.nullable().optional(),stroke_color:N.string().optional(),dash_length:ao.optional(),dash_gap:ao.optional(),points:N.array(_r),subcircuit_id:N.string().optional()}),Jyt=N.record(N.object({left_margin:Di.optional(),right_margin:Di.optional(),top_margin:Di.optional(),bottom_margin:Di.optional()})),Wyt=N.object({left_size:N.number(),right_size:N.number(),top_size:N.number().optional(),bottom_size:N.number().optional()}),jyt=N.object({left_side:N.object({pins:N.array(N.number()),direction:N.enum([\"top-to-bottom\",\"bottom-to-top\"]).optional()}).optional(),right_side:N.object({pins:N.array(N.number()),direction:N.enum([\"top-to-bottom\",\"bottom-to-top\"]).optional()}).optional(),top_side:N.object({pins:N.array(N.number()),direction:N.enum([\"left-to-right\",\"right-to-left\"]).optional()}).optional(),bottom_side:N.object({pins:N.array(N.number()),direction:N.enum([\"left-to-right\",\"right-to-left\"]).optional()}).optional()}),$yt=N.union([Wyt,jyt]),qyt=N.object({type:N.literal(\"schematic_component\"),size:C8e,center:_r,source_component_id:N.string().optional(),schematic_component_id:N.string(),schematic_sheet_id:N.string().optional(),schematic_symbol_id:N.string().optional(),pin_spacing:Di.optional(),pin_styles:Jyt.optional(),box_width:Di.optional(),symbol_name:N.string().optional(),port_arrangement:$yt.optional(),port_labels:N.record(N.string()).optional(),symbol_display_value:N.string().optional(),subcircuit_id:N.string().optional(),schematic_group_id:N.string().optional(),is_schematic_group:N.boolean().optional(),source_group_id:N.string().optional(),is_box_with_pins:N.boolean().optional().default(!0)}),Cio=N.object({kicad_symbol:dyt.optional()}).catchall(N.unknown()),Xyt=N.object({type:N.literal(\"schematic_symbol\"),schematic_symbol_id:N.string(),name:N.string().optional(),metadata:Cio.optional()}).describe(\"Defines a named schematic symbol that can be referenced by components.\"),Zyt=N.object({type:N.literal(\"schematic_line\"),schematic_line_id:So(\"schematic_line\"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),x1:ao,y1:ao,x2:ao,y2:ao,stroke_width:ao.nullable().optional(),color:N.string().default(\"#000000\"),is_dashed:N.boolean().default(!1),dash_length:ao.optional(),dash_gap:ao.optional(),subcircuit_id:N.string().optional()}).describe(\"Draws a styled line on the schematic\"),e2t=N.object({type:N.literal(\"schematic_rect\"),schematic_rect_id:So(\"schematic_rect\"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:_r,width:ao,height:ao,rotation:im.default(0),stroke_width:ao.nullable().optional(),color:N.string().default(\"#000000\"),is_filled:N.boolean().default(!1),fill_color:N.string().optional(),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe(\"Draws a styled rectangle on the schematic\"),t2t=N.object({type:N.literal(\"schematic_circle\"),schematic_circle_id:So(\"schematic_circle\"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:_r,radius:ao,stroke_width:ao.nullable().optional(),color:N.string().default(\"#000000\"),is_filled:N.boolean().default(!1),fill_color:N.string().optional(),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe(\"Draws a styled circle on the schematic\"),n2t=N.object({type:N.literal(\"schematic_arc\"),schematic_arc_id:So(\"schematic_arc\"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:_r,radius:ao,start_angle_degrees:im,end_angle_degrees:im,direction:N.enum([\"clockwise\",\"counterclockwise\"]).default(\"counterclockwise\"),stroke_width:ao.nullable().optional(),color:N.string().default(\"#000000\"),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe(\"Draws a styled arc on the schematic\"),o2t=N.object({type:N.literal(\"schematic_trace\"),schematic_trace_id:N.string(),schematic_sheet_id:N.string().optional(),source_trace_id:N.string().optional(),junctions:N.array(N.object({x:N.number(),y:N.number()})),edges:N.array(N.object({from:N.object({x:N.number(),y:N.number()}),to:N.object({x:N.number(),y:N.number()}),is_crossing:N.boolean().optional(),from_schematic_port_id:N.string().optional(),to_schematic_port_id:N.string().optional()})),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}),yio=N.enum([\"center\",\"left\",\"right\",\"top\",\"bottom\"]),i2t=N.object({type:N.literal(\"schematic_text\"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),schematic_text_id:N.string(),text:N.string(),font_size:N.number().default(.18),position:N.object({x:ao,y:ao}),rotation:N.number().default(0),anchor:N.union([yio.describe(\"legacy\"),ob]).default(\"center\"),color:N.string().default(\"#000000\"),subcircuit_id:N.string().optional()}),r2t=N.object({type:N.literal(\"schematic_port\"),schematic_port_id:N.string(),source_port_id:N.string(),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),center:_r,facing_direction:N.enum([\"up\",\"down\",\"left\",\"right\"]).optional(),distance_from_component_edge:N.number().optional(),side_of_component:N.enum([\"top\",\"bottom\",\"left\",\"right\"]).optional(),true_ccw_index:N.number().optional(),pin_number:N.number().optional(),display_pin_label:N.string().optional(),subcircuit_id:N.string().optional(),is_connected:N.boolean().optional(),has_input_arrow:N.boolean().optional(),has_output_arrow:N.boolean().optional(),is_drawn_with_inversion_circle:N.boolean().optional()}).describe(\"Defines a port on a schematic component\"),s2t=N.object({type:N.literal(\"schematic_net_label\"),schematic_net_label_id:So(\"schematic_net_label\"),schematic_sheet_id:N.string().optional(),schematic_trace_id:N.string().optional(),source_trace_id:N.string().optional(),source_net_id:N.string(),center:_r,anchor_position:_r.optional(),anchor_side:N.enum([\"top\",\"bottom\",\"left\",\"right\"]),text:N.string(),symbol_name:N.string().optional(),is_movable:N.boolean().optional(),subcircuit_id:N.string().optional()}),a2t=Wl.extend({type:N.literal(\"schematic_error\"),schematic_error_id:N.string(),error_type:N.literal(\"schematic_port_not_found\").default(\"schematic_port_not_found\"),subcircuit_id:N.string().optional()}).describe(\"Defines a schematic error on the schematic\"),A2t=Wl.extend({type:N.literal(\"schematic_layout_error\"),schematic_layout_error_id:So(\"schematic_layout_error\"),error_type:N.literal(\"schematic_layout_error\").default(\"schematic_layout_error\"),source_group_id:N.string(),schematic_group_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when schematic layout fails for a group\"),rAe=N.object({type:N.literal(\"schematic_debug_object\"),label:N.string().optional(),subcircuit_id:N.string().optional()}),c2t=rAe.extend({shape:N.literal(\"rect\"),center:_r,size:C8e}),l2t=rAe.extend({shape:N.literal(\"line\"),start:_r,end:_r}),u2t=rAe.extend({shape:N.literal(\"point\"),center:_r}),g2t=N.discriminatedUnion(\"shape\",[c2t,l2t,u2t]),d2t=N.object({type:N.literal(\"schematic_voltage_probe\"),schematic_voltage_probe_id:N.string(),schematic_sheet_id:N.string().optional(),source_component_id:N.string().optional(),name:N.string().optional(),position:_r,schematic_trace_id:N.string(),voltage:tb.optional(),subcircuit_id:N.string().optional(),color:N.string().optional(),label_alignment:ob.optional()}).describe(\"Defines a voltage probe measurement point on a schematic trace\"),h2t=N.object({type:N.literal(\"schematic_manual_edit_conflict_warning\"),schematic_manual_edit_conflict_warning_id:So(\"schematic_manual_edit_conflict_warning\"),warning_type:N.literal(\"schematic_manual_edit_conflict_warning\").default(\"schematic_manual_edit_conflict_warning\"),message:N.string(),schematic_component_id:N.string(),schematic_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_component_id:N.string()}).describe(\"Warning emitted when a component has both manual placement and explicit schX/schY coordinates\"),p2t=N.object({type:N.literal(\"schematic_group\"),schematic_group_id:So(\"schematic_group\"),schematic_sheet_id:N.string().optional(),source_group_id:N.string(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),width:Di,height:Di,center:_r,schematic_component_ids:N.array(N.string()),show_as_schematic_box:N.boolean().optional(),name:N.string().optional(),description:N.string().optional()}).describe(\"Defines a group of components on the schematic\"),m2t=N.object({type:N.literal(\"schematic_table\"),schematic_table_id:So(\"schematic_table\"),schematic_sheet_id:N.string().optional(),anchor_position:_r,column_widths:N.array(ao),row_heights:N.array(ao),cell_padding:ao.optional(),border_width:ao.optional(),subcircuit_id:N.string().optional(),schematic_component_id:N.string().optional(),anchor:ob.optional()}).describe(\"Defines a table on the schematic\"),_2t=N.object({type:N.literal(\"schematic_table_cell\"),schematic_table_cell_id:So(\"schematic_table_cell\"),schematic_sheet_id:N.string().optional(),schematic_table_id:N.string(),start_row_index:N.number(),end_row_index:N.number(),start_column_index:N.number(),end_column_index:N.number(),text:N.string().optional(),center:_r,width:ao,height:ao,horizontal_align:N.enum([\"left\",\"center\",\"right\"]).optional(),vertical_align:N.enum([\"top\",\"middle\",\"bottom\"]).optional(),font_size:ao.optional(),subcircuit_id:N.string().optional()}).describe(\"Defines a cell within a schematic_table\"),f2t=N.object({type:N.literal(\"schematic_sheet\"),schematic_sheet_id:So(\"schematic_sheet\"),name:N.string().optional(),sheet_index:N.number().optional(),subcircuit_id:N.string().optional(),outline_color:N.string().optional()}).describe(\"Defines a schematic sheet or page that components can be placed on\"),I2t=N.object({x:ao,y:ao,bulge:N.number().optional()}),j8e=N.object({vertices:N.array(I2t)}),$8e=N.object({outer_ring:j8e,inner_rings:N.array(j8e).default([])}),C2t=N.object({x:ao,y:ao,via:N.boolean().optional(),via_to_layer:WA.optional()}),xio=N.array(C2t),y2t=N.object({x:ao,y:ao,via:N.boolean().optional(),to_layer:WA.optional(),trace_width:ao.optional()}),x2t=N.object({min_trace_width:Di.optional(),min_board_edge_clearance:Di.optional(),min_via_hole_edge_to_via_hole_edge_clearance:Di.optional(),min_plated_hole_drill_edge_to_drill_edge_clearance:Di.optional(),min_trace_to_pad_edge_clearance:Di.optional(),min_pad_edge_to_pad_edge_clearance:Di.optional(),min_same_net_trace_edge_to_trace_edge_clearance:Di.optional(),min_different_net_trace_edge_to_trace_edge_clearance:Di.optional(),min_via_edge_to_pad_edge_clearance:Di.optional(),min_via_hole_diameter:Di.optional(),min_via_pad_diameter:Di.optional()}),E2t=N.object({type:N.literal(\"pcb_component\"),pcb_component_id:So(\"pcb_component\"),source_component_id:N.string(),center:_r,layer:WA,rotation:im,display_offset_x:N.string().optional().describe(\"How to display the x offset for this part, usually corresponding with how the user specified it\"),display_offset_y:N.string().optional().describe(\"How to display the y offset for this part, usually corresponding with how the user specified it\"),width:Di,height:Di,do_not_place:N.boolean().optional(),is_allowed_to_be_off_board:N.boolean().optional(),subcircuit_id:N.string().optional(),pcb_group_id:N.string().optional(),position_mode:N.enum([\"packed\",\"relative_to_group_anchor\",\"relative_to_another_component\",\"none\"]).optional(),anchor_position:_r.optional(),anchor_alignment:ob.optional(),positioned_relative_to_pcb_group_id:N.string().optional(),positioned_relative_to_pcb_board_id:N.string().optional(),cable_insertion_center:_r.optional(),insertion_direction:N.enum([\"from_above\",\"from_left\",\"from_right\",\"from_front\",\"from_back\"]).optional(),metadata:N.object({kicad_footprint:Ayt.optional()}).optional(),obstructs_within_bounds:N.boolean().default(!0).describe(\"Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath\")}).describe(\"Defines a component on the PCB\"),B2t=N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:So(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"circle\"),hole_diameter:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Eio=B2t.describe(\"Defines a circular hole on the PCB\"),b2t=N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:So(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"rect\"),hole_width:N.number(),hole_height:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Bio=b2t.describe(\"Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.\"),S2t=N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:So(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.enum([\"circle\",\"square\"]),hole_diameter:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),bio=S2t.describe(\"Defines a circular or square hole on the PCB\"),Q2t=N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:So(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"oval\"),hole_width:N.number(),hole_height:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Sio=Q2t.describe(\"Defines an oval hole on the PCB\"),v2t=N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:So(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"pill\"),hole_width:N.number(),hole_height:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Qio=v2t.describe(\"Defines a pill-shaped hole on the PCB\"),w2t=N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:So(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"rotated_pill\"),hole_width:N.number(),hole_height:N.number(),x:ao,y:ao,ccw_rotation:im,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),vio=w2t.describe(\"Defines a rotated pill-shaped hole on the PCB\"),P2t=S2t.or(Q2t).or(v2t).or(w2t).or(B2t).or(b2t),wio=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"circle\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),outer_diameter:N.number(),hole_diameter:N.number(),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So(\"pcb_plated_hole\"),soldermask_margin:N.number().optional()}),Pio=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.enum([\"oval\",\"pill\"]),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),outer_width:N.number(),outer_height:N.number(),hole_width:N.number(),hole_height:N.number(),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,ccw_rotation:im,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So(\"pcb_plated_hole\"),soldermask_margin:N.number().optional()}),Mio=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"circular_hole_with_rect_pad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal(\"circle\"),pad_shape:N.literal(\"rect\"),hole_diameter:N.number(),rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),hole_offset_x:ao.default(0),hole_offset_y:ao.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So(\"pcb_plated_hole\"),soldermask_margin:N.number().optional(),rect_ccw_rotation:im.optional()}),Dio=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"pill_hole_with_rect_pad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal(\"pill\"),pad_shape:N.literal(\"rect\"),hole_width:N.number(),hole_height:N.number(),rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),hole_offset_x:ao.default(0),hole_offset_y:ao.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So(\"pcb_plated_hole\"),soldermask_margin:N.number().optional()}),Nio=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"rotated_pill_hole_with_rect_pad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal(\"rotated_pill\"),pad_shape:N.literal(\"rect\"),hole_width:N.number(),hole_height:N.number(),hole_ccw_rotation:im,rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),rect_ccw_rotation:im,hole_offset_x:ao.default(0),hole_offset_y:ao.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So(\"pcb_plated_hole\"),soldermask_margin:N.number().optional()}),Rio=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"hole_with_polygon_pad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.enum([\"circle\",\"oval\",\"pill\",\"rotated_pill\"]),hole_diameter:N.number().optional(),hole_width:N.number().optional(),hole_height:N.number().optional(),pad_outline:N.array(N.object({x:ao,y:ao})).min(3),hole_offset_x:ao.default(0),hole_offset_y:ao.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So(\"pcb_plated_hole\"),soldermask_margin:N.number().optional(),ccw_rotation:im.optional()}),M2t=N.union([wio,Pio,Mio,Dio,Nio,Rio]),D2t=N.object({type:N.literal(\"pcb_port\"),pcb_port_id:So(\"pcb_port\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_port_id:N.string(),pcb_component_id:N.string().optional(),x:ao,y:ao,layers:N.array(WA),is_board_pinout:N.boolean().optional()}).describe(\"Defines a port on the PCB\"),Tio=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"circle\"),pcb_smtpad_id:So(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,radius:N.number(),layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),kio=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"rect\"),pcb_smtpad_id:So(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),rect_border_radius:N.number().optional(),corner_radius:N.number().optional(),layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional(),soldermask_margin_left:N.number().optional(),soldermask_margin_top:N.number().optional(),soldermask_margin_right:N.number().optional(),soldermask_margin_bottom:N.number().optional()}),Fio=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"rotated_rect\"),pcb_smtpad_id:So(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),rect_border_radius:N.number().optional(),corner_radius:N.number().optional(),ccw_rotation:im,layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional(),soldermask_margin_left:N.number().optional(),soldermask_margin_top:N.number().optional(),soldermask_margin_right:N.number().optional(),soldermask_margin_bottom:N.number().optional()}),N2t=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"pill\"),pcb_smtpad_id:So(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),radius:N.number(),layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Lio=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"rotated_pill\"),pcb_smtpad_id:So(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),radius:N.number(),ccw_rotation:im,layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Hio=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"polygon\"),pcb_smtpad_id:So(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),points:N.array(_r),layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),R2t=N.discriminatedUnion(\"shape\",[Tio,kio,Fio,Lio,N2t,Hio]).describe(\"Defines an SMT pad on the PCB\"),Oio=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"circle\"),pcb_solder_paste_id:So(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,radius:N.number(),layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Gio=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"rect\"),pcb_solder_paste_id:So(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Yio=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"pill\"),pcb_solder_paste_id:So(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),radius:N.number(),layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Uio=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"rotated_rect\"),pcb_solder_paste_id:So(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),ccw_rotation:ao,layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Kio=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"oval\"),pcb_solder_paste_id:So(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),T2t=N.union([Oio,Gio,Yio,Uio,Kio]).describe(\"Defines solderpaste on the PCB\"),k2t=N.object({type:N.literal(\"pcb_text\"),pcb_text_id:So(\"pcb_text\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),text:N.string(),center:_r,layer:WA,width:Di,height:Di,lines:N.number(),align:N.enum([\"bottom-left\"])}).describe(\"Defines text on the PCB\"),F2t=N.object({route_type:N.literal(\"wire\"),x:ao,y:ao,width:ao,copper_pour_id:N.string().optional(),is_inside_copper_pour:N.boolean().optional(),start_pcb_port_id:N.string().optional(),end_pcb_port_id:N.string().optional(),layer:WA}),L2t=N.object({route_type:N.literal(\"via\"),x:ao,y:ao,copper_pour_id:N.string().optional(),is_inside_copper_pour:N.boolean().optional(),hole_diameter:ao.optional(),outer_diameter:ao.optional(),from_layer:WA,to_layer:WA}),H2t=N.object({route_type:N.literal(\"through_pad\"),start:_r,end:_r,width:ao,start_layer:WA,end_layer:WA,pcb_smtpad_id:N.string().optional(),pcb_plated_hole_id:N.string().optional()}),O2t=N.union([F2t,L2t,H2t]),G2t=N.object({type:N.literal(\"pcb_trace\"),source_trace_id:N.string().optional(),pcb_component_id:N.string().optional(),pcb_trace_id:So(\"pcb_trace\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),route_thickness_mode:N.enum([\"constant\",\"interpolated\"]).default(\"constant\").optional(),route_order_index:N.number().optional(),should_round_corners:N.boolean().optional(),trace_length:N.number().optional(),highlight_color:N.string().optional(),route:N.array(O2t)}).describe(\"Defines a trace on the PCB\"),Y2t=N.object({type:N.literal(\"pcb_trace_warning\"),pcb_trace_warning_id:So(\"pcb_trace_warning\"),warning_type:N.literal(\"pcb_trace_warning\").default(\"pcb_trace_warning\"),message:N.string(),center:_r.optional(),pcb_trace_id:N.string(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines a trace warning on the PCB\"),U2t=N.object({type:N.literal(\"pcb_trace_too_long_warning\"),pcb_trace_too_long_warning_id:So(\"pcb_trace_too_long_warning\"),warning_type:N.literal(\"pcb_trace_too_long_warning\").default(\"pcb_trace_too_long_warning\"),message:N.string(),pcb_trace_id:N.string(),source_net_id:N.string().optional(),source_trace_id:N.string().optional(),actual_trace_length:ao,maximum_trace_length:ao,subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a PCB trace is longer than its maximum allowed length\"),K2t=Wl.extend({type:N.literal(\"pcb_trace_error\"),pcb_trace_error_id:So(\"pcb_trace_error\"),error_type:N.literal(\"pcb_trace_error\").default(\"pcb_trace_error\"),center:_r.optional(),pcb_trace_id:N.string(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines a trace error on the PCB\"),V2t=Wl.extend({type:N.literal(\"pcb_trace_missing_error\"),pcb_trace_missing_error_id:So(\"pcb_trace_missing_error\"),error_type:N.literal(\"pcb_trace_missing_error\").default(\"pcb_trace_missing_error\"),center:_r.optional(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines an error when a source trace has no corresponding PCB trace\"),z2t=Wl.extend({type:N.literal(\"pcb_port_not_matched_error\"),pcb_error_id:So(\"pcb_error\"),error_type:N.literal(\"pcb_port_not_matched_error\").default(\"pcb_port_not_matched_error\"),pcb_component_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines a trace error on the PCB where a port is not matched\"),J2t=Wl.extend({type:N.literal(\"pcb_port_not_connected_error\"),pcb_port_not_connected_error_id:So(\"pcb_port_not_connected_error\"),error_type:N.literal(\"pcb_port_not_connected_error\").default(\"pcb_port_not_connected_error\"),pcb_port_ids:N.array(N.string()),pcb_component_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines an error when a pcb port is not connected to any trace\"),W2t=N.object({type:N.literal(\"pcb_net\"),pcb_net_id:So(\"pcb_net\"),source_net_id:N.string().optional(),highlight_color:N.string().optional()}).describe(\"Defines a net on the PCB\"),j2t=N.object({type:N.literal(\"pcb_via\"),pcb_via_id:So(\"pcb_via\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),x:ao,y:ao,outer_diameter:ao.default(\"0.6mm\"),hole_diameter:ao.default(\"0.25mm\"),from_layer:WA.optional(),to_layer:WA.optional(),layers:N.array(WA),pcb_trace_id:N.string().optional(),net_is_assignable:N.boolean().optional(),net_assigned:N.boolean().optional(),is_tented:N.boolean().optional()}).describe(\"Defines a via on the PCB\"),$2t=N.object({type:N.literal(\"pcb_board\"),pcb_board_id:So(\"pcb_board\"),pcb_panel_id:N.string().optional(),carrier_pcb_board_id:N.string().optional(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),is_mounted_to_carrier_board:N.boolean().optional(),width:Di.optional(),height:Di.optional(),center:_r,display_offset_x:N.string().optional().describe(\"How to display the x offset for this board, usually corresponding with how the user specified it\"),display_offset_y:N.string().optional().describe(\"How to display the y offset for this board, usually corresponding with how the user specified it\"),thickness:Di.optional().default(1.4),num_layers:N.number().optional().default(4),outline:N.array(_r).optional(),shape:N.enum([\"rect\",\"polygon\"]).optional(),material:N.enum([\"fr4\",\"fr1\"]).default(\"fr4\"),solder_mask_color:N.string().optional(),silkscreen_color:N.string().optional(),anchor_position:_r.optional(),anchor_alignment:ob.optional(),position_mode:N.enum([\"relative_to_panel_anchor\",\"none\"]).optional()}).merge(x2t).describe(\"Defines the board outline of the PCB\"),q2t=N.object({type:N.literal(\"pcb_panel\"),pcb_panel_id:So(\"pcb_panel\"),width:Di,height:Di,center:_r,thickness:Di.optional().default(1.4),covered_with_solder_mask:N.boolean().optional().default(!0)}).describe(\"Defines a PCB panel that can contain multiple boards\"),X2t=Wl.extend({type:N.literal(\"pcb_placement_error\"),pcb_placement_error_id:So(\"pcb_placement_error\"),error_type:N.literal(\"pcb_placement_error\").default(\"pcb_placement_error\"),subcircuit_id:N.string().optional()}).describe(\"Defines a placement error on the PCB\"),Z2t=Wl.extend({type:N.literal(\"pcb_panelization_placement_error\"),pcb_panelization_placement_error_id:So(\"pcb_panelization_placement_error\"),error_type:N.literal(\"pcb_panelization_placement_error\").default(\"pcb_panelization_placement_error\"),pcb_panel_id:N.string().optional(),pcb_board_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Defines a panelization placement error on the PCB\"),ext=N.object({type:N.literal(\"pcb_trace_hint\"),pcb_trace_hint_id:So(\"pcb_trace_hint\"),pcb_port_id:N.string(),pcb_component_id:N.string(),route:N.array(y2t),subcircuit_id:N.string().optional()}).describe(\"A hint that can be used during generation of a PCB trace\"),txt=N.object({type:N.literal(\"pcb_silkscreen_line\"),pcb_silkscreen_line_id:So(\"pcb_silkscreen_line\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),stroke_width:ao.default(\"0.1mm\"),x1:ao,y1:ao,x2:ao,y2:ao,layer:W_}).describe(\"Defines a silkscreen line on the PCB\"),nxt=N.object({type:N.literal(\"pcb_silkscreen_path\"),pcb_silkscreen_path_id:So(\"pcb_silkscreen_path\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,route:N.array(_r),stroke_width:Di}).describe(\"Defines a silkscreen path on the PCB\"),oxt=N.object({type:N.literal(\"pcb_silkscreen_text\"),pcb_silkscreen_text_id:So(\"pcb_silkscreen_text\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:ao.default(\"0.2mm\"),pcb_component_id:N.string(),text:N.string(),is_knockout:N.boolean().default(!1).optional(),knockout_padding:N.object({left:Di,top:Di,bottom:Di,right:Di}).default({left:\"0.2mm\",top:\"0.2mm\",bottom:\"0.2mm\",right:\"0.2mm\"}).optional(),ccw_rotation:N.number().optional(),layer:WA,is_mirrored:N.boolean().default(!1).optional(),anchor_position:_r.default({x:0,y:0}),anchor_alignment:ob.default(\"center\")}).describe(\"Defines silkscreen text on the PCB\"),ixt=N.object({type:N.literal(\"pcb_copper_text\"),pcb_copper_text_id:So(\"pcb_copper_text\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:ao.default(\"0.2mm\"),pcb_component_id:N.string(),text:N.string(),is_knockout:N.boolean().default(!1).optional(),knockout_padding:N.object({left:Di,top:Di,bottom:Di,right:Di}).default({left:\"0.2mm\",top:\"0.2mm\",bottom:\"0.2mm\",right:\"0.2mm\"}).optional(),ccw_rotation:N.number().optional(),layer:WA,is_mirrored:N.boolean().default(!1).optional(),anchor_position:_r.default({x:0,y:0}),anchor_alignment:ob.default(\"center\")}).describe(\"Defines copper text on the PCB\"),rxt=N.object({type:N.literal(\"pcb_silkscreen_rect\"),pcb_silkscreen_rect_id:So(\"pcb_silkscreen_rect\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,layer:WA,stroke_width:Di.default(\"1mm\"),corner_radius:Di.optional(),is_filled:N.boolean().default(!0).optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),ccw_rotation:N.number().optional()}).describe(\"Defines a silkscreen rect on the PCB\"),sxt=N.object({type:N.literal(\"pcb_silkscreen_circle\"),pcb_silkscreen_circle_id:So(\"pcb_silkscreen_circle\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,radius:Di,layer:W_,stroke_width:Di.default(\"1mm\"),is_filled:N.boolean().optional()}).describe(\"Defines a silkscreen circle on the PCB\"),axt=N.object({type:N.literal(\"pcb_silkscreen_oval\"),pcb_silkscreen_oval_id:So(\"pcb_silkscreen_oval\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,radius_x:ao,radius_y:ao,layer:W_,ccw_rotation:im.optional()}).describe(\"Defines a silkscreen oval on the PCB\"),Axt=N.object({type:N.literal(\"pcb_silkscreen_graphic\"),pcb_silkscreen_graphic_id:So(\"pcb_silkscreen_graphic\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,image_asset:y8e.optional()}).extend({shape:N.literal(\"brep\"),brep_shape:$8e}).describe(\"Defines a BRep silkscreen graphic on the PCB\"),cxt=N.discriminatedUnion(\"shape\",[Axt]).describe(\"Defines a silkscreen graphic on the PCB\"),lxt=N.object({type:N.literal(\"pcb_silkscreen_pill\"),pcb_silkscreen_pill_id:So(\"pcb_silkscreen_pill\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,layer:WA,ccw_rotation:N.number().optional()}).describe(\"Defines a silkscreen pill on the PCB\"),uxt=N.object({type:N.literal(\"pcb_fabrication_note_text\"),pcb_fabrication_note_text_id:So(\"pcb_fabrication_note_text\"),subcircuit_id:N.string().optional(),pcb_group_id:N.string().optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:ao.default(\"1mm\"),pcb_component_id:N.string(),text:N.string(),ccw_rotation:N.number().optional(),layer:W_,anchor_position:_r.default({x:0,y:0}),anchor_alignment:N.enum([\"center\",\"top_left\",\"top_right\",\"bottom_left\",\"bottom_right\"]).default(\"center\"),color:N.string().optional()}).describe(\"Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators\"),gxt=N.object({type:N.literal(\"pcb_fabrication_note_path\"),pcb_fabrication_note_path_id:So(\"pcb_fabrication_note_path\"),pcb_component_id:N.string(),subcircuit_id:N.string().optional(),layer:WA,route:N.array(_r),stroke_width:Di,color:N.string().optional()}).describe(\"Defines a fabrication path on the PCB for fabricators or assemblers\"),dxt=N.object({type:N.literal(\"pcb_fabrication_note_rect\"),pcb_fabrication_note_rect_id:So(\"pcb_fabrication_note_rect\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,layer:W_,stroke_width:Di.default(\"0.1mm\"),corner_radius:Di.optional(),is_filled:N.boolean().optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),color:N.string().optional()}).describe(\"Defines a fabrication note rectangle on the PCB\"),hxt=N.object({type:N.literal(\"pcb_fabrication_note_dimension\"),pcb_fabrication_note_dimension_id:So(\"pcb_fabrication_note_dimension\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,from:_r,to:_r,text:N.string().optional(),text_ccw_rotation:N.number().optional(),offset:Di.optional(),offset_distance:Di.optional(),offset_direction:N.object({x:N.number(),y:N.number()}).optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:Di.default(\"1mm\"),color:N.string().optional(),arrow_size:Di.default(\"1mm\")}).describe(\"Defines a measurement annotation within PCB fabrication notes\"),pxt=N.object({type:N.literal(\"pcb_note_text\"),pcb_note_text_id:So(\"pcb_note_text\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:ao.default(\"1mm\"),text:N.string().optional(),anchor_position:_r.default({x:0,y:0}),anchor_alignment:N.enum([\"center\",\"top_left\",\"top_right\",\"bottom_left\",\"bottom_right\"]).default(\"center\"),layer:W_.default(\"top\"),is_mirrored_from_top_view:N.boolean().optional(),color:N.string().optional()}).describe(\"Defines a documentation note in text on the PCB\"),mxt=N.object({type:N.literal(\"pcb_note_rect\"),pcb_note_rect_id:So(\"pcb_note_rect\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),center:_r,width:Di,height:Di,layer:W_.default(\"top\"),stroke_width:Di.default(\"0.1mm\"),corner_radius:Di.optional(),is_filled:N.boolean().optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),color:N.string().optional()}).describe(\"Defines a rectangular documentation note on the PCB\"),_xt=N.object({type:N.literal(\"pcb_note_path\"),pcb_note_path_id:So(\"pcb_note_path\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),route:N.array(_r),layer:W_.default(\"top\"),stroke_width:Di.default(\"0.1mm\"),color:N.string().optional()}).describe(\"Defines a polyline documentation note on the PCB\"),fxt=N.object({type:N.literal(\"pcb_note_line\"),pcb_note_line_id:So(\"pcb_note_line\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),x1:ao,y1:ao,x2:ao,y2:ao,layer:W_.default(\"top\"),stroke_width:ao.default(\"0.1mm\"),color:N.string().optional(),is_dashed:N.boolean().optional()}).describe(\"Defines a straight documentation note line on the PCB\"),Ixt=N.object({type:N.literal(\"pcb_note_dimension\"),pcb_note_dimension_id:So(\"pcb_note_dimension\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),from:_r,to:_r,text:N.string().optional(),text_ccw_rotation:N.number().optional(),offset_distance:Di.optional(),offset_direction:N.object({x:N.number(),y:N.number()}).optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:Di.default(\"1mm\"),layer:W_.default(\"top\"),color:N.string().optional(),arrow_size:Di.default(\"1mm\")}).describe(\"Defines a measurement annotation within PCB documentation notes\"),Cxt=Wl.extend({type:N.literal(\"pcb_footprint_overlap_error\"),pcb_error_id:So(\"pcb_error\"),error_type:N.literal(\"pcb_footprint_overlap_error\").default(\"pcb_footprint_overlap_error\"),pcb_smtpad_ids:N.array(N.string()).optional(),pcb_plated_hole_ids:N.array(N.string()).optional(),pcb_hole_ids:N.array(N.string()).optional(),pcb_keepout_ids:N.array(N.string()).optional()}).describe(\"Error emitted when a pcb footprint overlaps with another element\"),yxt=Wl.extend({type:N.literal(\"pcb_courtyard_overlap_error\"),pcb_error_id:So(\"pcb_error\"),error_type:N.literal(\"pcb_courtyard_overlap_error\").default(\"pcb_courtyard_overlap_error\"),pcb_component_ids:N.tuple([N.string(),N.string()])}).describe(\"Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another\"),xxt=N.object({type:N.literal(\"pcb_keepout\"),shape:N.literal(\"rect\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:ao,height:ao,pcb_keepout_id:N.string(),layers:N.array(N.string()),description:N.string().optional()}).or(N.object({type:N.literal(\"pcb_keepout\"),shape:N.literal(\"circle\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,radius:ao,pcb_keepout_id:N.string(),layers:N.array(N.string()),description:N.string().optional()})),sAe=N.object({type:N.literal(\"pcb_cutout\"),pcb_cutout_id:So(\"pcb_cutout\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_board_id:N.string().optional(),pcb_panel_id:N.string().optional()}),Ext=sAe.extend({shape:N.literal(\"rect\"),center:_r,width:Di,height:Di,rotation:im.optional(),corner_radius:Di.optional()}),Bxt=sAe.extend({shape:N.literal(\"circle\"),center:_r,radius:Di}),bxt=sAe.extend({shape:N.literal(\"polygon\"),points:N.array(_r)}),Sxt=sAe.extend({shape:N.literal(\"path\"),route:N.array(_r),slot_width:Di,slot_length:Di.optional(),space_between_slots:Di.optional(),slot_corner_radius:Di.optional()}),Qxt=N.discriminatedUnion(\"shape\",[Ext,Bxt,bxt,Sxt]).describe(\"Defines a cutout on the PCB, removing board material.\"),vxt=Wl.extend({type:N.literal(\"pcb_missing_footprint_error\"),pcb_missing_footprint_error_id:So(\"pcb_missing_footprint_error\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal(\"pcb_missing_footprint_error\").default(\"pcb_missing_footprint_error\"),source_component_id:N.string()}).describe(\"Defines a missing footprint error on the PCB\"),wxt=Wl.extend({type:N.literal(\"external_footprint_load_error\"),external_footprint_load_error_id:So(\"external_footprint_load_error\"),pcb_component_id:N.string(),source_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),footprinter_string:N.string().optional(),error_type:N.literal(\"external_footprint_load_error\").default(\"external_footprint_load_error\")}).describe(\"Defines an error when an external footprint fails to load\"),Pxt=Wl.extend({type:N.literal(\"circuit_json_footprint_load_error\"),circuit_json_footprint_load_error_id:So(\"circuit_json_footprint_load_error\"),pcb_component_id:N.string(),source_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal(\"circuit_json_footprint_load_error\").default(\"circuit_json_footprint_load_error\"),circuit_json:N.array(N.any()).optional()}).describe(\"Defines an error when a circuit JSON footprint fails to load\"),Mxt=N.object({type:N.literal(\"pcb_group\"),pcb_group_id:So(\"pcb_group\"),source_group_id:N.string(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),width:Di.optional(),height:Di.optional(),center:_r,display_offset_x:N.string().optional().describe(\"How to display the x offset for this group, usually corresponding with how the user specified it\"),display_offset_y:N.string().optional().describe(\"How to display the y offset for this group, usually corresponding with how the user specified it\"),outline:N.array(_r).optional(),anchor_position:_r.optional(),anchor_alignment:ob.default(\"center\"),position_mode:N.enum([\"packed\",\"relative_to_group_anchor\",\"none\"]).optional(),positioned_relative_to_pcb_group_id:N.string().optional(),positioned_relative_to_pcb_board_id:N.string().optional(),pcb_component_ids:N.array(N.string()),child_layout_mode:N.enum([\"packed\",\"none\"]).optional(),name:N.string().optional(),description:N.string().optional(),layout_mode:N.string().optional(),autorouter_configuration:N.object({trace_clearance:Di}).optional(),autorouter_used_string:N.string().optional()}).describe(\"Defines a group of components on the PCB\"),Dxt=Wl.extend({type:N.literal(\"pcb_autorouting_error\"),pcb_error_id:So(\"pcb_autorouting_error\"),error_type:N.literal(\"pcb_autorouting_error\").default(\"pcb_autorouting_error\"),subcircuit_id:N.string().optional()}).describe(\"The autorouting has failed to route a portion of the board\"),Nxt=N.object({type:N.literal(\"pcb_manual_edit_conflict_warning\"),pcb_manual_edit_conflict_warning_id:So(\"pcb_manual_edit_conflict_warning\"),warning_type:N.literal(\"pcb_manual_edit_conflict_warning\").default(\"pcb_manual_edit_conflict_warning\"),message:N.string(),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_component_id:N.string()}).describe(\"Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates\"),Rxt=N.enum([\"x-\",\"x+\",\"y+\",\"y-\"]),Txt=N.object({type:N.literal(\"pcb_connector_not_in_accessible_orientation_warning\"),pcb_connector_not_in_accessible_orientation_warning_id:So(\"pcb_connector_not_in_accessible_orientation_warning\"),warning_type:N.literal(\"pcb_connector_not_in_accessible_orientation_warning\").default(\"pcb_connector_not_in_accessible_orientation_warning\"),message:N.string(),pcb_component_id:N.string(),source_component_id:N.string().optional(),pcb_board_id:N.string().optional(),facing_direction:Rxt,recommended_facing_direction:Rxt,subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction\"),kxt=N.object({type:N.literal(\"supplier_footprint_mismatch_warning\"),supplier_footprint_mismatch_warning_id:So(\"supplier_footprint_mismatch_warning\"),warning_type:N.literal(\"supplier_footprint_mismatch_warning\").default(\"supplier_footprint_mismatch_warning\"),message:N.string(),source_component_id:N.string(),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),supplier_name:oAe.optional(),supplier_part_number:N.string().optional(),supplier_footprint_url:N.string().optional(),footprint_copper_intersection_over_union:N.number()}).describe(\"Warning emitted when a supplier part footprint does not match the expected footprint\"),Fxt=N.object({type:N.literal(\"pcb_breakout_point\"),pcb_breakout_point_id:So(\"pcb_breakout_point\"),pcb_group_id:N.string(),subcircuit_id:N.string().optional(),source_trace_id:N.string().optional(),source_port_id:N.string().optional(),source_net_id:N.string().optional(),x:ao,y:ao}).describe(\"Defines a routing target within a pcb_group for a source_trace or source_net\"),Lxt=N.object({type:N.literal(\"pcb_ground_plane\"),pcb_ground_plane_id:So(\"pcb_ground_plane\"),source_pcb_ground_plane_id:N.string(),source_net_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Defines a ground plane on the PCB\"),Hxt=N.object({type:N.literal(\"pcb_ground_plane_region\"),pcb_ground_plane_region_id:So(\"pcb_ground_plane_region\"),pcb_ground_plane_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:WA,points:N.array(_r)}).describe(\"Defines a polygon region of a ground plane\"),Oxt=N.object({type:N.literal(\"pcb_thermal_spoke\"),pcb_thermal_spoke_id:So(\"pcb_thermal_spoke\"),pcb_ground_plane_id:N.string(),shape:N.string(),spoke_count:N.number(),spoke_thickness:ao,spoke_inner_diameter:ao,spoke_outer_diameter:ao,pcb_plated_hole_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Pattern for connecting a ground plane to a plated hole\"),q8e=N.object({type:N.literal(\"pcb_copper_pour\"),pcb_copper_pour_id:So(\"pcb_copper_pour\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:WA,source_net_id:N.string().optional(),covered_with_solder_mask:N.boolean().optional().default(!0)}),Gxt=q8e.extend({shape:N.literal(\"rect\"),center:_r,width:Di,height:Di,rotation:im.optional()}),Yxt=q8e.extend({shape:N.literal(\"brep\"),brep_shape:$8e}),Uxt=q8e.extend({shape:N.literal(\"polygon\"),points:N.array(_r)}),Kxt=N.discriminatedUnion(\"shape\",[Gxt,Yxt,Uxt]).describe(\"Defines a copper pour on the PCB.\"),Vxt=Wl.extend({type:N.literal(\"pcb_component_outside_board_error\"),pcb_component_outside_board_error_id:So(\"pcb_component_outside_board_error\"),error_type:N.literal(\"pcb_component_outside_board_error\").default(\"pcb_component_outside_board_error\"),pcb_component_id:N.string(),pcb_board_id:N.string(),component_center:_r,component_bounds:N.object({min_x:N.number(),max_x:N.number(),min_y:N.number(),max_y:N.number()}),subcircuit_id:N.string().optional(),source_component_id:N.string().optional()}).describe(\"Error emitted when a PCB component is placed outside the board boundaries\"),zxt=Wl.extend({type:N.literal(\"pcb_component_not_on_board_edge_error\"),pcb_component_not_on_board_edge_error_id:So(\"pcb_component_not_on_board_edge_error\"),error_type:N.literal(\"pcb_component_not_on_board_edge_error\").default(\"pcb_component_not_on_board_edge_error\"),pcb_component_id:N.string(),pcb_board_id:N.string(),component_center:_r,pad_to_nearest_board_edge_distance:N.number(),source_component_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when a component that must be placed on the board edge is centered away from the edge\"),Jxt=Wl.extend({type:N.literal(\"pcb_component_invalid_layer_error\"),pcb_component_invalid_layer_error_id:So(\"pcb_component_invalid_layer_error\"),error_type:N.literal(\"pcb_component_invalid_layer_error\").default(\"pcb_component_invalid_layer_error\"),pcb_component_id:N.string().optional(),source_component_id:N.string(),layer:WA,subcircuit_id:N.string().optional()}).describe(\"Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)\"),Wxt=Wl.extend({type:N.literal(\"pcb_via_clearance_error\"),pcb_error_id:So(\"pcb_error\"),error_type:N.literal(\"pcb_via_clearance_error\").default(\"pcb_via_clearance_error\"),pcb_via_ids:N.array(N.string()).min(2),minimum_clearance:ao.optional(),actual_clearance:ao.optional(),pcb_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when vias are closer than the allowed clearance\"),jxt=Wl.extend({type:N.literal(\"pcb_via_trace_clearance_error\"),pcb_via_trace_clearance_error_id:So(\"pcb_via_trace_clearance_error\"),error_type:N.literal(\"pcb_via_trace_clearance_error\").default(\"pcb_via_trace_clearance_error\"),pcb_via_id:N.string(),pcb_trace_id:N.string(),minimum_clearance:ao.optional(),actual_clearance:ao.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when a via and trace are closer than the allowed clearance\"),$xt=Wl.extend({type:N.literal(\"pcb_pad_pad_clearance_error\"),pcb_pad_pad_clearance_error_id:So(\"pcb_pad_pad_clearance_error\"),error_type:N.literal(\"pcb_pad_pad_clearance_error\").default(\"pcb_pad_pad_clearance_error\"),pcb_pad_ids:N.array(N.string()).min(2),minimum_clearance:ao.optional(),actual_clearance:ao.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when pads are closer than the allowed clearance\"),qxt=Wl.extend({type:N.literal(\"pcb_pad_trace_clearance_error\"),pcb_pad_trace_clearance_error_id:So(\"pcb_pad_trace_clearance_error\"),error_type:N.literal(\"pcb_pad_trace_clearance_error\").default(\"pcb_pad_trace_clearance_error\"),pcb_pad_id:N.string(),pcb_trace_id:N.string(),minimum_clearance:ao.optional(),actual_clearance:ao.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when a pad and trace are closer than allowed clearance\"),Xxt=N.object({type:N.literal(\"pcb_courtyard_rect\"),pcb_courtyard_rect_id:So(\"pcb_courtyard_rect\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,layer:W_,ccw_rotation:im.optional(),color:N.string().optional()}).describe(\"Defines a courtyard rectangle on the PCB\"),Zxt=N.object({type:N.literal(\"pcb_courtyard_outline\"),pcb_courtyard_outline_id:So(\"pcb_courtyard_outline\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,outline:N.array(_r).min(2)}).describe(\"Defines a courtyard outline on the PCB\"),e3t=N.object({type:N.literal(\"pcb_courtyard_polygon\"),pcb_courtyard_polygon_id:So(\"pcb_courtyard_polygon\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,points:N.array(_r).min(3),color:N.string().optional()}).describe(\"Defines a courtyard polygon on the PCB\"),t3t=N.object({type:N.literal(\"pcb_courtyard_circle\"),pcb_courtyard_circle_id:So(\"pcb_courtyard_circle\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,radius:Di,layer:W_,color:N.string().optional()}).describe(\"Defines a courtyard circle on the PCB\"),n3t=N.object({type:N.literal(\"pcb_courtyard_pill\"),pcb_courtyard_pill_id:So(\"pcb_courtyard_pill\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,radius:Di,layer:W_,color:N.string().optional()}).describe(\"Defines a courtyard pill on the PCB\"),Vio=[\"obj\",\"stl\",\"3mf\",\"gltf\",\"glb\",\"step\",\"wrl\"],o3t=[\"x+\",\"x-\",\"y+\",\"y-\",\"z+\",\"z-\"],zio={obj:\"z+\",stl:\"z+\",\"3mf\":\"z+\",gltf:\"y+\",glb:\"y+\",step:\"z+\",wrl:\"y+\"},i3t=N.object({type:N.literal(\"cad_component\"),cad_component_id:N.string(),pcb_component_id:N.string(),source_component_id:N.string(),position:nb,rotation:nb.optional(),size:nb.optional(),layer:WA.optional(),subcircuit_id:N.string().optional(),footprinter_string:N.string().optional(),model_obj_url:N.string().optional(),model_stl_url:N.string().optional(),model_3mf_url:N.string().optional(),model_gltf_url:N.string().optional(),model_glb_url:N.string().optional(),model_step_url:N.string().optional(),model_wrl_url:N.string().optional(),model_asset:y8e.optional(),model_unit_to_mm_scale_factor:N.number().optional(),model_board_normal_direction:N.enum(o3t).optional().describe(`The direction in the model's coordinate space that is considered \"up\" or \"coming out of the board surface\"`),model_origin_position:nb.optional(),model_origin_alignment:N.enum([\"unknown\",\"center\",\"center_of_component_on_board_surface\",\"bottom_center_of_component\"]).optional(),model_object_fit:N.enum([\"contain_within_bounds\",\"fill_bounds\"]).optional().default(\"contain_within_bounds\"),model_jscad:N.any().optional(),show_as_translucent_model:N.boolean().optional(),show_as_bounding_box:N.boolean().optional(),anchor_alignment:N.enum([\"center\",\"center_of_component_on_board_surface\"]).optional().default(\"center\")}).describe(\"Defines a component on the PCB\"),X8e=N.enum([\"sinewave\",\"square\",\"triangle\",\"sawtooth\"]),Jio=N.union([N.string(),N.number()]).transform(t=\u003etypeof t==\"string\"?t.endsWith(\"%\")?parseFloat(t.slice(0,-1))/100:parseFloat(t):t).pipe(N.number().min(0,\"Duty cycle must be non-negative\").max(1,\"Duty cycle cannot be greater than 100%\")),r3t=N.object({type:N.literal(\"simulation_voltage_source\"),simulation_voltage_source_id:So(\"simulation_voltage_source\"),is_dc_source:N.literal(!0).optional().default(!0),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),voltage:tb}).describe(\"Defines a DC voltage source for simulation\"),s3t=N.object({type:N.literal(\"simulation_voltage_source\"),simulation_voltage_source_id:So(\"simulation_voltage_source\"),is_dc_source:N.literal(!1),terminal1_source_port_id:N.string().optional(),terminal2_source_port_id:N.string().optional(),terminal1_source_net_id:N.string().optional(),terminal2_source_net_id:N.string().optional(),voltage:tb.optional(),frequency:tN.optional(),peak_to_peak_voltage:tb.optional(),wave_shape:X8e.optional(),phase:im.optional(),duty_cycle:Jio.optional(),pulse_delay:J_.optional(),rise_time:J_.optional(),fall_time:J_.optional(),pulse_width:J_.optional(),period:J_.optional()}).describe(\"Defines an AC voltage source for simulation\"),a3t=N.union([r3t,s3t]).describe(\"Defines a voltage source for simulation\"),Wio=N.union([N.string(),N.number()]).transform(t=\u003etypeof t==\"string\"?t.endsWith(\"%\")?parseFloat(t.slice(0,-1))/100:parseFloat(t):t).pipe(N.number().min(0,\"Duty cycle must be non-negative\").max(1,\"Duty cycle cannot be greater than 100%\")),A3t=N.object({type:N.literal(\"simulation_current_source\"),simulation_current_source_id:So(\"simulation_current_source\"),is_dc_source:N.literal(!0).optional().default(!0),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),current:vL}).describe(\"Defines a DC current source for simulation\"),c3t=N.object({type:N.literal(\"simulation_current_source\"),simulation_current_source_id:So(\"simulation_current_source\"),is_dc_source:N.literal(!1),terminal1_source_port_id:N.string().optional(),terminal2_source_port_id:N.string().optional(),terminal1_source_net_id:N.string().optional(),terminal2_source_net_id:N.string().optional(),current:vL.optional(),frequency:tN.optional(),peak_to_peak_current:vL.optional(),wave_shape:X8e.optional(),phase:im.optional(),duty_cycle:Wio.optional()}).describe(\"Defines an AC current source for simulation\"),l3t=N.union([A3t,c3t]).describe(\"Defines a current source for simulation\"),u3t=N.union([N.literal(\"spice_dc_sweep\"),N.literal(\"spice_dc_operating_point\"),N.literal(\"spice_transient_analysis\"),N.literal(\"spice_ac_analysis\")]),g3t=N.object({method:N.enum([\"trap\",\"gear\"]).optional(),reltol:N.union([N.number(),N.string()]).optional(),abstol:N.union([N.number(),N.string()]).optional(),vntol:N.union([N.number(),N.string()]).optional()}).describe(\"SPICE solver options for a simulation experiment\"),d3t=N.object({type:N.literal(\"simulation_experiment\"),simulation_experiment_id:So(\"simulation_experiment\"),name:N.string(),experiment_type:u3t,time_per_step:wL.optional(),start_time_ms:J_.optional(),end_time_ms:J_.optional(),spice_options:g3t.optional()}).describe(\"Defines a simulation experiment configuration\"),h3t=N.object({type:N.literal(\"simulation_transient_voltage_graph\"),simulation_transient_voltage_graph_id:So(\"simulation_transient_voltage_graph\"),simulation_experiment_id:N.string(),timestamps_ms:N.array(N.number()).optional(),voltage_levels:N.array(N.number()),source_component_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),time_per_step:wL,start_time_ms:J_,end_time_ms:J_,name:N.string().optional(),color:N.string().optional()}).describe(\"Stores voltage measurements over time for a simulation\"),p3t=N.object({type:N.literal(\"simulation_transient_current_graph\"),simulation_transient_current_graph_id:So(\"simulation_transient_current_graph\"),simulation_experiment_id:N.string(),timestamps_ms:N.array(N.number()).optional(),current_levels:N.array(N.number()),source_component_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),time_per_step:wL,start_time_ms:J_,end_time_ms:J_,name:N.string().optional(),color:N.string().optional()}).describe(\"Stores current measurements over time for a simulation\"),m3t=N.object({type:N.literal(\"simulation_switch\"),simulation_switch_id:So(\"simulation_switch\"),source_component_id:N.string().optional(),closes_at:J_.optional(),opens_at:J_.optional(),starts_closed:N.boolean().optional(),switching_frequency:tN.optional()}).describe(\"Defines a switch for simulation timing control\"),_3t=N.object({type:N.literal(\"simulation_voltage_probe\"),simulation_voltage_probe_id:So(\"simulation_voltage_probe\"),source_component_id:N.string().optional(),name:N.string().optional(),signal_input_source_port_id:N.string().optional(),signal_input_source_net_id:N.string().optional(),reference_input_source_port_id:N.string().optional(),reference_input_source_net_id:N.string().optional(),subcircuit_id:N.string().optional(),color:N.string().optional()}).describe(\"Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.\").superRefine((t,e)=\u003e{if(t.reference_input_source_port_id||t.reference_input_source_net_id){const n=!!t.signal_input_source_port_id||!!t.reference_input_source_port_id,o=!!t.signal_input_source_net_id||!!t.reference_input_source_net_id;n\u0026\u0026o?e.addIssue({code:N.ZodIssueCode.custom,message:\"Cannot mix port and net connections in a differential probe.\"}):n?t.signal_input_source_port_id\u0026\u0026t.reference_input_source_port_id||e.addIssue({code:N.ZodIssueCode.custom,message:\"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id.\"}):o\u0026\u0026(t.signal_input_source_net_id\u0026\u0026t.reference_input_source_net_id||e.addIssue({code:N.ZodIssueCode.custom,message:\"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id.\"}))}else!!t.signal_input_source_port_id==!!t.signal_input_source_net_id\u0026\u0026e.addIssue({code:N.ZodIssueCode.custom,message:\"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id.\"})}),f3t=N.object({type:N.literal(\"simulation_current_probe\"),simulation_current_probe_id:So(\"simulation_current_probe\"),source_component_id:N.string().optional(),name:N.string().optional(),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),subcircuit_id:N.string().optional(),color:N.string().optional()}).describe(\"Defines a current probe for simulation. It measures current flowing from the positive endpoint to the negative endpoint.\").superRefine((t,e)=\u003e{const n=!!t.positive_source_port_id,o=!!t.negative_source_port_id,i=!!t.positive_source_net_id,r=!!t.negative_source_net_id,s=n||o,a=i||r;s\u0026\u0026a?e.addIssue({code:N.ZodIssueCode.custom,message:\"Cannot mix port and net connections in a current probe.\"}):s?n\u0026\u0026o||e.addIssue({code:N.ZodIssueCode.custom,message:\"Current probe using source ports requires both positive_source_port_id and negative_source_port_id.\"}):a?i\u0026\u0026r||e.addIssue({code:N.ZodIssueCode.custom,message:\"Current probe using source nets requires both positive_source_net_id and negative_source_net_id.\"}):e.addIssue({code:N.ZodIssueCode.custom,message:\"A current probe must have either positive/negative source port ids or positive/negative source net ids.\"})}),I3t=Wl.extend({type:N.literal(\"simulation_unknown_experiment_error\"),simulation_unknown_experiment_error_id:So(\"simulation_unknown_experiment_error\"),error_type:N.literal(\"simulation_unknown_experiment_error\").default(\"simulation_unknown_experiment_error\"),simulation_experiment_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"An unknown error occurred during the simulation experiment.\"),C3t=N.object({type:N.literal(\"simulation_op_amp\"),simulation_op_amp_id:So(\"simulation_op_amp\"),source_component_id:N.string().optional(),inverting_input_source_port_id:N.string(),non_inverting_input_source_port_id:N.string(),output_source_port_id:N.string(),positive_supply_source_port_id:N.string(),negative_supply_source_port_id:N.string()}).describe(\"Defines a simple ideal operational amplifier for simulation\"),y3t=N.object({type:N.literal(\"simulation_spice_subcircuit\"),simulation_spice_subcircuit_id:So(\"simulation_spice_subcircuit\"),source_component_id:N.string(),spice_pin_to_source_port_map:N.record(N.string(),N.string()),subcircuit_source:N.string()}).describe(\"Defines a custom SPICE subcircuit model for simulation\"),x3t=t=\u003et!==void 0,E3t=N.object({type:N.literal(\"simulation_oscilloscope_trace\"),simulation_oscilloscope_trace_id:So(\"simulation_oscilloscope_trace\"),simulation_transient_voltage_graph_id:N.string().optional(),simulation_transient_current_graph_id:N.string().optional(),simulation_voltage_probe_id:N.string().optional(),simulation_current_probe_id:N.string().optional(),display_name:N.string().optional(),color:N.string().optional(),display_center_value:N.number().optional(),display_center_offset_divs:N.number().optional(),volts_per_div:N.number().positive().optional(),amps_per_div:N.number().positive().optional()}).describe(\"Defines how a simulation measurement is rendered as an oscilloscope-style trace.\").superRefine((t,e)=\u003e{const n=[t.simulation_transient_voltage_graph_id,t.simulation_voltage_probe_id].filter(x3t).length,o=[t.simulation_transient_current_graph_id,t.simulation_current_probe_id].filter(x3t).length;n+o!==1\u0026\u0026e.addIssue({code:N.ZodIssueCode.custom,message:\"An oscilloscope trace must reference exactly one voltage graph, current graph, voltage probe, or current probe.\"}),n\u003e0\u0026\u0026t.amps_per_div!==void 0\u0026\u0026e.addIssue({code:N.ZodIssueCode.custom,message:\"Voltage oscilloscope traces must use volts_per_div, not amps_per_div.\"}),o\u003e0\u0026\u0026t.volts_per_div!==void 0\u0026\u0026e.addIssue({code:N.ZodIssueCode.custom,message:\"Current oscilloscope traces must use amps_per_div, not volts_per_div.\"})}),B3t=N.union([Myt,wyt,Pyt,vyt,Nyt,Dyt,S8e,E8e,iAe,b8e,B8e,Q8e,v8e,w8e,D8e,N8e,R8e,H8e,T8e,k8e,F8e,L8e,M8e,P8e,kyt,Fyt,Ryt,O8e,G8e,Y8e,U8e,Lyt,K8e,V8e,Hyt,Oyt,Gyt,Yyt,Uyt,Kyt,z8e,J8e,Tyt,E2t,P2t,vxt,wxt,Pxt,Nxt,Txt,kxt,M2t,xxt,D2t,W2t,k2t,G2t,Y2t,U2t,j2t,R2t,T2t,$2t,q2t,Mxt,ext,txt,nxt,oxt,lxt,ixt,rxt,sxt,axt,cxt,K2t,V2t,X2t,Z2t,z2t,J2t,Wxt,jxt,$xt,qxt,gxt,uxt,dxt,hxt,pxt,mxt,_xt,fxt,Ixt,Dxt,Cxt,yxt,Fxt,Qxt,Lxt,Hxt,Oxt,Kxt,Vxt,zxt,Jxt,Xxt,Zxt,e3t,t3t,n3t,Vyt,i2t,Zyt,e2t,t2t,n2t,qyt,Xyt,r2t,o2t,zyt,a2t,A2t,s2t,g2t,d2t,h2t,p2t,f2t,m2t,_2t,i3t,a3t,l3t,d3t,h3t,p3t,m3t,_3t,f3t,E3t,I3t,C3t,y3t]),aAe=B3t;function b3t(t,e,n){if(!e||!n)return;let o=t.get(e);o||(o=new Set,t.set(e,o)),o.add(n);let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(e)}var yx=(t,e={})=\u003e{const n=t;let o=n._internal_store;if(!o){o={counts:{},editCount:0},n._internal_store=o;for(const r of n){const s=r.type,a=r[`${s}_id`];if(!a)continue;const A=Number.parseInt(a.split(\"_\").pop());Number.isNaN(A)||(o.counts[s]=Math.max(o.counts[s]??0,A))}}const i=new Proxy({},{get:(r,s)=\u003e{if(s===\"toArray\")return()=\u003e(n.editCount=o.editCount,n);if(s===\"editCount\")return o.editCount;if(s===\"subtree\")return A=\u003eyx((function(c,l){if(!l.subcircuit_id\u0026\u0026!l.source_group_id)return[...c];let u=l;if(l.subcircuit_id){const m=new Set([l.subcircuit_id]),_=new Map,f=new Map;for(const C of c)if(C.type===\"source_group\"){const y=C.source_group_id,x=C.subcircuit_id;x\u0026\u0026f.set(y,x);const E=C.parent_source_group_id;E\u0026\u0026(_.has(E)||_.set(E,[]),_.get(E).push(y))}let I;for(const[C,y]of f)if(y===l.subcircuit_id){I=C;break}if(I){const C=y=\u003e{const x=_.get(y)||[];for(const E of x){const B=f.get(E);B\u0026\u0026m.add(B),C(E)}};C(I),u={...l,subcircuit_ids:Array.from(m)}}}const g=new Map;for(const m of c){const _=m[`${m.type}_id`];typeof _==\"string\"\u0026\u0026g.set(_,m)}const h=new Map;for(const m of c){const _=Object.entries(m);for(const[f,I]of _)if(f!==\"parent_source_group_id\"){if(f.endsWith(\"_id\")\u0026\u0026typeof I==\"string\")b3t(h,m,g.get(I));else if(f.endsWith(\"_ids\")\u0026\u0026Array.isArray(I))for(const C of I)typeof C==\"string\"\u0026\u0026b3t(h,m,g.get(C))}}const d=[],p=new Set;for(const m of c){let _=!1;(u.subcircuit_id\u0026\u0026\"subcircuit_id\"in m\u0026\u0026m.subcircuit_id===u.subcircuit_id||u.subcircuit_ids\u0026\u0026\"subcircuit_id\"in m\u0026\u0026m.subcircuit_id\u0026\u0026u.subcircuit_ids.includes(m.subcircuit_id)||u.source_group_id\u0026\u0026\"source_group_id\"in m\u0026\u0026m.source_group_id===u.source_group_id||u.source_group_id\u0026\u0026\"member_source_group_ids\"in m\u0026\u0026Array.isArray(m.member_source_group_ids)\u0026\u0026m.member_source_group_ids.includes(u.source_group_id))\u0026\u0026(_=!0),_\u0026\u0026(d.push(m),p.add(m))}for(;d.length\u003e0;){const m=d.shift(),_=h.get(m);if(_)for(const f of _)p.has(f)||(p.add(f),d.push(f))}return c.filter(m=\u003ep.has(m))})(n,A),e);if(s===\"insert\")return A=\u003e{const c=A.type;if(!c)throw new Error(\"insert requires an element with a type\");o.counts[c]??=-1,o.counts[c]++;const l=o.counts[c],u={...A,type:c,[`${c}_id`]:`${c}_${l}`};return e.validateInserts\u0026\u0026(Vae[c]??aAe).parse(u),n.push(u),o.editCount++,u};if(s===\"insertAll\")return A=\u003eA.map(c=\u003ei.insert(c));const a=s;return{get:A=\u003en.find(c=\u003ec.type===a\u0026\u0026c[`${a}_id`]===A),getUsing:A=\u003e{const c=Object.keys(A);if(c.length!==1)throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");const l=c[0],u=l.replace(\"_id\",\"\"),g=n.find(h=\u003eh.type===u\u0026\u0026h[l]===A[l]);return g?n.find(h=\u003eh.type===a\u0026\u0026h[`${a}_id`]===g[`${a}_id`]):null},getWhere:A=\u003e{const c=Object.keys(A);return n.find(l=\u003el.type===a\u0026\u0026c.every(u=\u003el[u]===A[u]))},list:A=\u003e{const c=A?Object.keys(A):[];return n.filter(l=\u003el.type===a\u0026\u0026c.every(u=\u003el[u]===A[u]))},insert:A=\u003e{o.counts[a]??=-1,o.counts[a]++;const c=o.counts[a],l={type:a,[`${a}_id`]:`${a}_${c}`,...A};return e.validateInserts\u0026\u0026(Vae[a]??aAe).parse(l),n.push(l),o.editCount++,l},delete:A=\u003e{const c=n.find(l=\u003el[`${a}_id`]===A);c\u0026\u0026(n.splice(n.indexOf(c),1),o.editCount++)},update:(A,c)=\u003e{const l=n.find(u=\u003eu.type===a\u0026\u0026u[`${a}_id`]===A);return l?(Object.assign(l,c),o.editCount++,l):null},select:A=\u003e{if(a===\"source_component\")return n.find(c=\u003ec.type===\"source_component\"\u0026\u0026c.name===A.replace(/\\./g,\"\"));if(a===\"pcb_port\"||a===\"source_port\"||a===\"schematic_port\"){const[c,l]=A.replace(/\\./g,\"\").split(/[\\s\\\u003e]+/),u=n.find(h=\u003eh.type===\"source_component\"\u0026\u0026h.name===c);if(!u)return null;const g=n.find(h=\u003eh.type===\"source_port\"\u0026\u0026h.source_component_id===u.source_component_id\u0026\u0026(h.name===l||(h.port_hints??[]).includes(l)));if(!g)return null;if(a===\"source_port\")return g;if(a===\"pcb_port\")return n.find(h=\u003eh.type===\"pcb_port\"\u0026\u0026h.source_port_id===g.source_port_id);if(a===\"schematic_port\")return n.find(h=\u003eh.type===\"schematic_port\"\u0026\u0026h.source_port_id===g.source_port_id)}}}}});return i};yx.unparsed=yx;var nI=yx;function Z8e(t){const e=t.type;return`${e}:${t[`${e}_id`]}`}var S3t=(t,e={})=\u003e{let n=t._internal_store_indexed;if(!n){n={counts:{},editCount:0,indexes:{}};for(const r of t){const s=r.type,a=r[`${s}_id`];if(!a)continue;const A=Number.parseInt(a.split(\"_\").pop()||\"\");Number.isNaN(A)||(n.counts[s]=Math.max(n.counts[s]??0,A))}const o=e.indexConfig||{},i=n.indexes;if(o.byId\u0026\u0026(i.byId=new Map),o.byType\u0026\u0026(i.byType=new Map),o.byRelation\u0026\u0026(i.byRelation=new Map),o.bySubcircuit\u0026\u0026(i.bySubcircuit=new Map),o.byCustomField\u0026\u0026o.byCustomField.length\u003e0){i.byCustomField=new Map;for(const r of o.byCustomField)i.byCustomField.set(r,new Map)}for(const r of t){if(o.byId){const s=Z8e(r);i.byId.set(s,r)}if(o.byType){const s=i.byType.get(r.type)||[];s.push(r),i.byType.set(r.type,s)}if(o.byRelation){const s=Object.entries(r);for(const[a,A]of s)if(a.endsWith(\"_id\")\u0026\u0026a!==`${r.type}_id`\u0026\u0026typeof A==\"string\"){const c=i.byRelation.get(a)||new Map,l=c.get(A)||[];l.push(r),c.set(A,l),i.byRelation.set(a,c)}}if(o.bySubcircuit\u0026\u0026\"subcircuit_id\"in r){const s=r.subcircuit_id;if(s\u0026\u0026typeof s==\"string\"){const a=i.bySubcircuit.get(s)||[];a.push(r),i.bySubcircuit.set(s,a)}}if(o.byCustomField\u0026\u0026i.byCustomField){for(const s of o.byCustomField)if(s in r){const a=r[s];if(a!==void 0\u0026\u0026(typeof a==\"string\"||typeof a==\"number\")){const A=String(a),c=i.byCustomField.get(s),l=c.get(A)||[];l.push(r),c.set(A,l)}}}}t._internal_store_indexed=n}return new Proxy({},{get:(o,i)=\u003e{if(i===\"toArray\")return()=\u003e(t.editCount=n.editCount,t);if(i===\"editCount\")return n.editCount;const r=i;return{get:s=\u003e{const a=e.indexConfig||{};return a.byId\u0026\u0026n.indexes.byId?n.indexes.byId.get(`${r}:${s}`)||null:a.byType\u0026\u0026n.indexes.byType?(n.indexes.byType.get(r)||[]).find(A=\u003eA[`${r}_id`]===s)||null:t.find(A=\u003eA.type===r\u0026\u0026A[`${r}_id`]===s)||null},getUsing:s=\u003e{const a=e.indexConfig||{},A=Object.keys(s);if(A.length!==1)throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");const c=A[0],l=c.replace(\"_id\",\"\");if(a.byRelation\u0026\u0026n.indexes.byRelation){const g=n.indexes.byRelation.get(c);if(g){const h=(g.get(s[c])||[]).find(p=\u003ep.type===l);if(!h)return null;const d=h[`${r}_id`];return a.byId\u0026\u0026n.indexes.byId?n.indexes.byId.get(`${r}:${d}`)||null:a.byType\u0026\u0026n.indexes.byType?(n.indexes.byType.get(r)||[]).find(p=\u003ep[`${r}_id`]===d)||null:t.find(p=\u003ep.type===r\u0026\u0026p[`${r}_id`]===d)||null}}const u=t.find(g=\u003eg.type===l\u0026\u0026g[c]===s[c]);return u\u0026\u0026t.find(g=\u003eg.type===r\u0026\u0026g[`${r}_id`]===u[`${r}_id`])||null},getWhere:s=\u003e{const a=e.indexConfig||{},A=Object.keys(s);if(A.length===1\u0026\u0026a.byCustomField\u0026\u0026n.indexes.byCustomField){const c=A[0],l=n.indexes.byCustomField.get(c);if(l){const u=String(s[c]);return(l.get(u)||[]).find(g=\u003eg.type===r)||null}}if(\"subcircuit_id\"in s\u0026\u0026a.bySubcircuit\u0026\u0026n.indexes.bySubcircuit){const c=s.subcircuit_id;return(n.indexes.bySubcircuit.get(c)||[]).find(l=\u003el.type===r\u0026\u0026A.every(u=\u003el[u]===s[u]))||null}return a.byType\u0026\u0026n.indexes.byType?(n.indexes.byType.get(r)||[]).find(c=\u003eA.every(l=\u003ec[l]===s[l]))||null:t.find(c=\u003ec.type===r\u0026\u0026A.every(l=\u003ec[l]===s[l]))||null},list:s=\u003e{const a=e.indexConfig||{},A=s?Object.keys(s):[];if(A.length===0\u0026\u0026a.byType\u0026\u0026n.indexes.byType)return n.indexes.byType.get(r)||[];if(A.length===1\u0026\u0026A[0]===\"subcircuit_id\"\u0026\u0026a.bySubcircuit\u0026\u0026n.indexes.bySubcircuit){const l=s.subcircuit_id;return(n.indexes.bySubcircuit.get(l)||[]).filter(u=\u003eu.type===r)}let c;return c=a.byType\u0026\u0026n.indexes.byType?n.indexes.byType.get(r)||[]:t.filter(l=\u003el.type===r),A.length\u003e0?c.filter(l=\u003eA.every(u=\u003el[u]===s[u])):c},insert:s=\u003e{n.counts[r]??=-1,n.counts[r]++;const a=n.counts[r],A={type:r,[`${r}_id`]:`${r}_${a}`,...s};e.validateInserts\u0026\u0026(Vae[r]??aAe).parse(A),t.push(A),n.editCount++;const c=e.indexConfig||{};if(c.byId\u0026\u0026n.indexes.byId){const l=Z8e(A);n.indexes.byId.set(l,A)}if(c.byType\u0026\u0026n.indexes.byType){const l=n.indexes.byType.get(r)||[];l.push(A),n.indexes.byType.set(r,l)}if(c.byRelation\u0026\u0026n.indexes.byRelation){const l=Object.entries(A);for(const[u,g]of l)if(u.endsWith(\"_id\")\u0026\u0026u!==`${A.type}_id`\u0026\u0026typeof g==\"string\"){const h=n.indexes.byRelation.get(u)||new Map,d=h.get(g)||[];d.push(A),h.set(g,d),n.indexes.byRelation.set(u,h)}}if(c.bySubcircuit\u0026\u0026n.indexes.bySubcircuit\u0026\u0026\"subcircuit_id\"in A){const l=A.subcircuit_id;if(l\u0026\u0026typeof l==\"string\"){const u=n.indexes.bySubcircuit.get(l)||[];u.push(A),n.indexes.bySubcircuit.set(l,u)}}if(c.byCustomField\u0026\u0026n.indexes.byCustomField){for(const l of c.byCustomField)if(l in A){const u=A[l];if(u!==void 0\u0026\u0026(typeof u==\"string\"||typeof u==\"number\")){const g=String(u),h=n.indexes.byCustomField.get(l),d=h.get(g)||[];d.push(A),h.set(g,d)}}}return A},delete:s=\u003e{const a=e.indexConfig||{};let A;if(a.byId\u0026\u0026n.indexes.byId?A=n.indexes.byId.get(`${r}:${s}`):a.byType\u0026\u0026n.indexes.byType?A=(n.indexes.byType.get(r)||[]).find(u=\u003eu[`${r}_id`]===s):A=t.find(l=\u003el[`${r}_id`]===s),!A)return;const c=t.indexOf(A);if(c\u003e=0\u0026\u0026(t.splice(c,1),n.editCount++),a.byId\u0026\u0026n.indexes.byId){const l=Z8e(A);n.indexes.byId.delete(l)}if(a.byType\u0026\u0026n.indexes.byType){const l=(n.indexes.byType.get(r)||[]).filter(u=\u003eu[`${r}_id`]!==s);n.indexes.byType.set(r,l)}if(a.byRelation\u0026\u0026n.indexes.byRelation)for(const[l,u]of n.indexes.byRelation.entries())for(const[g,h]of u.entries()){const d=h.filter(p=\u003ep!==A);d.length===0?u.delete(g):u.set(g,d)}if(a.bySubcircuit\u0026\u0026n.indexes.bySubcircuit\u0026\u0026\"subcircuit_id\"in A){const l=A.subcircuit_id;if(l){const u=(n.indexes.bySubcircuit.get(l)||[]).filter(g=\u003eg!==A);u.length===0?n.indexes.bySubcircuit.delete(l):n.indexes.bySubcircuit.set(l,u)}}if(a.byCustomField\u0026\u0026n.indexes.byCustomField)for(const l of n.indexes.byCustomField.values())for(const[u,g]of l.entries()){const h=g.filter(d=\u003ed!==A);h.length===0?l.delete(u):l.set(u,h)}},update:(s,a)=\u003e{const A=e.indexConfig||{};let c;if(A.byId\u0026\u0026n.indexes.byId?c=n.indexes.byId.get(`${r}:${s}`):A.byType\u0026\u0026n.indexes.byType?c=(n.indexes.byType.get(r)||[]).find(u=\u003eu[`${r}_id`]===s):c=t.find(l=\u003el.type===r\u0026\u0026l[`${r}_id`]===s),!c)return null;if(A.byRelation\u0026\u0026n.indexes.byRelation){const l=Object.entries(c);for(const[u,g]of l)if(u.endsWith(\"_id\")\u0026\u0026u!==`${c.type}_id`\u0026\u0026typeof g==\"string\"\u0026\u0026u in a\u0026\u0026a[u]!==g){const h=n.indexes.byRelation.get(u);if(h){const d=(h.get(g)||[]).filter(p=\u003ep!==c);d.length===0?h.delete(g):h.set(g,d)}}}if(A.bySubcircuit\u0026\u0026n.indexes.bySubcircuit\u0026\u0026\"subcircuit_id\"in c\u0026\u0026\"subcircuit_id\"in a){const l=c.subcircuit_id;if(l!==a.subcircuit_id){const u=(n.indexes.bySubcircuit.get(l)||[]).filter(g=\u003eg!==c);u.length===0?n.indexes.bySubcircuit.delete(l):n.indexes.bySubcircuit.set(l,u)}}if(A.byCustomField\u0026\u0026n.indexes.byCustomField){for(const l of A.byCustomField)if(l in c\u0026\u0026l in a\u0026\u0026c[l]!==a[l]){const u=n.indexes.byCustomField.get(l);if(u){const g=String(c[l]),h=(u.get(g)||[]).filter(d=\u003ed!==c);h.length===0?u.delete(g):u.set(g,h)}}}if(Object.assign(c,a),n.editCount++,A.byRelation\u0026\u0026n.indexes.byRelation){const l=Object.entries(c);for(const[u,g]of l)if(u.endsWith(\"_id\")\u0026\u0026u!==`${c.type}_id`\u0026\u0026typeof g==\"string\"\u0026\u0026u in a){const h=n.indexes.byRelation.get(u)||new Map,d=h.get(g)||[];d.includes(c)||(d.push(c),h.set(g,d),n.indexes.byRelation.set(u,h))}}if(A.bySubcircuit\u0026\u0026n.indexes.bySubcircuit\u0026\u0026\"subcircuit_id\"in c\u0026\u0026\"subcircuit_id\"in a){const l=c.subcircuit_id;if(l\u0026\u0026typeof l==\"string\"){const u=n.indexes.bySubcircuit.get(l)||[];u.includes(c)||(u.push(c),n.indexes.bySubcircuit.set(l,u))}}if(A.byCustomField\u0026\u0026n.indexes.byCustomField){for(const l of A.byCustomField)if(l in c\u0026\u0026l in a){const u=c[l];if(u!==void 0\u0026\u0026(typeof u==\"string\"||typeof u==\"number\")){const g=String(u),h=n.indexes.byCustomField.get(l),d=h.get(g)||[];d.includes(c)||(d.push(c),h.set(g,d))}}}return c},select:s=\u003e{if(r===\"source_component\")return t.find(a=\u003ea.type===\"source_component\"\u0026\u0026a.name===s.replace(/\\./g,\"\"))||null;if(r===\"pcb_port\"||r===\"source_port\"||r===\"schematic_port\"){const[a,A]=s.replace(/\\./g,\"\").split(/[\\s\\\u003e]+/),c=t.find(u=\u003eu.type===\"source_component\"\u0026\u0026u.name===a);if(!c)return null;const l=t.find(u=\u003eu.type===\"source_port\"\u0026\u0026u.source_component_id===c.source_component_id\u0026\u0026(u.name===A||(u.port_hints??[]).includes(A)));if(!l)return null;if(r===\"source_port\")return l;if(r===\"pcb_port\")return t.find(u=\u003eu.type===\"pcb_port\"\u0026\u0026u.source_port_id===l.source_port_id)||null;if(r===\"schematic_port\")return t.find(u=\u003eu.type===\"schematic_port\"\u0026\u0026u.source_port_id===l.source_port_id)||null}return null}}}})};S3t.unparsed=S3t;var Q3t=t=\u003et[`${t.type}_id`];function ebe(t,e){const n=yx(t).pcb_trace.get(e);if(!n)return`trace[${e}]`;const o=n.route.flatMap(i=\u003e[i.start_pcb_port_id,i.end_pcb_port_id]).filter(Boolean);return o.length===0?`trace[${e}]`:`trace[${o.map(i=\u003e{const r=(function(s){const a=yx(t).pcb_port.get(s);if(!a)return null;const A=a.pcb_component_id?yx(t).pcb_component.get(a.pcb_component_id):void 0;if(!A)return null;const c=yx(t).source_component.get(A.source_component_id);if(!c)return null;const l=yx(t).source_port.get(a.source_port_id),u=l?.port_hints?l.port_hints[1]:\"\";return{componentName:c.name,portHint:u}})(i);return r?`.${r.componentName} \u003e port.${r.portHint}`:`port[${i}]`}).join(\", \")}]`}var tbe=(t,e)=\u003e{const n=yx(t).pcb_port.get(e);if(!n)return`pcb_port[#${e}]`;const o=n.pcb_component_id?yx(t).pcb_component.get(n.pcb_component_id):void 0;if(!o)return`pcb_port[#${e}]`;const i=yx(t).source_component.get(o.source_component_id);if(!i)return`pcb_port[#${e}]`;const r=yx(t).source_port.get(n.source_port_id);if(!r)return`pcb_port[#${e}]`;let s;return s=r?.port_hints\u0026\u0026r.port_hints.length\u003e0||r.port_hints\u0026\u0026r.port_hints.length\u003e0?r.port_hints[0]:e,`pcb_port[.${i.name} \u003e .${s}]`},Ny=(t,e)=\u003e{if(typeof e==\"string\"){const n=((o,i)=\u003eo.find(r=\u003eQ3t(r)===i)??null)(t,e);return Ny(t,n)}switch(e.type){case\"pcb_port\":return tbe(t,e.pcb_port_id);case\"pcb_smtpad\":return(function(n,o){const i=yx(n).pcb_smtpad.get(o);return i\u0026\u0026i.pcb_port_id?tbe(n,i.pcb_port_id):`smtpad[${o}]`})(t,e.pcb_smtpad_id);case\"pcb_trace\":return ebe(t,e.pcb_trace_id);case\"source_component\":return`source_component[${e.name}]`;default:return`${e.type}[#${Q3t(e)}]`}},v3t=(t,e)=\u003e({minX:Math.min(t.minX,e.minX),minY:Math.min(t.minY,e.minY),maxX:Math.max(t.maxX,e.maxX),maxY:Math.max(t.maxY,e.maxY)}),AAe=(t,e,n)=\u003e{const o=n/2;return{minX:t-o,minY:e-o,maxX:t+o,maxY:e+o}},jio=(t,e,n,o,i)=\u003e{const r=n/2,s=o/2,a=i*Math.PI/180,A=Math.cos(a),c=Math.sin(a),l=[{x:-r,y:-s},{x:r,y:-s},{x:r,y:s},{x:-r,y:s}].map(u=\u003e({x:t+u.x*A-u.y*c,y:e+u.x*c+u.y*A}));return{minX:Math.min(...l.map(u=\u003eu.x)),minY:Math.min(...l.map(u=\u003eu.y)),maxX:Math.max(...l.map(u=\u003eu.x)),maxY:Math.max(...l.map(u=\u003eu.y))}},nbe=t=\u003e{let e=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const r of t){if(!r.type.startsWith(\"pcb_\"))continue;if(r.type===\"pcb_smtpad\"\u0026\u0026r.shape===\"polygon\"\u0026\u0026Array.isArray(r.points)){for(const l of r.points)e=Math.min(e,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y);continue}if(r.type===\"pcb_hole\"\u0026\u0026r.hole_shape===\"circle\"){const l=AAe(r.x,r.y,r.hole_diameter);e=Math.min(e,l.minX),n=Math.min(n,l.minY),o=Math.max(o,l.maxX),i=Math.max(i,l.maxY);continue}if(r.type===\"pcb_plated_hole\"){let l;if(\"outer_diameter\"in r\u0026\u0026typeof r.outer_diameter==\"number\"?l=AAe(r.x,r.y,r.outer_diameter):\"hole_diameter\"in r\u0026\u0026typeof r.hole_diameter==\"number\"\u0026\u0026(l=AAe(r.x,r.y,r.hole_diameter)),\"rect_pad_width\"in r\u0026\u0026typeof r.rect_pad_width==\"number\"\u0026\u0026\"rect_pad_height\"in r\u0026\u0026typeof r.rect_pad_height==\"number\"){const u=jio(r.x,r.y,r.rect_pad_width,r.rect_pad_height,\"rect_ccw_rotation\"in r?r.rect_ccw_rotation??0:0);l=l?v3t(l,u):u}if(\"hole_diameter\"in r\u0026\u0026typeof r.hole_diameter==\"number\"){const u=AAe(r.x+(\"hole_offset_x\"in r?r.hole_offset_x??0:0),r.y+(\"hole_offset_y\"in r?r.hole_offset_y??0:0),r.hole_diameter);l=l?v3t(l,u):u}if(l){e=Math.min(e,l.minX),n=Math.min(n,l.minY),o=Math.max(o,l.maxX),i=Math.max(i,l.maxY);continue}}let s,a,A,c;if(\"x\"in r\u0026\u0026\"y\"in r\u0026\u0026(s=Number(r.x),a=Number(r.y)),\"outer_diameter\"in r\u0026\u0026(A=Number(r.outer_diameter),c=Number(r.outer_diameter)),\"width\"in r\u0026\u0026(A=Number(r.width)),\"height\"in r\u0026\u0026(c=Number(r.height)),\"center\"in r\u0026\u0026(s=r.center.x,a=r.center.y),s!==void 0\u0026\u0026a!==void 0)e=Math.min(e,s),n=Math.min(n,a),o=Math.max(o,s),i=Math.max(i,a),A!==void 0\u0026\u0026c!==void 0\u0026\u0026(e=Math.min(e,s-A/2),n=Math.min(n,a-c/2),o=Math.max(o,s+A/2),i=Math.max(i,a+c/2)),\"radius\"in r\u0026\u0026(e=Math.min(e,s-r.radius),n=Math.min(n,a-r.radius),o=Math.max(o,s+r.radius),i=Math.max(i,a+r.radius));else if(r.type===\"pcb_trace\")for(const l of r.route)e=Math.min(e,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y);else if(r.type===\"pcb_courtyard_outline\")for(const l of r.outline)e=Math.min(e,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y);else if(r.type===\"pcb_courtyard_polygon\")for(const l of r.points)e=Math.min(e,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y)}return{minX:e,minY:n,maxX:o,maxY:i}},gv=t=\u003et[`${t.type}_id`],w3t={Hz:{baseUnit:\"Hz\",variants:{MHz:1e6,kHz:1e3,Hz:1}},g:{baseUnit:\"g\",variants:{kg:1e3,g:1}},Ω:{baseUnit:\"Ω\",variants:{mΩ:.001,Ω:1,kΩ:1e3,KΩ:1e3,kohm:1e3,MΩ:1e6,GΩ:1e9,TΩ:1e12}},V:{baseUnit:\"V\",variants:{mV:.001,V:1,kV:1e3,KV:1e3,MV:1e6,GV:1e9,TV:1e12}},A:{baseUnit:\"A\",variants:{µA:1e-6,mA:.001,ma:.001,A:1,kA:1e3,MA:1e6}},F:{baseUnit:\"F\",variants:{pF:1e-12,nF:1e-9,µF:1e-6,uF:1e-6,mF:.001,F:1}},ml:{baseUnit:\"ml\",variants:{ml:1,mL:1,l:1e3,L:1e3}},deg:{baseUnit:\"deg\",variants:{rad:180/Math.PI}},ms:{baseUnit:\"ms\",variants:{fs:1e-12,ps:1e-9,ns:1e-6,us:.001,µs:.001,ms:1,s:1e3}},mm:{baseUnit:\"mm\",variants:{nm:1e-6,µm:.001,um:.001,mm:1,cm:10,dm:100,m:1e3,km:1e6,in:25.4,ft:304.8,IN:25.4,FT:304.8,yd:914.4,mi:1609344,mil:.0254}}},obe=new Set;for(const[t,e]of Object.entries(w3t)){obe.add(t);for(const n of Object.keys(e.variants))obe.add(n)}var P3t={tera:1e12,T:1e12,giga:1e9,G:1e9,mega:1e6,M:1e6,kilo:1e3,k:1e3,deci:.1,d:.1,centi:.01,c:.01,milli:.001,m:.001,micro:1e-6,u:1e-6,µ:1e-6,nano:1e-9,n:1e-9,pico:1e-12,p:1e-12};function sB(t){if(t==null)return{parsedUnit:null,unitOfValue:null,value:null};if(typeof t==\"string\"\u0026\u0026t.match(/^-?[\\d\\.]+$/))return{value:Number.parseFloat(t),parsedUnit:null,unitOfValue:null};if(typeof t==\"number\")return{value:t,parsedUnit:null,unitOfValue:null};if(typeof t==\"object\"\u0026\u0026\"x\"in t\u0026\u0026\"y\"in t){const{parsedUnit:a,unitOfValue:A}=sB(t.x),c=sB(t.x),l=sB(t.y);return c.value===null||l.value===null?{parsedUnit:null,unitOfValue:null,value:null}:{parsedUnit:a,unitOfValue:A,value:{x:c.value,y:l.value}}}const e=t.toString().split(\"\").reverse().join(\"\"),n=e.match(/[^\\d\\s]+/)?.[0];if(!n)throw new Error(`Could not determine unit: \"${t}\"`);const o=n.split(\"\").reverse().join(\"\"),i=t.slice(0,-o.length);if(o in P3t\u0026\u0026!obe.has(o)){const a=P3t[o];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(i)*a}}const{baseUnit:r,conversionFactor:s}=(function(a){for(const[A,c]of Object.entries(w3t))if(a in c.variants)return{baseUnit:c.baseUnit,conversionFactor:c.variants[a]};return{baseUnit:a,conversionFactor:1}})(o);return{parsedUnit:o,unitOfValue:r,value:s*Number.parseFloat(i)}}var ibe=N.string().or(N.number()).transform(t=\u003esB(t).value),M3t=N.string().or(N.number()).transform(t=\u003esB(t).value).transform(t=\u003eNumber.parseFloat(t.toPrecision(12))),$io=N.string().or(N.number()).transform(t=\u003esB(t).value),dv=N.string().or(N.number()).transform(t=\u003esB(t).value),Ui=N.string().or(N.number()).transform(t=\u003esB(t).value),PL=N.string().or(N.number()).transform(t=\u003esB(t).value),ho=Ui,HJ=N.string().or(N.number()).transform(t=\u003esB(t).value),rbe=N.string().or(N.number()).transform(t=\u003esB(t).value),ML=rbe,qio=N.string().datetime(),jm=N.string().or(N.number()).transform(t=\u003etypeof t==\"number\"?t:t.endsWith(\"deg\")?Number.parseFloat(t.split(\"deg\")[0]):t.endsWith(\"rad\")?180*Number.parseFloat(t.split(\"rad\")[0])/Math.PI:Number.parseFloat(t)),Xio=N.number().or(N.string().endsWith(\"mAh\")).transform(t=\u003e{if(typeof t==\"string\"){const e=t.replace(\"mAh\",\"\"),n=Number.parseFloat(e);if(Number.isNaN(n))throw new Error(\"Invalid capacity\");return n}return t}).describe(\"Battery capacity in mAh\"),Lr=N.object({x:ho,y:ho}),nN=N.object({x:ho,y:ho,z:ho}),D3t=N.object({width:N.number(),height:N.number()}),Yo=t=\u003eN.string().optional().default(()=\u003e`${t}_${(e=\u003e{const n=\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";return Array.from({length:e},()=\u003en[Math.floor(62*Math.random())]).join(\"\")})(10)}`),hv=N.enum([\"top_left\",\"top_center\",\"top_right\",\"center_left\",\"center\",\"center_right\",\"bottom_left\",\"bottom_center\",\"bottom_right\"]),Zio=(N.enum([\"top_silkscreen\",\"bottom_silkscreen\",\"top_copper\",\"bottom_copper\",\"top_soldermask\",\"bottom_soldermask\",\"top_fabrication_note\",\"bottom_fabrication_note\",\"top_user_note\",\"bottom_user_note\",\"top_courtyard\",\"bottom_courtyard\",\"inner1_copper\",\"inner2_copper\",\"inner3_copper\",\"inner4_copper\",\"inner5_copper\",\"inner6_copper\",\"edge_cuts\",\"drill\"]),N.object({project_relative_path:N.string(),url:N.string(),mimetype:N.string()})),sbe=Lr.extend({rotation:jm.optional()}),N3t=N.object({size:Lr.optional(),thickness:ho.optional()}),ero=N.object({font:N3t.optional()}),cAe=N.object({value:N.string(),at:sbe.optional(),layer:N.string().optional(),uuid:N.string().optional(),hide:N.boolean().optional(),effects:ero.optional()}),tro=N.object({Reference:cAe.optional(),Value:cAe.optional(),Datasheet:cAe.optional(),Description:cAe.optional()}),nro=N.object({through_hole:N.boolean().optional(),smd:N.boolean().optional(),exclude_from_pos_files:N.boolean().optional(),exclude_from_bom:N.boolean().optional()}),oro=N.object({name:N.string(),type:N.string(),shape:N.string().optional(),at:sbe.optional(),size:Lr.optional(),drill:ho.optional(),layers:N.array(N.string()).optional(),removeUnusedLayers:N.boolean().optional(),uuid:N.string().optional()}),iro=N.object({path:N.string(),offset:nN.optional(),scale:nN.optional(),rotate:nN.optional()}),rro=N.object({footprintName:N.string().optional(),version:N.union([N.number(),N.string()]).optional(),generator:N.string().optional(),generatorVersion:N.union([N.number(),N.string()]).optional(),layer:N.string().optional(),properties:tro.optional(),attributes:nro.optional(),pads:N.array(oro).optional(),embeddedFonts:N.boolean().optional(),model:iro.optional()}),sro=N.object({hide:N.boolean().optional()}),aro=N.object({offset:ho.optional(),hide:N.boolean().optional()}),Aro=N.object({font:N3t.optional(),justify:N.union([N.string(),N.array(N.string())]).optional(),hide:N.boolean().optional()}),oN=N.object({value:N.string(),id:N.union([N.number(),N.string()]).optional(),at:sbe.optional(),effects:Aro.optional()}),cro=N.object({Reference:oN.optional(),Value:oN.optional(),Footprint:oN.optional(),Datasheet:oN.optional(),Description:oN.optional(),ki_keywords:oN.optional(),ki_fp_filters:oN.optional()}),lro=N.object({symbolName:N.string().optional(),extends:N.string().optional(),pinNumbers:sro.optional(),pinNames:aro.optional(),excludeFromSim:N.boolean().optional(),inBom:N.boolean().optional(),onBoard:N.boolean().optional(),properties:cro.optional(),embeddedFonts:N.boolean().optional()}),N0=N.object({error_type:N.string(),message:N.string(),is_fatal:N.boolean().optional()}),R3t=N.enum([\"jlcpcb\",\"macrofab\",\"pcbway\",\"digikey\",\"mouser\",\"lcsc\"]),Mg=N.object({type:N.literal(\"source_component\"),ftype:N.string().optional(),source_component_id:N.string(),name:N.string(),manufacturer_part_number:N.string().optional(),supplier_part_numbers:N.record(R3t,N.array(N.string())).optional(),display_value:N.string().optional(),display_name:N.string().optional(),are_pins_interchangeable:N.boolean().optional(),internally_connected_source_port_ids:N.array(N.array(N.string())).optional(),source_group_id:N.string().optional(),subcircuit_id:N.string().optional()}),T3t=Mg.extend({ftype:N.literal(\"simple_capacitor\"),capacitance:M3t,max_voltage_rating:dv.optional(),display_capacitance:N.string().optional(),max_decoupling_trace_length:ho.optional()}),k3t=Mg.extend({ftype:N.literal(\"simple_resistor\"),resistance:ibe,display_resistance:N.string().optional()}),abe=Mg.extend({ftype:N.literal(\"simple_diode\")}),uro=Mg.extend({ftype:N.literal(\"simple_fiducial\")}),F3t=abe.extend({ftype:N.literal(\"simple_led\"),color:N.string().optional(),wavelength:N.string().optional()}),gro=Mg.extend({ftype:N.literal(\"simple_ground\")}),L3t=Mg.extend({ftype:N.literal(\"simple_chip\")}),H3t=Mg.extend({ftype:N.literal(\"simple_power_source\"),voltage:dv}),dro=Mg.extend({ftype:N.literal(\"simple_current_source\"),current:HJ,frequency:PL.optional(),peak_to_peak_current:HJ.optional(),wave_shape:N.enum([\"sine\",\"square\",\"triangle\",\"sawtooth\",\"dc\"]).optional().default(\"dc\"),phase:N.number().optional(),duty_cycle:N.number().min(0).max(1).optional()}),hro=N.object({must_be_connected:N.boolean().optional(),provides_power:N.boolean().optional(),requires_power:N.boolean().optional(),provides_ground:N.boolean().optional(),requires_ground:N.boolean().optional(),provides_voltage:N.union([N.string(),N.number()]).optional(),requires_voltage:N.union([N.string(),N.number()]).optional(),do_not_connect:N.boolean().optional(),include_in_board_pinout:N.boolean().optional(),can_use_internal_pullup:N.boolean().optional(),is_using_internal_pullup:N.boolean().optional(),needs_external_pullup:N.boolean().optional(),can_use_internal_pulldown:N.boolean().optional(),is_using_internal_pulldown:N.boolean().optional(),needs_external_pulldown:N.boolean().optional(),can_use_open_drain:N.boolean().optional(),is_using_open_drain:N.boolean().optional(),can_use_push_pull:N.boolean().optional(),is_using_push_pull:N.boolean().optional(),should_have_decoupling_capacitor:N.boolean().optional(),recommended_decoupling_capacitor_capacitance:N.union([N.string(),N.number()]).optional(),is_configured_for_i2c_sda:N.boolean().optional(),is_configured_for_i2c_scl:N.boolean().optional(),is_configured_for_spi_mosi:N.boolean().optional(),is_configured_for_spi_miso:N.boolean().optional(),is_configured_for_spi_sck:N.boolean().optional(),is_configured_for_spi_cs:N.boolean().optional(),is_configured_for_uart_tx:N.boolean().optional(),is_configured_for_uart_rx:N.boolean().optional(),supports_i2c_sda:N.boolean().optional(),supports_i2c_scl:N.boolean().optional(),supports_spi_mosi:N.boolean().optional(),supports_spi_miso:N.boolean().optional(),supports_spi_sck:N.boolean().optional(),supports_spi_cs:N.boolean().optional(),supports_uart_tx:N.boolean().optional(),supports_uart_rx:N.boolean().optional()}),pro=Mg.extend({ftype:N.literal(\"simple_fuse\"),current_rating_amps:N.number().describe(\"Nominal current in amps the fuse is rated for\"),voltage_rating_volts:N.number().describe(\"Voltage rating in volts, e.g. ±5V would be 5\")}),O3t=Mg.extend({ftype:N.literal(\"simple_battery\"),capacity:Xio}),G3t=Mg.extend({ftype:N.literal(\"simple_inductor\"),inductance:$io,display_inductance:N.string().optional(),max_current_rating:N.number().optional()}),Y3t=Mg.extend({ftype:N.literal(\"simple_push_button\")}),U3t=Mg.extend({ftype:N.literal(\"simple_potentiometer\"),max_resistance:ibe,display_max_resistance:N.string().optional()}),mro=Mg.extend({ftype:N.literal(\"simple_crystal\"),frequency:N.number().describe(\"Frequency in Hz\"),load_capacitance:N.number().optional().describe(\"Load capacitance in pF\"),pin_variant:N.enum([\"two_pin\",\"four_pin\"]).optional()}),K3t=Mg.extend({ftype:N.literal(\"simple_pin_header\"),pin_count:N.number(),gender:N.enum([\"male\",\"female\"]).optional().default(\"male\")}),_ro=Mg.extend({ftype:N.literal(\"simple_connector\"),standard:N.enum([\"usb_c\",\"m2\"]).optional()}),V3t=Mg.extend({ftype:N.literal(\"simple_pinout\")}),z3t=Mg.extend({ftype:N.literal(\"simple_resonator\"),load_capacitance:M3t,equivalent_series_resistance:ibe.optional(),frequency:PL}),J3t=Mg.extend({ftype:N.literal(\"simple_transistor\"),transistor_type:N.enum([\"npn\",\"pnp\"])}),W3t=Mg.extend({ftype:N.literal(\"simple_test_point\"),footprint_variant:N.enum([\"pad\",\"through_hole\"]).optional(),pad_shape:N.enum([\"rect\",\"circle\"]).optional(),pad_diameter:N.union([N.number(),N.string()]).optional(),hole_diameter:N.union([N.number(),N.string()]).optional(),width:N.union([N.number(),N.string()]).optional(),height:N.union([N.number(),N.string()]).optional()}),j3t=Mg.extend({ftype:N.literal(\"simple_mosfet\"),channel_type:N.enum([\"n\",\"p\"]),mosfet_mode:N.enum([\"enhancement\",\"depletion\"])}),$3t=Mg.extend({ftype:N.literal(\"simple_op_amp\")}),q3t=Mg.extend({ftype:N.literal(\"simple_switch\")}),X3t=N.object({type:N.literal(\"source_project_metadata\"),name:N.string().optional(),software_used_string:N.string().optional(),project_url:N.string().optional(),created_at:qio.optional()}),fro=N0.extend({type:N.literal(\"source_missing_property_error\"),source_missing_property_error_id:Yo(\"source_missing_property_error\"),source_component_id:N.string(),property_name:N.string(),subcircuit_id:N.string().optional(),error_type:N.literal(\"source_missing_property_error\").default(\"source_missing_property_error\")}).describe(\"The source code is missing a property\"),Iro=N0.extend({type:N.literal(\"source_failed_to_create_component_error\"),source_failed_to_create_component_error_id:Yo(\"source_failed_to_create_component_error\"),error_type:N.literal(\"source_failed_to_create_component_error\").default(\"source_failed_to_create_component_error\"),component_name:N.string().optional(),subcircuit_id:N.string().optional(),parent_source_component_id:N.string().optional(),pcb_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),schematic_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional()}).describe(\"Error emitted when a component fails to be constructed\"),Z3t=N0.extend({type:N.literal(\"source_invalid_component_property_error\"),source_invalid_component_property_error_id:Yo(\"source_invalid_component_property_error\"),source_component_id:N.string(),property_name:N.string(),property_value:N.unknown().optional(),expected_format:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal(\"source_invalid_component_property_error\").default(\"source_invalid_component_property_error\")}).describe(\"The source component property is invalid\"),eEt=N0.extend({type:N.literal(\"source_trace_not_connected_error\"),source_trace_not_connected_error_id:Yo(\"source_trace_not_connected_error\"),error_type:N.literal(\"source_trace_not_connected_error\").default(\"source_trace_not_connected_error\"),subcircuit_id:N.string().optional(),source_group_id:N.string().optional(),source_trace_id:N.string().optional(),connected_source_port_ids:N.array(N.string()).optional(),selectors_not_found:N.array(N.string()).optional()}).describe(\"Occurs when a source trace selector does not match any ports\"),Cro=N.object({type:N.literal(\"source_property_ignored_warning\"),source_property_ignored_warning_id:Yo(\"source_property_ignored_warning\"),source_component_id:N.string(),property_name:N.string(),subcircuit_id:N.string().optional(),error_type:N.literal(\"source_property_ignored_warning\").default(\"source_property_ignored_warning\"),message:N.string()}).describe(\"The source property was ignored\"),tEt=N.object({type:N.literal(\"source_pin_missing_trace_warning\"),source_pin_missing_trace_warning_id:Yo(\"source_pin_missing_trace_warning\"),warning_type:N.literal(\"source_pin_missing_trace_warning\").default(\"source_pin_missing_trace_warning\"),message:N.string(),source_component_id:N.string(),source_port_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a source component pin is missing a trace connection\"),nEt=N.object({type:N.literal(\"source_missing_manufacturer_part_number_warning\"),source_missing_manufacturer_part_number_warning_id:Yo(\"source_missing_manufacturer_part_number_warning\"),warning_type:N.literal(\"source_missing_manufacturer_part_number_warning\").default(\"source_missing_manufacturer_part_number_warning\"),message:N.string(),source_component_id:N.string(),standard:N.string(),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a standard connector is missing manufacturer part number\"),yro=Mg.extend({ftype:N.literal(\"simple_voltage_probe\")}),xro=Mg.extend({ftype:N.literal(\"interconnect\")}),oEt=N0.extend({type:N.literal(\"source_i2c_misconfigured_error\"),source_i2c_misconfigured_error_id:Yo(\"source_i2c_misconfigured_error\"),error_type:N.literal(\"source_i2c_misconfigured_error\").default(\"source_i2c_misconfigured_error\"),source_port_ids:N.array(N.string())}).describe(\"Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net\"),Ero=Mg.extend({ftype:N.literal(\"simple_voltage_source\"),voltage:dv,frequency:PL.optional(),peak_to_peak_voltage:dv.optional(),wave_shape:N.enum([\"sinewave\",\"square\",\"triangle\",\"sawtooth\"]).optional(),phase:jm.optional(),duty_cycle:N.number().optional().describe(\"Duty cycle as a fraction (0 to 1)\")}),Bro=N.union([k3t,T3t,abe,uro,F3t,gro,L3t,H3t,dro,O3t,G3t,Y3t,U3t,mro,K3t,_ro,V3t,z3t,q3t,J3t,W3t,j3t,$3t,pro,yro,xro,Ero,X3t,fro,Z3t,Iro,eEt,Cro,tEt,nEt,oEt]),bro=N.object({type:N.literal(\"source_port\"),pin_number:N.number().optional(),port_hints:N.array(N.string()).optional(),name:N.string(),source_port_id:N.string(),source_component_id:N.string().optional(),source_group_id:N.string().optional(),most_frequently_referenced_by_name:N.string().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}).merge(hro),Sro=N.object({type:N.literal(\"source_component_internal_connection\"),source_component_internal_connection_id:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}),Qro=N.object({type:N.literal(\"source_trace\"),source_trace_id:N.string(),connected_source_port_ids:N.array(N.string()),connected_source_net_ids:N.array(N.string()),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),max_length:N.number().optional(),min_trace_thickness:N.number().optional(),display_name:N.string().optional()}),vro=N.object({type:N.literal(\"source_group\"),source_group_id:N.string(),subcircuit_id:N.string().optional(),parent_subcircuit_id:N.string().optional(),parent_source_group_id:N.string().optional(),is_subcircuit:N.boolean().optional(),show_as_schematic_box:N.boolean().optional(),name:N.string().optional(),was_automatically_named:N.boolean().optional()}),wro=N.object({type:N.literal(\"source_net\"),source_net_id:N.string(),name:N.string(),member_source_group_ids:N.array(N.string()),is_power:N.boolean().optional(),is_ground:N.boolean().optional(),is_digital_signal:N.boolean().optional(),is_analog_signal:N.boolean().optional(),is_positive_voltage_source:N.boolean().optional(),trace_width:N.number().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}),Pro=N.object({type:N.literal(\"source_board\"),source_board_id:N.string(),source_group_id:N.string(),title:N.string().optional()}).describe(\"Defines a board in the source domain\"),Mro=N0.extend({type:N.literal(\"source_ambiguous_port_reference\"),source_ambiguous_port_reference_id:Yo(\"source_ambiguous_port_reference\"),error_type:N.literal(\"source_ambiguous_port_reference\").default(\"source_ambiguous_port_reference\"),source_port_id:N.string().optional(),source_component_id:N.string().optional()}).describe(\"Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous\"),Dro=N.object({type:N.literal(\"source_pcb_ground_plane\"),source_pcb_ground_plane_id:N.string(),source_group_id:N.string(),source_net_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Defines a ground plane in the source domain\"),lAe=[\"top\",\"bottom\",\"inner1\",\"inner2\",\"inner3\",\"inner4\",\"inner5\",\"inner6\"],iEt=N.enum(lAe),Pc=iEt.or(N.object({name:iEt})).transform(t=\u003etypeof t==\"string\"?t:t.name),mC=N.enum([\"top\",\"bottom\"]),Nro=N.object({type:N.literal(\"source_manually_placed_via\"),source_manually_placed_via_id:N.string(),source_group_id:N.string(),source_net_id:N.string(),subcircuit_id:N.string().optional(),source_trace_id:N.string().optional()}).describe(\"Defines a via that is manually placed in the source domain\"),Rro=N.object({type:N.literal(\"source_no_power_pin_defined_warning\"),source_no_power_pin_defined_warning_id:Yo(\"source_no_power_pin_defined_warning\"),warning_type:N.literal(\"source_no_power_pin_defined_warning\").default(\"source_no_power_pin_defined_warning\"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a chip has no source ports with requires_power=true\"),Tro=N.object({type:N.literal(\"source_no_ground_pin_defined_warning\"),source_no_ground_pin_defined_warning_id:Yo(\"source_no_ground_pin_defined_warning\"),warning_type:N.literal(\"source_no_ground_pin_defined_warning\").default(\"source_no_ground_pin_defined_warning\"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a chip has no source ports marked as ground pins\"),kro=N.object({type:N.literal(\"source_component_pins_underspecified_warning\"),source_component_pins_underspecified_warning_id:Yo(\"source_component_pins_underspecified_warning\"),warning_type:N.literal(\"source_component_pins_underspecified_warning\").default(\"source_component_pins_underspecified_warning\"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Warning emitted when all ports on a source component are underspecified\"),Fro=N0.extend({type:N.literal(\"source_pin_must_be_connected_error\"),source_pin_must_be_connected_error_id:Yo(\"source_pin_must_be_connected_error\"),error_type:N.literal(\"source_pin_must_be_connected_error\").default(\"source_pin_must_be_connected_error\"),source_component_id:N.string(),source_port_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when a pin with mustBeConnected attribute is not connected to any trace\"),Lro=N0.extend({type:N.literal(\"unknown_error_finding_part\"),unknown_error_finding_part_id:Yo(\"unknown_error_finding_part\"),error_type:N.literal(\"unknown_error_finding_part\").default(\"unknown_error_finding_part\"),source_component_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when an unexpected error occurs while finding a part\"),Hro=N.object({type:N.literal(\"schematic_box\"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),width:ho,height:ho,is_dashed:N.boolean().default(!1),x:ho,y:ho,subcircuit_id:N.string().optional()}).describe(\"Draws a box on the schematic\"),Oro=N.object({type:N.literal(\"schematic_path\"),schematic_path_id:Yo(\"schematic_path\"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),fill_color:N.string().optional(),is_filled:N.boolean().optional(),stroke_width:ho.nullable().optional(),stroke_color:N.string().optional(),points:N.array(Lr),subcircuit_id:N.string().optional()}),Gro=N.record(N.object({left_margin:Ui.optional(),right_margin:Ui.optional(),top_margin:Ui.optional(),bottom_margin:Ui.optional()})),Yro=N.object({left_size:N.number(),right_size:N.number(),top_size:N.number().optional(),bottom_size:N.number().optional()}),Uro=N.object({left_side:N.object({pins:N.array(N.number()),direction:N.enum([\"top-to-bottom\",\"bottom-to-top\"]).optional()}).optional(),right_side:N.object({pins:N.array(N.number()),direction:N.enum([\"top-to-bottom\",\"bottom-to-top\"]).optional()}).optional(),top_side:N.object({pins:N.array(N.number()),direction:N.enum([\"left-to-right\",\"right-to-left\"]).optional()}).optional(),bottom_side:N.object({pins:N.array(N.number()),direction:N.enum([\"left-to-right\",\"right-to-left\"]).optional()}).optional()}),Kro=N.union([Yro,Uro]),Vro=N.object({type:N.literal(\"schematic_component\"),size:D3t,center:Lr,source_component_id:N.string().optional(),schematic_component_id:N.string(),schematic_symbol_id:N.string().optional(),pin_spacing:Ui.optional(),pin_styles:Gro.optional(),box_width:Ui.optional(),symbol_name:N.string().optional(),port_arrangement:Kro.optional(),port_labels:N.record(N.string()).optional(),symbol_display_value:N.string().optional(),subcircuit_id:N.string().optional(),schematic_group_id:N.string().optional(),is_schematic_group:N.boolean().optional(),source_group_id:N.string().optional(),is_box_with_pins:N.boolean().optional().default(!0)}),zro=N.object({kicad_symbol:lro.optional()}).catchall(N.unknown()),Jro=N.object({type:N.literal(\"schematic_symbol\"),schematic_symbol_id:N.string(),name:N.string().optional(),metadata:zro.optional()}).describe(\"Defines a named schematic symbol that can be referenced by components.\"),Wro=N.object({type:N.literal(\"schematic_line\"),schematic_line_id:Yo(\"schematic_line\"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),x1:ho,y1:ho,x2:ho,y2:ho,stroke_width:ho.nullable().optional(),color:N.string().default(\"#000000\"),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe(\"Draws a styled line on the schematic\"),jro=N.object({type:N.literal(\"schematic_rect\"),schematic_rect_id:Yo(\"schematic_rect\"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:Lr,width:ho,height:ho,rotation:jm.default(0),stroke_width:ho.nullable().optional(),color:N.string().default(\"#000000\"),is_filled:N.boolean().default(!1),fill_color:N.string().optional(),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe(\"Draws a styled rectangle on the schematic\"),$ro=N.object({type:N.literal(\"schematic_circle\"),schematic_circle_id:Yo(\"schematic_circle\"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:Lr,radius:ho,stroke_width:ho.nullable().optional(),color:N.string().default(\"#000000\"),is_filled:N.boolean().default(!1),fill_color:N.string().optional(),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe(\"Draws a styled circle on the schematic\"),qro=N.object({type:N.literal(\"schematic_arc\"),schematic_arc_id:Yo(\"schematic_arc\"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:Lr,radius:ho,start_angle_degrees:jm,end_angle_degrees:jm,direction:N.enum([\"clockwise\",\"counterclockwise\"]).default(\"counterclockwise\"),stroke_width:ho.nullable().optional(),color:N.string().default(\"#000000\"),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe(\"Draws a styled arc on the schematic\"),Xro=N.object({type:N.literal(\"schematic_trace\"),schematic_trace_id:N.string(),source_trace_id:N.string().optional(),junctions:N.array(N.object({x:N.number(),y:N.number()})),edges:N.array(N.object({from:N.object({x:N.number(),y:N.number()}),to:N.object({x:N.number(),y:N.number()}),is_crossing:N.boolean().optional(),from_schematic_port_id:N.string().optional(),to_schematic_port_id:N.string().optional()})),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}),Zro=N.enum([\"center\",\"left\",\"right\",\"top\",\"bottom\"]),eso=N.object({type:N.literal(\"schematic_text\"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),schematic_text_id:N.string(),text:N.string(),font_size:N.number().default(.18),position:N.object({x:ho,y:ho}),rotation:N.number().default(0),anchor:N.union([Zro.describe(\"legacy\"),hv]).default(\"center\"),color:N.string().default(\"#000000\"),subcircuit_id:N.string().optional()}),tso=N.object({type:N.literal(\"schematic_port\"),schematic_port_id:N.string(),source_port_id:N.string(),schematic_component_id:N.string().optional(),center:Lr,facing_direction:N.enum([\"up\",\"down\",\"left\",\"right\"]).optional(),distance_from_component_edge:N.number().optional(),side_of_component:N.enum([\"top\",\"bottom\",\"left\",\"right\"]).optional(),true_ccw_index:N.number().optional(),pin_number:N.number().optional(),display_pin_label:N.string().optional(),subcircuit_id:N.string().optional(),is_connected:N.boolean().optional(),has_input_arrow:N.boolean().optional(),has_output_arrow:N.boolean().optional(),is_drawn_with_inversion_circle:N.boolean().optional()}).describe(\"Defines a port on a schematic component\"),nso=N.object({type:N.literal(\"schematic_net_label\"),schematic_net_label_id:Yo(\"schematic_net_label\"),schematic_trace_id:N.string().optional(),source_trace_id:N.string().optional(),source_net_id:N.string(),center:Lr,anchor_position:Lr.optional(),anchor_side:N.enum([\"top\",\"bottom\",\"left\",\"right\"]),text:N.string(),symbol_name:N.string().optional(),is_movable:N.boolean().optional(),subcircuit_id:N.string().optional()}),oso=N0.extend({type:N.literal(\"schematic_error\"),schematic_error_id:N.string(),error_type:N.literal(\"schematic_port_not_found\").default(\"schematic_port_not_found\"),subcircuit_id:N.string().optional()}).describe(\"Defines a schematic error on the schematic\"),iso=N0.extend({type:N.literal(\"schematic_layout_error\"),schematic_layout_error_id:Yo(\"schematic_layout_error\"),error_type:N.literal(\"schematic_layout_error\").default(\"schematic_layout_error\"),source_group_id:N.string(),schematic_group_id:N.string(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when schematic layout fails for a group\"),Abe=N.object({type:N.literal(\"schematic_debug_object\"),label:N.string().optional(),subcircuit_id:N.string().optional()}),rso=Abe.extend({shape:N.literal(\"rect\"),center:Lr,size:D3t}),sso=Abe.extend({shape:N.literal(\"line\"),start:Lr,end:Lr}),aso=Abe.extend({shape:N.literal(\"point\"),center:Lr}),Aso=N.discriminatedUnion(\"shape\",[rso,sso,aso]),cso=N.object({type:N.literal(\"schematic_voltage_probe\"),schematic_voltage_probe_id:N.string(),source_component_id:N.string().optional(),name:N.string().optional(),position:Lr,schematic_trace_id:N.string(),voltage:dv.optional(),subcircuit_id:N.string().optional(),color:N.string().optional(),label_alignment:hv.optional()}).describe(\"Defines a voltage probe measurement point on a schematic trace\"),lso=N.object({type:N.literal(\"schematic_manual_edit_conflict_warning\"),schematic_manual_edit_conflict_warning_id:Yo(\"schematic_manual_edit_conflict_warning\"),warning_type:N.literal(\"schematic_manual_edit_conflict_warning\").default(\"schematic_manual_edit_conflict_warning\"),message:N.string(),schematic_component_id:N.string(),schematic_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_component_id:N.string()}).describe(\"Warning emitted when a component has both manual placement and explicit schX/schY coordinates\"),uso=N.object({type:N.literal(\"schematic_group\"),schematic_group_id:Yo(\"schematic_group\"),source_group_id:N.string(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),width:Ui,height:Ui,center:Lr,schematic_component_ids:N.array(N.string()),show_as_schematic_box:N.boolean().optional(),name:N.string().optional(),description:N.string().optional()}).describe(\"Defines a group of components on the schematic\"),gso=N.object({type:N.literal(\"schematic_table\"),schematic_table_id:Yo(\"schematic_table\"),anchor_position:Lr,column_widths:N.array(ho),row_heights:N.array(ho),cell_padding:ho.optional(),border_width:ho.optional(),subcircuit_id:N.string().optional(),schematic_component_id:N.string().optional(),anchor:hv.optional()}).describe(\"Defines a table on the schematic\"),dso=N.object({type:N.literal(\"schematic_table_cell\"),schematic_table_cell_id:Yo(\"schematic_table_cell\"),schematic_table_id:N.string(),start_row_index:N.number(),end_row_index:N.number(),start_column_index:N.number(),end_column_index:N.number(),text:N.string().optional(),center:Lr,width:ho,height:ho,horizontal_align:N.enum([\"left\",\"center\",\"right\"]).optional(),vertical_align:N.enum([\"top\",\"middle\",\"bottom\"]).optional(),font_size:ho.optional(),subcircuit_id:N.string().optional()}).describe(\"Defines a cell within a schematic_table\"),hso=N.object({type:N.literal(\"schematic_sheet\"),schematic_sheet_id:Yo(\"schematic_sheet\"),name:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Defines a schematic sheet or page that components can be placed on\"),pso=N.object({x:ho,y:ho,bulge:N.number().optional()}),rEt=N.object({vertices:N.array(pso)}),mso=N.object({outer_ring:rEt,inner_rings:N.array(rEt).default([])}),_so=N.object({x:ho,y:ho,via:N.boolean().optional(),via_to_layer:Pc.optional()}),fso=(N.array(_so),N.object({x:ho,y:ho,via:N.boolean().optional(),to_layer:Pc.optional(),trace_width:ho.optional()})),Iso=N.object({min_trace_width:Ui.optional(),min_board_edge_clearance:Ui.optional(),min_via_hole_edge_to_via_hole_edge_clearance:Ui.optional(),min_plated_hole_drill_edge_to_drill_edge_clearance:Ui.optional(),min_trace_to_pad_edge_clearance:Ui.optional(),min_pad_edge_to_pad_edge_clearance:Ui.optional(),min_same_net_trace_edge_to_trace_edge_clearance:Ui.optional(),min_different_net_trace_edge_to_trace_edge_clearance:Ui.optional(),min_via_hole_diameter:Ui.optional(),min_via_pad_diameter:Ui.optional()}),Cso=N.object({type:N.literal(\"pcb_component\"),pcb_component_id:Yo(\"pcb_component\"),source_component_id:N.string(),center:Lr,layer:Pc,rotation:jm,display_offset_x:N.string().optional().describe(\"How to display the x offset for this part, usually corresponding with how the user specified it\"),display_offset_y:N.string().optional().describe(\"How to display the y offset for this part, usually corresponding with how the user specified it\"),width:Ui,height:Ui,do_not_place:N.boolean().optional(),is_allowed_to_be_off_board:N.boolean().optional(),subcircuit_id:N.string().optional(),pcb_group_id:N.string().optional(),position_mode:N.enum([\"packed\",\"relative_to_group_anchor\",\"relative_to_another_component\",\"none\"]).optional(),anchor_position:Lr.optional(),anchor_alignment:hv.optional(),positioned_relative_to_pcb_group_id:N.string().optional(),positioned_relative_to_pcb_board_id:N.string().optional(),cable_insertion_center:Lr.optional(),insertion_direction:N.enum([\"from_above\",\"from_left\",\"from_right\",\"from_front\",\"from_back\"]).optional(),metadata:N.object({kicad_footprint:rro.optional()}).optional(),obstructs_within_bounds:N.boolean().default(!0).describe(\"Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath\")}).describe(\"Defines a component on the PCB\"),sEt=N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:Yo(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"circle\"),hole_diameter:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),aEt=(sEt.describe(\"Defines a circular hole on the PCB\"),N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:Yo(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"rect\"),hole_width:N.number(),hole_height:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),AEt=(aEt.describe(\"Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.\"),N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:Yo(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.enum([\"circle\",\"square\"]),hole_diameter:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),cEt=(AEt.describe(\"Defines a circular or square hole on the PCB\"),N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:Yo(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"oval\"),hole_width:N.number(),hole_height:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),lEt=(cEt.describe(\"Defines an oval hole on the PCB\"),N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:Yo(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"pill\"),hole_width:N.number(),hole_height:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),uEt=(lEt.describe(\"Defines a pill-shaped hole on the PCB\"),N.object({type:N.literal(\"pcb_hole\"),pcb_hole_id:Yo(\"pcb_hole\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal(\"rotated_pill\"),hole_width:N.number(),hole_height:N.number(),x:ho,y:ho,ccw_rotation:jm,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),yso=(uEt.describe(\"Defines a rotated pill-shaped hole on the PCB\"),AEt.or(cEt).or(lEt).or(uEt).or(sEt).or(aEt)),xso=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"circle\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),outer_diameter:N.number(),hole_diameter:N.number(),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo(\"pcb_plated_hole\"),soldermask_margin:N.number().optional()}),Eso=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.enum([\"oval\",\"pill\"]),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),outer_width:N.number(),outer_height:N.number(),hole_width:N.number(),hole_height:N.number(),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,ccw_rotation:jm,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo(\"pcb_plated_hole\"),soldermask_margin:N.number().optional()}),Bso=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"circular_hole_with_rect_pad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal(\"circle\"),pad_shape:N.literal(\"rect\"),hole_diameter:N.number(),rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),hole_offset_x:ho.default(0),hole_offset_y:ho.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo(\"pcb_plated_hole\"),soldermask_margin:N.number().optional(),rect_ccw_rotation:jm.optional()}),bso=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"pill_hole_with_rect_pad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal(\"pill\"),pad_shape:N.literal(\"rect\"),hole_width:N.number(),hole_height:N.number(),rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),hole_offset_x:ho.default(0),hole_offset_y:ho.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo(\"pcb_plated_hole\"),soldermask_margin:N.number().optional()}),Sso=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"rotated_pill_hole_with_rect_pad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal(\"rotated_pill\"),pad_shape:N.literal(\"rect\"),hole_width:N.number(),hole_height:N.number(),hole_ccw_rotation:jm,rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),rect_ccw_rotation:jm,hole_offset_x:ho.default(0),hole_offset_y:ho.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo(\"pcb_plated_hole\"),soldermask_margin:N.number().optional()}),Qso=N.object({type:N.literal(\"pcb_plated_hole\"),shape:N.literal(\"hole_with_polygon_pad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.enum([\"circle\",\"oval\",\"pill\",\"rotated_pill\"]),hole_diameter:N.number().optional(),hole_width:N.number().optional(),hole_height:N.number().optional(),pad_outline:N.array(N.object({x:ho,y:ho})).min(3),hole_offset_x:ho.default(0),hole_offset_y:ho.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo(\"pcb_plated_hole\"),soldermask_margin:N.number().optional(),ccw_rotation:jm.optional()}),vso=N.union([xso,Eso,Bso,bso,Sso,Qso]),wso=N.object({type:N.literal(\"pcb_port\"),pcb_port_id:Yo(\"pcb_port\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_port_id:N.string(),pcb_component_id:N.string().optional(),x:ho,y:ho,layers:N.array(Pc),is_board_pinout:N.boolean().optional()}).describe(\"Defines a port on the PCB\"),Pso=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"circle\"),pcb_smtpad_id:Yo(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,radius:N.number(),layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Mso=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"rect\"),pcb_smtpad_id:Yo(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),rect_border_radius:N.number().optional(),corner_radius:N.number().optional(),layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional(),soldermask_margin_left:N.number().optional(),soldermask_margin_top:N.number().optional(),soldermask_margin_right:N.number().optional(),soldermask_margin_bottom:N.number().optional()}),Dso=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"rotated_rect\"),pcb_smtpad_id:Yo(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),rect_border_radius:N.number().optional(),corner_radius:N.number().optional(),ccw_rotation:jm,layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional(),soldermask_margin_left:N.number().optional(),soldermask_margin_top:N.number().optional(),soldermask_margin_right:N.number().optional(),soldermask_margin_bottom:N.number().optional()}),Nso=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"pill\"),pcb_smtpad_id:Yo(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),radius:N.number(),layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Rso=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"rotated_pill\"),pcb_smtpad_id:Yo(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),radius:N.number(),ccw_rotation:jm,layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Tso=N.object({type:N.literal(\"pcb_smtpad\"),shape:N.literal(\"polygon\"),pcb_smtpad_id:Yo(\"pcb_smtpad\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),points:N.array(Lr),layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),kso=N.discriminatedUnion(\"shape\",[Pso,Mso,Dso,Rso,Nso,Tso]).describe(\"Defines an SMT pad on the PCB\"),Fso=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"circle\"),pcb_solder_paste_id:Yo(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,radius:N.number(),layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Lso=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"rect\"),pcb_solder_paste_id:Yo(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Hso=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"pill\"),pcb_solder_paste_id:Yo(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),radius:N.number(),layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Oso=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"rotated_rect\"),pcb_solder_paste_id:Yo(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),ccw_rotation:ho,layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Gso=N.object({type:N.literal(\"pcb_solder_paste\"),shape:N.literal(\"oval\"),pcb_solder_paste_id:Yo(\"pcb_solder_paste\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Yso=N.union([Fso,Lso,Hso,Oso,Gso]).describe(\"Defines solderpaste on the PCB\"),Uso=N.object({type:N.literal(\"pcb_text\"),pcb_text_id:Yo(\"pcb_text\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),text:N.string(),center:Lr,layer:Pc,width:Ui,height:Ui,lines:N.number(),align:N.enum([\"bottom-left\"])}).describe(\"Defines text on the PCB\"),Kso=N.object({route_type:N.literal(\"wire\"),x:ho,y:ho,width:ho,copper_pour_id:N.string().optional(),is_inside_copper_pour:N.boolean().optional(),start_pcb_port_id:N.string().optional(),end_pcb_port_id:N.string().optional(),layer:Pc}),Vso=N.object({route_type:N.literal(\"via\"),x:ho,y:ho,copper_pour_id:N.string().optional(),is_inside_copper_pour:N.boolean().optional(),hole_diameter:ho.optional(),outer_diameter:ho.optional(),from_layer:Pc,to_layer:Pc}),zso=N.union([Kso,Vso]),Jso=N.object({type:N.literal(\"pcb_trace\"),source_trace_id:N.string().optional(),pcb_component_id:N.string().optional(),pcb_trace_id:Yo(\"pcb_trace\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),route_thickness_mode:N.enum([\"constant\",\"interpolated\"]).default(\"constant\").optional(),route_order_index:N.number().optional(),should_round_corners:N.boolean().optional(),trace_length:N.number().optional(),highlight_color:N.string().optional(),route:N.array(zso)}).describe(\"Defines a trace on the PCB\"),Wso=N.object({type:N.literal(\"pcb_trace_warning\"),pcb_trace_warning_id:Yo(\"pcb_trace_warning\"),warning_type:N.literal(\"pcb_trace_warning\").default(\"pcb_trace_warning\"),message:N.string(),center:Lr.optional(),pcb_trace_id:N.string(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines a trace warning on the PCB\"),jso=N0.extend({type:N.literal(\"pcb_trace_error\"),pcb_trace_error_id:Yo(\"pcb_trace_error\"),error_type:N.literal(\"pcb_trace_error\").default(\"pcb_trace_error\"),center:Lr.optional(),pcb_trace_id:N.string(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines a trace error on the PCB\"),$so=N0.extend({type:N.literal(\"pcb_trace_missing_error\"),pcb_trace_missing_error_id:Yo(\"pcb_trace_missing_error\"),error_type:N.literal(\"pcb_trace_missing_error\").default(\"pcb_trace_missing_error\"),center:Lr.optional(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines an error when a source trace has no corresponding PCB trace\"),qso=N0.extend({type:N.literal(\"pcb_port_not_matched_error\"),pcb_error_id:Yo(\"pcb_error\"),error_type:N.literal(\"pcb_port_not_matched_error\").default(\"pcb_port_not_matched_error\"),pcb_component_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines a trace error on the PCB where a port is not matched\"),Xso=N0.extend({type:N.literal(\"pcb_port_not_connected_error\"),pcb_port_not_connected_error_id:Yo(\"pcb_port_not_connected_error\"),error_type:N.literal(\"pcb_port_not_connected_error\").default(\"pcb_port_not_connected_error\"),pcb_port_ids:N.array(N.string()),pcb_component_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe(\"Defines an error when a pcb port is not connected to any trace\"),Zso=N.object({type:N.literal(\"pcb_net\"),pcb_net_id:Yo(\"pcb_net\"),source_net_id:N.string().optional(),highlight_color:N.string().optional()}).describe(\"Defines a net on the PCB\"),eao=N.object({type:N.literal(\"pcb_via\"),pcb_via_id:Yo(\"pcb_via\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),x:ho,y:ho,outer_diameter:ho.default(\"0.6mm\"),hole_diameter:ho.default(\"0.25mm\"),from_layer:Pc.optional(),to_layer:Pc.optional(),layers:N.array(Pc),pcb_trace_id:N.string().optional(),net_is_assignable:N.boolean().optional(),net_assigned:N.boolean().optional(),is_tented:N.boolean().optional()}).describe(\"Defines a via on the PCB\"),tao=N.object({type:N.literal(\"pcb_board\"),pcb_board_id:Yo(\"pcb_board\"),pcb_panel_id:N.string().optional(),carrier_pcb_board_id:N.string().optional(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),is_mounted_to_carrier_board:N.boolean().optional(),width:Ui.optional(),height:Ui.optional(),center:Lr,display_offset_x:N.string().optional().describe(\"How to display the x offset for this board, usually corresponding with how the user specified it\"),display_offset_y:N.string().optional().describe(\"How to display the y offset for this board, usually corresponding with how the user specified it\"),thickness:Ui.optional().default(1.4),num_layers:N.number().optional().default(4),outline:N.array(Lr).optional(),shape:N.enum([\"rect\",\"polygon\"]).optional(),material:N.enum([\"fr4\",\"fr1\"]).default(\"fr4\"),anchor_position:Lr.optional(),anchor_alignment:hv.optional(),position_mode:N.enum([\"relative_to_panel_anchor\",\"none\"]).optional()}).merge(Iso).describe(\"Defines the board outline of the PCB\"),nao=N.object({type:N.literal(\"pcb_panel\"),pcb_panel_id:Yo(\"pcb_panel\"),width:Ui,height:Ui,center:Lr,thickness:Ui.optional().default(1.4),covered_with_solder_mask:N.boolean().optional().default(!0)}).describe(\"Defines a PCB panel that can contain multiple boards\"),oao=N0.extend({type:N.literal(\"pcb_placement_error\"),pcb_placement_error_id:Yo(\"pcb_placement_error\"),error_type:N.literal(\"pcb_placement_error\").default(\"pcb_placement_error\"),subcircuit_id:N.string().optional()}).describe(\"Defines a placement error on the PCB\"),iao=N0.extend({type:N.literal(\"pcb_panelization_placement_error\"),pcb_panelization_placement_error_id:Yo(\"pcb_panelization_placement_error\"),error_type:N.literal(\"pcb_panelization_placement_error\").default(\"pcb_panelization_placement_error\"),pcb_panel_id:N.string().optional(),pcb_board_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Defines a panelization placement error on the PCB\"),rao=N.object({type:N.literal(\"pcb_trace_hint\"),pcb_trace_hint_id:Yo(\"pcb_trace_hint\"),pcb_port_id:N.string(),pcb_component_id:N.string(),route:N.array(fso),subcircuit_id:N.string().optional()}).describe(\"A hint that can be used during generation of a PCB trace\"),sao=N.object({type:N.literal(\"pcb_silkscreen_line\"),pcb_silkscreen_line_id:Yo(\"pcb_silkscreen_line\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),stroke_width:ho.default(\"0.1mm\"),x1:ho,y1:ho,x2:ho,y2:ho,layer:mC}).describe(\"Defines a silkscreen line on the PCB\"),aao=N.object({type:N.literal(\"pcb_silkscreen_path\"),pcb_silkscreen_path_id:Yo(\"pcb_silkscreen_path\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:mC,route:N.array(Lr),stroke_width:Ui}).describe(\"Defines a silkscreen path on the PCB\"),Aao=N.object({type:N.literal(\"pcb_silkscreen_text\"),pcb_silkscreen_text_id:Yo(\"pcb_silkscreen_text\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:ho.default(\"0.2mm\"),pcb_component_id:N.string(),text:N.string(),is_knockout:N.boolean().default(!1).optional(),knockout_padding:N.object({left:Ui,top:Ui,bottom:Ui,right:Ui}).default({left:\"0.2mm\",top:\"0.2mm\",bottom:\"0.2mm\",right:\"0.2mm\"}).optional(),ccw_rotation:N.number().optional(),layer:Pc,is_mirrored:N.boolean().default(!1).optional(),anchor_position:Lr.default({x:0,y:0}),anchor_alignment:hv.default(\"center\")}).describe(\"Defines silkscreen text on the PCB\"),cao=N.object({type:N.literal(\"pcb_copper_text\"),pcb_copper_text_id:Yo(\"pcb_copper_text\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:ho.default(\"0.2mm\"),pcb_component_id:N.string(),text:N.string(),is_knockout:N.boolean().default(!1).optional(),knockout_padding:N.object({left:Ui,top:Ui,bottom:Ui,right:Ui}).default({left:\"0.2mm\",top:\"0.2mm\",bottom:\"0.2mm\",right:\"0.2mm\"}).optional(),ccw_rotation:N.number().optional(),layer:Pc,is_mirrored:N.boolean().default(!1).optional(),anchor_position:Lr.default({x:0,y:0}),anchor_alignment:hv.default(\"center\")}).describe(\"Defines copper text on the PCB\"),lao=N.object({type:N.literal(\"pcb_silkscreen_rect\"),pcb_silkscreen_rect_id:Yo(\"pcb_silkscreen_rect\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:Pc,stroke_width:Ui.default(\"1mm\"),corner_radius:Ui.optional(),is_filled:N.boolean().default(!0).optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),ccw_rotation:N.number().optional()}).describe(\"Defines a silkscreen rect on the PCB\"),uao=N.object({type:N.literal(\"pcb_silkscreen_circle\"),pcb_silkscreen_circle_id:Yo(\"pcb_silkscreen_circle\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,radius:Ui,layer:mC,stroke_width:Ui.default(\"1mm\"),is_filled:N.boolean().optional()}).describe(\"Defines a silkscreen circle on the PCB\"),gao=N.object({type:N.literal(\"pcb_silkscreen_oval\"),pcb_silkscreen_oval_id:Yo(\"pcb_silkscreen_oval\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,radius_x:ho,radius_y:ho,layer:mC,ccw_rotation:jm.optional()}).describe(\"Defines a silkscreen oval on the PCB\"),dao=N.object({type:N.literal(\"pcb_silkscreen_pill\"),pcb_silkscreen_pill_id:Yo(\"pcb_silkscreen_pill\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:Pc,ccw_rotation:N.number().optional()}).describe(\"Defines a silkscreen pill on the PCB\"),hao=N.object({type:N.literal(\"pcb_fabrication_note_text\"),pcb_fabrication_note_text_id:Yo(\"pcb_fabrication_note_text\"),subcircuit_id:N.string().optional(),pcb_group_id:N.string().optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:ho.default(\"1mm\"),pcb_component_id:N.string(),text:N.string(),layer:mC,anchor_position:Lr.default({x:0,y:0}),anchor_alignment:N.enum([\"center\",\"top_left\",\"top_right\",\"bottom_left\",\"bottom_right\"]).default(\"center\"),color:N.string().optional()}).describe(\"Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators\"),pao=N.object({type:N.literal(\"pcb_fabrication_note_path\"),pcb_fabrication_note_path_id:Yo(\"pcb_fabrication_note_path\"),pcb_component_id:N.string(),subcircuit_id:N.string().optional(),layer:Pc,route:N.array(Lr),stroke_width:Ui,color:N.string().optional()}).describe(\"Defines a fabrication path on the PCB for fabricators or assemblers\"),mao=N.object({type:N.literal(\"pcb_fabrication_note_rect\"),pcb_fabrication_note_rect_id:Yo(\"pcb_fabrication_note_rect\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:mC,stroke_width:Ui.default(\"0.1mm\"),corner_radius:Ui.optional(),is_filled:N.boolean().optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),color:N.string().optional()}).describe(\"Defines a fabrication note rectangle on the PCB\"),_ao=N.object({type:N.literal(\"pcb_fabrication_note_dimension\"),pcb_fabrication_note_dimension_id:Yo(\"pcb_fabrication_note_dimension\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:mC,from:Lr,to:Lr,text:N.string().optional(),text_ccw_rotation:N.number().optional(),offset:Ui.optional(),offset_distance:Ui.optional(),offset_direction:N.object({x:N.number(),y:N.number()}).optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:Ui.default(\"1mm\"),color:N.string().optional(),arrow_size:Ui.default(\"1mm\")}).describe(\"Defines a measurement annotation within PCB fabrication notes\"),fao=N.object({type:N.literal(\"pcb_note_text\"),pcb_note_text_id:Yo(\"pcb_note_text\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:ho.default(\"1mm\"),text:N.string().optional(),anchor_position:Lr.default({x:0,y:0}),anchor_alignment:N.enum([\"center\",\"top_left\",\"top_right\",\"bottom_left\",\"bottom_right\"]).default(\"center\"),layer:mC.default(\"top\"),is_mirrored_from_top_view:N.boolean().optional(),color:N.string().optional()}).describe(\"Defines a documentation note in text on the PCB\"),Iao=N.object({type:N.literal(\"pcb_note_rect\"),pcb_note_rect_id:Yo(\"pcb_note_rect\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:mC.default(\"top\"),stroke_width:Ui.default(\"0.1mm\"),corner_radius:Ui.optional(),is_filled:N.boolean().optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),color:N.string().optional()}).describe(\"Defines a rectangular documentation note on the PCB\"),Cao=N.object({type:N.literal(\"pcb_note_path\"),pcb_note_path_id:Yo(\"pcb_note_path\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),route:N.array(Lr),layer:mC.default(\"top\"),stroke_width:Ui.default(\"0.1mm\"),color:N.string().optional()}).describe(\"Defines a polyline documentation note on the PCB\"),yao=N.object({type:N.literal(\"pcb_note_line\"),pcb_note_line_id:Yo(\"pcb_note_line\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),x1:ho,y1:ho,x2:ho,y2:ho,layer:mC.default(\"top\"),stroke_width:ho.default(\"0.1mm\"),color:N.string().optional(),is_dashed:N.boolean().optional()}).describe(\"Defines a straight documentation note line on the PCB\"),xao=N.object({type:N.literal(\"pcb_note_dimension\"),pcb_note_dimension_id:Yo(\"pcb_note_dimension\"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),from:Lr,to:Lr,text:N.string().optional(),text_ccw_rotation:N.number().optional(),offset_distance:Ui.optional(),offset_direction:N.object({x:N.number(),y:N.number()}).optional(),font:N.literal(\"tscircuit2024\").default(\"tscircuit2024\"),font_size:Ui.default(\"1mm\"),layer:mC.default(\"top\"),color:N.string().optional(),arrow_size:Ui.default(\"1mm\")}).describe(\"Defines a measurement annotation within PCB documentation notes\"),Eao=N0.extend({type:N.literal(\"pcb_footprint_overlap_error\"),pcb_error_id:Yo(\"pcb_error\"),error_type:N.literal(\"pcb_footprint_overlap_error\").default(\"pcb_footprint_overlap_error\"),pcb_smtpad_ids:N.array(N.string()).optional(),pcb_plated_hole_ids:N.array(N.string()).optional(),pcb_hole_ids:N.array(N.string()).optional(),pcb_keepout_ids:N.array(N.string()).optional()}).describe(\"Error emitted when a pcb footprint overlaps with another element\"),Bao=N0.extend({type:N.literal(\"pcb_courtyard_overlap_error\"),pcb_error_id:Yo(\"pcb_error\"),error_type:N.literal(\"pcb_courtyard_overlap_error\").default(\"pcb_courtyard_overlap_error\"),pcb_component_ids:N.tuple([N.string(),N.string()])}).describe(\"Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another\"),bao=N.object({type:N.literal(\"pcb_keepout\"),shape:N.literal(\"rect\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:ho,height:ho,pcb_keepout_id:N.string(),layers:N.array(N.string()),description:N.string().optional()}).or(N.object({type:N.literal(\"pcb_keepout\"),shape:N.literal(\"circle\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,radius:ho,pcb_keepout_id:N.string(),layers:N.array(N.string()),description:N.string().optional()})),uAe=N.object({type:N.literal(\"pcb_cutout\"),pcb_cutout_id:Yo(\"pcb_cutout\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_board_id:N.string().optional(),pcb_panel_id:N.string().optional()}),Sao=uAe.extend({shape:N.literal(\"rect\"),center:Lr,width:Ui,height:Ui,rotation:jm.optional(),corner_radius:Ui.optional()}),Qao=uAe.extend({shape:N.literal(\"circle\"),center:Lr,radius:Ui}),vao=uAe.extend({shape:N.literal(\"polygon\"),points:N.array(Lr)}),wao=uAe.extend({shape:N.literal(\"path\"),route:N.array(Lr),slot_width:Ui,slot_length:Ui.optional(),space_between_slots:Ui.optional(),slot_corner_radius:Ui.optional()}),Pao=N.discriminatedUnion(\"shape\",[Sao,Qao,vao,wao]).describe(\"Defines a cutout on the PCB, removing board material.\"),Mao=N0.extend({type:N.literal(\"pcb_missing_footprint_error\"),pcb_missing_footprint_error_id:Yo(\"pcb_missing_footprint_error\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal(\"pcb_missing_footprint_error\").default(\"pcb_missing_footprint_error\"),source_component_id:N.string()}).describe(\"Defines a missing footprint error on the PCB\"),Dao=N0.extend({type:N.literal(\"external_footprint_load_error\"),external_footprint_load_error_id:Yo(\"external_footprint_load_error\"),pcb_component_id:N.string(),source_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),footprinter_string:N.string().optional(),error_type:N.literal(\"external_footprint_load_error\").default(\"external_footprint_load_error\")}).describe(\"Defines an error when an external footprint fails to load\"),Nao=N0.extend({type:N.literal(\"circuit_json_footprint_load_error\"),circuit_json_footprint_load_error_id:Yo(\"circuit_json_footprint_load_error\"),pcb_component_id:N.string(),source_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal(\"circuit_json_footprint_load_error\").default(\"circuit_json_footprint_load_error\"),circuit_json:N.array(N.any()).optional()}).describe(\"Defines an error when a circuit JSON footprint fails to load\"),Rao=N.object({type:N.literal(\"pcb_group\"),pcb_group_id:Yo(\"pcb_group\"),source_group_id:N.string(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),width:Ui.optional(),height:Ui.optional(),center:Lr,display_offset_x:N.string().optional().describe(\"How to display the x offset for this group, usually corresponding with how the user specified it\"),display_offset_y:N.string().optional().describe(\"How to display the y offset for this group, usually corresponding with how the user specified it\"),outline:N.array(Lr).optional(),anchor_position:Lr.optional(),anchor_alignment:hv.default(\"center\"),position_mode:N.enum([\"packed\",\"relative_to_group_anchor\",\"none\"]).optional(),positioned_relative_to_pcb_group_id:N.string().optional(),positioned_relative_to_pcb_board_id:N.string().optional(),pcb_component_ids:N.array(N.string()),child_layout_mode:N.enum([\"packed\",\"none\"]).optional(),name:N.string().optional(),description:N.string().optional(),layout_mode:N.string().optional(),autorouter_configuration:N.object({trace_clearance:Ui}).optional(),autorouter_used_string:N.string().optional()}).describe(\"Defines a group of components on the PCB\"),Tao=N0.extend({type:N.literal(\"pcb_autorouting_error\"),pcb_error_id:Yo(\"pcb_autorouting_error\"),error_type:N.literal(\"pcb_autorouting_error\").default(\"pcb_autorouting_error\"),subcircuit_id:N.string().optional()}).describe(\"The autorouting has failed to route a portion of the board\"),kao=N.object({type:N.literal(\"pcb_manual_edit_conflict_warning\"),pcb_manual_edit_conflict_warning_id:Yo(\"pcb_manual_edit_conflict_warning\"),warning_type:N.literal(\"pcb_manual_edit_conflict_warning\").default(\"pcb_manual_edit_conflict_warning\"),message:N.string(),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_component_id:N.string()}).describe(\"Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates\"),gEt=N.enum([\"x-\",\"x+\",\"y+\",\"y-\"]),Fao=N.object({type:N.literal(\"pcb_connector_not_in_accessible_orientation_warning\"),pcb_connector_not_in_accessible_orientation_warning_id:Yo(\"pcb_connector_not_in_accessible_orientation_warning\"),warning_type:N.literal(\"pcb_connector_not_in_accessible_orientation_warning\").default(\"pcb_connector_not_in_accessible_orientation_warning\"),message:N.string(),pcb_component_id:N.string(),source_component_id:N.string().optional(),pcb_board_id:N.string().optional(),facing_direction:gEt,recommended_facing_direction:gEt,subcircuit_id:N.string().optional()}).describe(\"Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction\"),Lao=N.object({type:N.literal(\"supplier_footprint_mismatch_warning\"),supplier_footprint_mismatch_warning_id:Yo(\"supplier_footprint_mismatch_warning\"),warning_type:N.literal(\"supplier_footprint_mismatch_warning\").default(\"supplier_footprint_mismatch_warning\"),message:N.string(),source_component_id:N.string(),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),supplier_name:R3t.optional(),supplier_part_number:N.string().optional(),supplier_footprint_url:N.string().optional(),footprint_copper_intersection_over_union:N.number()}).describe(\"Warning emitted when a supplier part footprint does not match the expected footprint\"),Hao=N.object({type:N.literal(\"pcb_breakout_point\"),pcb_breakout_point_id:Yo(\"pcb_breakout_point\"),pcb_group_id:N.string(),subcircuit_id:N.string().optional(),source_trace_id:N.string().optional(),source_port_id:N.string().optional(),source_net_id:N.string().optional(),x:ho,y:ho}).describe(\"Defines a routing target within a pcb_group for a source_trace or source_net\"),Oao=N.object({type:N.literal(\"pcb_ground_plane\"),pcb_ground_plane_id:Yo(\"pcb_ground_plane\"),source_pcb_ground_plane_id:N.string(),source_net_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Defines a ground plane on the PCB\"),Gao=N.object({type:N.literal(\"pcb_ground_plane_region\"),pcb_ground_plane_region_id:Yo(\"pcb_ground_plane_region\"),pcb_ground_plane_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:Pc,points:N.array(Lr)}).describe(\"Defines a polygon region of a ground plane\"),Yao=N.object({type:N.literal(\"pcb_thermal_spoke\"),pcb_thermal_spoke_id:Yo(\"pcb_thermal_spoke\"),pcb_ground_plane_id:N.string(),shape:N.string(),spoke_count:N.number(),spoke_thickness:ho,spoke_inner_diameter:ho,spoke_outer_diameter:ho,pcb_plated_hole_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Pattern for connecting a ground plane to a plated hole\"),cbe=N.object({type:N.literal(\"pcb_copper_pour\"),pcb_copper_pour_id:Yo(\"pcb_copper_pour\"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:Pc,source_net_id:N.string().optional(),covered_with_solder_mask:N.boolean().optional().default(!0)}),Uao=cbe.extend({shape:N.literal(\"rect\"),center:Lr,width:Ui,height:Ui,rotation:jm.optional()}),Kao=cbe.extend({shape:N.literal(\"brep\"),brep_shape:mso}),Vao=cbe.extend({shape:N.literal(\"polygon\"),points:N.array(Lr)}),zao=N.discriminatedUnion(\"shape\",[Uao,Kao,Vao]).describe(\"Defines a copper pour on the PCB.\"),Jao=N0.extend({type:N.literal(\"pcb_component_outside_board_error\"),pcb_component_outside_board_error_id:Yo(\"pcb_component_outside_board_error\"),error_type:N.literal(\"pcb_component_outside_board_error\").default(\"pcb_component_outside_board_error\"),pcb_component_id:N.string(),pcb_board_id:N.string(),component_center:Lr,component_bounds:N.object({min_x:N.number(),max_x:N.number(),min_y:N.number(),max_y:N.number()}),subcircuit_id:N.string().optional(),source_component_id:N.string().optional()}).describe(\"Error emitted when a PCB component is placed outside the board boundaries\"),Wao=N0.extend({type:N.literal(\"pcb_component_not_on_board_edge_error\"),pcb_component_not_on_board_edge_error_id:Yo(\"pcb_component_not_on_board_edge_error\"),error_type:N.literal(\"pcb_component_not_on_board_edge_error\").default(\"pcb_component_not_on_board_edge_error\"),pcb_component_id:N.string(),pcb_board_id:N.string(),component_center:Lr,pad_to_nearest_board_edge_distance:N.number(),source_component_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when a component that must be placed on the board edge is centered away from the edge\"),jao=N0.extend({type:N.literal(\"pcb_component_invalid_layer_error\"),pcb_component_invalid_layer_error_id:Yo(\"pcb_component_invalid_layer_error\"),error_type:N.literal(\"pcb_component_invalid_layer_error\").default(\"pcb_component_invalid_layer_error\"),pcb_component_id:N.string().optional(),source_component_id:N.string(),layer:Pc,subcircuit_id:N.string().optional()}).describe(\"Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)\"),$ao=N0.extend({type:N.literal(\"pcb_via_clearance_error\"),pcb_error_id:Yo(\"pcb_error\"),error_type:N.literal(\"pcb_via_clearance_error\").default(\"pcb_via_clearance_error\"),pcb_via_ids:N.array(N.string()).min(2),minimum_clearance:ho.optional(),actual_clearance:ho.optional(),pcb_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when vias are closer than the allowed clearance\"),qao=N0.extend({type:N.literal(\"pcb_via_trace_clearance_error\"),pcb_via_trace_clearance_error_id:Yo(\"pcb_via_trace_clearance_error\"),error_type:N.literal(\"pcb_via_trace_clearance_error\").default(\"pcb_via_trace_clearance_error\"),pcb_via_id:N.string(),pcb_trace_id:N.string(),minimum_clearance:ho.optional(),actual_clearance:ho.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when a via and trace are closer than the allowed clearance\"),Xao=N0.extend({type:N.literal(\"pcb_pad_pad_clearance_error\"),pcb_pad_pad_clearance_error_id:Yo(\"pcb_pad_pad_clearance_error\"),error_type:N.literal(\"pcb_pad_pad_clearance_error\").default(\"pcb_pad_pad_clearance_error\"),pcb_pad_ids:N.array(N.string()).min(2),minimum_clearance:ho.optional(),actual_clearance:ho.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when pads are closer than the allowed clearance\"),Zao=N0.extend({type:N.literal(\"pcb_pad_trace_clearance_error\"),pcb_pad_trace_clearance_error_id:Yo(\"pcb_pad_trace_clearance_error\"),error_type:N.literal(\"pcb_pad_trace_clearance_error\").default(\"pcb_pad_trace_clearance_error\"),pcb_pad_id:N.string(),pcb_trace_id:N.string(),minimum_clearance:ho.optional(),actual_clearance:ho.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe(\"Error emitted when a pad and trace are closer than allowed clearance\"),eAo=N.object({type:N.literal(\"pcb_courtyard_rect\"),pcb_courtyard_rect_id:Yo(\"pcb_courtyard_rect\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:mC,ccw_rotation:jm.optional(),color:N.string().optional()}).describe(\"Defines a courtyard rectangle on the PCB\"),tAo=N.object({type:N.literal(\"pcb_courtyard_outline\"),pcb_courtyard_outline_id:Yo(\"pcb_courtyard_outline\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:mC,outline:N.array(Lr).min(2)}).describe(\"Defines a courtyard outline on the PCB\"),nAo=N.object({type:N.literal(\"pcb_courtyard_polygon\"),pcb_courtyard_polygon_id:Yo(\"pcb_courtyard_polygon\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:mC,points:N.array(Lr).min(3),color:N.string().optional()}).describe(\"Defines a courtyard polygon on the PCB\"),oAo=N.object({type:N.literal(\"pcb_courtyard_circle\"),pcb_courtyard_circle_id:Yo(\"pcb_courtyard_circle\"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,radius:Ui,layer:mC,color:N.string().optional()}).describe(\"Defines a courtyard circle on the PCB\"),iAo=N.object({type:N.literal(\"cad_component\"),cad_component_id:N.string(),pcb_component_id:N.string(),source_component_id:N.string(),position:nN,rotation:nN.optional(),size:nN.optional(),layer:Pc.optional(),subcircuit_id:N.string().optional(),footprinter_string:N.string().optional(),model_obj_url:N.string().optional(),model_stl_url:N.string().optional(),model_3mf_url:N.string().optional(),model_gltf_url:N.string().optional(),model_glb_url:N.string().optional(),model_step_url:N.string().optional(),model_wrl_url:N.string().optional(),model_asset:Zio.optional(),model_unit_to_mm_scale_factor:N.number().optional(),model_board_normal_direction:N.enum([\"x+\",\"x-\",\"y+\",\"y-\",\"z+\",\"z-\"]).optional().describe(`The direction in the model's coordinate space that is considered \"up\" or \"coming out of the board surface\"`),model_origin_position:nN.optional(),model_origin_alignment:N.enum([\"unknown\",\"center\",\"center_of_component_on_board_surface\",\"bottom_center_of_component\"]).optional(),model_object_fit:N.enum([\"contain_within_bounds\",\"fill_bounds\"]).optional().default(\"contain_within_bounds\"),model_jscad:N.any().optional(),show_as_translucent_model:N.boolean().optional(),anchor_alignment:N.enum([\"center\",\"center_of_component_on_board_surface\"]).optional().default(\"center\")}).describe(\"Defines a component on the PCB\"),dEt=N.enum([\"sinewave\",\"square\",\"triangle\",\"sawtooth\"]),rAo=N.union([N.string(),N.number()]).transform(t=\u003etypeof t==\"string\"?t.endsWith(\"%\")?parseFloat(t.slice(0,-1))/100:parseFloat(t):t).pipe(N.number().min(0,\"Duty cycle must be non-negative\").max(1,\"Duty cycle cannot be greater than 100%\")),sAo=N.object({type:N.literal(\"simulation_voltage_source\"),simulation_voltage_source_id:Yo(\"simulation_voltage_source\"),is_dc_source:N.literal(!0).optional().default(!0),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),voltage:dv}).describe(\"Defines a DC voltage source for simulation\"),aAo=N.object({type:N.literal(\"simulation_voltage_source\"),simulation_voltage_source_id:Yo(\"simulation_voltage_source\"),is_dc_source:N.literal(!1),terminal1_source_port_id:N.string().optional(),terminal2_source_port_id:N.string().optional(),terminal1_source_net_id:N.string().optional(),terminal2_source_net_id:N.string().optional(),voltage:dv.optional(),frequency:PL.optional(),peak_to_peak_voltage:dv.optional(),wave_shape:dEt.optional(),phase:jm.optional(),duty_cycle:rAo.optional()}).describe(\"Defines an AC voltage source for simulation\"),AAo=N.union([sAo,aAo]).describe(\"Defines a voltage source for simulation\"),cAo=N.union([N.string(),N.number()]).transform(t=\u003etypeof t==\"string\"?t.endsWith(\"%\")?parseFloat(t.slice(0,-1))/100:parseFloat(t):t).pipe(N.number().min(0,\"Duty cycle must be non-negative\").max(1,\"Duty cycle cannot be greater than 100%\")),lAo=N.object({type:N.literal(\"simulation_current_source\"),simulation_current_source_id:Yo(\"simulation_current_source\"),is_dc_source:N.literal(!0).optional().default(!0),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),current:HJ}).describe(\"Defines a DC current source for simulation\"),uAo=N.object({type:N.literal(\"simulation_current_source\"),simulation_current_source_id:Yo(\"simulation_current_source\"),is_dc_source:N.literal(!1),terminal1_source_port_id:N.string().optional(),terminal2_source_port_id:N.string().optional(),terminal1_source_net_id:N.string().optional(),terminal2_source_net_id:N.string().optional(),current:HJ.optional(),frequency:PL.optional(),peak_to_peak_current:HJ.optional(),wave_shape:dEt.optional(),phase:jm.optional(),duty_cycle:cAo.optional()}).describe(\"Defines an AC current source for simulation\"),gAo=N.union([lAo,uAo]).describe(\"Defines a current source for simulation\"),dAo=N.union([N.literal(\"spice_dc_sweep\"),N.literal(\"spice_dc_operating_point\"),N.literal(\"spice_transient_analysis\"),N.literal(\"spice_ac_analysis\")]),hAo=N.object({type:N.literal(\"simulation_experiment\"),simulation_experiment_id:Yo(\"simulation_experiment\"),name:N.string(),experiment_type:dAo,time_per_step:rbe.optional(),start_time_ms:ML.optional(),end_time_ms:ML.optional()}).describe(\"Defines a simulation experiment configuration\"),pAo=N.object({type:N.literal(\"simulation_transient_voltage_graph\"),simulation_transient_voltage_graph_id:Yo(\"simulation_transient_voltage_graph\"),simulation_experiment_id:N.string(),timestamps_ms:N.array(N.number()).optional(),voltage_levels:N.array(N.number()),source_component_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),time_per_step:rbe,start_time_ms:ML,end_time_ms:ML,name:N.string().optional(),color:N.string().optional()}).describe(\"Stores voltage measurements over time for a simulation\"),mAo=N.object({type:N.literal(\"simulation_switch\"),simulation_switch_id:Yo(\"simulation_switch\"),source_component_id:N.string().optional(),closes_at:ML.optional(),opens_at:ML.optional(),starts_closed:N.boolean().optional(),switching_frequency:PL.optional()}).describe(\"Defines a switch for simulation timing control\"),_Ao=N.object({type:N.literal(\"simulation_voltage_probe\"),simulation_voltage_probe_id:Yo(\"simulation_voltage_probe\"),source_component_id:N.string().optional(),name:N.string().optional(),signal_input_source_port_id:N.string().optional(),signal_input_source_net_id:N.string().optional(),reference_input_source_port_id:N.string().optional(),reference_input_source_net_id:N.string().optional(),subcircuit_id:N.string().optional(),color:N.string().optional()}).describe(\"Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.\").superRefine((t,e)=\u003e{if(t.reference_input_source_port_id||t.reference_input_source_net_id){const n=!!t.signal_input_source_port_id||!!t.reference_input_source_port_id,o=!!t.signal_input_source_net_id||!!t.reference_input_source_net_id;n\u0026\u0026o?e.addIssue({code:N.ZodIssueCode.custom,message:\"Cannot mix port and net connections in a differential probe.\"}):n?t.signal_input_source_port_id\u0026\u0026t.reference_input_source_port_id||e.addIssue({code:N.ZodIssueCode.custom,message:\"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id.\"}):o\u0026\u0026(t.signal_input_source_net_id\u0026\u0026t.reference_input_source_net_id||e.addIssue({code:N.ZodIssueCode.custom,message:\"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id.\"}))}else!!t.signal_input_source_port_id==!!t.signal_input_source_net_id\u0026\u0026e.addIssue({code:N.ZodIssueCode.custom,message:\"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id.\"})}),fAo=N0.extend({type:N.literal(\"simulation_unknown_experiment_error\"),simulation_unknown_experiment_error_id:Yo(\"simulation_unknown_experiment_error\"),error_type:N.literal(\"simulation_unknown_experiment_error\").default(\"simulation_unknown_experiment_error\"),simulation_experiment_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe(\"An unknown error occurred during the simulation experiment.\"),IAo=N.object({type:N.literal(\"simulation_op_amp\"),simulation_op_amp_id:Yo(\"simulation_op_amp\"),source_component_id:N.string().optional(),inverting_input_source_port_id:N.string(),non_inverting_input_source_port_id:N.string(),output_source_port_id:N.string(),positive_supply_source_port_id:N.string(),negative_supply_source_port_id:N.string()}).describe(\"Defines a simple ideal operational amplifier for simulation\"),hEt=(N.union([Qro,bro,Sro,Bro,wro,vro,L3t,T3t,abe,F3t,k3t,H3t,O3t,G3t,K3t,V3t,z3t,q3t,J3t,W3t,j3t,$3t,U3t,Y3t,Dro,Nro,Pro,X3t,Z3t,eEt,tEt,nEt,Rro,Tro,kro,Fro,Lro,oEt,Mro,Cso,yso,Mao,Dao,Nao,kao,Fao,Lao,vso,bao,wso,Zso,Uso,Jso,Wso,eao,kso,Yso,tao,nao,Rao,rao,sao,aao,Aao,dao,cao,lao,uao,gao,jso,$so,oao,iao,qso,Xso,$ao,qao,Xao,Zao,pao,hao,mao,_ao,fao,Iao,Cao,yao,xao,Tao,Eao,Bao,Hao,Pao,Oao,Gao,Yao,zao,Jao,Wao,jao,eAo,tAo,nAo,oAo,Hro,eso,Wro,jro,$ro,qro,Vro,Jro,tso,Xro,Oro,oso,iso,nso,Aso,cso,lso,uso,hso,gso,dso,iAo,AAo,gAo,hAo,pAo,mAo,_Ao,fAo,IAo]),!0),OJ={CCW:-1,CW:1,NOT_ORIENTABLE:0},CAo=2*Math.PI,gAe=Object.freeze({__proto__:null,BOUNDARY:2,CCW:hEt,CONTAINS:3,CW:!1,END_VERTEX:2,INSIDE:1,INTERLACE:4,NOT_VERTEX:0,ORIENTATION:OJ,OUTSIDE:0,OVERLAP_OPPOSITE:2,OVERLAP_SAME:1,PIx2:CAo,START_VERTEX:1}),_7=1e-6;function pEt(t){_7=t}function mEt(){return _7}function lbe(t){return t\u003c_7\u0026\u0026t\u003e-_7}function iN(t,e){return t-e\u003c_7\u0026\u0026t-e\u003e-_7}function _Et(t,e){return t-e\u003e_7}function fEt(t,e){return t-e\u003c-_7}var Ke={Utils:Object.freeze({__proto__:null,DECIMALS:3,EQ:iN,EQ_0:lbe,GE:function(t,e){return t-e\u003e-_7},GT:_Et,LE:function(t,e){return t-e\u003c_7},LT:fEt,getTolerance:mEt,setTolerance:pEt}),Errors:void 0,Matrix:void 0,Planar_set:void 0,Point:void 0,Vector:void 0,Line:void 0,Circle:void 0,Segment:void 0,Arc:void 0,Box:void 0,Edge:void 0,Face:void 0,Ray:void 0,Ray_shooting:void 0,Multiline:void 0,Polygon:void 0,Distance:void 0,Inversion:void 0};for(let t in gAe)Ke[t]=gAe[t];Object.defineProperty(Ke,\"DP_TOL\",{get:function(){return mEt()},set:function(t){pEt(t)}});var ud=class{static get ILLEGAL_PARAMETERS(){return new ReferenceError(\"Illegal Parameters\")}static get ZERO_DIVISION(){return new Error(\"Zero division\")}static get UNRESOLVED_BOUNDARY_CONFLICT(){return new Error(\"Unresolved boundary conflict in boolean operation\")}static get INFINITE_LOOP(){return new Error(\"Infinite loop\")}static get CANNOT_COMPLETE_BOOLEAN_OPERATION(){return new Error(\"Cannot complete boolean operation\")}static get CANNOT_INVOKE_ABSTRACT_METHOD(){return new Error(\"Abstract method cannot be invoked\")}static get OPERATION_IS_NOT_SUPPORTED(){return new Error(\"Operation is not supported\")}static get UNSUPPORTED_SHAPE_TYPE(){return new Error(\"Unsupported shape type\")}};Ke.Errors=ud;var ube=class{constructor(t,e){this.first=t,this.last=e||this.first}[Symbol.iterator](){let t;return{next:()=\u003e(t=t?t.next:this.first,{value:t,done:t===void 0})}}get size(){let t=0;for(let e of this)t++;return t}toArray(t=void 0,e=void 0){let n=[],o=t||this.first,i=e||this.last,r=o;if(r===void 0)return n;do n.push(r),r=r.next;while(r!==i.next);return n}append(t){return this.isEmpty()?this.first=t:(t.prev=this.last,this.last.next=t),this.last=t,this.last.next=void 0,this.first.prev=void 0,this}insert(t,e){if(this.isEmpty())this.first=t,this.last=t;else if(e==null)t.next=this.first,this.first.prev=t,this.first=t;else{let n=e.next;e.next=t,n\u0026\u0026(n.prev=t),t.prev=e,t.next=n,this.last===e\u0026\u0026(this.last=t)}return this.last.next=void 0,this.first.prev=void 0,this}remove(t){return t===this.first\u0026\u0026t===this.last?(this.first=void 0,this.last=void 0):(t.prev\u0026\u0026(t.prev.next=t.next),t.next\u0026\u0026(t.next.prev=t.prev),t===this.first\u0026\u0026(this.first=t.next),t===this.last\u0026\u0026(this.last=t.prev)),this}isEmpty(){return this.first===void 0}static testInfiniteLoop(t){let e=t,n=t;do{if(e!=t\u0026\u0026e===n)throw ud.INFINITE_LOOP;e=e.next,n=n.next.next}while(e!=t)}},IEt={stroke:\"black\"},yAo=class{constructor(t=IEt){for(const e in t)this[e]=t[e];this.stroke=t.stroke??IEt.stroke}toAttributesString(){return Object.keys(this).reduce((t,e)=\u003et+(this[e]!==void 0?this.toAttrString(e,this[e]):\"\"),\"\")}toAttrString(t,e){const n=t===\"className\"?\"class\":this.convertCamelToKebabCase(t);return e===null?`${n} `:`${n}=\"${e.toString()}\" `}convertCamelToKebabCase(t){return t.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join(\"-\").toLowerCase()}};function rN(t){return new yAo(t).toAttributesString()}function DL(t,e){let n=[],[o,i,r]=t.standard,[s,a,A]=e.standard,c=o*a-i*s,l=r*a-i*A,u=o*A-r*s;if(!Ke.Utils.EQ_0(c)){let g,h;i===0?(g=r/o,h=u/c):a===0?(g=A/s,h=u/c):o===0?(g=l/c,h=r/i):s===0?(g=l/c,h=A/a):(g=l/c,h=u/c),n.push(new Ke.Point(g,h))}return n}function sN(t,e){let n=[],o=e.pc.projectionOn(t),i=e.pc.distanceTo(o)[0];if(Ke.Utils.EQ(i,e.r))n.push(o);else if(Ke.Utils.LT(i,e.r)){let r,s,a=Math.sqrt(e.r*e.r-i*i);r=t.norm.rotate90CCW().multiply(a),s=o.translate(r),n.push(s),r=t.norm.rotate90CW().multiply(a),s=o.translate(r),n.push(s)}return n}function NL(t,e){let n=[];for(let o of e.toSegments()){let i=GJ(o,t);for(let r of i)PEt(r,n)||n.push(r)}return n}function dAe(t,e){let n=[];if(NL(t,e.box).length===0)return n;let o=sN(t,new Ke.Circle(e.pc,e.r));for(let i of o)i.on(e)\u0026\u0026n.push(i);return n}function GJ(t,e){let n=[];return t.ps.on(e)\u0026\u0026n.push(t.ps),t.pe.on(e)\u0026\u0026!t.isZeroLength()\u0026\u0026n.push(t.pe),n.length\u003e0||t.isZeroLength()||t.ps.leftTo(e)\u0026\u0026t.pe.leftTo(e)||!t.ps.leftTo(e)\u0026\u0026!t.pe.leftTo(e)?n:DL(new Ke.Line(t.ps,t.pe),e)}function hAe(t,e){let n=[];if(t.isZeroLength())return t.ps.on(e)\u0026\u0026n.push(t.ps),n;if(e.isZeroLength())return e.ps.on(t)\u0026\u0026n.push(e.ps),n;let o=new Ke.Line(t.ps,t.pe),i=new Ke.Line(e.ps,e.pe);if(o.incidentTo(i))t.ps.on(e)\u0026\u0026n.push(t.ps),t.pe.on(e)\u0026\u0026n.push(t.pe),!e.ps.on(t)||e.ps.equalTo(t.ps)||e.ps.equalTo(t.pe)||n.push(e.ps),!e.pe.on(t)||e.pe.equalTo(t.ps)||e.pe.equalTo(t.pe)||n.push(e.pe);else if(o.parallelTo(i)){const r=new Ke.Vector(t.ps,t.pe),s=new Ke.Vector(e.ps,e.pe),a=new Ke.Vector(t.ps,e.ps),A=r.cross(s);if(!Ke.Utils.EQ_0(A)){const c=a.cross(s)/A,l=a.cross(r)/A;Ke.Utils.GE(c,0)\u0026\u0026Ke.Utils.LE(c,1)\u0026\u0026Ke.Utils.GE(l,0)\u0026\u0026Ke.Utils.LE(l,1)\u0026\u0026n.push(CEt(t.ps.translate(r.multiply(c)),t,e))}}else{let r=DL(o,i);r.length\u003e0\u0026\u0026yEt(r[0],t)\u0026\u0026yEt(r[0],e)\u0026\u0026n.push(CEt(r[0],t,e))}return n}function CEt(t,e,n){for(const o of[e.ps,e.pe,n.ps,n.pe])if(t.equalTo(o))return o;return t}function yEt(t,e){const n=e.box;return Ke.Utils.LE(t.x,n.xmax)\u0026\u0026Ke.Utils.GE(t.x,n.xmin)\u0026\u0026Ke.Utils.LE(t.y,n.ymax)\u0026\u0026Ke.Utils.GE(t.y,n.ymin)}function pAe(t,e){let n=[];if(t.isZeroLength()){let[i,r]=t.ps.distanceTo(e.pc);return Ke.Utils.EQ(i,e.r)\u0026\u0026n.push(t.ps),n}let o=sN(new Ke.Line(t.ps,t.pe),e);for(let i of o)i.on(t)\u0026\u0026n.push(i);return n}function RL(t,e){let n=[];if(t.isZeroLength())return t.ps.on(e)\u0026\u0026n.push(t.ps),n;let o=sN(new Ke.Line(t.ps,t.pe),new Ke.Circle(e.pc,e.r));for(let i of o)i.on(t)\u0026\u0026i.on(e)\u0026\u0026n.push(i);return n}function xEt(t,e){let n=[],o=new Ke.Vector(t.pc,e.pc),i=t.r,r=e.r;if(Ke.Utils.EQ_0(i)||Ke.Utils.EQ_0(r))return n;if(Ke.Utils.EQ_0(o.x)\u0026\u0026Ke.Utils.EQ_0(o.y)\u0026\u0026Ke.Utils.EQ(i,r))return n.push(t.pc.translate(-i,0)),n;let s,a=t.pc.distanceTo(e.pc)[0];if(Ke.Utils.GT(a,i+r)||Ke.Utils.LT(a,Math.abs(i-r)))return n;if(o.x/=a,o.y/=a,Ke.Utils.EQ(a,i+r)||Ke.Utils.EQ(a,Math.abs(i-r)))return s=t.pc.translate(i*o.x,i*o.y),n.push(s),n;let A=i*i/(2*a)-r*r/(2*a)+a/2,c=t.pc.translate(A*o.x,A*o.y),l=Math.sqrt(i*i-A*A);return s=c.translate(o.rotate90CCW().multiply(l)),n.push(s),s=c.translate(o.rotate90CW().multiply(l)),n.push(s),n}function EEt(t,e){let n=[];if(t.pc.equalTo(e.pc)\u0026\u0026Ke.Utils.EQ(t.r,e.r)){let s;return s=t.start,s.on(e)\u0026\u0026n.push(s),s=t.end,s.on(e)\u0026\u0026n.push(s),s=e.start,s.on(t)\u0026\u0026n.push(s),s=e.end,s.on(t)\u0026\u0026n.push(s),n}let o=new Ke.Circle(t.pc,t.r),i=new Ke.Circle(e.pc,e.r),r=o.intersect(i);for(let s of r)s.on(t)\u0026\u0026s.on(e)\u0026\u0026n.push(s);return n}function gbe(t,e){let n=[];if(e.pc.equalTo(t.pc)\u0026\u0026Ke.Utils.EQ(e.r,t.r))return n.push(t.start),n.push(t.end),n;let o=xEt(e,new Ke.Circle(t.pc,t.r));for(let i of o)i.on(t)\u0026\u0026n.push(i);return n}function BEt(t,e){return t.isSegment?hAe(t.shape,e):RL(e,t.shape)}function bEt(t,e){return t.isSegment?RL(t.shape,e):EEt(t.shape,e)}function SEt(t,e){return t.isSegment?GJ(t.shape,e):dAe(e,t.shape)}function xAo(t,e){return t.isSegment?pAe(t.shape,e):gbe(t.shape,e)}function dbe(t,e){let n=[];for(let o of e.edges)for(let i of BEt(o,t))n.push(i);return n}function hbe(t,e){let n=[];for(let o of e.edges)for(let i of bEt(o,t))n.push(i);return n}function YJ(t,e){let n=[];if(e.isEmpty())return n;for(let o of e.edges)for(let i of SEt(o,t))PEt(i,n)||n.push(i);return t.sortPoints(n)}function QEt(t,e){let n=[];if(e.isEmpty())return n;for(let o of e.edges)for(let i of xAo(o,t))n.push(i);return n}function vEt(t,e){return t.isSegment?BEt(e,t.shape):t.isArc?bEt(e,t.shape):t.isLine?SEt(e,t.shape):t.isRay?(n=e,o=t.shape,n.isSegment?pbe(o,n.shape):mbe(o,n.shape)):[];var n,o}function wEt(t,e){let n=[];if(e.isEmpty()||t.shape.box.not_intersect(e.box))return n;let o=e.edges.search(t.shape.box);for(let i of o)n=[...n,...vEt(t,i)];return n}function PEt(t,e){return e.some(n=\u003en.equalTo(t))}function pv(t){return new Ke.Line(t.start,t.norm)}function pbe(t,e){return GJ(e,pv(t)).filter(n=\u003et.contains(n))}function mbe(t,e){return dAe(pv(t),e).filter(n=\u003et.contains(n))}function MEt(t,e){return sN(pv(t),e).filter(n=\u003et.contains(n))}function DEt(t,e){return DL(pv(t),e).filter(n=\u003et.contains(n))}function NEt(t,e){return YJ(pv(t),e).filter(n=\u003et.contains(n))}function REt(t,e){if(t.intersect\u0026\u0026t.intersect instanceof Function)return t.intersect(e);throw ud.UNSUPPORTED_SHAPE_TYPE}function TL(t,e){let n=[];for(let o of e)n=[...n,...REt(t,o.shape)];return n}var aN=class $te extends ube{constructor(...e){if(super(),this.isInfinite=!1,e.length===1\u0026\u0026e[0]instanceof Array\u0026\u0026e[0].length\u003e0){const n=e[0],o=n.length,i=s=\u003es instanceof Ke.Segment||s instanceof Ke.Arc||s instanceof Ke.Ray,r=s=\u003es instanceof Ke.Segment||s instanceof Ke.Arc;if(!(o===1\u0026\u0026(s=\u003es instanceof Ke.Segment||s instanceof Ke.Arc||s instanceof Ke.Ray||s instanceof Ke.Line)(n[0])||o\u003e1\u0026\u0026i(n[0])\u0026\u0026i(n[o-1])\u0026\u0026n.slice(1,o-1).every(r)))throw Ke.Errors.ILLEGAL_PARAMETERS;this.isInfinite=n.some(s=\u003es instanceof Ke.Ray||s instanceof Ke.Line);for(let s of n){let a=new Ke.Edge(s);this.append(a)}this.setArcLength()}}get edges(){return[...this]}get box(){return this.edges.reduce((e,n)=\u003ee.merge(n.box),new Ke.Box)}get vertices(){let e=this.edges.map(n=\u003en.start);return e.push(this.last.end),e}get length(){if(this.isEmpty())return 0;if(this.isInfinite)return Number.POSITIVE_INFINITY;let e=0;for(let n of this)e+=n.length;return e}clone(){return new $te(this.toShapes())}setArcLength(){for(let e of this)this.setOneEdgeArcLength(e)}setOneEdgeArcLength(e){e===this.first?e.arc_length=0:e.arc_length=e.prev.arc_length+e.prev.length}pointAtLength(e){if(e\u003ethis.length||e\u003c0||this.isInfinite)return null;let n=null;for(let o of this)if(e\u003e=o.arc_length\u0026\u0026(o===this.last||e\u003co.next.arc_length)){n=o.pointAtLength(e-o.arc_length);break}return n}addVertex(e,n){let o=n.shape.split(e);if(o[0]===null)return n.prev;if(o[1]===null)return n;let i=new Ke.Edge(o[0]),r=n.prev;return this.insert(i,r),n.shape=o[1],i}getChain(e,n){let o=[];for(let i=e;i!==n.next;i=i.next)o.push(i);return o}split(e){for(let n of e){let o=this.findEdgeByPoint(n);this.addVertex(n,o)}return this}findEdgeByPoint(e){let n;for(let o of this)if(o.shape.contains(e)){n=o;break}return n}distanceTo(e){if(e instanceof Ke.Point){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Line){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Circle){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Segment){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Arc){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Box){const[n,o]=Ke.Distance.shape2multiline(new Ke.Polygon(e),this);return[n,o.reverse()]}if(e instanceof Ke.Multiline)return Ke.Distance.multiline2multiline(this,e);throw Ke.Errors.UNSUPPORTED_SHAPE_TYPE}intersect(e){return e instanceof Ke.Multiline?(function(n,o){let i=[];for(let r of n)for(let s of o)i=[...i,...REt(r.shape,s.shape)];return i})(this,e):TL(e,this)}contains(e){if(e instanceof Ke.Point)return this.edges.some(n=\u003en.shape.contains(e));throw Ke.Errors.UNSUPPORTED_SHAPE_TYPE}translate(e){return new $te(this.edges.map(n=\u003en.shape.translate(e)))}rotate(e=0,n=new Ke.Point){return new $te(this.edges.map(o=\u003eo.shape.rotate(e,n)))}transform(e=new Ke.Matrix){return new $te(this.edges.map(n=\u003en.shape.transform(e)))}toShapes(){return this.edges.map(e=\u003ee.shape.clone())}toJSON(){return this.edges.map(e=\u003ee.toJSON())}svgPoints(){return this.vertices.map(e=\u003e`${e.x},${e.y}`).join(\" \")}dpath(){let e=`M${this.first.start.x},${this.first.start.y}`;for(let n of this)e+=n.svg();return e}svg(e={}){let n=`\n\u003cpath ${rN({fill:\"none\",...e})} d=\"`;n+=`\nM${this.first.start.x},${this.first.start.y}`;for(let o of this)n+=o.svg();return n+=`\" \u003e\n\u003c/path\u003e`,n}};Ke.Multiline=aN;function kL(t,e,n){let o=n.length,i=t.shape.split(e);if(i.length===0)return;let r=0;r=i[0]===null?0:i[1]===null?t.shape.length:i[0].length;let s,a=0;iN(r,0)\u0026\u0026(a|=1),iN(r,t.shape.length)\u0026\u0026(a|=2),s=r===1/0?i[0].coord(e):2\u0026a\u0026\u0026t.next\u0026\u0026t.next.arc_length===0?0:t.arc_length+r,n.push({id:o,pt:e,arc_length:s,edge_before:t,edge_after:void 0,face:t.face,is_vertex:a})}function UJ(t){t.int_points1_sorted=mv(t.int_points1),t.int_points2_sorted=mv(t.int_points2)}function mv(t){let e=new Map,n=0;for(let o of t)e.has(o.face)||(e.set(o.face,n),n++);for(let o of t)o.faceId=e.get(o.face);return t.slice().sort(EAo)}function EAo(t,e){return t.faceId\u003ce.faceId?-1:t.faceId\u003ee.faceId?1:t.arc_length\u003ce.arc_length?-1:t.arc_length\u003ee.arc_length?1:0}function _be(t){if(t.int_points1.length\u003c2)return;let e,n,o,i,r=!1;for(let s=0;s\u003ct.int_points1_sorted.length;s++)if(t.int_points1_sorted[s].id!==-1){e=t.int_points1_sorted[s],n=t.int_points2[e.id];for(let a=s+1;a\u003ct.int_points1_sorted.length\u0026\u0026(o=t.int_points1_sorted[a],iN(o.arc_length,e.arc_length));a++)o.id!==-1\u0026\u0026(i=t.int_points2[o.id],i.id!==-1\u0026\u0026o.edge_before===e.edge_before\u0026\u0026o.edge_after===e.edge_after\u0026\u0026i.edge_before===n.edge_before\u0026\u0026i.edge_after===n.edge_after\u0026\u0026(o.id=-1,i.id=-1,r=!0))}n=t.int_points2_sorted[0],e=t.int_points1[n.id];for(let s=1;s\u003ct.int_points2_sorted.length;s++){let a=t.int_points2_sorted[s];if(a.id===-1)continue;if(n.id===-1||!iN(a.arc_length,n.arc_length)){n=a,e=t.int_points1[n.id];continue}let A=t.int_points1[a.id];A.edge_before===e.edge_before\u0026\u0026A.edge_after===e.edge_after\u0026\u0026a.edge_before===n.edge_before\u0026\u0026a.edge_after===n.edge_after\u0026\u0026(A.id=-1,a.id=-1,r=!0)}r\u0026\u0026(t.int_points1=t.int_points1.filter(s=\u003es.id\u003e=0),t.int_points2=t.int_points2.filter(s=\u003es.id\u003e=0),t.int_points1.forEach((s,a)=\u003es.id=a),t.int_points2.forEach((s,a)=\u003es.id=a))}function fbe(t){for(let e of t)e.edge_before\u0026\u0026(e.edge_before.bvStart=void 0,e.edge_before.bvEnd=void 0,e.edge_before.bv=void 0,e.edge_before.overlap=void 0),e.edge_after\u0026\u0026(e.edge_after.bvStart=void 0,e.edge_after.bvEnd=void 0,e.edge_after.bv=void 0,e.edge_after.overlap=void 0);for(let e of t)e.edge_before\u0026\u0026(e.edge_before.bvEnd=2),e.edge_after\u0026\u0026(e.edge_after.bvStart=2)}function Ibe(t,e){for(let n of t)n.edge_before\u0026\u0026n.edge_before.setInclusion(e),n.edge_after\u0026\u0026n.edge_after.setInclusion(e)}function FL(t,e,n){let o,i,r=1;if(t.length===1)return 1;o=t[e];for(let s=e+1;s\u003ct.length\u0026\u0026o.face===n\u0026\u0026(i=t[s],i.pt.equalTo(o.pt)\u0026\u0026i.edge_before===o.edge_before\u0026\u0026i.edge_after===o.edge_after);s++)r++;return r}function LL(t,e){if(e){for(let n of e){let o=n.edge_before;if(n.is_vertex=0,o.shape.start\u0026\u0026o.shape.start.equalTo(n.pt)\u0026\u0026(n.is_vertex|=1),o.shape.end\u0026\u0026o.shape.end.equalTo(n.pt)\u0026\u0026(n.is_vertex|=2),1\u0026n.is_vertex){n.edge_before=o.prev,o.prev\u0026\u0026(n.is_vertex=2);continue}if(2\u0026n.is_vertex)continue;let i=t.addVertex(n.pt,o);n.edge_before=i}for(let n of e)n.edge_before?n.edge_after=n.edge_before.next:t instanceof aN\u0026\u00261\u0026n.is_vertex\u0026\u0026(n.edge_after=t.first)}}function TEt(t,e,n){const o=t.edge_before,i=e.edge_after,r=n.length;o.next=n[0],n[0].prev=o,n[r-1].next=i,i.prev=n[r-1]}Ke.multiline=(...t)=\u003enew Ke.Multiline(...t);var{INSIDE:f7,OUTSIDE:I7,BOUNDARY:$f,OVERLAP_SAME:BAo,OVERLAP_OPPOSITE:bAo}=gAe,{NOT_VERTEX:Yhr,START_VERTEX:kEt,END_VERTEX:FEt}=gAe;function Cbe(t,e){let n=e.clone().reverse(),[o]=KJ(t,n,3,!0);return o}function LEt(t,e){let[n]=KJ(t,e,2,!0);return n}function HEt(t,e){let[n,o]=KJ(t,e,2,!1),i=[];for(let s of n.faces)i=[...i,...[...s.edges].map(a=\u003ea.shape)];let r=[];for(let s of o.faces)r=[...r,...[...s.edges].map(a=\u003ea.shape)];return[i,r]}function ybe(t,e){let[n]=KJ(t,e,3,!1),o=[];for(let i of n.faces)o=[...o,...[...i.edges].map(r=\u003er.shape)];return o}function OEt(t,e){let n=t.clone(),o=e.clone(),i=GEt(n,o);return UJ(i),LL(n,i.int_points1_sorted),LL(o,i.int_points2_sorted),_be(i),UJ(i),[i.int_points1_sorted.map(r=\u003er.pt),i.int_points2_sorted.map(r=\u003er.pt)]}function SAo(t,e,n,o){let i=YEt(t,n.int_points1),r=YEt(e,n.int_points2);for(UEt(i,e),UEt(r,t),fbe(n.int_points1),fbe(n.int_points2),Ibe(n.int_points1,e),Ibe(n.int_points2,t);QAo(t,e,n.int_points1,n.int_points1_sorted,n.int_points2,n););(function(s){let a,A,c,l=s.int_points1.length;for(let u=0;u\u003cl;u++){let g=s.int_points1_sorted[u];g.face!==a\u0026\u0026(A=u,a=g.face);let h,d=u,p=FL(s.int_points1_sorted,u,a);h=d+p\u003cl\u0026\u0026s.int_points1_sorted[d+p].face===a?d+p:A;let m=FL(s.int_points1_sorted,h,a);c=null;for(let E=h;E\u003ch+m;E++){let B=s.int_points1_sorted[E];if(B.face===a\u0026\u0026s.int_points2[B.id].face===s.int_points2[g.id].face){c=B;break}}if(c===null)continue;let _=g.edge_after,f=c.edge_before;if(_.bv!==2||f.bv!==2||_!==f)continue;let I=s.int_points2[g.id],C=s.int_points2[c.id],y=I.edge_after,x=C.edge_before;y.bv===2\u0026\u0026x.bv===2\u0026\u0026y===x||(I=s.int_points2[c.id],C=s.int_points2[g.id],y=I.edge_after,x=C.edge_before),y.bv===2\u0026\u0026x.bv===2\u0026\u0026y===x\u0026\u0026_.setOverlap(y)}})(n),xbe(t,o,n.int_points1_sorted,!0),xbe(e,o,n.int_points2_sorted,!1),KEt(t,i,o,!0),KEt(e,r,o,!1)}function KJ(t,e,n,o){let i=t.clone(),r=e.clone(),s=GEt(i,r);return UJ(s),LL(i,s.int_points1_sorted),LL(r,s.int_points2_sorted),_be(s),UJ(s),SAo(i,r,s,n),o\u0026\u0026(function(a,A,c){(function(l,u,g,h){for(let d of u.faces){for(let p of d)l.edges.add(p);h.find(p=\u003ep.face===d)===void 0\u0026\u0026l.addFace(d.first,d.last)}})(a,A,0,c.int_points2),(function(l,u,g){if(g.int_points1.length!==0)for(let h=0;h\u003cg.int_points1.length;h++){let d=g.int_points1[h],p=g.int_points2[h];if(d.edge_before!==void 0\u0026\u0026d.edge_after===void 0\u0026\u0026p.edge_before===void 0\u0026\u0026p.edge_after!==void 0\u0026\u0026(d.edge_before.next=p.edge_after,p.edge_after.prev=d.edge_before,d.edge_after=p.edge_after,p.edge_before=d.edge_before),p.edge_before!==void 0\u0026\u0026p.edge_after===void 0\u0026\u0026d.edge_before===void 0\u0026\u0026d.edge_after!==void 0\u0026\u0026(p.edge_before.next=d.edge_after,d.edge_after.prev=p.edge_before,p.edge_after=d.edge_after,d.edge_before=p.edge_before),d.edge_before!==void 0\u0026\u0026d.edge_after===void 0)for(let m of g.int_points1_sorted)m!==d\u0026\u0026m.edge_before===void 0\u0026\u0026m.edge_after!==void 0\u0026\u0026m.pt.equalTo(d.pt)\u0026\u0026(d.edge_before.next=m.edge_after,m.edge_after.prev=d.edge_before,d.edge_after=m.edge_after,m.edge_before=d.edge_before);if(p.edge_before!==void 0\u0026\u0026p.edge_after===void 0)for(let m of g.int_points2_sorted)m!==p\u0026\u0026m.edge_before===void 0\u0026\u0026m.edge_after!==void 0\u0026\u0026m.pt.equalTo(p.pt)\u0026\u0026(p.edge_before.next=m.edge_after,m.edge_after.prev=p.edge_before,p.edge_after=m.edge_after,m.edge_before=p.edge_before)}})(0,0,c),Ebe(a,c.int_points1),Ebe(A,c.int_points2),Bbe(a,c.int_points1,c.int_points2),Bbe(a,c.int_points2,c.int_points1),VEt(a),VEt(A)})(i,r,s),[i,r]}function GEt(t,e){let n={int_points1:[],int_points2:[]};for(let o of t.edges){let i=e.edges.search(o.box);for(let r of i){let s=o.shape.intersect(r.shape);for(let a of s)kL(o,a,n.int_points1),kL(r,a,n.int_points2)}}return n}function YEt(t,e){let n=[];for(let o of t.faces)e.find(i=\u003ei.face===o)||n.push(o);return n}function UEt(t,e){for(let n of t)n.first.bv=n.first.bvStart=n.first.bvEnd=void 0,n.first.setInclusion(e)}function QAo(t,e,n,o,i,r){let s,a,A,c=o.length,l=!1;for(let u=0;u\u003cc;u++){let g=o[u];g.face!==s\u0026\u0026(a=u,s=g.face);let h,d=u,p=FL(o,u,s);h=d+p\u003cc\u0026\u0026o[d+p].face===s?d+p:a;let m=FL(o,h,s);A=null;for(let I=h;I\u003ch+m;I++){let C=o[I];if(C.face===s\u0026\u0026i[C.id].face===i[g.id].face){A=C;break}}if(A===null)continue;let _=g.edge_after,f=A.edge_before;if(_.bv!==$f||f.bv==$f)if(_.bv==$f||f.bv!==$f){if(_.bv===$f\u0026\u0026f.bv===$f\u0026\u0026_!=f||_.bv===f7\u0026\u0026f.bv===I7||_.bv===I7\u0026\u0026f.bv===f7){let I=_.next;for(;I!=f;)I.bvStart=void 0,I.bvEnd=void 0,I.bv=void 0,I.setInclusion(e),I=I.next}if(_.bv===$f\u0026\u0026f.bv===$f\u0026\u0026_!=f){let I,C=_.next;for(;C!=f;){if(C.bv!=$f){if(I===void 0)I=C.bv;else if(C.bv!=I)throw ud.UNRESOLVED_BOUNDARY_CONFLICT}C=C.next}I!=null\u0026\u0026(_.bv=I,f.bv=I);continue}if(_.bv===f7\u0026\u0026f.bv===I7||_.bv===I7\u0026\u0026f.bv===f7){let I=_;for(;I!=f;){if(I.bvStart===_.bv\u0026\u0026I.bvEnd===f.bv){let[C,y]=I.shape.distanceTo(e);if(C\u003c10*Ke.DP_TOL){kL(I,y.ps,n);let x=n[n.length-1];if(x.is_vertex\u0026kEt)x.edge_after=I,x.edge_before=I.prev,I.bvStart=$f,I.bv=void 0,I.setInclusion(e);else if(x.is_vertex\u0026FEt)x.edge_after=I.next,I.bvEnd=$f,I.bv=void 0,I.setInclusion(e);else{let S=e.addVertex(x.pt,I);x.edge_before=S,x.edge_after=S.next,S.setInclusion(e),S.next.bvStart=$f,S.next.bvEnd=void 0,S.next.bv=void 0,S.next.setInclusion(e)}let E=e.findEdgeByPoint(y.pe);kL(E,y.pe,i);let B=i[i.length-1];if(B.is_vertex\u0026kEt)B.edge_after=E,B.edge_before=E.prev;else if(B.is_vertex\u0026FEt)B.edge_after=E.next;else{let S=i.find(w=\u003ew.edge_after===E),Q=e.addVertex(B.pt,E);B.edge_before=Q,B.edge_after=Q.next,S\u0026\u0026(S.edge_after=Q),Q.bvStart=void 0,Q.bvEnd=$f,Q.bv=void 0,Q.setInclusion(t),Q.next.bvStart=$f,Q.next.bvEnd=void 0,Q.next.bv=void 0,Q.next.setInclusion(t)}UJ(r),l=!0;break}}I=I.next}if(l)break;throw ud.UNRESOLVED_BOUNDARY_CONFLICT}}else f.bv=_.bv;else _.bv=f.bv}return l}function xbe(t,e,n,o){if(!n)return;let i,r,s,a;for(let A=0;A\u003cn.length;A++){if(s=n[A],s.face!==i\u0026\u0026(r=A,i=s.face),i.isEmpty())continue;let c,l=A,u=FL(n,A,i);c=l+u\u003cn.length\u0026\u0026n[l+u].face===s.face?l+u:r,a=n[c];let g=c,h=FL(n,g,i),d=s.edge_after,p=a.edge_before;if(d.bv===f7\u0026\u0026p.bv===f7\u0026\u0026e===1||d.bv===I7\u0026\u0026p.bv===I7\u0026\u0026e===2||(d.bv===I7||p.bv===I7)\u0026\u0026e===3\u0026\u0026!o||(d.bv===f7||p.bv===f7)\u0026\u0026e===3\u0026\u0026o||d.bv===$f\u0026\u0026p.bv===$f\u0026\u0026d.overlap\u0026BAo\u0026\u0026o||d.bv===$f\u0026\u0026p.bv===$f\u0026\u0026d.overlap\u0026bAo){t.removeChain(i,d,p);for(let m=l;m\u003cl+u;m++)n[m].edge_after=void 0;for(let m=g;m\u003cg+h;m++)n[m].edge_before=void 0}A+=u-1}}function Ebe(t,e){for(let n of e)t.faces.delete(n.face),n.face=void 0,n.edge_before\u0026\u0026(n.edge_before.face=void 0),n.edge_after\u0026\u0026(n.edge_after.face=void 0)}function Bbe(t,e,n){for(let o of e){if(o.edge_before===void 0||o.edge_after===void 0||o.face||o.edge_after.face||o.edge_before.face)continue;let i=o.edge_after,r=o.edge_before;try{ube.testInfiniteLoop(i)}catch{throw ud.CANNOT_COMPLETE_BOOLEAN_OPERATION}let s=t.addFace(i,r);for(let a of e)a.edge_before\u0026\u0026a.edge_after\u0026\u0026a.edge_before.face===s\u0026\u0026a.edge_after.face===s\u0026\u0026(a.face=s);for(let a of n)a.edge_before\u0026\u0026a.edge_after\u0026\u0026a.edge_before.face===s\u0026\u0026a.edge_after.face===s\u0026\u0026(a.face=s)}}function KEt(t,e,n,o){for(let i of e){let r=i.first.bv;(n===1\u0026\u0026r===f7||n===3\u0026\u0026r===f7\u0026\u0026o||n===3\u0026\u0026r===I7\u0026\u0026!o||n===2\u0026\u0026r===I7)\u0026\u0026t.deleteFace(i)}}function VEt(t){const e=[];for(const n of t.edges)n.face\u0026\u0026t.faces.has(n.face)||e.push(n);for(const n of e)t.edges.delete(n)}var vAo=Object.freeze({__proto__:null,BOOLEAN_INTERSECT:2,BOOLEAN_SUBTRACT:3,BOOLEAN_UNION:1,calculateIntersections:OEt,innerClip:HEt,intersect:LEt,outerClip:ybe,removeNotRelevantChains:xbe,removeOldFaces:Ebe,restoreFaces:Bbe,subtract:Cbe,unify:function(t,e){let[n]=KJ(t,e,1,!0);return n}}),wAo=RegExp(\"T.F..FFF.|T.F...F..\"),PAo=RegExp(\"T........|.T.......|...T.....|....T....\"),MAo=RegExp(\"FT.......|F..T.....|F...T....\"),DAo=RegExp(\"T.F..F...\"),NAo=RegExp(\"T.F..F...|.TF..F...|..FT.F...|..F.TF...\"),HL=class{constructor(){this.m=new Array(9).fill(void 0)}get I2I(){return this.m[0]}set I2I(t){this.m[0]=t}get I2B(){return this.m[1]}set I2B(t){this.m[1]=t}get I2E(){return this.m[2]}set I2E(t){this.m[2]=t}get B2I(){return this.m[3]}set B2I(t){this.m[3]=t}get B2B(){return this.m[4]}set B2B(t){this.m[4]=t}get B2E(){return this.m[5]}set B2E(t){this.m[5]=t}get E2I(){return this.m[6]}set E2I(t){this.m[6]=t}get E2B(){return this.m[7]}set E2B(t){this.m[7]=t}get E2E(){return this.m[8]}set E2E(t){this.m[8]=t}toString(){return this.m.map(t=\u003et instanceof Array\u0026\u0026t.length\u003e0?\"T\":t instanceof Array\u0026\u0026t.length===0?\"F\":\"*\").join(\"\")}equal(){return wAo.test(this.toString())}intersect(){return PAo.test(this.toString())}touch(){return MAo.test(this.toString())}inside(){return DAo.test(this.toString())}covered(){return NAo.test(this.toString())}};function VJ(t,e){let n,o=new Ke.Ray(e),i=new Ke.Line(o.pt,o.norm);const r=new Ke.Box(o.box.xmin-Ke.DP_TOL,o.box.ymin-Ke.DP_TOL,o.box.xmax+Ke.DP_TOL,o.box.ymax+Ke.DP_TOL);if(t.box.not_intersect(r))return Ke.OUTSIDE;let s=t.edges.search(r);if(s.length===0)return Ke.OUTSIDE;for(let l of s)if(l.shape.contains(e))return Ke.BOUNDARY;let a=[...t.faces],A=[];for(let l of s)for(let u of o.intersect(l.shape)){if(u.equalTo(e))return Ke.BOUNDARY;A.push({pt:u,edge:l,face_index:a.indexOf(l.face)})}A.sort((l,u)=\u003efEt(l.pt.x,u.pt.x)?-1:_Et(l.pt.x,u.pt.x)?1:l.face_index\u003cu.face_index?-1:l.face_index\u003eu.face_index?1:l.edge.arc_length\u003cu.edge.arc_length?-1:l.edge.arc_length\u003eu.edge.arc_length?1:0);let c=0;for(let l=0;l\u003cA.length;l++){let u=A[l];if(u.pt.equalTo(u.edge.shape.start)){if(l\u003e0\u0026\u0026u.pt.equalTo(A[l-1].pt)\u0026\u0026u.face_index===A[l-1].face_index\u0026\u0026u.edge.prev===A[l-1].edge)continue;let g=u.edge.prev;for(;lbe(g.length);)g=g.prev;let h=g.shape.tangentInEnd(),d=u.pt.translate(h),p=u.edge.shape.tangentInStart(),m=u.pt.translate(p),_=d.leftTo(i),f=m.leftTo(i);(_\u0026\u0026!f||!_\u0026\u0026f)\u0026\u0026c++}else if(u.pt.equalTo(u.edge.shape.end)){if(l\u003e0\u0026\u0026u.pt.equalTo(A[l-1].pt)\u0026\u0026u.face_index===A[l-1].face_index\u0026\u0026u.edge.next===A[l-1].edge)continue;let g=u.edge.next;for(;lbe(g.length);)g=g.next;let h=g.shape.tangentInStart(),d=u.pt.translate(h),p=u.edge.shape.tangentInEnd(),m=u.pt.translate(p),_=d.leftTo(i),f=m.leftTo(i);(_\u0026\u0026!f||!_\u0026\u0026f)\u0026\u0026c++}else if(u.edge.shape instanceof Ke.Segment)c++;else{let g=u.edge.shape.box;iN(u.pt.y,g.ymin)||iN(u.pt.y,g.ymax)||c++}}return n=c%2==1?1:0,n}function zEt(t,e){return OL(t,e).intersect()}function JEt(t,e){return OL(t,e).inside()}function WEt(t,e){return OL(t,e).covered()}function jEt(t,e){return WEt(e,t)}function OL(t,e){return t instanceof Ke.Line\u0026\u0026e instanceof Ke.Line?(function(n,o){let i=new HL,r=DL(n,o);return r.length===0?n.contains(o.pt)\u0026\u0026o.contains(n.pt)?(i.I2I=[n],i.I2E=[],i.E2I=[]):(i.I2I=[],i.I2E=[n],i.E2I=[o]):(i.I2I=r,i.I2E=n.split(r),i.E2I=o.split(r)),i})(t,e):t instanceof Ke.Line\u0026\u0026e instanceof Ke.Circle?(function(n,o){let i=new HL,r=sN(n,o);if(r.length===0)i.I2I=[],i.I2B=[],i.I2E=[n],i.E2I=[o];else if(r.length===1)i.I2I=[],i.I2B=r,i.I2E=n.split(r),i.E2I=[o];else{let s=new aN([n]),a=n.sortPoints(r);s.split(a);let A=s.toShapes();i.I2I=[A[1]],i.I2B=a,i.I2E=[A[0],A[2]],i.E2I=new Ke.Polygon([o.toArc()]).cutWithLine(n)}return i})(t,e):t instanceof Ke.Line\u0026\u0026e instanceof Ke.Box?(function(n,o){let i=new HL,r=NL(n,o);if(r.length===0)i.I2I=[],i.I2B=[],i.I2E=[n],i.E2I=[o];else if(r.length===1)i.I2I=[],i.I2B=r,i.I2E=n.split(r),i.E2I=[o];else{let s=new aN([n]),a=n.sortPoints(r);s.split(a);let A=s.toShapes();o.toSegments().some(c=\u003ec.contains(r[0])\u0026\u0026c.contains(r[1]))?(i.I2I=[],i.I2B=[A[1]],i.I2E=[A[0],A[2]],i.E2I=[o]):(i.I2I=[A[1]],i.I2B=a,i.I2E=[A[0],A[2]],i.E2I=new Ke.Polygon(o.toSegments()).cutWithLine(n))}return i})(t,e):t instanceof Ke.Line\u0026\u0026e instanceof Ke.Polygon?(function(n,o){let i=new HL,r=YJ(n,o),s=new aN([n]),a=r.length\u003e0?r.slice():n.sortPoints(r);return s.split(a),[...s].forEach(A=\u003eA.setInclusion(o)),i.I2I=[...s].filter(A=\u003eA.bv===Ke.INSIDE).map(A=\u003eA.shape),i.I2B=[...s].slice(1).map(A=\u003eA.bv===Ke.BOUNDARY?A.shape:A.shape.start),i.I2E=[...s].filter(A=\u003eA.bv===Ke.OUTSIDE).map(A=\u003eA.shape),i.E2I=o.cutWithLine(n),i})(t,e):(t instanceof Ke.Segment||t instanceof Ke.Arc)\u0026\u0026e instanceof Ke.Polygon?$Et(t,e):(t instanceof Ke.Segment||t instanceof Ke.Arc)\u0026\u0026(e instanceof Ke.Circle||e instanceof Ke.Box)?$Et(t,new Ke.Polygon(e)):t instanceof Ke.Polygon\u0026\u0026e instanceof Ke.Polygon?mAe(t,e):(t instanceof Ke.Circle||t instanceof Ke.Box)\u0026\u0026(e instanceof Ke.Circle||e instanceof Ke.Box)?mAe(new Ke.Polygon(t),new Ke.Polygon(e)):(t instanceof Ke.Circle||t instanceof Ke.Box)\u0026\u0026e instanceof Ke.Polygon?mAe(new Ke.Polygon(t),e):t instanceof Ke.Polygon\u0026\u0026(e instanceof Ke.Circle||e instanceof Ke.Box)?mAe(t,new Ke.Polygon(e)):void 0}function $Et(t,e){let n=new HL,o=(function(s,a){return s instanceof Ke.Line?YJ(s,a):s instanceof Ke.Segment?dbe(s,a):s instanceof Ke.Arc?hbe(s,a):[]})(t,e),i=o.length\u003e0?o.slice():t.sortPoints(o),r=new aN([t]);r.split(i),[...r].forEach(s=\u003es.setInclusion(e)),n.I2I=[...r].filter(s=\u003es.bv===Ke.INSIDE).map(s=\u003es.shape),n.I2B=[...r].slice(1).map(s=\u003es.bv===Ke.BOUNDARY?s.shape:s.shape.start),n.I2E=[...r].filter(s=\u003es.bv===Ke.OUTSIDE).map(s=\u003es.shape),n.B2I=[],n.B2B=[],n.B2E=[];for(let s of[t.start,t.end])switch(VJ(e,s)){case Ke.INSIDE:n.B2I.push(s);break;case Ke.BOUNDARY:n.B2B.push(s);break;case Ke.OUTSIDE:n.B2E.push(s)}return n}function mAe(t,e){let n=new HL,[o,i]=OEt(t,e),r=LEt(t,e),s=Cbe(t,e),a=Cbe(e,t),[A,c]=HEt(t,e),l=ybe(t,e),u=ybe(e,t);return n.I2I=r.isEmpty()?[]:[r],n.I2B=c,n.I2E=s.isEmpty()?[]:[s],n.B2I=A,n.B2B=o,n.B2E=l,n.E2I=a.isEmpty()?[]:[a],n.E2B=u,n}var RAo=Object.freeze({__proto__:null,contain:function(t,e){return JEt(e,t)},cover:jEt,covered:WEt,disjoint:function(t,e){return!zEt(t,e)},equal:function(t,e){return OL(t,e).equal()},inside:JEt,intersect:zEt,relate:OL,touch:function(t,e){return OL(t,e).touch()}}),zJ=class kk{constructor(e=1,n=0,o=0,i=1,r=0,s=0){this.a=e,this.b=n,this.c=o,this.d=i,this.tx=r,this.ty=s}fromMatrix3x3(e){const[n,o,i]=e[0],[r,s,a]=e[1];return new kk(n,r,o,s,i,a)}toMatrix3x3(){return[[this.a,this.c,this.tx],[this.b,this.d,this.ty],[0,0,1]]}clone(){return new kk(this.a,this.b,this.c,this.d,this.tx,this.ty)}transform(e){return[e[0]*this.a+e[1]*this.c+this.tx,e[0]*this.b+e[1]*this.d+this.ty]}multiply(e){return new kk(this.a*e.a+this.c*e.b,this.b*e.a+this.d*e.b,this.a*e.c+this.c*e.d,this.b*e.c+this.d*e.d,this.a*e.tx+this.c*e.ty+this.tx,this.b*e.tx+this.d*e.ty+this.ty)}translate(...e){let n,o;if(e.length!=1||isNaN(e[0].x)||isNaN(e[0].y)){if(e.length!==2||typeof e[0]!=\"number\"||typeof e[1]!=\"number\")throw ud.ILLEGAL_PARAMETERS;n=e[0],o=e[1]}else n=e[0].x,o=e[0].y;return this.multiply(new kk(1,0,0,1,n,o))}rotate(e,n=0,o=0){let i=Math.cos(e),r=Math.sin(e);return this.translate(n,o).multiply(new kk(i,r,-r,i,0,0)).translate(-n,-o)}scale(e,n){return this.multiply(new kk(e,0,0,n,0,0))}equalTo(e){return!!Ke.Utils.EQ(this.tx,e.tx)\u0026\u0026!!Ke.Utils.EQ(this.ty,e.ty)\u0026\u0026!!Ke.Utils.EQ(this.a,e.a)\u0026\u0026!!Ke.Utils.EQ(this.b,e.b)\u0026\u0026!!Ke.Utils.EQ(this.c,e.c)\u0026\u0026!!Ke.Utils.EQ(this.d,e.d)}};Ke.Matrix=zJ,Ke.matrix=(...t)=\u003enew Ke.Matrix(...t);var TAo=class{constructor(t,e){this.low=t,this.high=e}get max(){return this.clone()}less_than(t){return this.low\u003ct.low||this.low===t.low\u0026\u0026this.high\u003ct.high}equal_to(t){return this.low===t.low\u0026\u0026this.high===t.high}intersect(t){return!this.not_intersect(t)}not_intersect(t){return this.high\u003ct.low||t.high\u003cthis.low}merge(t){const e=this.low===void 0?t.low:this.low\u003ct.low?this.low:t.low,n=this.high===void 0?t.high:this.high\u003et.high?this.high:t.high,o=this.clone();return o.low=e,o.high=n,o}output(){return[this.low,this.high]}comparable_less_than(t,e){return t\u003ce}},kAo=class d5n extends TAo{clone(){return new d5n(this.low,this.high)}},_v=class{constructor(t,e,n=null,o=null,i=null,r=0){if(this.left=n,this.right=o,this.parent=i,this.color=r,this.item={key:void 0,values:[]},e!==void 0\u0026\u0026this.item.values.push(e),t!==void 0)if(Array.isArray(t)){const[s,a]=t;if(!Number.isNaN(s)\u0026\u0026!Number.isNaN(a)){let A=s,c=a;A\u003ec\u0026\u0026([A,c]=[c,A]),this.item.key=new kAo(A,c)}}else this.item.key=t;this.max=this.item.key?this.item.key.max:void 0}isNil(){return this.item.key===void 0\u0026\u0026this.item.values.length===0\u0026\u0026this.left===null\u0026\u0026this.right===null\u0026\u0026this.color===0}requireKey(){if(!this.item.key)throw new Error(\"Node key is undefined (nil/sentinel). Operation is not applicable.\");return this.item.key}less_than(t){const e=this.requireKey(),n=t.requireKey();return e.less_than(n)}_value_equal(t){const e=this.item.values[0],n=t.item.values[0];return e\u0026\u0026n\u0026\u0026e.equal_to?e.equal_to(n):e===n}equal_to(t){const e=this.requireKey(),n=t.requireKey();return e.equal_to(n)}intersect(t){const e=this.requireKey(),n=t.requireKey();return e.intersect(n)}copy_data(t){this.item.key=t.item.key,this.item.values=t.item.values.slice()}update_max(){this.max=this.item.key?this.item.key.max:void 0,this.right\u0026\u0026this.right.max\u0026\u0026(this.max=this.max?this.max.merge(this.right.max):this.right.max),this.left\u0026\u0026this.left.max\u0026\u0026(this.max=this.max?this.max.merge(this.left.max):this.left.max)}not_intersect_left_subtree(t){if(!this.left)return!0;const e=this.left.max?this.left.max.high:this.left.item.key.high,n=this.requireKey(),o=t.requireKey();return n.comparable_less_than(e,o.low)}not_intersect_right_subtree(t){if(!this.right)return!0;const e=this.right.max?this.right.max.low:this.right.item.key.low,n=this.requireKey(),o=t.requireKey();return n.comparable_less_than(o.high,e)}},bbe=class h5n{constructor(){this.root=null,this.nil_node=new _v}get size(){let e=0;return this.tree_walk(this.root,n=\u003ee+=n.item.values.length),e}get keys(){const e=[];return this.tree_walk(this.root,n=\u003ee.push(n.item.key.output())),e}get values(){const e=[];return this.tree_walk(this.root,n=\u003e{for(const o of n.item.values)e.push(o)}),e}get items(){const e=[];return this.tree_walk(this.root,n=\u003e{const o=n.item.key.output();for(const i of n.item.values)e.push({key:o,value:i})}),e}isEmpty(){return this.root==null||this.root===this.nil_node}clear(){this.root=null}insert(e,n=e){if(e===void 0)return;const o=this.tree_search(this.root,new _v(e));if(o)return o.item.values.push(n),o;const i=new _v(e,n,this.nil_node,this.nil_node,null,1);return this.tree_insert(i),this.recalc_max(i),i}exist(e,n=e){const o=this.tree_search(this.root,new _v(e));return!!o\u0026\u0026(arguments.length\u003c2||n===e||o.item.values.some(i=\u003ei\u0026\u0026i.equal_to?i.equal_to(n):i===n))}remove(e,n=e){const o=this.tree_search(this.root,new _v(e));if(!o)return;if(arguments.length\u003c2)return this.tree_delete(o),o;const i=o.item.values.findIndex(r=\u003er\u0026\u0026r.equal_to?r.equal_to(n):r===n);return i\u003e=0?(o.item.va","content_mimetype":"text/plain","created_at":"2026-10-05T13:15:35.021Z"}; window.SSR_PACKAGE_RELEASES = [{"package_release_id":"a56db1f7-99bf-4f14-b32e-ab5431f039d0","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.19","github_commit_sha":null,"is_locked":false,"is_latest":true,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T13:15:23.548Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-6eb8ae0e3705282d2c5b6af9de5b0a5a","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=a56db1f7-99bf-4f14-b32e-ab5431f039d0\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=a56db1f7-99bf-4f14-b32e-ab5431f039d0\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=a56db1f7-99bf-4f14-b32e-ab5431f039d0\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"8c707e6d-446a-4b11-8780-d980a2b6494b","user_code_job_started_at":"2026-10-05T13:30:31.188Z","user_code_job_completed_at":"2026-10-05T13:36:06.374Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=fc822d6e83ede29cb53d172f7155634cdc596139a58cdb1c014d59d17492c7e1","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"b0d81c84-a226-464b-84a4-a655185a3a25","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.18","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T12:40:09.172Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-5e6dee74e06130ba1abedd4457510217","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=b0d81c84-a226-464b-84a4-a655185a3a25\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=b0d81c84-a226-464b-84a4-a655185a3a25\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=b0d81c84-a226-464b-84a4-a655185a3a25\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"2991f513-e5d8-4c7a-aaa0-2b7f2a68225d","user_code_job_started_at":"2026-10-05T12:42:32.098Z","user_code_job_completed_at":"2026-10-05T12:49:07.396Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=4f86521a8365124b06c76ccbd0aea9019032167491b5b467077c7a02ced49a41","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"4fa538fc-bfff-490e-9f59-243aaf206a0e","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.17","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T11:49:00.446Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-1c8ee8b89eec6e227c9616af021fb396","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=4fa538fc-bfff-490e-9f59-243aaf206a0e\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=4fa538fc-bfff-490e-9f59-243aaf206a0e\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=4fa538fc-bfff-490e-9f59-243aaf206a0e\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"5fc8d342-8923-4fa1-84aa-34984c9a77d2","user_code_job_started_at":"2026-10-05T11:50:18.413Z","user_code_job_completed_at":"2026-10-05T12:20:20.902Z","user_code_job_error":{"message":"Build timed out after 30 minutes","error_code":"user_code_job_timeout"},"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=213321f1092ec68a13466939f33e380ad9537c815ae2bf5594c11793768490c9","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"b67e103d-d359-4f47-b2a9-0f903c841431","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.16","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T11:17:26.970Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-bd0dfc621c57205fba9f8d8a2fe06917","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=b67e103d-d359-4f47-b2a9-0f903c841431\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=b67e103d-d359-4f47-b2a9-0f903c841431\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=b67e103d-d359-4f47-b2a9-0f903c841431\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"9c76ac3c-31ab-49c3-a2cf-c41ca2f64da1","user_code_job_started_at":"2026-10-05T11:19:43.035Z","user_code_job_completed_at":"2026-10-05T11:30:00.497Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=09c2571c8594cc5446af1ac461ebcbcf0adb0d8cbcae71522948e75d14fe4c8d","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"0bbc98b2-d526-41f0-b246-bed75ed24b86","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.15","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T10:46:55.472Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-715cefa259ee7f0247b1b614b14f8b7e","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=0bbc98b2-d526-41f0-b246-bed75ed24b86\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=0bbc98b2-d526-41f0-b246-bed75ed24b86\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=0bbc98b2-d526-41f0-b246-bed75ed24b86\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"18ce8d3d-ad7e-4cd0-811a-6afc0b8d5465","user_code_job_started_at":"2026-10-05T10:59:52.697Z","user_code_job_completed_at":"2026-10-05T11:07:38.031Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=7af4644656c74ce99e99241f2d5894cc1aa3ffa1341d798f79d619f1b39aeffa","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"e9f238ea-c9b4-46b5-8849-29781fd999f4","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.12","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T09:34:47.276Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-a0656aa2da3d10b804b917660ed827b2","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=e9f238ea-c9b4-46b5-8849-29781fd999f4\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=e9f238ea-c9b4-46b5-8849-29781fd999f4\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=e9f238ea-c9b4-46b5-8849-29781fd999f4\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"a96806df-4353-48e8-b890-c50f521cb7e3","user_code_job_started_at":"2026-10-05T09:51:54.289Z","user_code_job_completed_at":"2026-10-05T10:13:23.429Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=ca97a49f7a9ebf82d8b7f1f5f6cf5f4bead642d1fc3851e57dbcfe25c3ef045f","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"7367de0f-e2cf-43bb-94f0-2c5434bff2b2","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.11","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T09:14:49.936Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-61d9b2efba862b3954b4b2a65264fe42","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=7367de0f-e2cf-43bb-94f0-2c5434bff2b2\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=7367de0f-e2cf-43bb-94f0-2c5434bff2b2\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=7367de0f-e2cf-43bb-94f0-2c5434bff2b2\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"8d3f4822-a570-4e98-9413-e2d5f629390c","user_code_job_started_at":"2026-10-05T09:15:54.152Z","user_code_job_completed_at":"2026-10-05T09:27:20.635Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=cfc8867bc4d639b40c0e74571f988aee8d776f2c8ce777e1897e84d476e1e7be","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"a9bd2d0b-8385-4ec9-9161-b4b045223edf","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.10","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T08:15:45.499Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-d404b30a0c8f20182d1ac6578217eada","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=a9bd2d0b-8385-4ec9-9161-b4b045223edf\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=a9bd2d0b-8385-4ec9-9161-b4b045223edf\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=a9bd2d0b-8385-4ec9-9161-b4b045223edf\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"3c1e0217-c73f-497c-a1d2-92490908d45c","user_code_job_started_at":"2026-10-05T08:20:44.239Z","user_code_job_completed_at":"2026-10-05T08:28:33.533Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=f0cda6b774cc88b59005d5b4fde56ae0dfceda649d56a89227d9eb5891788b45","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"634fb4eb-78e7-4dae-9a60-170630d10c39","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.9","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T07:49:23.366Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-b3ec16d1349b1d763cb802fb56c4eb5c","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=634fb4eb-78e7-4dae-9a60-170630d10c39\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=634fb4eb-78e7-4dae-9a60-170630d10c39\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=634fb4eb-78e7-4dae-9a60-170630d10c39\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"ba5f3a49-4474-4f6b-aaba-2bea883c2254","user_code_job_started_at":"2026-10-05T07:53:53.718Z","user_code_job_completed_at":"2026-10-05T08:04:14.215Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=a267d59279c15d74ab2f90a8c1647617b788e330ee29be5cef05c7dc72533493","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"53f45203-3e94-44cb-8e73-c8ed97d767d3","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.8","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T07:20:49.673Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-b2322aa668cde8ad296b75adca2b40e2","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=53f45203-3e94-44cb-8e73-c8ed97d767d3\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=53f45203-3e94-44cb-8e73-c8ed97d767d3\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=53f45203-3e94-44cb-8e73-c8ed97d767d3\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"4bd25e6a-980f-4d91-af03-8dcdabee4b24","user_code_job_started_at":"2026-10-05T07:22:15.388Z","user_code_job_completed_at":"2026-10-05T07:27:04.421Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=b512648421af19f71c7159c59da773f447b14befeabe06554abefa308b912d65","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"45d52ddf-a51d-46d4-9317-a78c01694cb1","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.7","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T05:38:14.445Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-d47c5b7e1407c9dcb4cbe5b9eac66a0f","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=45d52ddf-a51d-46d4-9317-a78c01694cb1\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=45d52ddf-a51d-46d4-9317-a78c01694cb1\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=45d52ddf-a51d-46d4-9317-a78c01694cb1\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"9145ecdb-39d1-4c86-8dcb-56dcb80ec739","user_code_job_started_at":"2026-10-05T05:42:40.257Z","user_code_job_completed_at":"2026-10-05T05:47:57.834Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=ce3d8d517d1ebc80458fafcf556332d5f49d7a1bceff2b1fe93c46de6452fc5a","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"d757a095-04de-48c8-b6e4-3d2ec8ce81cd","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.6","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T04:46:17.047Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-c97a22aae1657103e327908164f9c045","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=d757a095-04de-48c8-b6e4-3d2ec8ce81cd\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=d757a095-04de-48c8-b6e4-3d2ec8ce81cd\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=d757a095-04de-48c8-b6e4-3d2ec8ce81cd\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"513bdf82-a08d-49b9-a5b9-9034a97a809b","user_code_job_started_at":"2026-10-05T04:55:45.526Z","user_code_job_completed_at":"2026-10-05T05:03:03.781Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=e8de376a3c61eefc6f950e1bbd22fc81a72ed93da6f4b556d8fdc70dd7626038","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"29ddf4a0-6df5-4bf6-b7db-4ac4c7072c25","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.5","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T02:44:08.793Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-fcfb777c24f6df873e623a7d142514f0","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=29ddf4a0-6df5-4bf6-b7db-4ac4c7072c25\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=29ddf4a0-6df5-4bf6-b7db-4ac4c7072c25\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=29ddf4a0-6df5-4bf6-b7db-4ac4c7072c25\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"5948f3dd-37c3-4847-9494-13770e28b82c","user_code_job_started_at":"2026-10-05T02:52:43.128Z","user_code_job_completed_at":"2026-10-05T03:01:02.367Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=7fec255850c162f893ce5454cd1f55664114ec87478a9e657084e8e5e6ffc3a1","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"07c051a2-d349-46f2-9157-6c98cc3ae76d","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.4","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T01:35:01.188Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-fdefbc9b7a664cd926e8f2c3a463a4be","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=07c051a2-d349-46f2-9157-6c98cc3ae76d\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=07c051a2-d349-46f2-9157-6c98cc3ae76d\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=07c051a2-d349-46f2-9157-6c98cc3ae76d\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"6bbc2d0d-6fde-4113-9604-bb935d16d41d","user_code_job_started_at":"2026-10-05T01:39:51.775Z","user_code_job_completed_at":"2026-10-05T01:47:48.597Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=9e419461cdd6c04c78acd3264fdc71637b5a7e53e73d70d95fc8afd0f66aa118","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"97585b6d-8a91-4be0-bf4d-a168d61df90c","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.3","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T00:47:26.560Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-04010698d7538846241ce9b89224fd40","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=97585b6d-8a91-4be0-bf4d-a168d61df90c\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=97585b6d-8a91-4be0-bf4d-a168d61df90c\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=97585b6d-8a91-4be0-bf4d-a168d61df90c\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"bdbdb7ab-b4ca-40ce-bb80-7d791aaa4eed","user_code_job_started_at":"2026-10-05T00:50:25.910Z","user_code_job_completed_at":"2026-10-05T00:58:25.368Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=7a51abfa54e74e33e7a9d7fee115ddde0668908e770da41935d5fb91096d96bb","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"11a162c1-951f-47e3-8f83-660b7c8dec6b","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.2","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-04T20:42:25.857Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-b295b7fc212ec482ce2d90f1cc809bf9","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=11a162c1-951f-47e3-8f83-660b7c8dec6b\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=11a162c1-951f-47e3-8f83-660b7c8dec6b\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=11a162c1-951f-47e3-8f83-660b7c8dec6b\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"363c3448-fb09-4da6-b9bf-bc0e216b3531","user_code_job_started_at":"2026-10-04T22:04:21.772Z","user_code_job_completed_at":"2026-10-04T22:08:27.541Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=85b5b1bf068520a999c1e95c00bb11ca65b4c545a10dbb184d93a6d87476a69d","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"20c1facb-7cd6-4235-b2bc-6f24d9e89563","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.1","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-03T06:56:20.205Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-0aa20af2734ddbc93d819bac000d1aa4","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=20c1facb-7cd6-4235-b2bc-6f24d9e89563\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=20c1facb-7cd6-4235-b2bc-6f24d9e89563\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=20c1facb-7cd6-4235-b2bc-6f24d9e89563\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"0ea02129-f9cc-40f2-9cf2-8b08e970252a","user_code_job_started_at":"2026-10-03T07:53:29.792Z","user_code_job_completed_at":"2026-10-03T08:23:36.379Z","user_code_job_error":{"message":"Build timed out after 30 minutes","error_code":"user_code_job_timeout"},"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=87de178b6a93ad8f6ee24fae8e568d36c20bd3897f1a929bd42618fe4d3032a8","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"package_release_id":"f050d04e-367c-49f8-869a-5a164b9c57c6","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.0","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-03T04:37:46.866Z","circuit_json_build_error":null,"circuit_json_build_error_last_updated_at":null,"has_transpiled":false,"transpilation_error":null,"transpilation_logs":null,"transpilation_in_progress":false,"transpilation_started_at":null,"transpilation_completed_at":null,"transpilation_is_stale":true,"transpilation_display_status":"pending","fs_sha":"md5-7749d273fff3d95957d72d46760a76d6","circuit_json_build_logs":null,"circuit_json_build_in_progress":false,"circuit_json_build_started_at":null,"circuit_json_build_completed_at":null,"circuit_json_build_is_stale":true,"circuit_json_build_display_status":"pending","image_generation_error":null,"image_generation_error_last_updated_at":null,"image_generation_logs":null,"image_generation_in_progress":false,"image_generation_started_at":null,"image_generation_completed_at":null,"image_generation_is_stale":true,"image_generation_display_status":"pending","pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=f050d04e-367c-49f8-869a-5a164b9c57c6\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=f050d04e-367c-49f8-869a-5a164b9c57c6\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=f050d04e-367c-49f8-869a-5a164b9c57c6\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"284e991b-f173-46f7-beb2-c5d918bd6108","user_code_job_started_at":"2026-10-03T04:42:59.772Z","user_code_job_completed_at":"2026-10-03T04:46:38.270Z","user_code_job_error":null,"user_code_job_completed_logs":null,"user_code_job_log_stream_url":"https://usercode.tscircuit.com/user_code_jobs/view_log_stream?user_code_job_id=66e2eeea84f02308b7774bae328a63deac3599a68c496a213f856b3ae61e5c86","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null}]; window.SSR_PACKAGE_BUILDS = []; window.SSR_RELATED_PACKAGES = [{"package_id":"d2ea0487-143c-447f-a62e-ab971c2524cd","creator_account_id":"9f398687-69d0-4ef4-a48c-bb6dc990e7df","latest_package_release_id":"bde55b83-e437-4d8f-b5c0-1e0b68a70ec3","last_built_release_id":"bde55b83-e437-4d8f-b5c0-1e0b68a70ec3","latest_package_release_fs_sha":"md5-4095a4495925ad2deb356dc9c3cccaaf","latest_pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=bde55b83-e437-4d8f-b5c0-1e0b68a70ec3\u0026file_path=dist%2Findex%2Fpcb.svg","latest_sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=bde55b83-e437-4d8f-b5c0-1e0b68a70ec3\u0026file_path=dist%2Findex%2Fschematic.svg","latest_cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=bde55b83-e437-4d8f-b5c0-1e0b68a70ec3\u0026file_path=dist%2Findex%2F3d.png","latest_version":"1.4.0","license":"unset","owner_org_id":"7ca3101d-0ece-4182-a775-d3aee7d7f0a0","org_owner_tscircuit_handle":"astra","owner_github_username":null,"github_repo_full_name":null,"is_source_from_github":false,"description":null,"name":"astra/nema17-stepper-motor-controller-spring-clamp-rp2040","unscoped_name":"nema17-stepper-motor-controller-spring-clamp-rp2040","star_count":0,"created_at":"2026-09-26T19:14:57.511Z","updated_at":"2026-09-28T19:52:44.691Z","ai_description":"A 4-layer RP2040 controller board that negotiates USB‑C PD motor power and drives a NEMA17 stepper via a DRV8825, with current sensing, thermal shutdown, RGB status LED, buzzer alarm, optional AS5600 encoder, protection/filtering, and test points.","ai_usage_instructions":null,"is_private":false,"is_unlisted":false,"is_public":true,"public_dist_enabled":false,"has_public_dist":true,"starred_at":null,"default_view":"files","website":null,"github_installation_id":null,"allow_pr_previews":false,"related_type":"same_author","thumbnail_url":"https://api.tscircuit.com/package_files/view?package_release_id=bde55b83-e437-4d8f-b5c0-1e0b68a70ec3\u0026file_path=dist%2Findex%2Fpcb.svg"},{"package_id":"7c4f7ef6-0c20-441e-b5a5-1952d955eccf","creator_account_id":"d16b4134-1b33-4d60-bdf2-151748766d5b","latest_package_release_id":"cbdd52b4-d52e-4095-8882-d107ff959339","last_built_release_id":"cbdd52b4-d52e-4095-8882-d107ff959339","latest_package_release_fs_sha":"md5-2ea962e9b2b863a7a4703b259838dc8e","latest_pcb_preview_image_url":"https://registry-api.tscircuit.com/package_files/view?package_release_id=cbdd52b4-d52e-4095-8882-d107ff959339\u0026file_path=dist%2Findex%2Fpcb.svg","latest_sch_preview_image_url":"https://registry-api.tscircuit.com/package_files/view?package_release_id=cbdd52b4-d52e-4095-8882-d107ff959339\u0026file_path=dist%2Findex%2Fschematic.svg","latest_cad_preview_image_url":"https://registry-api.tscircuit.com/package_files/download?package_release_id=cbdd52b4-d52e-4095-8882-d107ff959339\u0026file_path=dist%2Findex%2F3d.png","latest_version":"0.0.1","license":"unset","owner_org_id":"9e4219cf-4b9e-4932-9128-52cef42cad89","org_owner_tscircuit_handle":"0hmx3","owner_github_username":null,"github_repo_full_name":null,"is_source_from_github":false,"description":"","name":"aura/diy-power-delivery-trigger","unscoped_name":"diy-power-delivery-trigger","star_count":0,"created_at":"2026-04-23T21:10:31.029Z","updated_at":"2026-04-25T11:57:14.077Z","ai_description":"This hardware design implements a USB Type-C port with supporting power management and signal conditioning components, including a USB-C connector, a FUSB302 USB-C port controller, ESD protection diodes, a buck converter for 3.3V power regulation, an STM32 microcontroller for control and processing, an RGB LED indicator, push button, terminal block connections, and associated filtering and support components.","ai_usage_instructions":null,"is_private":false,"is_unlisted":false,"is_public":true,"public_dist_enabled":false,"has_public_dist":true,"starred_at":null,"default_view":"files","website":null,"github_installation_id":null,"allow_pr_previews":false,"related_type":"similar_ai_description","thumbnail_url":"https://registry-api.tscircuit.com/package_files/view?package_release_id=cbdd52b4-d52e-4095-8882-d107ff959339\u0026file_path=dist%2Findex%2Fpcb.svg"},{"package_id":"78c97ef5-3f00-466a-93ba-5ad748a0cb2d","creator_account_id":"9f398687-69d0-4ef4-a48c-bb6dc990e7df","latest_package_release_id":"43abb248-47c9-4cfd-9d4c-99af86d33572","last_built_release_id":"43abb248-47c9-4cfd-9d4c-99af86d33572","latest_package_release_fs_sha":"md5-f95e3b44ac11a208f017f25beb325180","latest_pcb_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=43abb248-47c9-4cfd-9d4c-99af86d33572\u0026file_path=dist%2Findex%2Fpcb.svg","latest_sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=43abb248-47c9-4cfd-9d4c-99af86d33572\u0026file_path=dist%2Findex%2Fschematic.svg","latest_cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=43abb248-47c9-4cfd-9d4c-99af86d33572\u0026file_path=dist%2Findex%2F3d.png","latest_version":"1.3.4","license":"unset","owner_org_id":"2d29cfe5-d314-4a54-b56a-a6fa34c19af3","org_owner_tscircuit_handle":"muse1","owner_github_username":null,"github_repo_full_name":null,"is_source_from_github":false,"description":null,"name":"muse/esp32-eink-display","unscoped_name":"esp32-eink-display","star_count":0,"created_at":"2026-10-03T00:27:01.165Z","updated_at":"2026-10-03T03:05:45.691Z","ai_description":"A 55×46 mm two-layer ESP32-S3 e-paper controller board with USB‑C power/programming, buck regulation, FPC display connector, UC8179-style boost/charge-pump circuitry, ESD protection, controls, and routed passive components.","ai_usage_instructions":null,"is_private":false,"is_unlisted":false,"is_public":true,"public_dist_enabled":false,"has_public_dist":true,"starred_at":null,"default_view":"files","website":null,"github_installation_id":null,"allow_pr_previews":false,"related_type":"random","thumbnail_url":"https://api.tscircuit.com/package_files/view?package_release_id=43abb248-47c9-4cfd-9d4c-99af86d33572\u0026file_path=dist%2Findex%2Fpcb.svg"}]; window.SSR_PACKAGE_ROUTE = {"author":"astra","packageName":"am3352-sbc","packageNameWithScope":"astra/am3352-sbc","version":null,"isLegacyRoute":false,"kind":"file","filePath":"dist/viewer-part-02.txt"};

astra/am3352-sbc

A 4-layer AM3352 single-board computer with 128‑MiB DDR3, PMIC power regulation, USB‑C 5‑V PD input, dual USB host ports, HDMI output with ESD protection, microSD/UART/JTAG interfaces, addressable RGB indicators, and a PWM-driven buzzer.

Version
0.1.19
License
unset
Stars
0

dist/viewer-part-02.txt

(d.x+p.x)/2,y:(d.y+p.y)/2}};s.has(g)||s.set(g,m)}}return Array.from(s.values())}function zjn(t,{connMap:e,minClearance:n}={}){const o=OF(t),i=xmt(t);if(o.length===0||i.length===0)return[];const r=X9(t);n??=Y8(r,"min_trace_to_pad_edge_clearance")??G8.min_trace_to_pad_edge_clearance,e??=Vf(t);const s=new yz({objects:o,getBounds:Z9,getId:c=>Yh(c)}),a=new Map,A=new Set;for(const c of i){const l=s.getObjectsInBounds(GF(c),n+c.thickness/2);for(const u of l){const g=Yh(u);if(!dx(u).includes(c.layer)||e.areIdsConnected(c.pcb_trace_id,g))continue;const h=`${g}_${c.pcb_trace_id}`,{gap:d,center:p}=Ise(c,u);if(Cse(d)){a.delete(h),A.add(h);continue}if(A.has(h)||d+q4>=n)continue;const m={type:"pcb_pad_trace_clearance_error",pcb_pad_trace_clearance_error_id:`pad_trace_clearance_${h}`,error_type:"pcb_pad_trace_clearance_error",message:`Pad ${eI(t,g)} and trace ${eI(t,c.pcb_trace_id)} are too close (clearance: ${hQ(d)}, minimum: ${hQ(n)})`,pcb_pad_id:g,pcb_trace_id:c.pcb_trace_id,minimum_clearance:n,actual_clearance:d,center:p},_=a.get(h);(!_||d<_.gap)&&a.set(h,{error:m,gap:d})}}return Array.from(a.values()).map(({error:c})=>c)}function Jjn(t,{connMap:e,minClearance:n}={}){const o=t.filter(A=>A.type==="pcb_via"),i=xmt(t);if(o.length===0||i.length===0)return[];const r=X9(t);n??=Y8(r,"min_trace_to_pad_edge_clearance")??G8.min_trace_to_pad_edge_clearance,e??=Vf(t);const s=new Map,a=new Set;for(const A of o)for(const c of i){if(!dx(A).includes(c.layer)||e.areIdsConnected(c.pcb_trace_id,A.pcb_via_id))continue;const l=`${A.pcb_via_id}_${c.pcb_trace_id}`,{gap:u,center:g}=Ise(c,A);if(Cse(u)){s.delete(l),a.add(l);continue}if(a.has(l)||u+q4>=n)continue;const h={type:"pcb_via_trace_clearance_error",pcb_via_trace_clearance_error_id:`via_trace_clearance_${l}`,error_type:"pcb_via_trace_clearance_error",message:`Via ${eI(t,A.pcb_via_id)} and trace ${eI(t,c.pcb_trace_id)} are too close (clearance: ${hQ(u)}, minimum: ${hQ(n)})`,pcb_via_id:A.pcb_via_id,pcb_trace_id:c.pcb_trace_id,minimum_clearance:n,actual_clearance:u,center:g},d=s.get(l);(!d||u<d.gap)&&s.set(l,{error:h,gap:u})}return Array.from(s.values()).map(({error:A})=>A)}function Wjn(t,{connMap:e,minClearance:n}={}){const o=t.filter(c=>c.type==="pcb_via"),i=OF(t);if(o.length===0||i.length===0)return[];const r=X9(t),s=n??Y8(r,"min_pad_edge_to_pad_edge_clearance")??G8.min_pad_edge_to_pad_edge_clearance;e??=Vf(t);const a=new yz({objects:i,getBounds:Z9,getId:Yh}),A=[];for(const c of o){const l=a.getObjectsInBounds(Z9(c),s);for(const u of l){const g=Yh(u);if(!dx(c).some(d=>dx(u).includes(d))||e.areIdsConnected(c.pcb_via_id,g))continue;const h=YQ(c,u);h+q4>=s||A.push({type:"pcb_pad_pad_clearance_error",pcb_pad_pad_clearance_error_id:`via_pad_clearance_${c.pcb_via_id}_${g}`,error_type:"pcb_pad_pad_clearance_error",message:`Via ${eI(t,c.pcb_via_id)} and pad ${eI(t,g)} are too close (clearance: ${hQ(h)}, minimum: ${hQ(s)})`,pcb_pad_ids:[c.pcb_via_id,g],minimum_clearance:s,actual_clearance:h,center:qWn(c,u)})}}return A}function jjn(t){const e=X9(t);if(e&&"is_via_in_pad_allowed"in e&&e.is_via_in_pad_allowed===!0)return[];const n=t.filter(A=>A.type==="pcb_via"),o=OF(t);if(n.length===0||o.length===0)return[];const i=Vf(t),r=new Map(o.map((A,c)=>[Yh(A),c])),s=new yz({objects:o,getBounds:Z9,getId:Yh}),a=[];for(const A of n){const c=s.getObjectsInBounds(Z9(A));for(const l of c){const u=Yh(l),g=dx(A),h=dx(l);if(!g.some(m=>h.includes(m))||i.areIdsConnected(A.pcb_via_id,u)||YQ(A,l)>0)continue;const d=r.get(u)??0,p=JWn(t,l,d);a.push({type:"pcb_placement_error",pcb_placement_error_id:`via_in_pad_${A.pcb_via_id}_${u}`,error_type:"pcb_placement_error",message:`Via copper at (${A.x.toFixed(2)}mm, ${A.y.toFixed(2)}mm) overlaps ${p}`,subcircuit_id:A.subcircuit_id??l.subcircuit_id})}}return a}var Ymt=t=>{const e=new Set;for(const n of t)n.type==="pcb_pad_trace_clearance_error"&&typeof n.pcb_trace_id=="string"&&typeof n.pcb_pad_id=="string"&&e.add(`overlap_${n.pcb_trace_id}_${n.pcb_pad_id}`),n.type==="pcb_via_trace_clearance_error"&&typeof n.pcb_trace_id=="string"&&typeof n.pcb_via_id=="string"&&e.add(`overlap_${n.pcb_trace_id}_${n.pcb_via_id}`);return t.filter(n=>{const o=n;return!(o.type==="pcb_trace_error"&&typeof o.pcb_trace_error_id=="string"&&e.has(o.pcb_trace_error_id))})};function $jn(t){const e=[],n=t.filter(a=>"source_component_id"in a&&(a.type==="source_component"||a.type.startsWith("source_simple_"))),o=t.filter(a=>a.type==="source_port"),i=t.filter(a=>a.type==="source_trace"),r=new Set;for(const a of i)for(const A of a.connected_source_port_ids??[])r.add(A);const s=new Map;for(const a of n)"internally_connected_source_port_ids"in a&&a.internally_connected_source_port_ids&&s.set(a.source_component_id,a.internally_connected_source_port_ids);for(const a of s.values())for(const A of a)if(A.some(c=>r.has(c)))for(const c of A)r.add(c);for(const a of o)if(a.must_be_connected===!0&&!r.has(a.source_port_id)){const c=n.find(l=>l.source_component_id===a.source_component_id)?.name??"Unknown";e.push({type:"source_pin_must_be_connected_error",source_pin_must_be_connected_error_id:`source_pin_must_be_connected_error_${a.source_port_id}`,error_type:"source_pin_must_be_connected_error",message:`Port ${a.name} on ${c} must be connected but is floating`,source_component_id:a.source_component_id??"",source_port_id:a.source_port_id,subcircuit_id:a.subcircuit_id})}return e}function qjn(t){const e=t.filter(r=>r.type==="source_component"&&(r.ftype==="simple_push_button"||r.ftype==="simple_switch")),n=t.filter(r=>r.type==="source_port"),o=t.filter(r=>r.type==="schematic_port"),i=[];for(const r of e){const s=o.flatMap(c=>{const l=n.find(u=>u.source_port_id===c.source_port_id&&u.source_component_id===r.source_component_id);return l?[l]:[]});if(s.length!==2)continue;const a=s[0].subcircuit_connectivity_map_key,A=s[1].subcircuit_connectivity_map_key;a&&a===A&&i.push(dV.parse({type:"source_component_misconfigured_error",message:`Switch ${r.name} has both schematic contacts connected to the same net. Check internallyConnectedPins and the footprint pin mapping.`,source_component_ids:[r.source_component_id],source_port_ids:s.map(c=>c.source_port_id),is_fatal:!0}))}return i}var Xjn=["must_be_connected","provides_power","requires_power","provides_ground","requires_ground","provides_voltage","requires_voltage","do_not_connect","include_in_board_pinout","can_use_internal_pullup","is_using_internal_pullup","needs_external_pullup","can_use_internal_pulldown","is_using_internal_pulldown","needs_external_pulldown","can_use_open_drain","is_using_open_drain","can_use_push_pull","is_using_push_pull","should_have_decoupling_capacitor","recommended_decoupling_capacitor_capacitance","is_configured_for_i2c_sda","is_configured_for_i2c_scl","is_configured_for_spi_mosi","is_configured_for_spi_miso","is_configured_for_spi_sck","is_configured_for_spi_cs","is_configured_for_uart_tx","is_configured_for_uart_rx","supports_i2c_sda","supports_i2c_scl","supports_spi_mosi","supports_spi_miso","supports_spi_sck","supports_spi_cs","supports_uart_tx","supports_uart_rx"];function Zjn(t){return Xjn.some(e=>t[e]!==void 0)}function e$n(t){const e=[],n=Xc(t),o=n.source_component.list(),i=n.source_port.list(),r=new Map;for(const s of i){if(!s.source_component_id)continue;const a=r.get(s.source_component_id)??[];a.push(s),r.set(s.source_component_id,a)}for(const s of o){if(s.ftype!=="simple_chip")continue;const a=r.get(s.source_component_id)??[];a.length===0||a.some(c=>Zjn(c))||e.push({type:"source_component_pins_underspecified_warning",source_component_pins_underspecified_warning_id:`source_component_pins_underspecified_warning_${s.source_component_id}`,warning_type:"source_component_pins_underspecified_warning",message:`All pins on ${s.name} are underspecified (no pinAttributes set)`,source_component_id:s.source_component_id,source_port_ids:a.map(c=>c.source_port_id),subcircuit_id:a[0]?.subcircuit_id})}return e}var Umt=(t,e)=>t.ftype==="simple_chip"&&e.filter(n=>n.do_not_connect!==!0).length>=2;function t$n(t){const e=[],n=Xc(t),o=n.source_component.list(),i=n.source_port.list(),r=new Map;for(const s of i){if(!s.source_component_id)continue;const a=r.get(s.source_component_id)??[];a.push(s),r.set(s.source_component_id,a)}for(const s of o){const a=r.get(s.source_component_id)??[];!Umt(s,a)||a.some(c=>c.requires_power===!0)||e.push({type:"source_no_power_pin_defined_warning",source_no_power_pin_defined_warning_id:`source_no_power_pin_defined_warning_${s.source_component_id}`,warning_type:"source_no_power_pin_defined_warning",message:`${s.name} has no pin with requires_power=true`,source_component_id:s.source_component_id,source_port_ids:a.map(c=>c.source_port_id),subcircuit_id:a[0]?.subcircuit_id})}return e}function n$n(t){const e=[],n=Xc(t),o=n.source_component.list(),i=n.source_port.list(),r=new Map;for(const s of i){if(!s.source_component_id)continue;const a=r.get(s.source_component_id)??[];a.push(s),r.set(s.source_component_id,a)}for(const s of o){const a=r.get(s.source_component_id)??[];!Umt(s,a)||a.some(c=>c.requires_ground===!0)||e.push({type:"source_no_ground_pin_defined_warning",source_no_ground_pin_defined_warning_id:`source_no_ground_pin_defined_warning_${s.source_component_id}`,warning_type:"source_no_ground_pin_defined_warning",message:`${s.name} has no pin with requires_ground=true`,source_component_id:s.source_component_id,source_port_ids:a.map(c=>c.source_port_id),subcircuit_id:a[0]?.subcircuit_id})}return e}var o$n=.2,Kmt=3,i$n=1e-9;function r$n(t){const e=t.filter(a=>a.type==="schematic_component"),n=t.filter(a=>a.type==="schematic_port"),o=t.filter(a=>a.type==="source_component"),i=new Map(o.map(a=>[a.source_component_id,a])),r=new Map;for(const a of n){if(!a.schematic_component_id)continue;const A=r.get(a.schematic_component_id)??[];A.push(a),r.set(a.schematic_component_id,A)}const s=[];for(const a of e){if(!a.is_box_with_pins||a.size.height<=0)continue;const A=(r.get(a.schematic_component_id)??[]).filter(I=>I.side_of_component==="left"||I.side_of_component==="right");if(A.length<2)continue;const c=A.map(I=>I.center.y),l=Math.max(...c),u=Math.min(...c),g=a.center.y+a.size.height/2,h=a.center.y-a.size.height/2,p=(a.pin_spacing??o$n)*Kmt,m={top:g-l,bottom:u-h},f=(a.source_component_id?i.get(a.source_component_id):void 0)?.name??a.schematic_component_id;for(const I of["top","bottom"]){const C=m[I];if(C<=p+i$n||C<=0)continue;const y=I==="top"?"above":"below",x=`excessive_${I}_padding`;s.push({type:"schematic_component_styling_warning",schematic_component_styling_warning_id:`schematic_component_styling_warning_${a.schematic_component_id}_${x}`,warning_type:"schematic_component_styling_warning",message:`${f} has excessive empty space ${y} its pins (${C.toFixed(2)}mm, more than ${Kmt} pin spacings)`,schematic_component_id:a.schematic_component_id,styling_issue_type:x,schematic_port_ids:A.map(E=>E.schematic_port_id),source_component_id:a.source_component_id,schematic_sheet_id:a.schematic_sheet_id,subcircuit_id:a.subcircuit_id})}}return s}var s$n=t=>/^unnamed_[a-z0-9_-]+\d+$/i.test(t),a$n=(t,e)=>{const{center:n,size:o}=e,i=1e-9;return t.position.x>=n.x-o.width/2-i&&t.position.x<=n.x+o.width/2+i&&t.position.y>=n.y-o.height/2-i&&t.position.y<=n.y+o.height/2+i};function A$n(t){const e=t.filter(A=>A.type==="schematic_component"),n=t.filter(A=>A.type==="source_component"),o=t.filter(A=>A.type==="schematic_text"),i=new Map(n.map(A=>[A.source_component_id,A])),r=new Map,s=[];for(const A of o){if(!A.schematic_component_id){A.schematic_symbol_id&&s.push(A);continue}const c=r.get(A.schematic_component_id)??new Set;c.add(A.text.trim()),r.set(A.schematic_component_id,c)}const a=[];for(const A of e){if(!A.source_component_id)continue;const c=i.get(A.source_component_id);if(!c)continue;const l=new Set([c.name,c.display_name].map(p=>p?.trim()).filter(p=>!!p)),u=[...l].find(p=>!s$n(p)),g=r.get(A.schematic_component_id),h=[...l].some(p=>g?.has(p))||s.some(p=>l.has(p.text.trim())&&a$n(p,A));if(u&&h)continue;const d=u??"Schematic component";a.push({type:"schematic_component_styling_warning",schematic_component_styling_warning_id:`schematic_component_styling_warning_${A.schematic_component_id}_missing_reference_designator_text`,warning_type:"schematic_component_styling_warning",message:`${d} is missing schematic reference designator text. For a custom symbol, add name="{REFDES}" inside the symbol.`,schematic_component_id:A.schematic_component_id,styling_issue_type:"missing_reference_designator_text",source_component_id:A.source_component_id,schematic_sheet_id:A.schematic_sheet_id,subcircuit_id:A.subcircuit_id})}return a}var KF=1e-9,c$n=t=>t.display_pin_label??`pin ${t.pin_number}`;function l$n(t){const e=t.filter(a=>a.type==="schematic_component"),n=t.filter(a=>a.type==="schematic_port"),o=t.filter(a=>a.type==="source_component"),i=new Map(o.map(a=>[a.source_component_id,a])),r=new Map;for(const a of n){if(!a.schematic_component_id)continue;const A=r.get(a.schematic_component_id)??[];A.push(a),r.set(a.schematic_component_id,A)}const s=[];for(const a of e){if(a.is_box_with_pins===!1||a.size.width<=0||a.size.height<=0)continue;const A=a.center.x-a.size.width/2,c=a.center.x+a.size.width/2,l=a.center.y-a.size.height/2,u=a.center.y+a.size.height/2,h=(r.get(a.schematic_component_id)??[]).filter(C=>C.side_of_component==="left"||C.side_of_component==="right"?C.center.y<l-KF||C.center.y>u+KF:C.side_of_component==="top"||C.side_of_component==="bottom"?C.center.x<A-KF||C.center.x>c+KF:!1).sort((C,y)=>{const x=C.side_of_component==="left"||C.side_of_component==="right",E=y.side_of_component==="left"||y.side_of_component==="right";return x&&E?y.center.y-C.center.y:!x&&!E?C.center.x-y.center.x:x?-1:1});if(h.length===0)continue;const d=Math.max(a.size.height,...h.filter(C=>C.side_of_component==="left"||C.side_of_component==="right").map(C=>2*Math.abs(C.center.y-a.center.y))),p=Math.max(a.size.width,...h.filter(C=>C.side_of_component==="top"||C.side_of_component==="bottom").map(C=>2*Math.abs(C.center.x-a.center.x))),m=[];d>a.size.height+KF&&m.push(`increase schHeight to at least ${d.toFixed(2)}mm`),p>a.size.width+KF&&m.push(`increase schWidth to at least ${p.toFixed(2)}mm`);const f=(a.source_component_id?i.get(a.source_component_id):void 0)?.name??a.schematic_component_id,I=h.map(c$n).join(", ");s.push({type:"schematic_component_styling_warning",schematic_component_styling_warning_id:`schematic_component_styling_warning_${a.schematic_component_id}_ports_outside_body`,warning_type:"schematic_component_styling_warning",message:`${f} has schematic pins outside its body (${I}); ${m.join(" and ")}`,schematic_component_id:a.schematic_component_id,styling_issue_type:"ports_outside_body",schematic_port_ids:h.map(C=>C.schematic_port_id),source_component_id:a.source_component_id,schematic_sheet_id:a.schematic_sheet_id,subcircuit_id:a.subcircuit_id})}return s}function Bse(t,e){const n=new Map,o=new Map;for(const c of t){const l=Yh(c);o.set(l,c),"pcb_component_id"in c&&c.pcb_component_id&&n.set(l,c.pcb_component_id)}const i=e.flatMap(c=>c.type==="pcb_footprint_overlap_error"?c.related_errors??[c]:[c]),r=new Map,s=new Map;for(const c of i){let l;if(c.type==="pcb_footprint_overlap_error"){if(c.pcb_keepout_ids?.length)continue;const h=c,d=[...c.pcb_smtpad_ids??[],...c.pcb_plated_hole_ids??[],...c.pcb_hole_ids??[]];if(d.some(p=>!n.has(p)))continue;l=h.pcb_component_ids??d.map(p=>n.get(p))}else if(c.type==="pcb_pad_pad_clearance_error"){if(c.pcb_pad_ids.some(h=>!n.has(h)))continue;l=c.pcb_pad_ids.map(h=>n.get(h))}else if(c.type==="pcb_courtyard_overlap_error")l=c.pcb_component_ids;else continue;if(l=[...new Set(l)].sort(),l.length!==2)continue;const u=JSON.stringify(l);s.set(c,u);const g=r.get(u)??[];g.push(c),r.set(u,g)}const a=new Map;for(const[c,l]of r){const u=l.filter(f=>f.type==="pcb_footprint_overlap_error");if(l.length<2||u.length===0)continue;const g=JSON.parse(c),h=g.map(f=>{const I=o.get(f),C=I?.type==="pcb_component"?o.get(I.source_component_id):void 0;return C?.type==="source_component"?C.name:f}),p=[[u.length,"footprint overlap"],[l.filter(f=>f.type==="pcb_pad_pad_clearance_error").length,"pad clearance violation"],[l.filter(f=>f.type==="pcb_courtyard_overlap_error").length,"courtyard conflict"]].filter(([f])=>f>0).map(([f,I])=>`${f} ${I}${f===1?"":"s"}`),m={type:"pcb_footprint_overlap_error",error_type:"pcb_footprint_overlap_error",pcb_error_id:`pcb_component_overlap_${g.join("_")}`,pcb_component_ids:g,message:`${h.join(" overlaps ")}: ${p.join(", ")}. Move the components apart.`,related_errors:l};l.some(f=>f.is_fatal)&&(m.is_fatal=!0);const _=new Set;for(const f of l)if(f.type==="pcb_footprint_overlap_error")for(const I of[...f.pcb_smtpad_ids??[],...f.pcb_plated_hole_ids??[],...f.pcb_hole_ids??[]])_.add(I);else if(f.type==="pcb_pad_pad_clearance_error")for(const I of f.pcb_pad_ids)_.add(I);for(const[f,I]of[["pcb_smtpad_ids","pcb_smtpad"],["pcb_plated_hole_ids","pcb_plated_hole"],["pcb_hole_ids","pcb_hole"]]){const C=[..._].filter(y=>o.get(y)?.type===I).sort();C.length&&(m[f]=C)}a.set(c,m)}const A=new Set;return i.flatMap(c=>{const l=s.get(c),u=l===void 0?void 0:a.get(l);return!u||l===void 0?[c]:A.has(l)?[]:(A.add(l),[u])})}function u$n(t){const e=new Map,n=s=>{let a=s;for(;e.has(a)&&e.get(a)!==a;)a=e.get(a);for(;e.has(s)&&e.get(s)!==a;){const A=e.get(s);e.set(s,a),s=A}return a},o=s=>{if(s.length<2)return;const a=n(s[0]);for(const A of s.slice(1))e.set(n(A),a)},i=new Map;for(const s of t){if(s.type==="source_net"&&s.name.trim()){const a=i.get(s.name)??[];a.push(s),i.set(s.name,a)}if(s.type==="source_trace"&&o([...s.connected_source_net_ids.map(a=>`net:${a}`),...s.connected_source_port_ids.map(a=>`port:${a}`)]),s.type==="source_component_internal_connection"&&o(s.source_port_ids.map(a=>`port:${a}`)),s.type==="source_component")for(const a of s.internally_connected_source_port_ids??[])o(a.map(A=>`port:${A}`))}const r=[];for(const[s,a]of i){const A=new Set(a.map(l=>n(`net:${l.source_net_id}`)));if(A.size<2)continue;const c=a.map(l=>l.source_net_id).sort();r.push({type:"source_confusing_net_name_warning",source_confusing_net_name_warning_id:`source_confusing_net_name_warning_${c[0]}`,warning_type:"source_confusing_net_name_warning",message:`Nets named "${s}" are not all connected (${A.size} separate electrical networks). Connect them or use distinct names to avoid confusion.`,source_net_ids:c,net_name:s,...a.every(l=>l.subcircuit_id===a[0].subcircuit_id)?{subcircuit_id:a[0].subcircuit_id}:{}})}return r}function g$n(t){switch(t.insertion_direction){case"from_left":return"x-";case"from_right":return"x+";case"from_top":return"y+";case"from_bottom":return"y-";case"from_above":case"from_below":return null;default:return null}}function d$n(t){if(t.insertion_direction)return g$n(t);if(!t.center||!t.cable_insertion_center)return null;const e=t.cable_insertion_center.x-t.center.x,n=t.cable_insertion_center.y-t.center.y;return Math.abs(e)<1e-6&&Math.abs(n)<1e-6?null:Math.abs(e)>=Math.abs(n)?e>=0?"x+":"x-":n>=0?"y+":"y-"}function h$n(t,e){if(!t.center)return null;const n=[{direction:"x-",distance:t.center.x-e.minX},{direction:"x+",distance:e.maxX-t.center.x},{direction:"y-",distance:t.center.y-e.minY},{direction:"y+",distance:e.maxY-t.center.y}];return n.sort((o,i)=>o.distance-i.distance),n[0]?.direction??null}function Vmt(t){const e=t.find(r=>r.type==="pcb_board");if(!e)return[];const n=(()=>{try{return BWn(e)}catch{return null}})();if(!n)return[];const o=[],i=t.filter(r=>r.type==="pcb_component");for(const r of i){const s=d$n(r),a=h$n(r,n);if(!s||!a||s===a)continue;const A=HF(t,r.pcb_component_id);o.push({type:"pcb_connector_not_in_accessible_orientation_warning",warning_type:"pcb_connector_not_in_accessible_orientation_warning",pcb_connector_not_in_accessible_orientation_warning_id:`pcb_connector_not_in_accessible_orientation_warning_${r.pcb_component_id}`,message:`${A} is facing ${s} but should face ${a} so the connector is accessible from the board edge`,pcb_component_id:r.pcb_component_id,source_component_id:r.source_component_id,pcb_board_id:e.pcb_board_id,facing_direction:s,recommended_facing_direction:a,subcircuit_id:r.subcircuit_id})}return o}function zmt(t){if(t.type==="pcb_courtyard_rect"){const e=t.width/2,n=t.height/2,o=[{x:-e,y:-n},{x:+e,y:-n},{x:+e,y:+n},{x:-e,y:+n}],i=(t.ccw_rotation??0)*Math.PI/180,r=Math.cos(i),s=Math.sin(i);return o.map(({x:a,y:A})=>({x:t.center.x+a*r-A*s,y:t.center.y+a*s+A*r}))}return t.type==="pcb_courtyard_circle"?Array.from({length:32},(n,o)=>{const i=2*Math.PI*o/32;return{x:t.center.x+t.radius*Math.cos(i),y:t.center.y+t.radius*Math.sin(i)}}):t.outline}function Jmt(t,e){const n=t.find(i=>i.type==="pcb_component"&&i.pcb_component_id===e);if(n?.type!=="pcb_component")return e;const o=t.find(i=>i.type==="source_component"&&i.source_component_id===n.source_component_id);return o?.type==="source_component"&&o.name?o.name:e}function p$n(t,e){if(t.some(n=>nD(n,e))||e.some(n=>nD(n,t)))return!0;for(let n=0;n<t.length;n++){const o=t[n],i=t[(n+1)%t.length];for(let r=0;r<e.length;r++){const s=e[r],a=e[(r+1)%e.length];if(X1(o,i,s,a))return!0}}return!1}function m$n(t){const e=t.filter(r=>r.type==="pcb_courtyard_rect"||r.type==="pcb_courtyard_circle"||r.type==="pcb_courtyard_outline"),n=new Map;for(const r of e){const s=r.pcb_component_id;n.has(s)||n.set(s,[]),n.get(s).push(r)}const o=Array.from(n.keys()),i=[];for(let r=0;r<o.length;r++)for(let s=r+1;s<o.length;s++){const a=o[r],A=o[s];let c=!1;e:for(const l of n.get(a))for(const u of n.get(A)){if("layer"in l&&"layer"in u&&l.layer!==u.layer)continue;const g=zmt(l),h=zmt(u);if(p$n(g,h)){c=!0;break e}}c&&i.push({type:"pcb_courtyard_overlap_error",pcb_error_id:`pcb_courtyard_overlap_${a}_${A}`,error_type:"pcb_courtyard_overlap_error",message:`Courtyard of ${Jmt(t,a)} overlaps with courtyard of ${Jmt(t,A)}`,pcb_component_ids:[a,A]})}return i}var _$n=t=>t.type==="pcb_courtyard_circle"||t.type==="pcb_courtyard_outline"||t.type==="pcb_courtyard_polygon"||t.type==="pcb_courtyard_rect",f$n=(t,e)=>{if(e.type==="pcb_courtyard_circle"){const o=t.x-e.center.x,i=t.y-e.center.y;return o*o+i*i<=e.radius*e.radius}if(e.type==="pcb_courtyard_rect"){const o=-1*(e.ccw_rotation??0)*Math.PI/180,i=t.x-e.center.x,r=t.y-e.center.y,s=i*Math.cos(o)-r*Math.sin(o),a=i*Math.sin(o)+r*Math.cos(o);return Math.abs(s)<=e.width/2&&Math.abs(a)<=e.height/2}const n=e.type==="pcb_courtyard_polygon"?e.points:e.outline;return nD(t,n)},I$n=(t,e)=>{const n=t.find(i=>i.type==="pcb_component"&&i.pcb_component_id===e),o=t.find(i=>i.type==="source_component"&&i.source_component_id===n?.source_component_id);return(o&&"name"in o?o.name:void 0)??HF(t,e)};function C$n(t){const e=t.filter(A=>A.type==="source_component"&&A.ftype==="simple_test_point"),n=new Set(e.map(A=>A.source_component_id)),o=new Map(e.map(A=>[A.source_component_id,A.name])),i=t.filter(A=>A.type==="pcb_component"&&n.has(A.source_component_id)),r=t.filter(_$n),s=[],a=new Set;for(const A of i)for(const c of r){if(c.pcb_component_id===A.pcb_component_id||c.layer!==A.layer||!f$n(A.center,c))continue;const l=`${A.pcb_component_id}:${c.pcb_component_id}`;if(a.has(l))continue;a.add(l);const u=o.get(A.source_component_id)??"Test point",g=I$n(t,c.pcb_component_id);s.push({type:"pcb_placement_error",pcb_placement_error_id:`testpoint_in_courtyard_${A.pcb_component_id}_${c.pcb_component_id}`,error_type:"pcb_placement_error",message:`Test point ${u} is not accessible because it is inside the courtyard of ${g}`,subcircuit_id:A.subcircuit_id})}return s}async function Wmt(t,{consolidateOverlaps:e=!0}={}){const n=[...gjn(t),...jjn(t),..._jn(t),...yjn(t),...Bjn(t),...Fjn(t),...Hjn(t),...Vjn(t),...m$n(t),...Vmt(t),...C$n(t)];return e?Bse(t,n):n}async function y$n(t){return[...$jn(t),...u$n(t),...qjn(t)]}async function x$n(t){return[...r$n(t),...A$n(t),...l$n(t)]}async function E$n(t){return[...e$n(t),...t$n(t),...n$n(t)]}async function jmt(t){return[...WWn(t),...Qjn(t),...Ujn(t),...Kjn(t),...ojn(t),...zjn(t),...Jjn(t),...Wjn(t),...bjn(t),...Sjn(t),...Mjn(t),...Njn(t)]}var $mt=()=>({minX:Number.POSITIVE_INFINITY,maxX:Number.NEGATIVE_INFINITY,minY:Number.POSITIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY}),QD=(t,e,n)=>{t.minX=Math.min(t.minX,e),t.maxX=Math.max(t.maxX,e),t.minY=Math.min(t.minY,n),t.maxY=Math.max(t.maxY,n)},vD=(t,e,n,o,i)=>{QD(t,e-o/2,n-i/2),QD(t,e+o/2,n+i/2)},qmt=t=>Number.isFinite(t.minX)&&Number.isFinite(t.maxX)&&Number.isFinite(t.minY)&&Number.isFinite(t.maxY),B$n=t=>t.find(e=>e.type==="pcb_component"),b$n=(t,e)=>e?t.filter(n=>"pcb_component_id"in n&&n.pcb_component_id===e):[],S$n=t=>{switch(t){case"from_left":case"from_x_neg":return"left";case"from_right":case"from_x_pos":return"right";case"from_top":case"from_y_pos":case"from_front":return"top";case"from_bottom":case"from_y_neg":case"from_back":return"bottom";case"from_above":case"from_z_pos":return"above";case"from_below":case"from_z_neg":return"below";default:return}},Q$n=t=>{if("insertion_direction"in t)return typeof t.insertion_direction=="string"?t.insertion_direction:void 0},v$n=(t,e)=>{const n=$mt();for(const o of t){if(o.type==="pcb_smtpad"){if("points"in o)for(const i of o.points)QD(n,i.x,i.y);else"x"in o&&"y"in o&&"width"in o&&"height"in o?vD(n,o.x,o.y,o.width,o.height):"x"in o&&"y"in o&&"radius"in o&&vD(n,o.x,o.y,o.radius*2,o.radius*2);continue}if(o.type==="pcb_plated_hole"){"outer_width"in o&&"outer_height"in o?vD(n,o.x,o.y,o.outer_width,o.outer_height):"outer_diameter"in o&&vD(n,o.x,o.y,o.outer_diameter,o.outer_diameter);continue}if(o.type==="pcb_hole"){"hole_diameter"in o?vD(n,o.x,o.y,o.hole_diameter,o.hole_diameter):"hole_width"in o&&"hole_height"in o&&vD(n,o.x,o.y,o.hole_width,o.hole_height);continue}if(o.type==="pcb_silkscreen_path"){for(const i of o.route)QD(n,i.x,i.y);continue}o.type==="pcb_component"&&vD(n,o.center.x,o.center.y,o.width,o.height)}return qmt(n)?n:e},w$n=(t,e)=>{const n=$mt();for(const o of t){if(o.type==="pcb_smtpad"&&("x"in o&&"y"in o&&QD(n,o.x,o.y),"points"in o))for(const i of o.points)QD(n,i.x,i.y);o.type==="pcb_plated_hole"&&o.pcb_port_id&&QD(n,o.x,o.y)}return qmt(n)?n:e},P$n=t=>{const e=B$n(t);if(!e)return{x:0,y:0,side:"bottom"};const n={minX:e.center.x-e.width/2,maxX:e.center.x+e.width/2,minY:e.center.y-e.height/2,maxY:e.center.y+e.height/2},o=b$n(t,e.pcb_component_id),i=v$n(o,n),r=w$n(o,n),s={left:r.minX-i.minX,right:i.maxX-r.maxX,top:i.maxY-r.maxY,bottom:r.minY-i.minY},a=Object.entries(s).sort((d,p)=>p[1]-d[1])[0]?.[0]??"bottom",A=S$n(Q$n(e))??a,c=i.maxX-i.minX,l=i.maxY-i.minY,u=Math.max(.4,Math.min(c,l)*.08),g=(i.minX+i.maxX)/2,h=(i.minY+i.maxY)/2;return A==="above"||A==="below"?{x:g,y:h,side:A,pcbComponentId:e.pcb_component_id}:A==="top"?{x:g,y:i.maxY+u,side:A,pcbComponentId:e.pcb_component_id}:A==="left"?{x:i.minX-u,y:h,side:A,pcbComponentId:e.pcb_component_id}:A==="right"?{x:i.maxX+u,y:h,side:A,pcbComponentId:e.pcb_component_id}:{x:g,y:i.minY-u,side:"bottom",pcbComponentId:e.pcb_component_id}};function U8(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var j9e={exports:{}},Xmt;function M$n(){return Xmt||(Xmt=1,(function(t,e){(function(n){t.exports=n()})(function(){return(function n(o,i,r){function s(c,l){if(!i[c]){if(!o[c]){var u=typeof U8=="function"&&U8;if(!l&&u)return u(c,!0);if(a)return a(c,!0);throw new Error("Cannot find module '"+c+"'")}l=i[c]={exports:{}},o[c][0].call(l.exports,function(g){var h=o[c][1][g];return s(h||g)},l,l.exports,n,o,i,r)}return i[c].exports}for(var a=typeof U8=="function"&&U8,A=0;A<r.length;A++)s(r[A]);return s})({1:[function(n,o,i){(function(r,s,a,A,c,l,u,g,h){var d=n("crypto");function p(x,E){E=f(x,E);var B;return(B=E.algorithm!=="passthrough"?d.createHash(E.algorithm):new y).write===void 0&&(B.write=B.update,B.end=B.update),C(E,B).dispatch(x),B.update||B.end(""),B.digest?B.digest(E.encoding==="buffer"?void 0:E.encoding):(x=B.read(),E.encoding!=="buffer"?x.toString(E.encoding):x)}(i=o.exports=p).sha1=function(x){return p(x)},i.keys=function(x){return p(x,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},i.MD5=function(x){return p(x,{algorithm:"md5",encoding:"hex"})},i.keysMD5=function(x){return p(x,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var m=d.getHashes?d.getHashes().slice():["sha1","md5"],_=(m.push("passthrough"),["buffer","hex","binary","base64"]);function f(x,E){var B={};if(B.algorithm=(E=E||{}).algorithm||"sha1",B.encoding=E.encoding||"hex",B.excludeValues=!!E.excludeValues,B.algorithm=B.algorithm.toLowerCase(),B.encoding=B.encoding.toLowerCase(),B.ignoreUnknown=E.ignoreUnknown===!0,B.respectType=E.respectType!==!1,B.respectFunctionNames=E.respectFunctionNames!==!1,B.respectFunctionProperties=E.respectFunctionProperties!==!1,B.unorderedArrays=E.unorderedArrays===!0,B.unorderedSets=E.unorderedSets!==!1,B.unorderedObjects=E.unorderedObjects!==!1,B.replacer=E.replacer||void 0,B.excludeKeys=E.excludeKeys||void 0,x===void 0)throw new Error("Object argument required.");for(var S=0;S<m.length;++S)m[S].toLowerCase()===B.algorithm.toLowerCase()&&(B.algorithm=m[S]);if(m.indexOf(B.algorithm)===-1)throw new Error('Algorithm "'+B.algorithm+'"  not supported. supported values: '+m.join(", "));if(_.indexOf(B.encoding)===-1&&B.algorithm!=="passthrough")throw new Error('Encoding "'+B.encoding+'"  not supported. supported values: '+_.join(", "));return B}function I(x){if(typeof x=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(x))!=null}function C(x,E,B){B=B||[];function S(Q){return E.update?E.update(Q,"utf8"):E.write(Q,"utf8")}return{dispatch:function(Q){return this["_"+((Q=x.replacer?x.replacer(Q):Q)===null?"null":typeof Q)](Q)},_object:function(Q){var w,M=Object.prototype.toString.call(Q),k=/\[object (.*)\]/i.exec(M);if(k=(k=k?k[1]:"unknown:["+M+"]").toLowerCase(),0<=(M=B.indexOf(Q)))return this.dispatch("[CIRCULAR:"+M+"]");if(B.push(Q),a!==void 0&&a.isBuffer&&a.isBuffer(Q))return S("buffer:"),S(Q);if(k==="object"||k==="function"||k==="asyncfunction")return M=Object.keys(Q),x.unorderedObjects&&(M=M.sort()),x.respectType===!1||I(Q)||M.splice(0,0,"prototype","__proto__","constructor"),x.excludeKeys&&(M=M.filter(function(R){return!x.excludeKeys(R)})),S("object:"+M.length+":"),w=this,M.forEach(function(R){w.dispatch(R),S(":"),x.excludeValues||w.dispatch(Q[R]),S(",")});if(!this["_"+k]){if(x.ignoreUnknown)return S("["+k+"]");throw new Error('Unknown object type "'+k+'"')}this["_"+k](Q)},_array:function(Q,R){R=R!==void 0?R:x.unorderedArrays!==!1;var M=this;if(S("array:"+Q.length+":"),!R||Q.length<=1)return Q.forEach(function(F){return M.dispatch(F)});var k=[],R=Q.map(function(F){var O=new y,U=B.slice();return C(x,O,U).dispatch(F),k=k.concat(U.slice(B.length)),O.read().toString()});return B=B.concat(k),R.sort(),this._array(R,!1)},_date:function(Q){return S("date:"+Q.toJSON())},_symbol:function(Q){return S("symbol:"+Q.toString())},_error:function(Q){return S("error:"+Q.toString())},_boolean:function(Q){return S("bool:"+Q.toString())},_string:function(Q){S("string:"+Q.length+":"),S(Q.toString())},_function:function(Q){S("fn:"),I(Q)?this.dispatch("[native]"):this.dispatch(Q.toString()),x.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(Q.name)),x.respectFunctionProperties&&this._object(Q)},_number:function(Q){return S("number:"+Q.toString())},_xml:function(Q){return S("xml:"+Q.toString())},_null:function(){return S("Null")},_undefined:function(){return S("Undefined")},_regexp:function(Q){return S("regex:"+Q.toString())},_uint8array:function(Q){return S("uint8array:"),this.dispatch(Array.prototype.slice.call(Q))},_uint8clampedarray:function(Q){return S("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(Q))},_int8array:function(Q){return S("int8array:"),this.dispatch(Array.prototype.slice.call(Q))},_uint16array:function(Q){return S("uint16array:"),this.dispatch(Array.prototype.slice.call(Q))},_int16array:function(Q){return S("int16array:"),this.dispatch(Array.prototype.slice.call(Q))},_uint32array:function(Q){return S("uint32array:"),this.dispatch(Array.prototype.slice.call(Q))},_int32array:function(Q){return S("int32array:"),this.dispatch(Array.prototype.slice.call(Q))},_float32array:function(Q){return S("float32array:"),this.dispatch(Array.prototype.slice.call(Q))},_float64array:function(Q){return S("float64array:"),this.dispatch(Array.prototype.slice.call(Q))},_arraybuffer:function(Q){return S("arraybuffer:"),this.dispatch(new Uint8Array(Q))},_url:function(Q){return S("url:"+Q.toString())},_map:function(Q){return S("map:"),Q=Array.from(Q),this._array(Q,x.unorderedSets!==!1)},_set:function(Q){return S("set:"),Q=Array.from(Q),this._array(Q,x.unorderedSets!==!1)},_file:function(Q){return S("file:"),this.dispatch([Q.name,Q.size,Q.type,Q.lastModfied])},_blob:function(){if(x.ignoreUnknown)return S("[blob]");throw Error(`Hashing Blob objects is currently not supported
(see https://github.com/puleos/object-hash/issues/26)
Use "options.replacer" or "options.ignoreUnknown"
`)},_domwindow:function(){return S("domwindow")},_bigint:function(Q){return S("bigint:"+Q.toString())},_process:function(){return S("process")},_timer:function(){return S("timer")},_pipe:function(){return S("pipe")},_tcp:function(){return S("tcp")},_udp:function(){return S("udp")},_tty:function(){return S("tty")},_statwatcher:function(){return S("statwatcher")},_securecontext:function(){return S("securecontext")},_connection:function(){return S("connection")},_zlib:function(){return S("zlib")},_context:function(){return S("context")},_nodescript:function(){return S("nodescript")},_httpparser:function(){return S("httpparser")},_dataview:function(){return S("dataview")},_signal:function(){return S("signal")},_fsevent:function(){return S("fsevent")},_tlswrap:function(){return S("tlswrap")}}}function y(){return{buf:"",write:function(x){this.buf+=x},end:function(x){this.buf+=x},read:function(){return this.buf}}}i.writeToStream=function(x,E,B){return B===void 0&&(B=E,E={}),C(E=f(x,E),B).dispatch(x)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(n,o,i){(function(r,s,a,A,c,l,u,g,h){(function(d){var p=typeof Uint8Array<"u"?Uint8Array:Array,m=43,_=47,f=48,I=97,C=65,y=45,x=95;function E(B){return B=B.charCodeAt(0),B===m||B===y?62:B===_||B===x?63:B<f?-1:B<f+10?B-f+26+26:B<C+26?B-C:B<I+26?B-I+26:void 0}d.toByteArray=function(B){var S,Q;if(0<B.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var w=B.length,w=B.charAt(w-2)==="="?2:B.charAt(w-1)==="="?1:0,M=new p(3*B.length/4-w),k=0<w?B.length-4:B.length,R=0;function F(O){M[R++]=O}for(S=0;S<k;S+=4,0)F((16711680&(Q=E(B.charAt(S))<<18|E(B.charAt(S+1))<<12|E(B.charAt(S+2))<<6|E(B.charAt(S+3))))>>16),F((65280&Q)>>8),F(255&Q);return w==2?F(255&(Q=E(B.charAt(S))<<2|E(B.charAt(S+1))>>4)):w==1&&(F((Q=E(B.charAt(S))<<10|E(B.charAt(S+1))<<4|E(B.charAt(S+2))>>2)>>8&255),F(255&Q)),M},d.fromByteArray=function(B){var S,Q,w,M,k=B.length%3,R="";function F(O){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(O)}for(S=0,w=B.length-k;S<w;S+=3)Q=(B[S]<<16)+(B[S+1]<<8)+B[S+2],R+=F((M=Q)>>18&63)+F(M>>12&63)+F(M>>6&63)+F(63&M);switch(k){case 1:R=(R+=F((Q=B[B.length-1])>>2))+F(Q<<4&63)+"==";break;case 2:R=(R=(R+=F((Q=(B[B.length-2]<<8)+B[B.length-1])>>10))+F(Q>>4&63))+F(Q<<2&63)+"="}return R}})(i===void 0?this.base64js={}:i)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(n,o,i){(function(r,s,m,A,c,l,u,g,h){var d=n("base64-js"),p=n("ieee754");function m(ue,fe,pe){if(!(this instanceof m))return new m(ue,fe,pe);var ye,Me,ve,he,Qe=typeof ue;if(fe==="base64"&&Qe=="string")for(ue=(he=ue).trim?he.trim():he.replace(/^\s+|\s+$/g,"");ue.length%4!=0;)ue+="=";if(Qe=="number")ye=Y(ue);else if(Qe=="string")ye=m.byteLength(ue,fe);else{if(Qe!="object")throw new Error("First argument needs to be a number, array or string.");ye=Y(ue.length)}if(m._useTypedArrays?Me=m._augment(new Uint8Array(ye)):((Me=this).length=ye,Me._isBuffer=!0),m._useTypedArrays&&typeof ue.byteLength=="number")Me._set(ue);else if(W(he=ue)||m.isBuffer(he)||he&&typeof he=="object"&&typeof he.length=="number")for(ve=0;ve<ye;ve++)m.isBuffer(ue)?Me[ve]=ue.readUInt8(ve):Me[ve]=ue[ve];else if(Qe=="string")Me.write(ue,0,fe);else if(Qe=="number"&&!m._useTypedArrays&&!pe)for(ve=0;ve<ye;ve++)Me[ve]=0;return Me}function _(ue,fe,pe,ye){return m._charsWritten=oe((function(Me){for(var ve=[],he=0;he<Me.length;he++)ve.push(255&Me.charCodeAt(he));return ve})(fe),ue,pe,ye)}function f(ue,fe,pe,ye){return m._charsWritten=oe((function(Me){for(var ve,he,Qe=[],Pe=0;Pe<Me.length;Pe++)he=Me.charCodeAt(Pe),ve=he>>8,he=he%256,Qe.push(he),Qe.push(ve);return Qe})(fe),ue,pe,ye)}function I(ue,fe,pe){var ye="";pe=Math.min(ue.length,pe);for(var Me=fe;Me<pe;Me++)ye+=String.fromCharCode(ue[Me]);return ye}function C(ue,fe,pe,ve){ve||(_e(typeof pe=="boolean","missing or invalid endian"),_e(fe!=null,"missing offset"),_e(fe+1<ue.length,"Trying to read beyond buffer length"));var Me,ve=ue.length;if(!(ve<=fe))return pe?(Me=ue[fe],fe+1<ve&&(Me|=ue[fe+1]<<8)):(Me=ue[fe]<<8,fe+1<ve&&(Me|=ue[fe+1])),Me}function y(ue,fe,pe,ve){ve||(_e(typeof pe=="boolean","missing or invalid endian"),_e(fe!=null,"missing offset"),_e(fe+3<ue.length,"Trying to read beyond buffer length"));var Me,ve=ue.length;if(!(ve<=fe))return pe?(fe+2<ve&&(Me=ue[fe+2]<<16),fe+1<ve&&(Me|=ue[fe+1]<<8),Me|=ue[fe],fe+3<ve&&(Me+=ue[fe+3]<<24>>>0)):(fe+1<ve&&(Me=ue[fe+1]<<16),fe+2<ve&&(Me|=ue[fe+2]<<8),fe+3<ve&&(Me|=ue[fe+3]),Me+=ue[fe]<<24>>>0),Me}function x(ue,fe,pe,ye){if(ye||(_e(typeof pe=="boolean","missing or invalid endian"),_e(fe!=null,"missing offset"),_e(fe+1<ue.length,"Trying to read beyond buffer length")),!(ue.length<=fe))return ye=C(ue,fe,pe,!0),32768&ye?-1*(65535-ye+1):ye}function E(ue,fe,pe,ye){if(ye||(_e(typeof pe=="boolean","missing or invalid endian"),_e(fe!=null,"missing offset"),_e(fe+3<ue.length,"Trying to read beyond buffer length")),!(ue.length<=fe))return ye=y(ue,fe,pe,!0),2147483648&ye?-1*(4294967295-ye+1):ye}function B(ue,fe,pe,ye){return ye||(_e(typeof pe=="boolean","missing or invalid endian"),_e(fe+3<ue.length,"Trying to read beyond buffer length")),p.read(ue,fe,pe,23,4)}function S(ue,fe,pe,ye){return ye||(_e(typeof pe=="boolean","missing or invalid endian"),_e(fe+7<ue.length,"Trying to read beyond buffer length")),p.read(ue,fe,pe,52,8)}function Q(ue,fe,pe,ye,Me){if(Me||(_e(fe!=null,"missing value"),_e(typeof ye=="boolean","missing or invalid endian"),_e(pe!=null,"missing offset"),_e(pe+1<ue.length,"trying to write beyond buffer length"),ne(fe,65535)),Me=ue.length,!(Me<=pe))for(var ve=0,he=Math.min(Me-pe,2);ve<he;ve++)ue[pe+ve]=(fe&255<<8*(ye?ve:1-ve))>>>8*(ye?ve:1-ve)}function w(ue,fe,pe,ye,Me){if(Me||(_e(fe!=null,"missing value"),_e(typeof ye=="boolean","missing or invalid endian"),_e(pe!=null,"missing offset"),_e(pe+3<ue.length,"trying to write beyond buffer length"),ne(fe,4294967295)),Me=ue.length,!(Me<=pe))for(var ve=0,he=Math.min(Me-pe,4);ve<he;ve++)ue[pe+ve]=fe>>>8*(ye?ve:3-ve)&255}function M(ue,fe,pe,ye,Me){Me||(_e(fe!=null,"missing value"),_e(typeof ye=="boolean","missing or invalid endian"),_e(pe!=null,"missing offset"),_e(pe+1<ue.length,"Trying to write beyond buffer length"),le(fe,32767,-32768)),ue.length<=pe||Q(ue,0<=fe?fe:65535+fe+1,pe,ye,Me)}function k(ue,fe,pe,ye,Me){Me||(_e(fe!=null,"missing value"),_e(typeof ye=="boolean","missing or invalid endian"),_e(pe!=null,"missing offset"),_e(pe+3<ue.length,"Trying to write beyond buffer length"),le(fe,2147483647,-2147483648)),ue.length<=pe||w(ue,0<=fe?fe:4294967295+fe+1,pe,ye,Me)}function R(ue,fe,pe,ye,Me){Me||(_e(fe!=null,"missing value"),_e(typeof ye=="boolean","missing or invalid endian"),_e(pe!=null,"missing offset"),_e(pe+3<ue.length,"Trying to write beyond buffer length"),ge(fe,34028234663852886e22,-34028234663852886e22)),ue.length<=pe||p.write(ue,fe,pe,ye,23,4)}function F(ue,fe,pe,ye,Me){Me||(_e(fe!=null,"missing value"),_e(typeof ye=="boolean","missing or invalid endian"),_e(pe!=null,"missing offset"),_e(pe+7<ue.length,"Trying to write beyond buffer length"),ge(fe,17976931348623157e292,-17976931348623157e292)),ue.length<=pe||p.write(ue,fe,pe,ye,52,8)}i.Buffer=m,i.SlowBuffer=m,i.INSPECT_MAX_BYTES=50,m.poolSize=8192,m._useTypedArrays=(function(){try{var ue=new ArrayBuffer(0),fe=new Uint8Array(ue);return fe.foo=function(){return 42},fe.foo()===42&&typeof fe.subarray=="function"}catch{return!1}})(),m.isEncoding=function(ue){switch(String(ue).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},m.isBuffer=function(ue){return!(ue==null||!ue._isBuffer)},m.byteLength=function(ue,fe){var pe;switch(ue+="",fe||"utf8"){case"hex":pe=ue.length/2;break;case"utf8":case"utf-8":pe=j(ue).length;break;case"ascii":case"binary":case"raw":pe=ue.length;break;case"base64":pe=J(ue).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":pe=2*ue.length;break;default:throw new Error("Unknown encoding")}return pe},m.concat=function(ue,fe){if(_e(W(ue),`Usage: Buffer.concat(list, [totalLength])
list should be an Array.`),ue.length===0)return new m(0);if(ue.length===1)return ue[0];if(typeof fe!="number")for(Me=fe=0;Me<ue.length;Me++)fe+=ue[Me].length;for(var pe=new m(fe),ye=0,Me=0;Me<ue.length;Me++){var ve=ue[Me];ve.copy(pe,ye),ye+=ve.length}return pe},m.prototype.write=function(ue,fe,pe,ye){isFinite(fe)?isFinite(pe)||(ye=pe,pe=void 0):(Pe=ye,ye=fe,fe=pe,pe=Pe),fe=Number(fe)||0;var Me,ve,he,Qe,Pe=this.length-fe;switch((!pe||Pe<(pe=Number(pe)))&&(pe=Pe),ye=String(ye||"utf8").toLowerCase()){case"hex":Me=(function(we,Te,Re,Ee){Re=Number(Re)||0;var ke=we.length-Re;(!Ee||ke<(Ee=Number(Ee)))&&(Ee=ke),_e((ke=Te.length)%2==0,"Invalid hex string"),ke/2<Ee&&(Ee=ke/2);for(var Ce=0;Ce<Ee;Ce++){var Le=parseInt(Te.substr(2*Ce,2),16);_e(!isNaN(Le),"Invalid hex string"),we[Re+Ce]=Le}return m._charsWritten=2*Ce,Ce})(this,ue,fe,pe);break;case"utf8":case"utf-8":ve=this,he=fe,Qe=pe,Me=m._charsWritten=oe(j(ue),ve,he,Qe);break;case"ascii":case"binary":Me=_(this,ue,fe,pe);break;case"base64":ve=this,he=fe,Qe=pe,Me=m._charsWritten=oe(J(ue),ve,he,Qe);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":Me=f(this,ue,fe,pe);break;default:throw new Error("Unknown encoding")}return Me},m.prototype.toString=function(ue,fe,pe){var ye,Me,ve,he,Qe=this;if(ue=String(ue||"utf8").toLowerCase(),fe=Number(fe)||0,(pe=pe!==void 0?Number(pe):Qe.length)===fe)return"";switch(ue){case"hex":ye=(function(Pe,we,Te){var Re=Pe.length;(!we||we<0)&&(we=0),(!Te||Te<0||Re<Te)&&(Te=Re);for(var Ee="",ke=we;ke<Te;ke++)Ee+=te(Pe[ke]);return Ee})(Qe,fe,pe);break;case"utf8":case"utf-8":ye=(function(Pe,we,Te){var Re="",Ee="";Te=Math.min(Pe.length,Te);for(var ke=we;ke<Te;ke++)Pe[ke]<=127?(Re+=ie(Ee)+String.fromCharCode(Pe[ke]),Ee=""):Ee+="%"+Pe[ke].toString(16);return Re+ie(Ee)})(Qe,fe,pe);break;case"ascii":case"binary":ye=I(Qe,fe,pe);break;case"base64":Me=Qe,he=pe,ye=(ve=fe)===0&&he===Me.length?d.fromByteArray(Me):d.fromByteArray(Me.slice(ve,he));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ye=(function(Pe,we,Te){for(var Re=Pe.slice(we,Te),Ee="",ke=0;ke<Re.length;ke+=2)Ee+=String.fromCharCode(Re[ke]+256*Re[ke+1]);return Ee})(Qe,fe,pe);break;default:throw new Error("Unknown encoding")}return ye},m.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},m.prototype.copy=function(ue,fe,pe,ye){if(fe=fe||0,(ye=ye||ye===0?ye:this.length)!==(pe=pe||0)&&ue.length!==0&&this.length!==0){_e(pe<=ye,"sourceEnd < sourceStart"),_e(0<=fe&&fe<ue.length,"targetStart out of bounds"),_e(0<=pe&&pe<this.length,"sourceStart out of bounds"),_e(0<=ye&&ye<=this.length,"sourceEnd out of bounds"),ye>this.length&&(ye=this.length);var Me=(ye=ue.length-fe<ye-pe?ue.length-fe+pe:ye)-pe;if(Me<100||!m._useTypedArrays)for(var ve=0;ve<Me;ve++)ue[ve+fe]=this[ve+pe];else ue._set(this.subarray(pe,pe+Me),fe)}},m.prototype.slice=function(ue,fe){var pe=this.length;if(ue=U(ue,pe,0),fe=U(fe,pe,pe),m._useTypedArrays)return m._augment(this.subarray(ue,fe));for(var ye=fe-ue,Me=new m(ye,void 0,!0),ve=0;ve<ye;ve++)Me[ve]=this[ve+ue];return Me},m.prototype.get=function(ue){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(ue)},m.prototype.set=function(ue,fe){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(ue,fe)},m.prototype.readUInt8=function(ue,fe){if(fe||(_e(ue!=null,"missing offset"),_e(ue<this.length,"Trying to read beyond buffer length")),!(ue>=this.length))return this[ue]},m.prototype.readUInt16LE=function(ue,fe){return C(this,ue,!0,fe)},m.prototype.readUInt16BE=function(ue,fe){return C(this,ue,!1,fe)},m.prototype.readUInt32LE=function(ue,fe){return y(this,ue,!0,fe)},m.prototype.readUInt32BE=function(ue,fe){return y(this,ue,!1,fe)},m.prototype.readInt8=function(ue,fe){if(fe||(_e(ue!=null,"missing offset"),_e(ue<this.length,"Trying to read beyond buffer length")),!(ue>=this.length))return 128&this[ue]?-1*(255-this[ue]+1):this[ue]},m.prototype.readInt16LE=function(ue,fe){return x(this,ue,!0,fe)},m.prototype.readInt16BE=function(ue,fe){return x(this,ue,!1,fe)},m.prototype.readInt32LE=function(ue,fe){return E(this,ue,!0,fe)},m.prototype.readInt32BE=function(ue,fe){return E(this,ue,!1,fe)},m.prototype.readFloatLE=function(ue,fe){return B(this,ue,!0,fe)},m.prototype.readFloatBE=function(ue,fe){return B(this,ue,!1,fe)},m.prototype.readDoubleLE=function(ue,fe){return S(this,ue,!0,fe)},m.prototype.readDoubleBE=function(ue,fe){return S(this,ue,!1,fe)},m.prototype.writeUInt8=function(ue,fe,pe){pe||(_e(ue!=null,"missing value"),_e(fe!=null,"missing offset"),_e(fe<this.length,"trying to write beyond buffer length"),ne(ue,255)),fe>=this.length||(this[fe]=ue)},m.prototype.writeUInt16LE=function(ue,fe,pe){Q(this,ue,fe,!0,pe)},m.prototype.writeUInt16BE=function(ue,fe,pe){Q(this,ue,fe,!1,pe)},m.prototype.writeUInt32LE=function(ue,fe,pe){w(this,ue,fe,!0,pe)},m.prototype.writeUInt32BE=function(ue,fe,pe){w(this,ue,fe,!1,pe)},m.prototype.writeInt8=function(ue,fe,pe){pe||(_e(ue!=null,"missing value"),_e(fe!=null,"missing offset"),_e(fe<this.length,"Trying to write beyond buffer length"),le(ue,127,-128)),fe>=this.length||(0<=ue?this.writeUInt8(ue,fe,pe):this.writeUInt8(255+ue+1,fe,pe))},m.prototype.writeInt16LE=function(ue,fe,pe){M(this,ue,fe,!0,pe)},m.prototype.writeInt16BE=function(ue,fe,pe){M(this,ue,fe,!1,pe)},m.prototype.writeInt32LE=function(ue,fe,pe){k(this,ue,fe,!0,pe)},m.prototype.writeInt32BE=function(ue,fe,pe){k(this,ue,fe,!1,pe)},m.prototype.writeFloatLE=function(ue,fe,pe){R(this,ue,fe,!0,pe)},m.prototype.writeFloatBE=function(ue,fe,pe){R(this,ue,fe,!1,pe)},m.prototype.writeDoubleLE=function(ue,fe,pe){F(this,ue,fe,!0,pe)},m.prototype.writeDoubleBE=function(ue,fe,pe){F(this,ue,fe,!1,pe)},m.prototype.fill=function(ue,fe,pe){if(fe=fe||0,pe=pe||this.length,_e(typeof(ue=typeof(ue=ue||0)=="string"?ue.charCodeAt(0):ue)=="number"&&!isNaN(ue),"value is not a number"),_e(fe<=pe,"end < start"),pe!==fe&&this.length!==0){_e(0<=fe&&fe<this.length,"start out of bounds"),_e(0<=pe&&pe<=this.length,"end out of bounds");for(var ye=fe;ye<pe;ye++)this[ye]=ue}},m.prototype.inspect=function(){for(var ue=[],fe=this.length,pe=0;pe<fe;pe++)if(ue[pe]=te(this[pe]),pe===i.INSPECT_MAX_BYTES){ue[pe+1]="...";break}return"<Buffer "+ue.join(" ")+">"},m.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(m._useTypedArrays)return new m(this).buffer;for(var ue=new Uint8Array(this.length),fe=0,pe=ue.length;fe<pe;fe+=1)ue[fe]=this[fe];return ue.buffer};var O=m.prototype;function U(ue,fe,pe){return typeof ue!="number"?pe:fe<=(ue=~~ue)?fe:0<=ue||0<=(ue+=fe)?ue:0}function Y(ue){return(ue=~~Math.ceil(+ue))<0?0:ue}function W(ue){return(Array.isArray||function(fe){return Object.prototype.toString.call(fe)==="[object Array]"})(ue)}function te(ue){return ue<16?"0"+ue.toString(16):ue.toString(16)}function j(ue){for(var fe=[],pe=0;pe<ue.length;pe++){var ye=ue.charCodeAt(pe);if(ye<=127)fe.push(ue.charCodeAt(pe));else for(var Me=pe,ve=(55296<=ye&&ye<=57343&&pe++,encodeURIComponent(ue.slice(Me,pe+1)).substr(1).split("%")),he=0;he<ve.length;he++)fe.push(parseInt(ve[he],16))}return fe}function J(ue){return d.toByteArray(ue)}function oe(ue,fe,pe,ye){for(var Me=0;Me<ye&&!(Me+pe>=fe.length||Me>=ue.length);Me++)fe[Me+pe]=ue[Me];return Me}function ie(ue){try{return decodeURIComponent(ue)}catch{return"�"}}function ne(ue,fe){_e(typeof ue=="number","cannot write a non-number as a number"),_e(0<=ue,"specified a negative value for writing an unsigned value"),_e(ue<=fe,"value is larger than maximum value for type"),_e(Math.floor(ue)===ue,"value has a fractional component")}function le(ue,fe,pe){_e(typeof ue=="number","cannot write a non-number as a number"),_e(ue<=fe,"value larger than maximum allowed value"),_e(pe<=ue,"value smaller than minimum allowed value"),_e(Math.floor(ue)===ue,"value has a fractional component")}function ge(ue,fe,pe){_e(typeof ue=="number","cannot write a non-number as a number"),_e(ue<=fe,"value larger than maximum allowed value"),_e(pe<=ue,"value smaller than minimum allowed value")}function _e(ue,fe){if(!ue)throw new Error(fe||"Failed assertion")}m._augment=function(ue){return ue._isBuffer=!0,ue._get=ue.get,ue._set=ue.set,ue.get=O.get,ue.set=O.set,ue.write=O.write,ue.toString=O.toString,ue.toLocaleString=O.toString,ue.toJSON=O.toJSON,ue.copy=O.copy,ue.slice=O.slice,ue.readUInt8=O.readUInt8,ue.readUInt16LE=O.readUInt16LE,ue.readUInt16BE=O.readUInt16BE,ue.readUInt32LE=O.readUInt32LE,ue.readUInt32BE=O.readUInt32BE,ue.readInt8=O.readInt8,ue.readInt16LE=O.readInt16LE,ue.readInt16BE=O.readInt16BE,ue.readInt32LE=O.readInt32LE,ue.readInt32BE=O.readInt32BE,ue.readFloatLE=O.readFloatLE,ue.readFloatBE=O.readFloatBE,ue.readDoubleLE=O.readDoubleLE,ue.readDoubleBE=O.readDoubleBE,ue.writeUInt8=O.writeUInt8,ue.writeUInt16LE=O.writeUInt16LE,ue.writeUInt16BE=O.writeUInt16BE,ue.writeUInt32LE=O.writeUInt32LE,ue.writeUInt32BE=O.writeUInt32BE,ue.writeInt8=O.writeInt8,ue.writeInt16LE=O.writeInt16LE,ue.writeInt16BE=O.writeInt16BE,ue.writeInt32LE=O.writeInt32LE,ue.writeInt32BE=O.writeInt32BE,ue.writeFloatLE=O.writeFloatLE,ue.writeFloatBE=O.writeFloatBE,ue.writeDoubleLE=O.writeDoubleLE,ue.writeDoubleBE=O.writeDoubleBE,ue.fill=O.fill,ue.inspect=O.inspect,ue.toArrayBuffer=O.toArrayBuffer,ue}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(n,o,i){(function(r,s,d,A,c,l,u,g,h){var d=n("buffer").Buffer,p=4,m=new d(p);m.fill(0),o.exports={hash:function(_,f,I,C){for(var y=f((function(Q,w){Q.length%p!=0&&(M=Q.length+(p-Q.length%p),Q=d.concat([Q,m],M));for(var M,k=[],R=w?Q.readInt32BE:Q.readInt32LE,F=0;F<Q.length;F+=p)k.push(R.call(Q,F));return k})(_=d.isBuffer(_)?_:new d(_),C),8*_.length),f=C,x=new d(I),E=f?x.writeInt32BE:x.writeInt32LE,B=0;B<y.length;B++)E.call(x,y[B],4*B,!0);return x}}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(n,o,i){(function(r,s,d,A,c,l,u,g,h){var d=n("buffer").Buffer,p=n("./sha"),m=n("./sha256"),_=n("./rng"),f={sha1:p,sha256:m,md5:n("./md5")},I=64,C=new d(I);function y(Q,w){var M=f[Q=Q||"sha1"],k=[];return M||x("algorithm:",Q,"is not yet supported"),{update:function(R){return d.isBuffer(R)||(R=new d(R)),k.push(R),R.length,this},digest:function(R){var F=d.concat(k),F=w?(function(O,U,Y){d.isBuffer(U)||(U=new d(U)),d.isBuffer(Y)||(Y=new d(Y)),U.length>I?U=O(U):U.length<I&&(U=d.concat([U,C],I));for(var W=new d(I),te=new d(I),j=0;j<I;j++)W[j]=54^U[j],te[j]=92^U[j];return Y=O(d.concat([W,Y])),O(d.concat([te,Y]))})(M,w,F):M(F);return k=null,R?F.toString(R):F}}}function x(){var Q=[].slice.call(arguments).join(" ");throw new Error([Q,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
`))}C.fill(0),i.createHash=function(Q){return y(Q)},i.createHmac=y,i.randomBytes=function(Q,w){if(!w||!w.call)return new d(_(Q));try{w.call(this,void 0,new d(_(Q)))}catch(M){w(M)}};var E,B=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],S=function(Q){i[Q]=function(){x("sorry,",Q,"is not implemented yet")}};for(E in B)S(B[E])}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(n,o,i){(function(r,s,a,A,c,l,u,g,h){var d=n("./helpers");function p(x,E){x[E>>5]|=128<<E%32,x[14+(E+64>>>9<<4)]=E;for(var B=1732584193,S=-271733879,Q=-1732584194,w=271733878,M=0;M<x.length;M+=16){var k=B,R=S,F=Q,O=w,B=_(B,S,Q,w,x[M+0],7,-680876936),w=_(w,B,S,Q,x[M+1],12,-389564586),Q=_(Q,w,B,S,x[M+2],17,606105819),S=_(S,Q,w,B,x[M+3],22,-1044525330);B=_(B,S,Q,w,x[M+4],7,-176418897),w=_(w,B,S,Q,x[M+5],12,1200080426),Q=_(Q,w,B,S,x[M+6],17,-1473231341),S=_(S,Q,w,B,x[M+7],22,-45705983),B=_(B,S,Q,w,x[M+8],7,1770035416),w=_(w,B,S,Q,x[M+9],12,-1958414417),Q=_(Q,w,B,S,x[M+10],17,-42063),S=_(S,Q,w,B,x[M+11],22,-1990404162),B=_(B,S,Q,w,x[M+12],7,1804603682),w=_(w,B,S,Q,x[M+13],12,-40341101),Q=_(Q,w,B,S,x[M+14],17,-1502002290),B=f(B,S=_(S,Q,w,B,x[M+15],22,1236535329),Q,w,x[M+1],5,-165796510),w=f(w,B,S,Q,x[M+6],9,-1069501632),Q=f(Q,w,B,S,x[M+11],14,643717713),S=f(S,Q,w,B,x[M+0],20,-373897302),B=f(B,S,Q,w,x[M+5],5,-701558691),w=f(w,B,S,Q,x[M+10],9,38016083),Q=f(Q,w,B,S,x[M+15],14,-660478335),S=f(S,Q,w,B,x[M+4],20,-405537848),B=f(B,S,Q,w,x[M+9],5,568446438),w=f(w,B,S,Q,x[M+14],9,-1019803690),Q=f(Q,w,B,S,x[M+3],14,-187363961),S=f(S,Q,w,B,x[M+8],20,1163531501),B=f(B,S,Q,w,x[M+13],5,-1444681467),w=f(w,B,S,Q,x[M+2],9,-51403784),Q=f(Q,w,B,S,x[M+7],14,1735328473),B=I(B,S=f(S,Q,w,B,x[M+12],20,-1926607734),Q,w,x[M+5],4,-378558),w=I(w,B,S,Q,x[M+8],11,-2022574463),Q=I(Q,w,B,S,x[M+11],16,1839030562),S=I(S,Q,w,B,x[M+14],23,-35309556),B=I(B,S,Q,w,x[M+1],4,-1530992060),w=I(w,B,S,Q,x[M+4],11,1272893353),Q=I(Q,w,B,S,x[M+7],16,-155497632),S=I(S,Q,w,B,x[M+10],23,-1094730640),B=I(B,S,Q,w,x[M+13],4,681279174),w=I(w,B,S,Q,x[M+0],11,-358537222),Q=I(Q,w,B,S,x[M+3],16,-722521979),S=I(S,Q,w,B,x[M+6],23,76029189),B=I(B,S,Q,w,x[M+9],4,-640364487),w=I(w,B,S,Q,x[M+12],11,-421815835),Q=I(Q,w,B,S,x[M+15],16,530742520),B=C(B,S=I(S,Q,w,B,x[M+2],23,-995338651),Q,w,x[M+0],6,-198630844),w=C(w,B,S,Q,x[M+7],10,1126891415),Q=C(Q,w,B,S,x[M+14],15,-1416354905),S=C(S,Q,w,B,x[M+5],21,-57434055),B=C(B,S,Q,w,x[M+12],6,1700485571),w=C(w,B,S,Q,x[M+3],10,-1894986606),Q=C(Q,w,B,S,x[M+10],15,-1051523),S=C(S,Q,w,B,x[M+1],21,-2054922799),B=C(B,S,Q,w,x[M+8],6,1873313359),w=C(w,B,S,Q,x[M+15],10,-30611744),Q=C(Q,w,B,S,x[M+6],15,-1560198380),S=C(S,Q,w,B,x[M+13],21,1309151649),B=C(B,S,Q,w,x[M+4],6,-145523070),w=C(w,B,S,Q,x[M+11],10,-1120210379),Q=C(Q,w,B,S,x[M+2],15,718787259),S=C(S,Q,w,B,x[M+9],21,-343485551),B=y(B,k),S=y(S,R),Q=y(Q,F),w=y(w,O)}return Array(B,S,Q,w)}function m(x,E,B,S,Q,w){return y((E=y(y(E,x),y(S,w)))<<Q|E>>>32-Q,B)}function _(x,E,B,S,Q,w,M){return m(E&B|~E&S,x,E,Q,w,M)}function f(x,E,B,S,Q,w,M){return m(E&S|B&~S,x,E,Q,w,M)}function I(x,E,B,S,Q,w,M){return m(E^B^S,x,E,Q,w,M)}function C(x,E,B,S,Q,w,M){return m(B^(E|~S),x,E,Q,w,M)}function y(x,E){var B=(65535&x)+(65535&E);return(x>>16)+(E>>16)+(B>>16)<<16|65535&B}o.exports=function(x){return d.hash(x,p,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(n,o,i){(function(r,s,a,A,c,l,u,g,h){o.exports=function(d){for(var p,m=new Array(d),_=0;_<d;_++)(3&_)==0&&(p=4294967296*Math.random()),m[_]=p>>>((3&_)<<3)&255;return m}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(n,o,i){(function(r,s,a,A,c,l,u,g,h){var d=n("./helpers");function p(f,I){f[I>>5]|=128<<24-I%32,f[15+(I+64>>9<<4)]=I;for(var C,y,x,E=Array(80),B=1732584193,S=-271733879,Q=-1732584194,w=271733878,M=-1009589776,k=0;k<f.length;k+=16){for(var R=B,F=S,O=Q,U=w,Y=M,W=0;W<80;W++){E[W]=W<16?f[k+W]:_(E[W-3]^E[W-8]^E[W-14]^E[W-16],1);var te=m(m(_(B,5),(te=S,y=Q,x=w,(C=W)<20?te&y|~te&x:!(C<40)&&C<60?te&y|te&x|y&x:te^y^x)),m(m(M,E[W]),(C=W)<20?1518500249:C<40?1859775393:C<60?-1894007588:-899497514)),M=w,w=Q,Q=_(S,30),S=B,B=te}B=m(B,R),S=m(S,F),Q=m(Q,O),w=m(w,U),M=m(M,Y)}return Array(B,S,Q,w,M)}function m(f,I){var C=(65535&f)+(65535&I);return(f>>16)+(I>>16)+(C>>16)<<16|65535&C}function _(f,I){return f<<I|f>>>32-I}o.exports=function(f){return d.hash(f,p,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(n,o,i){(function(r,s,a,A,c,l,u,g,h){function d(I,C){var y=(65535&I)+(65535&C);return(I>>16)+(C>>16)+(y>>16)<<16|65535&y}function p(I,C){var y,x=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),E=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),B=new Array(64);I[C>>5]|=128<<24-C%32,I[15+(C+64>>9<<4)]=C;for(var S,Q,w=0;w<I.length;w+=16){for(var M=E[0],k=E[1],R=E[2],F=E[3],O=E[4],U=E[5],Y=E[6],W=E[7],te=0;te<64;te++)B[te]=te<16?I[te+w]:d(d(d((Q=B[te-2],_(Q,17)^_(Q,19)^f(Q,10)),B[te-7]),(Q=B[te-15],_(Q,7)^_(Q,18)^f(Q,3))),B[te-16]),y=d(d(d(d(W,_(Q=O,6)^_(Q,11)^_(Q,25)),O&U^~O&Y),x[te]),B[te]),S=d(_(S=M,2)^_(S,13)^_(S,22),M&k^M&R^k&R),W=Y,Y=U,U=O,O=d(F,y),F=R,R=k,k=M,M=d(y,S);E[0]=d(M,E[0]),E[1]=d(k,E[1]),E[2]=d(R,E[2]),E[3]=d(F,E[3]),E[4]=d(O,E[4]),E[5]=d(U,E[5]),E[6]=d(Y,E[6]),E[7]=d(W,E[7])}return E}var m=n("./helpers"),_=function(I,C){return I>>>C|I<<32-C},f=function(I,C){return I>>>C};o.exports=function(I){return m.hash(I,p,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(n,o,i){(function(r,s,a,A,c,l,u,g,h){i.read=function(d,p,m,_,w){var I,C,y=8*w-_-1,x=(1<<y)-1,E=x>>1,B=-7,S=m?w-1:0,Q=m?-1:1,w=d[p+S];for(S+=Q,I=w&(1<<-B)-1,w>>=-B,B+=y;0<B;I=256*I+d[p+S],S+=Q,B-=8);for(C=I&(1<<-B)-1,I>>=-B,B+=_;0<B;C=256*C+d[p+S],S+=Q,B-=8);if(I===0)I=1-E;else{if(I===x)return C?NaN:1/0*(w?-1:1);C+=Math.pow(2,_),I-=E}return(w?-1:1)*C*Math.pow(2,I-_)},i.write=function(d,p,m,_,f,M){var C,y,x=8*M-f-1,E=(1<<x)-1,B=E>>1,S=f===23?Math.pow(2,-24)-Math.pow(2,-77):0,Q=_?0:M-1,w=_?1:-1,M=p<0||p===0&&1/p<0?1:0;for(p=Math.abs(p),isNaN(p)||p===1/0?(y=isNaN(p)?1:0,C=E):(C=Math.floor(Math.log(p)/Math.LN2),p*(_=Math.pow(2,-C))<1&&(C--,_*=2),2<=(p+=1<=C+B?S/_:S*Math.pow(2,1-B))*_&&(C++,_/=2),E<=C+B?(y=0,C=E):1<=C+B?(y=(p*_-1)*Math.pow(2,f),C+=B):(y=p*Math.pow(2,B-1)*Math.pow(2,f),C=0));8<=f;d[m+Q]=255&y,Q+=w,y/=256,f-=8);for(C=C<<f|y,x+=f;0<x;d[m+Q]=255&C,Q+=w,C/=256,x-=8);d[m+Q-w]|=128*M}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(n,o,i){(function(r,s,a,A,c,l,u,g,h){var d,p,m;function _(){}(r=o.exports={}).nextTick=(p=typeof window<"u"&&window.setImmediate,m=typeof window<"u"&&window.postMessage&&window.addEventListener,p?function(f){return window.setImmediate(f)}:m?(d=[],window.addEventListener("message",function(f){var I=f.source;I!==window&&I!==null||f.data!=="process-tick"||(f.stopPropagation(),0<d.length&&d.shift()())},!0),function(f){d.push(f),window.postMessage("process-tick","*")}):function(f){setTimeout(f,0)}),r.title="browser",r.browser=!0,r.env={},r.argv=[],r.on=_,r.addListener=_,r.once=_,r.off=_,r.removeListener=_,r.removeAllListeners=_,r.emit=_,r.binding=function(f){throw new Error("process.binding is not supported")},r.cwd=function(){return"/"},r.chdir=function(f){throw new Error("process.chdir is not supported")}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})})(j9e)),j9e.exports}var D$n=M$n();const $9e=_y(D$n);var N$n={env:{}},R$n=Object.create,q9e=Object.defineProperty,T$n=Object.getOwnPropertyDescriptor,Zmt=Object.getOwnPropertyNames,k$n=Object.getPrototypeOf,F$n=Object.prototype.hasOwnProperty,nm=(t,e)=>function(){return e||(0,t[Zmt(t)[0]])((e={exports:{}}).exports,e),e.exports},e_t=(t,e)=>{for(var n in e)q9e(t,n,{get:e[n],enumerable:!0})},X9e=(t,e,n)=>(n=t!=null?R$n(k$n(t)):{},((o,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of Zmt(i))F$n.call(o,a)||a===r||q9e(o,a,{get:()=>i[a],enumerable:!(s=T$n(i,a))||s.enumerable});return o})(!e&&t&&t.__esModule?n:q9e(n,"default",{value:t,enumerable:!0}),t)),L$n=nm({"node_modules/is-buffer/index.js"(t,e){function n(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}e.exports=function(o){return o!=null&&(n(o)||(function(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&n(i.slice(0,0))})(o)||!!o._isBuffer)}}}),H$n=nm({"node_modules/kind-of/index.js"(t,e){var n=L$n(),o=Object.prototype.toString;e.exports=function(i){if(i===void 0)return"undefined";if(i===null)return"null";if(i===!0||i===!1||i instanceof Boolean)return"boolean";if(typeof i=="string"||i instanceof String)return"string";if(typeof i=="number"||i instanceof Number)return"number";if(typeof i=="function"||i instanceof Function)return"function";if(Array.isArray!==void 0&&Array.isArray(i))return"array";if(i instanceof RegExp)return"regexp";if(i instanceof Date)return"date";var r=o.call(i);return r==="[object RegExp]"?"regexp":r==="[object Date]"?"date":r==="[object Arguments]"?"arguments":r==="[object Error]"?"error":n(i)?"buffer":r==="[object Set]"?"set":r==="[object WeakSet]"?"weakset":r==="[object Map]"?"map":r==="[object WeakMap]"?"weakmap":r==="[object Symbol]"?"symbol":r==="[object Int8Array]"?"int8array":r==="[object Uint8Array]"?"uint8array":r==="[object Uint8ClampedArray]"?"uint8clampedarray":r==="[object Int16Array]"?"int16array":r==="[object Uint16Array]"?"uint16array":r==="[object Int32Array]"?"int32array":r==="[object Uint32Array]"?"uint32array":r==="[object Float32Array]"?"float32array":r==="[object Float64Array]"?"float64array":"object"}}}),O$n=nm({"node_modules/rename-keys/index.js"(t,e){(function(){function n(o,i){if(typeof i!="function")return o;var r={};for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[i(s,o[s])||s]=o[s]);return r}e!==void 0&&e.exports?e.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):window.rename=n})()}}),G$n=nm({"node_modules/deep-rename-keys/index.js"(t,e){var n=H$n(),o=O$n();e.exports=function i(r,s){var a=n(r);if(a!=="object"&&a!=="array")throw new Error("expected an object");var A=[];for(var c in a==="object"&&(r=o(r,s),A={}),r)if(r.hasOwnProperty(c)){var l=r[c];n(l)==="object"||n(l)==="array"?A[c]=i(l,s):A[c]=l}return A}}}),Y$n=nm({"node_modules/xml-reader/node_modules/eventemitter3/index.js"(t,e){var n=Object.prototype.hasOwnProperty,o="~";function i(){}function r(a,A,c){this.fn=a,this.context=A,this.once=c||!1}function s(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(o=!1)),s.prototype.eventNames=function(){var a,A,c=[];if(this._eventsCount===0)return c;for(A in a=this._events)n.call(a,A)&&c.push(o?A.slice(1):A);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(a)):c},s.prototype.listeners=function(a,A){var c=o?o+a:a,l=this._events[c];if(A)return!!l;if(!l)return[];if(l.fn)return[l.fn];for(var u=0,g=l.length,h=new Array(g);u<g;u++)h[u]=l[u].fn;return h},s.prototype.emit=function(a,A,c,l,u,g){var h=o?o+a:a;if(!this._events[h])return!1;var d,p,m=this._events[h],_=arguments.length;if(m.fn){switch(m.once&&this.removeListener(a,m.fn,void 0,!0),_){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,A),!0;case 3:return m.fn.call(m.context,A,c),!0;case 4:return m.fn.call(m.context,A,c,l),!0;case 5:return m.fn.call(m.context,A,c,l,u),!0;case 6:return m.fn.call(m.context,A,c,l,u,g),!0}for(p=1,d=new Array(_-1);p<_;p++)d[p-1]=arguments[p];m.fn.apply(m.context,d)}else{var f,I=m.length;for(p=0;p<I;p++)switch(m[p].once&&this.removeListener(a,m[p].fn,void 0,!0),_){case 1:m[p].fn.call(m[p].context);break;case 2:m[p].fn.call(m[p].context,A);break;case 3:m[p].fn.call(m[p].context,A,c);break;case 4:m[p].fn.call(m[p].context,A,c,l);break;default:if(!d)for(f=1,d=new Array(_-1);f<_;f++)d[f-1]=arguments[f];m[p].fn.apply(m[p].context,d)}}return!0},s.prototype.on=function(a,A,c){var l=new r(A,c||this),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.once=function(a,A,c){var l=new r(A,c||this,!0),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.removeListener=function(a,A,c,l){var u=o?o+a:a;if(!this._events[u])return this;if(!A)return--this._eventsCount===0?this._events=new i:delete this._events[u],this;var g=this._events[u];if(g.fn)g.fn!==A||l&&!g.once||c&&g.context!==c||(--this._eventsCount===0?this._events=new i:delete this._events[u]);else{for(var h=0,d=[],p=g.length;h<p;h++)(g[h].fn!==A||l&&!g[h].once||c&&g[h].context!==c)&&d.push(g[h]);d.length?this._events[u]=d.length===1?d[0]:d:--this._eventsCount===0?this._events=new i:delete this._events[u]}return this},s.prototype.removeAllListeners=function(a){var A;return a?(A=o?o+a:a,this._events[A]&&(--this._eventsCount===0?this._events=new i:delete this._events[A])):(this._events=new i,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prototype.setMaxListeners=function(){return this},s.prefixed=o,s.EventEmitter=s,e!==void 0&&(e.exports=s)}}),U$n=nm({"node_modules/xml-lexer/node_modules/eventemitter3/index.js"(t,e){var n=Object.prototype.hasOwnProperty,o="~";function i(){}function r(a,A,c){this.fn=a,this.context=A,this.once=c||!1}function s(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(o=!1)),s.prototype.eventNames=function(){var a,A,c=[];if(this._eventsCount===0)return c;for(A in a=this._events)n.call(a,A)&&c.push(o?A.slice(1):A);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(a)):c},s.prototype.listeners=function(a,A){var c=o?o+a:a,l=this._events[c];if(A)return!!l;if(!l)return[];if(l.fn)return[l.fn];for(var u=0,g=l.length,h=new Array(g);u<g;u++)h[u]=l[u].fn;return h},s.prototype.emit=function(a,A,c,l,u,g){var h=o?o+a:a;if(!this._events[h])return!1;var d,p,m=this._events[h],_=arguments.length;if(m.fn){switch(m.once&&this.removeListener(a,m.fn,void 0,!0),_){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,A),!0;case 3:return m.fn.call(m.context,A,c),!0;case 4:return m.fn.call(m.context,A,c,l),!0;case 5:return m.fn.call(m.context,A,c,l,u),!0;case 6:return m.fn.call(m.context,A,c,l,u,g),!0}for(p=1,d=new Array(_-1);p<_;p++)d[p-1]=arguments[p];m.fn.apply(m.context,d)}else{var f,I=m.length;for(p=0;p<I;p++)switch(m[p].once&&this.removeListener(a,m[p].fn,void 0,!0),_){case 1:m[p].fn.call(m[p].context);break;case 2:m[p].fn.call(m[p].context,A);break;case 3:m[p].fn.call(m[p].context,A,c);break;case 4:m[p].fn.call(m[p].context,A,c,l);break;default:if(!d)for(f=1,d=new Array(_-1);f<_;f++)d[f-1]=arguments[f];m[p].fn.apply(m[p].context,d)}}return!0},s.prototype.on=function(a,A,c){var l=new r(A,c||this),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.once=function(a,A,c){var l=new r(A,c||this,!0),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.removeListener=function(a,A,c,l){var u=o?o+a:a;if(!this._events[u])return this;if(!A)return--this._eventsCount===0?this._events=new i:delete this._events[u],this;var g=this._events[u];if(g.fn)g.fn!==A||l&&!g.once||c&&g.context!==c||(--this._eventsCount===0?this._events=new i:delete this._events[u]);else{for(var h=0,d=[],p=g.length;h<p;h++)(g[h].fn!==A||l&&!g[h].once||c&&g[h].context!==c)&&d.push(g[h]);d.length?this._events[u]=d.length===1?d[0]:d:--this._eventsCount===0?this._events=new i:delete this._events[u]}return this},s.prototype.removeAllListeners=function(a){var A;return a?(A=o?o+a:a,this._events[A]&&(--this._eventsCount===0?this._events=new i:delete this._events[A])):(this._events=new i,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prototype.setMaxListeners=function(){return this},s.prefixed=o,s.EventEmitter=s,e!==void 0&&(e.exports=s)}}),K$n=nm({"node_modules/xml-lexer/dist/lexer.js"(t,e){function n(c,l,u){return l in c?Object.defineProperty(c,l,{value:u,enumerable:!0,configurable:!0,writable:!0}):c[l]=u,c}var o=U$n(),i=function(){},r={data:"state-data",cdata:"state-cdata",tagBegin:"state-tag-begin",tagName:"state-tag-name",tagEnd:"state-tag-end",attributeNameStart:"state-attribute-name-start",attributeName:"state-attribute-name",attributeNameEnd:"state-attribute-name-end",attributeValueBegin:"state-attribute-value-begin",attributeValue:"state-attribute-value"},s={lt:"action-lt",gt:"action-gt",space:"action-space",equal:"action-equal",quote:"action-quote",slash:"action-slash",char:"action-char",error:"action-error"},a={text:"text",openTag:"open-tag",closeTag:"close-tag",attributeName:"attribute-name",attributeValue:"attribute-value"},A={" ":s.space,"	":s.space,"\n":s.space,"\r":s.space,"<":s.lt,">":s.gt,'"':s.quote,"'":s.quote,"=":s.equal,"/":s.slash};e.exports={State:r,Action:s,Type:a,create:function(c){var l,u,g,h,d,p,m,_,f,I;c=Object.assign({debug:!1},c);var C=new o,y=r.data,x="",E="",B="",S="",Q="",w="",M=function(R,F){if(E[0]!=="?"&&E[0]!=="!"){var O={type:R,value:F};c.debug&&console.log("emit:",O),C.emit("data",O)}};C.stateMachine=(n(I={},r.data,(n(l={},s.lt,function(){x.trim()&&M(a.text,x),E="",Q=!1,y=r.tagBegin}),n(l,s.char,function(R){x+=R}),l)),n(I,r.cdata,n({},s.char,function(R){(x+=R).substr(-3)==="]]>"&&(M(a.text,x.slice(0,-3)),x="",y=r.data)})),n(I,r.tagBegin,(n(u={},s.space,i),n(u,s.char,function(R){E=R,y=r.tagName}),n(u,s.slash,function(){E="",Q=!0}),u)),n(I,r.tagName,(n(g={},s.space,function(){Q?y=r.tagEnd:(y=r.attributeNameStart,M(a.openTag,E))}),n(g,s.gt,function(){M(Q?a.closeTag:a.openTag,E),x="",y=r.data}),n(g,s.slash,function(){y=r.tagEnd,M(a.openTag,E)}),n(g,s.char,function(R){(E+=R)==="![CDATA["&&(y=r.cdata,x="",E="")}),g)),n(I,r.tagEnd,(n(h={},s.gt,function(){M(a.closeTag,E),x="",y=r.data}),n(h,s.char,i),h)),n(I,r.attributeNameStart,(n(d={},s.char,function(R){B=R,y=r.attributeName}),n(d,s.gt,function(){x="",y=r.data}),n(d,s.space,i),n(d,s.slash,function(){Q=!0,y=r.tagEnd}),d)),n(I,r.attributeName,(n(p={},s.space,function(){y=r.attributeNameEnd}),n(p,s.equal,function(){M(a.attributeName,B),y=r.attributeValueBegin}),n(p,s.gt,function(){S="",M(a.attributeName,B),M(a.attributeValue,S),x="",y=r.data}),n(p,s.slash,function(){Q=!0,S="",M(a.attributeName,B),M(a.attributeValue,S),y=r.tagEnd}),n(p,s.char,function(R){B+=R}),p)),n(I,r.attributeNameEnd,(n(m={},s.space,i),n(m,s.equal,function(){M(a.attributeName,B),y=r.attributeValueBegin}),n(m,s.gt,function(){S="",M(a.attributeName,B),M(a.attributeValue,S),x="",y=r.data}),n(m,s.char,function(R){S="",M(a.attributeName,B),M(a.attributeValue,S),B=R,y=r.attributeName}),m)),n(I,r.attributeValueBegin,(n(_={},s.space,i),n(_,s.quote,function(R){w=R,S="",y=r.attributeValue}),n(_,s.gt,function(){M(a.attributeValue,S=""),x="",y=r.data}),n(_,s.char,function(R){w="",S=R,y=r.attributeValue}),_)),n(I,r.attributeValue,(n(f={},s.space,function(R){w?S+=R:(M(a.attributeValue,S),y=r.attributeNameStart)}),n(f,s.quote,function(R){w===R?(M(a.attributeValue,S),y=r.attributeNameStart):S+=R}),n(f,s.gt,function(R){w?S+=R:(M(a.attributeValue,S),x="",y=r.data)}),n(f,s.slash,function(R){w?S+=R:(M(a.attributeValue,S),Q=!0,y=r.tagEnd)}),n(f,s.char,function(R){S+=R}),f)),I);var k=function(R){c.debug&&console.log(y,R);var F=C.stateMachine[y],O=F[(function(U){return A[U]||s.char})(R)]||F[s.error]||F[s.char];O(R)};return C.write=function(R){for(var F=R.length,O=0;O<F;O++)k(R[O])},C}}}}),V$n=nm({"node_modules/xml-reader/dist/reader.js"(t,e){var n=Y$n(),o=K$n(),i=o.Type,r={element:"element",text:"text"},s=function(A){return Object.assign({name:"",type:r.element,value:"",parent:null,attributes:{},children:[]},A)},a=function(A){A=Object.assign({stream:!1,parentNodes:!0,doneEvent:"done",tagPrefix:"tag:",emitTopLevelOnly:!1,debug:!1},A);var c=void 0,l=void 0,u=void 0,g=void 0,h=new n,d=function(p){switch(p.type){case i.openTag:if(u===null)(u=l).name=p.value;else{var m=s({name:p.value,parent:u});u.children.push(m),u=m}break;case i.closeTag:var _=u.parent;if(A.parentNodes||(u.parent=null),u.name!==p.value)break;A.stream&&_===l&&(l.children=[],u.parent=null),A.emitTopLevelOnly&&_!==l||(h.emit(A.tagPrefix+u.name,u),h.emit("tag",u.name,u)),u===l&&(c.removeAllListeners("data"),h.emit(A.doneEvent,u),l=null),u=_;break;case i.text:u&&u.children.push(s({type:r.text,value:p.value,parent:A.parentNodes?u:null}));break;case i.attributeName:g=p.value,u.attributes[g]="";break;case i.attributeValue:u.attributes[g]=p.value}};return h.reset=function(){(c=o.create({debug:A.debug})).on("data",d),l=s(),u=null,g="",h.parse=c.write},h.reset(),h};e.exports={parseSync:function(A,c){c=Object.assign({},c,{stream:!1,tagPrefix:":"});var l=a(c),u=void 0;return l.on("done",function(g){u=g}),l.parse(A),u},create:a,NodeType:r}}}),bse=nm({"node_modules/binary-search-bounds/search-bounds.js"(t,e){function n(A,c,l,u,g){for(var h=g+1;u<=g;){var d=u+g>>>1,p=A[d];(l!==void 0?l(p,c):p-c)>=0?(h=d,g=d-1):u=d+1}return h}function o(A,c,l,u,g){for(var h=g+1;u<=g;){var d=u+g>>>1,p=A[d];(l!==void 0?l(p,c):p-c)>0?(h=d,g=d-1):u=d+1}return h}function i(A,c,l,u,g){for(var h=u-1;u<=g;){var d=u+g>>>1,p=A[d];(l!==void 0?l(p,c):p-c)<0?(h=d,u=d+1):g=d-1}return h}function r(A,c,l,u,g){for(var h=u-1;u<=g;){var d=u+g>>>1,p=A[d];(l!==void 0?l(p,c):p-c)<=0?(h=d,u=d+1):g=d-1}return h}function s(A,c,l,u,g){for(;u<=g;){var h=u+g>>>1,d=A[h],p=l!==void 0?l(d,c):d-c;if(p===0)return h;p<=0?u=h+1:g=h-1}return-1}function a(A,c,l,u,g,h){return typeof l=="function"?h(A,c,l,u===void 0?0:0|u,g===void 0?A.length-1:0|g):h(A,c,void 0,l===void 0?0:0|l,u===void 0?A.length-1:0|u)}e.exports={ge:function(A,c,l,u,g){return a(A,c,l,u,g,n)},gt:function(A,c,l,u,g){return a(A,c,l,u,g,o)},lt:function(A,c,l,u,g){return a(A,c,l,u,g,i)},le:function(A,c,l,u,g){return a(A,c,l,u,g,r)},eq:function(A,c,l,u,g){return a(A,c,l,u,g,s)}}}}),Z9e=nm({"node_modules/two-product/two-product.js"(t,e){e.exports=function(o,i,r){var s=o*i,a=n*o,A=a-(a-o),c=o-A,l=n*i,u=l-(l-i),g=i-u,h=c*g-(s-A*u-c*u-A*g);return r?(r[0]=h,r[1]=s,r):[h,s]};var n=+(Math.pow(2,27)+1)}}),t_t=nm({"node_modules/robust-sum/robust-sum.js"(t,e){e.exports=function(n,o){var i=0|n.length,r=0|o.length;if(i===1&&r===1)return(function(B,S){var Q=B+S,w=Q-B,M=Q-w,k=S-w,R=B-M,F=R+k;return F?[F,Q]:[Q]})(n[0],o[0]);var s,a,A=new Array(i+r),c=0,l=0,u=0,g=Math.abs,h=n[l],d=g(h),p=o[u],m=g(p);d<m?(a=h,(l+=1)<i&&(d=g(h=n[l]))):(a=p,(u+=1)<r&&(m=g(p=o[u]))),l<i&&d<m||u>=r?(s=h,(l+=1)<i&&(d=g(h=n[l]))):(s=p,(u+=1)<r&&(m=g(p=o[u])));for(var _,f,I=s+a,C=I-s,y=a-C,x=y,E=I;l<i&&u<r;)d<m?(s=h,(l+=1)<i&&(d=g(h=n[l]))):(s=p,(u+=1)<r&&(m=g(p=o[u]))),(y=(a=x)-(C=(I=s+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_;for(;l<i;)(y=(a=x)-(C=(I=(s=h)+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_,(l+=1)<i&&(h=n[l]);for(;u<r;)(y=(a=x)-(C=(I=(s=p)+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_,(u+=1)<r&&(p=o[u]);return x&&(A[c++]=x),E&&(A[c++]=E),c||(A[c++]=0),A.length=c,A}}}),z$n=nm({"node_modules/two-sum/two-sum.js"(t,e){e.exports=function(n,o,i){var r=n+o,s=r-n,a=o-s,A=n-(r-s);return i?(i[0]=A+a,i[1]=r,i):[A+a,r]}}}),n_t=nm({"node_modules/robust-scale/robust-scale.js"(t,e){var n=Z9e(),o=z$n();e.exports=function(i,r){var s=i.length;if(s===1){var a=n(i[0],r);return a[0]?a:[a[1]]}var A=new Array(2*s),c=[.1,.1],l=[.1,.1],u=0;n(i[0],r,c),c[0]&&(A[u++]=c[0]);for(var g=1;g<s;++g){n(i[g],r,l);var h=c[1];o(h,l[0],c),c[0]&&(A[u++]=c[0]);var d=l[1],p=c[1],m=d+p,_=p-(m-d);c[1]=m,_&&(A[u++]=_)}return c[1]&&(A[u++]=c[1]),u===0&&(A[u++]=0),A.length=u,A}}}),o_t=nm({"node_modules/robust-subtract/robust-diff.js"(t,e){e.exports=function(n,o){var i=0|n.length,r=0|o.length;if(i===1&&r===1)return(function(B,S){var Q=B+S,w=Q-B,M=Q-w,k=S-w,R=B-M,F=R+k;return F?[F,Q]:[Q]})(n[0],-o[0]);var s,a,A=new Array(i+r),c=0,l=0,u=0,g=Math.abs,h=n[l],d=g(h),p=-o[u],m=g(p);d<m?(a=h,(l+=1)<i&&(d=g(h=n[l]))):(a=p,(u+=1)<r&&(m=g(p=-o[u]))),l<i&&d<m||u>=r?(s=h,(l+=1)<i&&(d=g(h=n[l]))):(s=p,(u+=1)<r&&(m=g(p=-o[u])));for(var _,f,I=s+a,C=I-s,y=a-C,x=y,E=I;l<i&&u<r;)d<m?(s=h,(l+=1)<i&&(d=g(h=n[l]))):(s=p,(u+=1)<r&&(m=g(p=-o[u]))),(y=(a=x)-(C=(I=s+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_;for(;l<i;)(y=(a=x)-(C=(I=(s=h)+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_,(l+=1)<i&&(h=n[l]);for(;u<r;)(y=(a=x)-(C=(I=(s=p)+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_,(u+=1)<r&&(p=-o[u]);return x&&(A[c++]=x),E&&(A[c++]=E),c||(A[c++]=0),A.length=c,A}}}),J$n=nm({"node_modules/robust-orientation/orientation.js"(t,e){var n=Z9e(),o=t_t(),i=n_t(),r=o_t();function s(p,m,_,f){return function(I,C,y){var x=p(p(m(C[1],y[0]),m(-y[1],C[0])),p(m(I[1],C[0]),m(-C[1],I[0]))),E=p(m(I[1],y[0]),m(-y[1],I[0])),B=f(x,E);return B[B.length-1]}}function a(p,m,_,f){return function(I,C,y,x){var E=p(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),C[2]),p(_(p(m(C[1],x[0]),m(-x[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),x[2]))),p(_(p(m(C[1],x[0]),m(-x[1],C[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),x[2])))),B=p(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),x[2]))),p(_(p(m(C[1],y[0]),m(-y[1],C[0])),I[2]),p(_(p(m(I[1],y[0]),m(-y[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),y[2])))),S=f(E,B);return S[S.length-1]}}function A(p,m,_,f){return function(I,C,y,x,E){var B=p(p(p(_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),y[2]),p(_(p(m(y[1],E[0]),m(-E[1],y[0])),-x[2]),_(p(m(y[1],x[0]),m(-x[1],y[0])),E[2]))),C[3]),p(_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),C[2]),p(_(p(m(C[1],E[0]),m(-E[1],C[0])),-x[2]),_(p(m(C[1],x[0]),m(-x[1],C[0])),E[2]))),-y[3]),_(p(_(p(m(y[1],E[0]),m(-E[1],y[0])),C[2]),p(_(p(m(C[1],E[0]),m(-E[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),E[2]))),x[3]))),p(_(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),C[2]),p(_(p(m(C[1],x[0]),m(-x[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),x[2]))),-E[3]),p(_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),C[2]),p(_(p(m(C[1],E[0]),m(-E[1],C[0])),-x[2]),_(p(m(C[1],x[0]),m(-x[1],C[0])),E[2]))),I[3]),_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-x[2]),_(p(m(I[1],x[0]),m(-x[1],I[0])),E[2]))),-C[3])))),p(p(_(p(_(p(m(C[1],E[0]),m(-E[1],C[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),E[2]))),x[3]),p(_(p(_(p(m(C[1],x[0]),m(-x[1],C[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),x[2]))),-E[3]),_(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),C[2]),p(_(p(m(C[1],x[0]),m(-x[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),x[2]))),I[3]))),p(_(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),x[2]))),-C[3]),p(_(p(_(p(m(C[1],x[0]),m(-x[1],C[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),x[2]))),y[3]),_(p(_(p(m(C[1],y[0]),m(-y[1],C[0])),I[2]),p(_(p(m(I[1],y[0]),m(-y[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),y[2]))),-x[3]))))),S=p(p(p(_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),y[2]),p(_(p(m(y[1],E[0]),m(-E[1],y[0])),-x[2]),_(p(m(y[1],x[0]),m(-x[1],y[0])),E[2]))),I[3]),_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-x[2]),_(p(m(I[1],x[0]),m(-x[1],I[0])),E[2]))),-y[3])),p(_(p(_(p(m(y[1],E[0]),m(-E[1],y[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),E[2]))),x[3]),_(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),x[2]))),-E[3]))),p(p(_(p(_(p(m(y[1],E[0]),m(-E[1],y[0])),C[2]),p(_(p(m(C[1],E[0]),m(-E[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),E[2]))),I[3]),_(p(_(p(m(y[1],E[0]),m(-E[1],y[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),E[2]))),-C[3])),p(_(p(_(p(m(C[1],E[0]),m(-E[1],C[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),E[2]))),y[3]),_(p(_(p(m(C[1],y[0]),m(-y[1],C[0])),I[2]),p(_(p(m(I[1],y[0]),m(-y[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),y[2]))),-E[3])))),Q=f(B,S);return Q[Q.length-1]}}function c(p){return(p===3?s:p===4?a:A)(o,n,i,r)}var l=c(3),u=c(4),g=[function(){return 0},function(){return 0},function(p,m){return m[0]-p[0]},function(p,m,_){var f,I=(p[1]-_[1])*(m[0]-_[0]),C=(p[0]-_[0])*(m[1]-_[1]),y=I-C;if(I>0){if(C<=0)return y;f=I+C}else{if(!(I<0)||C>=0)return y;f=-(I+C)}var x=33306690738754716e-32*f;return y>=x||y<=-x?y:l(p,m,_)},function(p,m,_,f){var I=p[0]-f[0],C=m[0]-f[0],y=_[0]-f[0],x=p[1]-f[1],E=m[1]-f[1],B=_[1]-f[1],S=p[2]-f[2],Q=m[2]-f[2],w=_[2]-f[2],M=C*B,k=y*E,R=y*x,F=I*B,O=I*E,U=C*x,Y=S*(M-k)+Q*(R-F)+w*(O-U),W=7771561172376103e-31*((Math.abs(M)+Math.abs(k))*Math.abs(S)+(Math.abs(R)+Math.abs(F))*Math.abs(Q)+(Math.abs(O)+Math.abs(U))*Math.abs(w));return Y>W||-Y>W?Y:u(p,m,_,f)}];function h(p){var m=g[p.length];return m||(m=g[p.length]=c(p.length)),m.apply(void 0,p)}function d(p,m,_,f,I,C,y){return function(x,E,B,S,Q){switch(arguments.length){case 0:case 1:return 0;case 2:return f(x,E);case 3:return I(x,E,B);case 4:return C(x,E,B,S);case 5:return y(x,E,B,S,Q)}for(var w=new Array(arguments.length),M=0;M<arguments.length;++M)w[M]=arguments[M];return p(w)}}(function(){for(;g.length<=5;)g.push(c(g.length));e.exports=d.apply(void 0,[h].concat(g));for(var p=0;p<=5;++p)e.exports[p]=g[p]})()}}),W$n=nm({"node_modules/cdt2d/lib/monotone.js"(t,e){var n=bse(),o=J$n()[3];function i(g,h,d,p,m){this.a=g,this.b=h,this.idx=d,this.lowerIds=p,this.upperIds=m}function r(g,h,d,p){this.a=g,this.b=h,this.type=d,this.idx=p}function s(g,h){var d=g.a[0]-h.a[0]||g.a[1]-h.a[1]||g.type-h.type;return d||(g.type!==0&&(d=o(g.a,g.b,h.b))?d:g.idx-h.idx)}function a(g,h){return o(g.a,g.b,h)}function A(g,h,d,p,m){for(var _=n.lt(h,p,a),f=n.gt(h,p,a),I=_;I<f;++I){for(var C=h[I],y=C.lowerIds,x=y.length;x>1&&o(d[y[x-2]],d[y[x-1]],p)>0;)g.push([y[x-1],y[x-2],m]),x-=1;y.length=x,y.push(m);var E=C.upperIds;for(x=E.length;x>1&&o(d[E[x-2]],d[E[x-1]],p)<0;)g.push([E[x-2],E[x-1],m]),x-=1;E.length=x,E.push(m)}}function c(g,h){var d;return(d=g.a[0]<h.a[0]?o(g.a,g.b,h.a):o(h.b,h.a,g.a))?d:(d=h.b[0]<g.b[0]?o(g.a,g.b,h.b):o(h.b,h.a,g.b))||g.idx-h.idx}function l(g,h,d){var p=n.le(g,d,c),m=g[p],_=m.upperIds,f=_[_.length-1];m.upperIds=[f],g.splice(p+1,0,new i(d.a,d.b,d.idx,[f],_))}function u(g,h,d){var p=d.a;d.a=d.b,d.b=p;var m=n.eq(g,d,c),_=g[m];g[m-1].upperIds=_.upperIds,g.splice(m,1)}e.exports=function(g,h){for(var d=g.length,p=h.length,m=[],_=0;_<d;++_)m.push(new r(g[_],null,0,_));for(_=0;_<p;++_){var f=h[_],I=g[f[0]],C=g[f[1]];I[0]<C[0]?m.push(new r(I,C,2,_),new r(C,I,1,_)):I[0]>C[0]&&m.push(new r(C,I,2,_),new r(I,C,1,_))}m.sort(s);for(var y=m[0].a[0]-(1+Math.abs(m[0].a[0]))*Math.pow(2,-52),x=[new i([y,1],[y,0],-1,[],[])],E=[],B=(_=0,m.length);_<B;++_){var S=m[_],Q=S.type;Q===0?A(E,x,g,S.a,S.idx):Q===2?l(x,g,S):u(x,g,S)}return E}}}),j$n=nm({"node_modules/cdt2d/lib/triangulation.js"(t,e){var n=bse();function o(s,a){this.stars=s,this.edges=a}e.exports=function(s,a){for(var A=new Array(s),c=0;c<s;++c)A[c]=[];return new o(A,a)};var i=o.prototype;function r(s,a,A){for(var c=1,l=s.length;c<l;c+=2)if(s[c-1]===a&&s[c]===A)return s[c-1]=s[l-2],s[c]=s[l-1],void(s.length=l-2)}i.isConstraint=(function(){var s=[0,0];function a(A,c){return A[0]-c[0]||A[1]-c[1]}return function(A,c){return s[0]=Math.min(A,c),s[1]=Math.max(A,c),n.eq(this.edges,s,a)>=0}})(),i.removeTriangle=function(s,a,A){var c=this.stars;r(c[s],a,A),r(c[a],A,s),r(c[A],s,a)},i.addTriangle=function(s,a,A){var c=this.stars;c[s].push(a,A),c[a].push(A,s),c[A].push(s,a)},i.opposite=function(s,a){for(var A=this.stars[a],c=1,l=A.length;c<l;c+=2)if(A[c]===s)return A[c-1];return-1},i.flip=function(s,a){var A=this.opposite(s,a),c=this.opposite(a,s);this.removeTriangle(s,a,A),this.removeTriangle(a,s,c),this.addTriangle(s,c,A),this.addTriangle(a,A,c)},i.edges=function(){for(var s=this.stars,a=[],A=0,c=s.length;A<c;++A)for(var l=s[A],u=0,g=l.length;u<g;u+=2)a.push([l[u],l[u+1]]);return a},i.cells=function(){for(var s=this.stars,a=[],A=0,c=s.length;A<c;++A)for(var l=s[A],u=0,g=l.length;u<g;u+=2){var h=l[u],d=l[u+1];A<Math.min(h,d)&&a.push([A,h,d])}return a}}}),$$n=nm({"node_modules/robust-in-sphere/in-sphere.js"(t,e){var n=Z9e(),o=t_t(),i=o_t(),r=n_t();function s(d){return(d===3?a:d===4?A:d===5?c:l)(o,i,n,r)}function a(d,p,m,_){return function(f,I,C){var y=m(f[0],f[0]),x=_(y,I[0]),E=_(y,C[0]),B=m(I[0],I[0]),S=_(B,f[0]),Q=_(B,C[0]),w=m(C[0],C[0]),M=_(w,f[0]),k=_(w,I[0]),R=d(p(k,Q),p(S,x)),F=p(M,E),O=p(R,F);return O[O.length-1]}}function A(d,p,m,_){return function(f,I,C,y){var x=d(m(f[0],f[0]),m(f[1],f[1])),E=_(x,I[0]),B=_(x,C[0]),S=_(x,y[0]),Q=d(m(I[0],I[0]),m(I[1],I[1])),w=_(Q,f[0]),M=_(Q,C[0]),k=_(Q,y[0]),R=d(m(C[0],C[0]),m(C[1],C[1])),F=_(R,f[0]),O=_(R,I[0]),U=_(R,y[0]),Y=d(m(y[0],y[0]),m(y[1],y[1])),W=_(Y,f[0]),te=_(Y,I[0]),j=_(Y,C[0]),J=d(d(_(p(j,U),I[1]),d(_(p(te,k),-C[1]),_(p(O,M),y[1]))),d(_(p(te,k),f[1]),d(_(p(W,S),-I[1]),_(p(w,E),y[1])))),oe=d(d(_(p(j,U),f[1]),d(_(p(W,S),-C[1]),_(p(F,B),y[1]))),d(_(p(O,M),f[1]),d(_(p(F,B),-I[1]),_(p(w,E),C[1])))),ie=p(J,oe);return ie[ie.length-1]}}function c(d,p,m,_){return function(f,I,C,y,x){var E=d(m(f[0],f[0]),d(m(f[1],f[1]),m(f[2],f[2]))),B=_(E,I[0]),S=_(E,C[0]),Q=_(E,y[0]),w=_(E,x[0]),M=d(m(I[0],I[0]),d(m(I[1],I[1]),m(I[2],I[2]))),k=_(M,f[0]),R=_(M,C[0]),F=_(M,y[0]),O=_(M,x[0]),U=d(m(C[0],C[0]),d(m(C[1],C[1]),m(C[2],C[2]))),Y=_(U,f[0]),W=_(U,I[0]),te=_(U,y[0]),j=_(U,x[0]),J=d(m(y[0],y[0]),d(m(y[1],y[1]),m(y[2],y[2]))),oe=_(J,f[0]),ie=_(J,I[0]),ne=_(J,C[0]),le=_(J,x[0]),ge=d(m(x[0],x[0]),d(m(x[1],x[1]),m(x[2],x[2]))),_e=_(ge,f[0]),ue=_(ge,I[0]),fe=_(ge,C[0]),pe=_(ge,y[0]),ye=d(d(d(_(d(_(p(pe,le),C[1]),d(_(p(fe,j),-y[1]),_(p(ne,te),x[1]))),I[2]),d(_(d(_(p(pe,le),I[1]),d(_(p(ue,O),-y[1]),_(p(ie,F),x[1]))),-C[2]),_(d(_(p(fe,j),I[1]),d(_(p(ue,O),-C[1]),_(p(W,R),x[1]))),y[2]))),d(_(d(_(p(ne,te),I[1]),d(_(p(ie,F),-C[1]),_(p(W,R),y[1]))),-x[2]),d(_(d(_(p(pe,le),I[1]),d(_(p(ue,O),-y[1]),_(p(ie,F),x[1]))),f[2]),_(d(_(p(pe,le),f[1]),d(_(p(_e,w),-y[1]),_(p(oe,Q),x[1]))),-I[2])))),d(d(_(d(_(p(ue,O),f[1]),d(_(p(_e,w),-I[1]),_(p(k,B),x[1]))),y[2]),d(_(d(_(p(ie,F),f[1]),d(_(p(oe,Q),-I[1]),_(p(k,B),y[1]))),-x[2]),_(d(_(p(ne,te),I[1]),d(_(p(ie,F),-C[1]),_(p(W,R),y[1]))),f[2]))),d(_(d(_(p(ne,te),f[1]),d(_(p(oe,Q),-C[1]),_(p(Y,S),y[1]))),-I[2]),d(_(d(_(p(ie,F),f[1]),d(_(p(oe,Q),-I[1]),_(p(k,B),y[1]))),C[2]),_(d(_(p(W,R),f[1]),d(_(p(Y,S),-I[1]),_(p(k,B),C[1]))),-y[2]))))),Me=d(d(d(_(d(_(p(pe,le),C[1]),d(_(p(fe,j),-y[1]),_(p(ne,te),x[1]))),f[2]),_(d(_(p(pe,le),f[1]),d(_(p(_e,w),-y[1]),_(p(oe,Q),x[1]))),-C[2])),d(_(d(_(p(fe,j),f[1]),d(_(p(_e,w),-C[1]),_(p(Y,S),x[1]))),y[2]),_(d(_(p(ne,te),f[1]),d(_(p(oe,Q),-C[1]),_(p(Y,S),y[1]))),-x[2]))),d(d(_(d(_(p(fe,j),I[1]),d(_(p(ue,O),-C[1]),_(p(W,R),x[1]))),f[2]),_(d(_(p(fe,j),f[1]),d(_(p(_e,w),-C[1]),_(p(Y,S),x[1]))),-I[2])),d(_(d(_(p(ue,O),f[1]),d(_(p(_e,w),-I[1]),_(p(k,B),x[1]))),C[2]),_(d(_(p(W,R),f[1]),d(_(p(Y,S),-I[1]),_(p(k,B),C[1]))),-x[2])))),ve=p(ye,Me);return ve[ve.length-1]}}function l(d,p,m,_){return function(f,I,C,y,x,E){var B=d(d(m(f[0],f[0]),m(f[1],f[1])),d(m(f[2],f[2]),m(f[3],f[3]))),S=_(B,I[0]),Q=_(B,C[0]),w=_(B,y[0]),M=_(B,x[0]),k=_(B,E[0]),R=d(d(m(I[0],I[0]),m(I[1],I[1])),d(m(I[2],I[2]),m(I[3],I[3]))),F=_(R,f[0]),O=_(R,C[0]),U=_(R,y[0]),Y=_(R,x[0]),W=_(R,E[0]),te=d(d(m(C[0],C[0]),m(C[1],C[1])),d(m(C[2],C[2]),m(C[3],C[3]))),j=_(te,f[0]),J=_(te,I[0]),oe=_(te,y[0]),ie=_(te,x[0]),ne=_(te,E[0]),le=d(d(m(y[0],y[0]),m(y[1],y[1])),d(m(y[2],y[2]),m(y[3],y[3]))),ge=_(le,f[0]),_e=_(le,I[0]),ue=_(le,C[0]),fe=_(le,x[0]),pe=_(le,E[0]),ye=d(d(m(x[0],x[0]),m(x[1],x[1])),d(m(x[2],x[2]),m(x[3],x[3]))),Me=_(ye,f[0]),ve=_(ye,I[0]),he=_(ye,C[0]),Qe=_(ye,y[0]),Pe=_(ye,E[0]),we=d(d(m(E[0],E[0]),m(E[1],E[1])),d(m(E[2],E[2]),m(E[3],E[3]))),Te=_(we,f[0]),Re=_(we,I[0]),Ee=_(we,C[0]),ke=_(we,y[0]),Ce=_(we,x[0]),Le=d(d(d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),C[2]),_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),-y[2])),d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),x[2]),_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),-E[2]))),I[3]),d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),I[2]),_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),-y[2])),d(_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),x[2]),_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),-E[2]))),-C[3]),_(d(d(_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),I[2]),_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),x[2]),_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),-E[2]))),y[3]))),d(d(_(d(d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),I[2]),_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),y[2]),_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),-E[2]))),-x[3]),_(d(d(_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),I[2]),_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),-C[2])),d(_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),y[2]),_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),-x[2]))),E[3])),d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),I[2]),_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),-y[2])),d(_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),x[2]),_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),-E[2]))),f[3]),_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-y[2])),d(_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),x[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-E[2]))),-I[3])))),d(d(d(_(d(d(_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),x[2]),_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),-E[2]))),y[3]),_(d(d(_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),f[2]),_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),y[2]),_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),-E[2]))),-x[3])),d(_(d(d(_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),f[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-I[2])),d(_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),y[2]),_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),-x[2]))),E[3]),_(d(d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),I[2]),_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),y[2]),_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),-E[2]))),f[3]))),d(d(_(d(d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),f[2]),_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),y[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-E[2]))),-I[3]),_(d(d(_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),f[2]),_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),y[2]),_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),-E[2]))),C[3])),d(_(d(d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),f[2]),_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-E[2]))),-y[3]),_(d(d(_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),f[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-I[2])),d(_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-y[2]))),E[3]))))),Ye=d(d(d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),C[2]),_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),-y[2])),d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),x[2]),_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),-E[2]))),f[3]),d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-y[2])),d(_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),x[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-E[2]))),-C[3]),_(d(d(_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),x[2]),_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),-E[2]))),y[3]))),d(d(_(d(d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),f[2]),_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),y[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-E[2]))),-x[3]),_(d(d(_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),f[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-C[2])),d(_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),y[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-x[2]))),E[3])),d(_(d(d(_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),I[2]),_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),x[2]),_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),-E[2]))),f[3]),_(d(d(_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),x[2]),_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),-E[2]))),-I[3])))),d(d(d(_(d(d(_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),x[2]),_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),-E[2]))),C[3]),_(d(d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),f[2]),_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-E[2]))),-x[3])),d(_(d(d(_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),f[2]),_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),-I[2])),d(_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-x[2]))),E[3]),_(d(d(_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),I[2]),_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),-C[2])),d(_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),y[2]),_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),-x[2]))),f[3]))),d(d(_(d(d(_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),f[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-C[2])),d(_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),y[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-x[2]))),-I[3]),_(d(d(_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),f[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-I[2])),d(_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),y[2]),_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),-x[2]))),C[3])),d(_(d(d(_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),f[2]),_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),-I[2])),d(_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-x[2]))),-y[3]),_(d(d(_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),f[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-I[2])),d(_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-y[2]))),x[3]))))),tt=p(Le,Ye);return tt[tt.length-1]}}var u=[function(){return 0},function(){return 0},function(){return 0}];function g(d){var p=u[d.length];return p||(p=u[d.length]=s(d.length)),p.apply(void 0,d)}function h(d,p,m,_,f,I,C,y){return function(x,E,B,S,Q,w){switch(arguments.length){case 0:case 1:return 0;case 2:return _(x,E);case 3:return f(x,E,B);case 4:return I(x,E,B,S);case 5:return C(x,E,B,S,Q);case 6:return y(x,E,B,S,Q,w)}for(var M=new Array(arguments.length),k=0;k<arguments.length;++k)M[k]=arguments[k];return d(M)}}(function(){for(;u.length<=6;)u.push(s(u.length));e.exports=h.apply(void 0,[g].concat(u));for(var d=0;d<=6;++d)e.exports[d]=u[d]})()}}),q$n=nm({"node_modules/cdt2d/lib/delaunay.js"(t,e){var n=$$n()[4];bse();function o(i,r,s,a,A,c){var l=r.opposite(a,A);if(!(l<0)){if(A<a){var u=a;a=A,A=u,u=c,c=l,l=u}r.isConstraint(a,A)||n(i[a],i[A],i[c],i[l])<0&&s.push(a,A)}}e.exports=function(i,r){for(var s=[],a=i.length,A=r.stars,c=0;c<a;++c)for(var l=A[c],u=1;u<l.length;u+=2)if(!((p=l[u])<c)&&!r.isConstraint(c,p)){for(var g=l[u-1],h=-1,d=1;d<l.length;d+=2)if(l[d-1]===p){h=l[d];break}h<0||n(i[c],i[p],i[g],i[h])<0&&s.push(c,p)}for(;s.length>0;){for(var p=s.pop(),m=(g=-1,h=-1,l=A[c=s.pop()],1);m<l.length;m+=2){var _=l[m-1],f=l[m];_===p?h=f:f===p&&(g=_)}g<0||h<0||n(i[c],i[p],i[g],i[h])>=0||(r.flip(c,p),o(i,r,s,g,c,h),o(i,r,s,c,h,g),o(i,r,s,h,p,g),o(i,r,s,p,g,h))}}}}),X$n=nm({"node_modules/cdt2d/lib/filter.js"(t,e){var n=bse();function o(r,s,a,A,c,l,u){this.cells=r,this.neighbor=s,this.flags=A,this.constraint=a,this.active=c,this.next=l,this.boundary=u}function i(r,s){return r[0]-s[0]||r[1]-s[1]||r[2]-s[2]}e.exports=function(r,s,a){var A=(function(y,x){for(var E=y.cells(),B=E.length,S=0;S<B;++S){var Q=(te=E[S])[0],w=te[1],M=te[2];w<M?w<Q&&(te[0]=w,te[1]=M,te[2]=Q):M<Q&&(te[0]=M,te[1]=Q,te[2]=w)}E.sort(i);var k=new Array(B);for(S=0;S<k.length;++S)k[S]=0;var R=[],F=[],O=new Array(3*B),U=new Array(3*B),Y=null;x&&(Y=[]);var W=new o(E,O,U,k,R,F,Y);for(S=0;S<B;++S)for(var te=E[S],j=0;j<3;++j){Q=te[j],w=te[(j+1)%3];var J=O[3*S+j]=W.locate(w,Q,y.opposite(w,Q)),oe=U[3*S+j]=y.isConstraint(Q,w);J<0&&(oe?F.push(S):(R.push(S),k[S]=1),x&&Y.push([w,Q,-1]))}return W})(r,a);if(s===0)return a?A.cells.concat(A.boundary):A.cells;for(var c=1,l=A.active,u=A.next,g=A.flags,h=A.cells,d=A.constraint,p=A.neighbor;l.length>0||u.length>0;){for(;l.length>0;){var m=l.pop();if(g[m]!==-c){g[m]=c,h[m];for(var _=0;_<3;++_){var f=p[3*m+_];f>=0&&g[f]===0&&(d[3*m+_]?u.push(f):(l.push(f),g[f]=c))}}}var I=u;u=l,l=I,u.length=0,c=-c}var C=(function(y,x,E){for(var B=0,S=0;S<y.length;++S)x[S]===E&&(y[B++]=y[S]);return y.length=B,y})(h,g,s);return a?C.concat(A.boundary):C},o.prototype.locate=(function(){var r=[0,0,0];return function(s,a,A){var c=s,l=a,u=A;return a<A?a<s&&(c=a,l=A,u=s):A<s&&(c=A,l=s,u=a),c<0?-1:(r[0]=c,r[1]=l,r[2]=u,n.eq(this.cells,r,i))}})()}}),Z$n=nm({"node_modules/cdt2d/cdt2d.js"(t,e){var n=W$n(),o=j$n(),i=q$n(),r=X$n();function s(c){return[Math.min(c[0],c[1]),Math.max(c[0],c[1])]}function a(c,l){return c[0]-l[0]||c[1]-l[1]}function A(c,l,u){return l in c?c[l]:u}e.exports=function(c,l,u){Array.isArray(l)?(u=u||{},l=l||[]):(u=l||{},l=[]);var g=!!A(u,"delaunay",!0),h=!!A(u,"interior",!0),d=!!A(u,"exterior",!0),p=!!A(u,"infinity",!1);if(!h&&!d||c.length===0)return[];var m=n(c,l);if(g||h!==d||p){for(var _=o(c.length,(function(C){return C.map(s).sort(a)})(l)),f=0;f<m.length;++f){var I=m[f];_.addTriangle(I[0],I[1],I[2])}return g&&i(c,_),d?h?p?r(_,0,p):_.cells():r(_,1,p):r(_,-1)}return m}}});function i_t(t,e){return Array.isArray(e)?[t.a*e[0]+t.c*e[1]+t.e,t.b*e[0]+t.d*e[1]+t.f]:{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}function r_t(t,e=0){return{a:1,c:0,e:t,b:0,d:1,f:e}}X9e(G$n()),X9e(V$n()),new TextEncoder,(()=>{const t=new Uint8Array(4);new Uint32Array(t.buffer)[0]=1,t[0]})();var eqn=new Uint16Array([255]),tqn=(new Uint8Array(eqn.buffer)[0],new Uint16Array([255]));new Uint8Array(tqn.buffer)[0],new TextDecoder("latin1");function px(){return px=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var o in n)({}).hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},px.apply(null,arguments)}function Sse(t,e){return(Sse=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(n,o){return n.__proto__=o,n})(t,e)}function s_t(t){return(s_t=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)})(t)}function a_t(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(a_t=function(){return!!t})()}function e7e(t){var e=typeof Map=="function"?new Map:void 0;return e7e=function(n){if(n===null||!(function(i){try{return Function.toString.call(i).indexOf("[native code]")!==-1}catch{return typeof i=="function"}})(n))return n;if(typeof n!="function")throw new TypeError("Super expression must either be null or a function");if(e!==void 0){if(e.has(n))return e.get(n);e.set(n,o)}function o(){return(function(i,r,s){if(a_t())return Reflect.construct.apply(null,arguments);var a=[null];a.push.apply(a,r);var A=new(i.bind.apply(i,a));return s&&Sse(A,s.prototype),A})(n,arguments,s_t(this).constructor)}return o.prototype=Object.create(n.prototype,{constructor:{value:o,enumerable:!1,writable:!0,configurable:!0}}),Sse(o,n)},e7e(t)}var nqn={1:`Passed invalid arguments to hsl, please pass multiple numbers e.g. hsl(360, 0.75, 0.4) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75 }).

`,2:`Passed invalid arguments to hsla, please pass multiple numbers e.g. hsla(360, 0.75, 0.4, 0.7) or an object e.g. rgb({ hue: 255, saturation: 0.4, lightness: 0.75, alpha: 0.7 }).

`,3:`Passed an incorrect argument to a color function, please pass a string representation of a color.

`,4:`Couldn't generate valid rgb string from %s, it returned %s.

`,5:`Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.

`,6:`Passed invalid arguments to rgb, please pass multiple numbers e.g. rgb(255, 205, 100) or an object e.g. rgb({ red: 255, green: 205, blue: 100 }).

`,7:`Passed invalid arguments to rgba, please pass multiple numbers e.g. rgb(255, 205, 100, 0.75) or an object e.g. rgb({ red: 255, green: 205, blue: 100, alpha: 0.75 }).

`,8:`Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.

`,9:`Please provide a number of steps to the modularScale helper.

`,10:`Please pass a number or one of the predefined scales to the modularScale helper as the ratio.

`,11:`Invalid value passed as base to modularScale, expected number or em string but got "%s"

`,12:`Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.

`,13:`Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.

`,14:`Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.

`,15:`Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.

`,16:`You must provide a template to this method.

`,17:`You passed an unsupported selector state to this method.

`,18:`minScreen and maxScreen must be provided as stringified numbers with the same units.

`,19:`fromSize and toSize must be provided as stringified numbers with the same units.

`,20:`expects either an array of objects or a single object with the properties prop, fromSize, and toSize.

`,21:"expects the objects in the first argument array to have the properties `prop`, `fromSize`, and `toSize`.\n\n",22:"expects the first argument object to have the properties `prop`, `fromSize`, and `toSize`.\n\n",23:`fontFace expects a name of a font-family.

`,24:`fontFace expects either the path to the font file(s) or a name of a local copy.

`,25:`fontFace expects localFonts to be an array.

`,26:`fontFace expects fileFormats to be an array.

`,27:`radialGradient requries at least 2 color-stops to properly render.

`,28:`Please supply a filename to retinaImage() as the first argument.

`,29:`Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.

`,30:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",31:`The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation

`,32:`To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])
To pass a single animation please supply them in simple values, e.g. animation('rotate', '2s')

`,33:`The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation

`,34:`borderRadius expects a radius value as a string or number as the second argument.

`,35:`borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.

`,36:`Property must be a string value.

`,37:`Syntax Error at %s.

`,38:`Formula contains a function that needs parentheses at %s.

`,39:`Formula is missing closing parenthesis at %s.

`,40:`Formula has too many closing parentheses at %s.

`,41:`All values in a formula must have the same unit or be unitless.

`,42:`Please provide a number of steps to the modularScale helper.

`,43:`Please pass a number or one of the predefined scales to the modularScale helper as the ratio.

`,44:`Invalid value passed as base to modularScale, expected number or em/rem string but got %s.

`,45:`Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.

`,46:`Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.

`,47:`minScreen and maxScreen must be provided as stringified numbers with the same units.

`,48:`fromSize and toSize must be provided as stringified numbers with the same units.

`,49:`Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.

`,50:`Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.

`,51:`Expects the first argument object to have the properties prop, fromSize, and toSize.

`,52:`fontFace expects either the path to the font file(s) or a name of a local copy.

`,53:`fontFace expects localFonts to be an array.

`,54:`fontFace expects fileFormats to be an array.

`,55:`fontFace expects a name of a font-family.

`,56:`linearGradient requries at least 2 color-stops to properly render.

`,57:`radialGradient requries at least 2 color-stops to properly render.

`,58:`Please supply a filename to retinaImage() as the first argument.

`,59:`Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.

`,60:"Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n",61:`Property must be a string value.

`,62:`borderRadius expects a radius value as a string or number as the second argument.

`,63:`borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.

`,64:`The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.

`,65:`To pass multiple animations please supply them in arrays, e.g. animation(['rotate', '2s'], ['move', '1s'])\\nTo pass a single animation please supply them in simple values, e.g. animation('rotate', '2s').

`,66:`The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.

`,67:`You must provide a template to this method.

`,68:`You passed an unsupported selector state to this method.

`,69:`Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.

`,70:`Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.

`,71:`Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.

`,72:`Passed invalid base value %s to %s(), please pass a value like "12px" or 12.

`,73:`Please provide a valid CSS variable.

`,74:`CSS variable not found and no default was provided.

`,75:`important requires a valid style object, got a %s instead.

`,76:`fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.

`,77:`remToPx expects a value in "rem" but you provided it in "%s".

`,78:`base must be set in "px" or "%" but you set it in "%s".
`};function oqn(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];var o,i=e[0],r=[];for(o=1;o<e.length;o+=1)r.push(e[o]);return r.forEach(function(s){i=i.replace(/%[a-z]/,s)}),i}var t7=(function(t){var e,n;function o(i){var r;if(N$n.env.NODE_ENV==="production")r=t.call(this,"An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#"+i+" for more information.")||this;else{for(var s=arguments.length,a=new Array(s>1?s-1:0),A=1;A<s;A++)a[A-1]=arguments[A];r=t.call(this,oqn.apply(void 0,[nqn[i]].concat(a)))||this}return(function(c){if(c===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return c})(r)}return n=t,(e=o).prototype=Object.create(n.prototype),e.prototype.constructor=e,Sse(e,n),o})(e7e(Error));function t7e(t){return Math.round(255*t)}function iqn(t,e,n){return t7e(t)+","+t7e(e)+","+t7e(n)}function Qse(t,e,n,o){if(o===void 0&&(o=iqn),e===0)return o(n,n,n);var i=(t%360+360)%360/60,r=(1-Math.abs(2*n-1))*e,s=r*(1-Math.abs(i%2-1)),a=0,A=0,c=0;i>=0&&i<1?(a=r,A=s):i>=1&&i<2?(a=s,A=r):i>=2&&i<3?(A=r,c=s):i>=3&&i<4?(A=s,c=r):i>=4&&i<5?(a=s,c=r):i>=5&&i<6&&(a=r,c=s);var l=n-r/2;return o(a+l,A+l,c+l)}var A_t={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkgrey:"a9a9a9",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkslategrey:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dimgrey:"696969",dodgerblue:"1e90ff",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",grey:"808080",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgray:"d3d3d3",lightgreen:"90ee90",lightgrey:"d3d3d3",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslategray:"789",lightslategrey:"789",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"0f0",limegreen:"32cd32",linen:"faf0e6",magenta:"f0f",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370db",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"db7093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",rebeccapurple:"639",red:"f00",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",slategrey:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",wheat:"f5deb3",white:"fff",whitesmoke:"f5f5f5",yellow:"ff0",yellowgreen:"9acd32"},rqn=/^#[a-fA-F0-9]{6}$/,sqn=/^#[a-fA-F0-9]{8}$/,aqn=/^#[a-fA-F0-9]{3}$/,Aqn=/^#[a-fA-F0-9]{4}$/,n7e=/^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i,cqn=/^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i,lqn=/^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i,uqn=/^hsl(?:a)?\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;function wD(t){if(typeof t!="string")throw new t7(3);var e=(function(g){if(typeof g!="string")return g;var h=g.toLowerCase();return A_t[h]?"#"+A_t[h]:g})(t);if(e.match(rqn))return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16)};if(e.match(sqn)){var n=parseFloat((parseInt(""+e[7]+e[8],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[2],16),green:parseInt(""+e[3]+e[4],16),blue:parseInt(""+e[5]+e[6],16),alpha:n}}if(e.match(aqn))return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16)};if(e.match(Aqn)){var o=parseFloat((parseInt(""+e[4]+e[4],16)/255).toFixed(2));return{red:parseInt(""+e[1]+e[1],16),green:parseInt(""+e[2]+e[2],16),blue:parseInt(""+e[3]+e[3],16),alpha:o}}var i=n7e.exec(e);if(i)return{red:parseInt(""+i[1],10),green:parseInt(""+i[2],10),blue:parseInt(""+i[3],10)};var r=cqn.exec(e.substring(0,50));if(r)return{red:parseInt(""+r[1],10),green:parseInt(""+r[2],10),blue:parseInt(""+r[3],10),alpha:parseFloat(""+r[4])>1?parseFloat(""+r[4])/100:parseFloat(""+r[4])};var s=lqn.exec(e);if(s){var a="rgb("+Qse(parseInt(""+s[1],10),parseInt(""+s[2],10)/100,parseInt(""+s[3],10)/100)+")",A=n7e.exec(a);if(!A)throw new t7(4,e,a);return{red:parseInt(""+A[1],10),green:parseInt(""+A[2],10),blue:parseInt(""+A[3],10)}}var c=uqn.exec(e.substring(0,50));if(c){var l="rgb("+Qse(parseInt(""+c[1],10),parseInt(""+c[2],10)/100,parseInt(""+c[3],10)/100)+")",u=n7e.exec(l);if(!u)throw new t7(4,e,l);return{red:parseInt(""+u[1],10),green:parseInt(""+u[2],10),blue:parseInt(""+u[3],10),alpha:parseFloat(""+c[4])>1?parseFloat(""+c[4])/100:parseFloat(""+c[4])}}throw new t7(5)}function UQ(t){return(function(e){var n,o=e.red/255,i=e.green/255,r=e.blue/255,s=Math.max(o,i,r),a=Math.min(o,i,r),A=(s+a)/2;if(s===a)return e.alpha!==void 0?{hue:0,saturation:0,lightness:A,alpha:e.alpha}:{hue:0,saturation:0,lightness:A};var c=s-a,l=A>.5?c/(2-s-a):c/(s+a);switch(s){case o:n=(i-r)/c+(i<r?6:0);break;case i:n=(r-o)/c+2;break;default:n=(o-i)/c+4}return n*=60,e.alpha!==void 0?{hue:n,saturation:l,lightness:A,alpha:e.alpha}:{hue:n,saturation:l,lightness:A}})(wD(t))}var o7e=function(t){return t.length===7&&t[1]===t[2]&&t[3]===t[4]&&t[5]===t[6]?"#"+t[1]+t[3]+t[5]:t};function PD(t){var e=t.toString(16);return e.length===1?"0"+e:e}function i7e(t){return PD(Math.round(255*t))}function gqn(t,e,n){return o7e("#"+i7e(t)+i7e(e)+i7e(n))}function c_t(t,e,n){return Qse(t,e,n,gqn)}function r7e(t,e,n){if(typeof t=="number"&&typeof e=="number"&&typeof n=="number")return o7e("#"+PD(t)+PD(e)+PD(n));if(typeof t=="object"&&e===void 0&&n===void 0)return o7e("#"+PD(t.red)+PD(t.green)+PD(t.blue));throw new t7(6)}function vse(t,e,n,o){if(typeof t=="string"&&typeof e=="number"){var i=wD(t);return"rgba("+i.red+","+i.green+","+i.blue+","+e+")"}if(typeof t=="number"&&typeof e=="number"&&typeof n=="number"&&typeof o=="number")return o>=1?r7e(t,e,n):"rgba("+t+","+e+","+n+","+o+")";if(typeof t=="object"&&e===void 0&&n===void 0&&o===void 0)return t.alpha>=1?r7e(t.red,t.green,t.blue):"rgba("+t.red+","+t.green+","+t.blue+","+t.alpha+")";throw new t7(7)}function KQ(t){if(typeof t!="object")throw new t7(8);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&typeof e.alpha=="number"})(t))return vse(t);if((function(e){return typeof e.red=="number"&&typeof e.green=="number"&&typeof e.blue=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(t))return r7e(t);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&typeof e.alpha=="number"})(t))return(function(e,n,o,i){if(typeof e=="object"&&n===void 0&&o===void 0&&i===void 0)return e.alpha>=1?c_t(e.hue,e.saturation,e.lightness):"rgba("+Qse(e.hue,e.saturation,e.lightness)+","+e.alpha+")";throw new t7(2)})(t);if((function(e){return typeof e.hue=="number"&&typeof e.saturation=="number"&&typeof e.lightness=="number"&&(typeof e.alpha!="number"||e.alpha===void 0)})(t))return(function(e,n,o){if(typeof e=="object"&&n===void 0&&o===void 0)return c_t(e.hue,e.saturation,e.lightness);throw new t7(1)})(t);throw new t7(8)}function l_t(t,e,n){return function(){var o=n.concat(Array.prototype.slice.call(arguments));return o.length>=e?t.apply(this,o):l_t(t,e,o)}}function K3(t){return l_t(t,t.length,[])}K3(function(t,e){if(e==="transparent")return e;var n=UQ(e);return KQ(px({},n,{hue:n.hue+parseFloat(t)}))});function VF(t,e,n){return Math.max(t,Math.min(e,n))}K3(function(t,e){if(e==="transparent")return e;var n=UQ(e);return KQ(px({},n,{lightness:VF(0,1,n.lightness-parseFloat(t))}))}),K3(function(t,e){if(e==="transparent")return e;var n=UQ(e);return KQ(px({},n,{saturation:VF(0,1,n.saturation-parseFloat(t))}))}),K3(function(t,e){if(e==="transparent")return e;var n=UQ(e);return KQ(px({},n,{lightness:VF(0,1,n.lightness+parseFloat(t))}))});var u_t=K3(function(t,e,n){if(e==="transparent")return n;if(n==="transparent")return e;if(t===0)return n;var o=wD(e),i=px({},o,{alpha:typeof o.alpha=="number"?o.alpha:1}),r=wD(n),s=px({},r,{alpha:typeof r.alpha=="number"?r.alpha:1}),a=i.alpha-s.alpha,A=2*parseFloat(t)-1,c=((A*a===-1?A:A+a)/(1+A*a)+1)/2,l=1-c;return vse({red:Math.floor(i.red*c+s.red*l),green:Math.floor(i.green*c+s.green*l),blue:Math.floor(i.blue*c+s.blue*l),alpha:i.alpha*parseFloat(t)+s.alpha*(1-parseFloat(t))})});K3(function(t,e){if(e==="transparent")return e;var n=wD(e);return vse(px({},n,{alpha:VF(0,1,(100*(typeof n.alpha=="number"?n.alpha:1)+100*parseFloat(t))/100)}))}),K3(function(t,e){if(e==="transparent")return e;var n=UQ(e);return KQ(px({},n,{saturation:VF(0,1,n.saturation+parseFloat(t))}))}),K3(function(t,e){return e==="transparent"?e:KQ(px({},UQ(e),{hue:parseFloat(t)}))}),K3(function(t,e){return e==="transparent"?e:KQ(px({},UQ(e),{lightness:parseFloat(t)}))}),K3(function(t,e){return e==="transparent"?e:KQ(px({},UQ(e),{saturation:parseFloat(t)}))}),K3(function(t,e){return e==="transparent"?e:u_t(parseFloat(t),"rgb(0, 0, 0)",e)}),K3(function(t,e){return e==="transparent"?e:u_t(parseFloat(t),"rgb(255, 255, 255)",e)});var Bz=K3(function(t,e){if(e==="transparent")return e;var n=wD(e);return vse(px({},n,{alpha:VF(0,1,+(100*(typeof n.alpha=="number"?n.alpha:1)-100*parseFloat(t)).toFixed(2)/100)}))}),g_t={0:"M0.301025 0.257813 L0.206593 0.283385 L0.122042 0.361307 L0.075923 0.474441 L0.064942 0.642221 L0.091296 0.78289 L0.159376 0.899463 L0.257104 0.961214 L0.344948 0.961214 L0.442678 0.899463 L0.510757 0.78289 L0.537111 0.642221 L0.526131 0.474441 L0.480012 0.361307 L0.39546 0.283385 L0.301025 0.257813",1:"M0.220426 0.40845 L0.381626 0.270996 L0.381626 0.948966",2:"M0.110409 0.39212 L0.125621 0.342293 L0.170571 0.295823 L0.244237 0.26431 L0.291518 0.257813 L0.373319 0.263799 L0.434683 0.290705 L0.468239 0.331966 L0.480292 0.379913 L0.479492 0.411806 L0.465088 0.465192 L0.402571 0.568988 L0.245134 0.766438 L0.07959 0.948045 L0.522462 0.948045",3:"M0.081606 0.345073 L0.119154 0.315633 L0.178996 0.284091 L0.255265 0.257813 L0.349133 0.263062 L0.43127 0.289348 L0.48994 0.336662 L0.525141 0.394491 L0.513407 0.457577 L0.466472 0.504892 L0.384334 0.541692 L0.290464 0.56272 L0.20833 0.573235 L0.290464 0.583749 L0.384334 0.610035 L0.466472 0.652092 L0.519274 0.709922 L0.531007 0.773007 L0.50754 0.841351 L0.454738 0.899179 L0.3726 0.946494 L0.310412 0.961214 L0.209503 0.959111 L0.127367 0.946494 L0.071046 0.929671",4:"M0.418494 0.270996 L0.048828 0.724199 L0.553224 0.724199 M0.414181 0.578167 L0.414181 0.94897",5:"M0.074951 0.270996 L0.074951 0.614701 L0.267655 0.5695 L0.405247 0.586502 L0.460002 0.617189 L0.498028 0.660731 L0.527101 0.779401 L0.513352 0.841049 L0.477274 0.889568 L0.406378 0.93463 L0.324445 0.958337 L0.247399 0.962139 L0.182516 0.949767 L0.130068 0.925508 L0.074951 0.875607 M0.074951 0.270996 L0.527101 0.270996",6:"M0.428549 0.257813 L0.341433 0.285053 L0.26073 0.312099 L0.192188 0.360182 L0.138902 0.410969 L0.098219 0.500422 L0.070249 0.584267 L0.067264 0.670716 L0.065164 0.756863 L0.087163 0.820973 L0.108168 0.861042 L0.157916 0.913131 L0.210981 0.948192 L0.29279 0.961214 L0.384548 0.956206 L0.456409 0.924151 L0.507262 0.881077 L0.5349 0.821975 L0.537111 0.771889 L0.521634 0.718798 L0.498418 0.67372 L0.463042 0.636657 L0.414398 0.613617 L0.34696 0.598591 L0.28284 0.595587 L0.215403 0.605604 L0.145756 0.641665 L0.109274 0.678729 L0.064942 0.724006",7:"M0.071534 0.270996 L0.530519 0.270996 L0.495935 0.291702 L0.477752 0.305407 L0.435186 0.346112 L0.412067 0.374136 L0.388565 0.40796 L0.365315 0.448098 L0.342943 0.495062 L0.322081 0.549366 L0.303364 0.611524 L0.287416 0.68205 L0.270077 0.80465 L0.26253 0.94897",8:"M0.286761 0.257813 L0.210684 0.27162 L0.1414 0.305622 L0.092494 0.382125 L0.111513 0.450128 L0.16857 0.502193 L0.228345 0.539382 L0.377781 0.594635 L0.470161 0.645637 L0.52586 0.706203 L0.538087 0.792269 L0.506841 0.87621 L0.438915 0.927212 L0.339743 0.961214 L0.263666 0.959089 L0.174004 0.929337 L0.102003 0.881523 L0.063965 0.811395 L0.066682 0.741266 L0.102003 0.671139 L0.180797 0.608448 L0.259591 0.580822 L0.358762 0.548945 L0.456576 0.49688 L0.486463 0.446941 L0.487822 0.362999 L0.453859 0.302434 L0.384574 0.265245 L0.286761 0.257813",9:"M0.511026 0.437812 L0.491026 0.347812 L0.451026 0.297812 L0.391026 0.267812 L0.311026 0.257813 L0.231026 0.267812 L0.161026 0.297812 L0.111026 0.347812 L0.091026 0.417812 L0.111026 0.487812 L0.161026 0.537812 L0.231026 0.567812 L0.311026 0.577812 L0.391026 0.557812 L0.451026 0.517812 L0.491026 0.477812 L0.511026 0.437812 M0.510026 0.438812 L0.434026 0.636812 L0.381026 0.777812 L0.337026 0.879812 L0.301026 0.957812","!":"M0.301026 0.270996 L0.301026 0.749566 M0.251466 0.94897 L0.350587 0.94897",'"':"M0.16504 0.270996 L0.16504 0.523022 M0.437013 0.270996 L0.437013 0.523022","#":"M0.20958 0.282227 L0.146515 0.949754 M0.461844 0.282227 L0.398779 0.949754 M0.032999 0.526969 L0.600587 0.452796 M0.001465 0.82366 L0.569055 0.749486",$:"M0.307121 0.240234 L0.307121 1.083502 M0.490031 0.415915 L0.404676 0.328075 L0.23396 0.310507 L0.136407 0.398347 L0.099828 0.521324 L0.124213 0.591596 L0.197379 0.644299 L0.429061 0.697003 L0.502224 0.749708 L0.526613 0.837547 L0.477836 0.960526 L0.355897 1.013228 L0.197379 0.99566 L0.112021 0.942957 L0.07544 0.837547","'":"M0.301026 0.270996 L0.301026 0.523022","(":"M0.413087 0.241211 L0.372337 0.28347 L0.331589 0.334184 L0.290838 0.393349 L0.25009 0.460965 L0.219528 0.528584 L0.199153 0.5962 L0.188966 0.655364 L0.199153 0.714529 L0.219528 0.782146 L0.25009 0.849764 L0.290838 0.91738 L0.331589 0.976544 L0.372337 1.027258 L0.413087 1.069491",")":"M0.188966 0.241211 L0.229716 0.28347 L0.270466 0.334184 L0.311213 0.393349 L0.351964 0.460965 L0.382526 0.528584 L0.4029 0.5962 L0.413087 0.655364 L0.4029 0.714529 L0.382526 0.782146 L0.351964 0.849764 L0.311213 0.91738 L0.270466 0.976544 L0.229716 1.027258 L0.188966 1.069491","*":"M0.301026 0.458702 L0.301026 0.681942 M0.301026 0.458702 L0.520997 0.536834 M0.301026 0.458702 L0.439954 0.257813 M0.301026 0.458702 L0.162098 0.257813 M0.301026 0.458702 L0.081055 0.536834","+":"M0.042969 0.66845 L0.559083 0.66845 M0.301023 0.428223 L0.301023 0.908661",",":"M0.38672 0.852051 L0.215333 1.030661 L0.301025 1.119971","-":"M0.173829 0.686035 L0.428224 0.686035",".":"M0.362549 0.851074 L0.239503 0.851074","/":"M0.062501 1.035249 L0.539551 0.270996","<":"M0.559083 0.441895 L0.042969 0.66939 L0.042969 0.66939 L0.559083 0.896902","=":"M0.042969 0.545898 L0.559083 0.545898 M0.042969 0.80837 L0.559083 0.80837",">":"M0.042969 0.441895 L0.559083 0.66939 L0.559083 0.66939 L0.042969 0.896902",A:"M0.018067 0.94897 L0.290179 0.270996 L0.583986 0.94897 M0.155303 0.684521 L0.433548 0.684521",B:"M0.063965 0.94897 L0.063965 0.278953 L0.209356 0.270996 L0.342486 0.294394 L0.432179 0.37292 L0.418224 0.48773 L0.312686 0.549166 L0.084728 0.575531 L0.306377 0.589434 L0.468877 0.647456 L0.538087 0.736658 L0.5324 0.85202 L0.501247 0.902983 L0.42355 0.944398 L0.063965 0.94897",C:"M0.529054 0.419847 L0.498425 0.345196 L0.442238 0.292341 L0.33583 0.257813 L0.257199 0.268357 L0.187906 0.303748 L0.120243 0.385432 L0.072998 0.599844 L0.110073 0.815385 L0.165381 0.902183 L0.222883 0.942801 L0.334904 0.961214 L0.43253 0.937679 L0.504816 0.868999 L0.529054 0.772065",D:"M0.064454 0.94897 L0.071838 0.285078 L0.171217 0.270996 L0.247348 0.272633 L0.37101 0.306078 L0.462461 0.378304 L0.514748 0.475555 L0.535591 0.576392 L0.537599 0.652313 L0.528065 0.717381 L0.508562 0.772419 L0.445948 0.855695 L0.362356 0.90871 L0.225203 0.945862 L0.064454 0.94897",E:"M0.080078 0.270996 L0.080078 0.94897 M0.080078 0.270996 L0.521974 0.270996 M0.080078 0.609981 L0.389405 0.609981 M0.080078 0.94897 L0.521974 0.94897",F:"M0.086426 0.270996 L0.086426 0.94897 M0.091304 0.275607 L0.515626 0.275607 M0.091304 0.607677 L0.447344 0.607677",G:"M0.498034 0.284943 L0.374621 0.257813 L0.244219 0.268648 L0.160577 0.311997 L0.094556 0.398116 L0.056397 0.58404 L0.076752 0.785532 L0.120865 0.858197 L0.188947 0.916734 L0.271008 0.953591 L0.357069 0.961214 L0.43715 0.932047 L0.501262 0.858539 L0.545656 0.648611 L0.329595 0.648131",H:"M0.066895 0.270996 L0.066895 0.94897 M0.066895 0.595658 L0.530009 0.595658 M0.535157 0.270996 L0.535157 0.94897",I:"M0.301026 0.270996 L0.301026 0.94897",J:"M0.506839 0.270996 L0.507814 0.782193 L0.498468 0.846168 L0.480733 0.880789 L0.455864 0.90832 L0.426095 0.929408 L0.360746 0.954812 L0.302508 0.962139 L0.223573 0.953638 L0.16538 0.930312 L0.137072 0.907715 L0.116428 0.880312 L0.102822 0.848819 L0.095633 0.813947 L0.094239 0.776413",K:"M0.035401 0.270996 L0.035401 0.94897 M0.502258 0.316194 L0.035401 0.687823 M0.212484 0.582361 L0.566652 0.933903",L:"M0.07544 0.270996 L0.07544 0.94897 L0.526613 0.94897",M:"M0.042481 0.94897 L0.042481 0.270996 L0.301027 0.712492 L0.559571 0.270996 L0.559571 0.94897",N:"M0.067871 0.94897 L0.067871 0.270996 L0.534181 0.94897 L0.525031 0.270996",O:"M0.287293 0.961214 L0.19843 0.933567 L0.1172 0.849451 L0.057129 0.563945 L0.114348 0.350255 L0.18455 0.289392 L0.306101 0.257813 L0.42054 0.29572 L0.487543 0.365003 L0.544923 0.625294 L0.516366 0.789624 L0.465476 0.884596 L0.375084 0.949287 L0.287293 0.961214",P:"M0.070557 0.94897 L0.070557 0.28379 L0.20704 0.270996 L0.329134 0.278993 L0.408525 0.300514 L0.444022 0.317908 L0.500637 0.368929 L0.525796 0.423728 L0.531496 0.50384 L0.508934 0.554205 L0.473724 0.582043 L0.417577 0.604365 L0.336375 0.620372 L0.226014 0.629268 L0.082368 0.630258",Q:"M0.282435 1.050813 L0.195447 1.019646 L0.115933 0.924817 L0.057129 0.602943 L0.113139 0.362034 L0.18186 0.293418 L0.300844 0.257813 L0.412868 0.300553 L0.478457 0.37866 L0.534625 0.672103 L0.506671 0.857367 L0.456855 0.964437 L0.368371 1.037368 L0.282435 1.050813 M0.341225 0.815559 L0.544923 1.070653",R:"M0.034912 0.944112 L0.034912 0.288556 L0.227127 0.270996 L0.362038 0.276867 L0.443423 0.294907 L0.477644 0.309614 L0.505809 0.328757 L0.526616 0.352817 L0.544963 0.418061 L0.543241 0.475921 L0.524463 0.517817 L0.49076 0.546518 L0.444265 0.564799 L0.355195 0.578739 L0.047653 0.589627 M0.303054 0.617306 L0.56714 0.94897",S:"M0.483037 0.364333 L0.407613 0.267477 L0.22883 0.257813 L0.128623 0.327565 L0.087712 0.455539 L0.104656 0.518727 L0.168054 0.573307 L0.41928 0.617318 L0.503796 0.669342 L0.535157 0.759324 L0.493846 0.900055 L0.367668 0.961214 L0.205436 0.956661 L0.116711 0.907038 L0.066895 0.790334",T:"M0.022949 0.270996 L0.579103 0.270996 M0.309284 0.270996 L0.309284 0.94897",U:"M0.072022 0.270996 L0.07308 0.648875 L0.080372 0.75167 L0.099024 0.827813 L0.134786 0.885729 L0.181571 0.924023 L0.251464 0.95168 L0.339655 0.962139 L0.401553 0.951668 L0.45232 0.924086 L0.482701 0.891771 L0.495745 0.870529 L0.515699 0.81637 L0.525014 0.744626 L0.530031 0.272017",V:"M0.027832 0.270996 L0.320083 0.94897 L0.57422 0.270996",W:"M0 0.270996 L0.079799 0.940377 L0.285198 0.472884 L0.505255 0.94897 L0.602052 0.270996",X:"M0.009034 0.270996 L0.586805 0.94897 M0.593019 0.270996 L0.015246 0.94897",Y:"M0.018067 0.270996 L0.293132 0.574135 M0.583986 0.271959 L0.294954 0.57606 L0.305277 0.94897",Z:"M0.053711 0.270996 L0.548341 0.270996 L0.053711 0.94897 L0.548341 0.94897","[":"M0.404542 0.240234 L0.197511 0.240234 L0.197511 1.069424 L0.404542 1.069424","\\":"M0.062501 0.270996 L0.539551 1.035249","]":"M0.19751 0.240234 L0.404542 0.240234 L0.404542 1.069424 L0.19751 1.069424","^":"M0.035156 0.523931 L0.301024 0.270996 L0.566896 0.523931",_:"M0 1.160601 L0.602052 1.160601",a:"M0.527101 0.439941 L0.527101 0.973965 M0.527101 0.553824 L0.451366 0.477535 L0.376759 0.439941 L0.263722 0.439941 L0.187989 0.477535 L0.112255 0.553824 L0.074951 0.66881 L0.074951 0.745099 L0.112255 0.85898 L0.187989 0.93527 L0.263722 0.973965 L0.376759 0.973965 L0.451366 0.93527 L0.527101 0.85898",b:"M0.07666 0.240234 L0.07666 0.959985 M0.07666 0.582737 L0.151822 0.514237 L0.225865 0.480483 L0.338045 0.480483 L0.413211 0.514237 L0.488374 0.582737 L0.525392 0.685983 L0.525392 0.754485 L0.488374 0.856739 L0.413211 0.92524 L0.338045 0.959985 L0.225865 0.959985 L0.151822 0.92524 L0.07666 0.856739",c:"M0.512452 0.553823 L0.441624 0.477535 L0.371854 0.439941 L0.26614 0.439941 L0.195312 0.477535 L0.124486 0.553823 L0.0896 0.668808 L0.0896 0.745099 L0.124486 0.858979 L0.195312 0.93527 L0.26614 0.973965 L0.371854 0.973965 L0.441624 0.93527 L0.512452 0.858979",d:"M0.525392 0.240234 L0.525392 0.959985 M0.525392 0.582737 L0.450232 0.514237 L0.376189 0.480483 L0.264006 0.480483 L0.188844 0.514237 L0.11368 0.582737 L0.076661 0.685983 L0.076661 0.754485 L0.11368 0.856739 L0.188844 0.92524 L0.264006 0.959985 L0.376189 0.959985 L0.450232 0.92524 L0.525392 0.856739",e:"M0.059571 0.668808 L0.542482 0.668808 M0.542482 0.592521 L0.502641 0.516231 L0.461594 0.477535 L0.381914 0.439941 L0.261186 0.439941 L0.180299 0.477535 L0.099412 0.553823 L0.059571 0.668808 L0.059571 0.745099 L0.099412 0.858979 L0.180299 0.93527 L0.261186 0.973965 L0.381914 0.973965 L0.461594 0.93527 L0.542482 0.858979",f:"M0.512941 0.240234 L0.406984 0.240234 L0.301026 0.274346 L0.248047 0.374731 L0.248047 0.946817 M0.089112 0.476088 L0.459965 0.476088",g:"M0.525392 0.439941 L0.525392 0.989395 L0.488373 1.091918 L0.45023 1.126757 L0.376189 1.160601 L0.264004 1.160601 L0.188844 1.126757 L0.113681 1.058075 L0.076661 0.954555 M0.525392 0.542467 L0.45023 0.473786 L0.376189 0.439941 L0.264004 0.439941 L0.188844 0.473786 L0.113681 0.542467 L0.076661 0.645988 L0.076661 0.714669 L0.113681 0.817193 L0.188844 0.885875 L0.264004 0.920713 L0.376189 0.920713 L0.45023 0.885875 L0.525392 0.817193",h:"M0.092041 0.240234 L0.092041 0.946817 M0.092041 0.61058 L0.205937 0.509225 L0.282214 0.476086 L0.396109 0.476086 L0.47187 0.509225 L0.510011 0.61058 L0.510011 0.946817",i:"M0.261026 0.240234 L0.341026 0.240234 M0.300978 0.476089 L0.300978 0.946817",j:"M0.3853 0.240234 L0.447023 0.240234 M0.416159 0.465708 L0.416159 1.011689 L0.383887 1.108586 L0.252832 1.140264 L0.15503 1.108586",k:"M0.065186 0.240234 L0.065186 0.946817 M0.493824 0.476086 L0.065186 0.812323 M0.236758 0.677829 L0.536867 0.946817",l:"M0.301026 0.234863 L0.301026 0.946441",m:"M0.050538 0.439941 L0.050538 0.960796 M0.050538 0.588758 L0.114405 0.476607 L0.157178 0.439941 L0.236864 0.439941 L0.279637 0.476607 L0.32241 0.588758 L0.32241 0.960796 M0.32241 0.588758 L0.386281 0.476607 L0.428467 0.439941 L0.50874 0.439941 L0.551515 0.476607 L0.551515 0.960796",n:"M0.092041 0.439941 L0.092041 0.960796 M0.092041 0.588758 L0.205936 0.476607 L0.282216 0.439941 L0.396113 0.439941 L0.471871 0.476607 L0.510011 0.588758 L0.510011 0.960796",o:"M0.247175 0.439941 L0.175178 0.477535 L0.103186 0.553823 L0.066895 0.668808 L0.066895 0.745099 L0.103186 0.858979 L0.175178 0.93527 L0.247175 0.973965 L0.354874 0.973965 L0.426872 0.93527 L0.498866 0.858979 L0.535157 0.745099 L0.535157 0.668808 L0.498866 0.553823 L0.426872 0.477535 L0.354874 0.439941 L0.247175 0.439941",p:"M0.076904 0.439941 L0.076904 1.154244 M0.076904 0.541563 L0.151986 0.473487 L0.225944 0.439941 L0.338005 0.439941 L0.413087 0.473487 L0.488166 0.541563 L0.525148 0.644169 L0.525148 0.712246 L0.488166 0.813866 L0.413087 0.881942 L0.338005 0.916471 L0.225944 0.916471 L0.151986 0.881942 L0.076904 0.813866",q:"M0.525148 0.441895 L0.525148 1.156195 M0.525148 0.5435 L0.450067 0.47544 L0.376106 0.441895 L0.264042 0.441895 L0.188966 0.47544 L0.113885 0.5435 L0.076905 0.646108 L0.076905 0.714187 L0.113885 0.815809 L0.188966 0.883886 L0.264042 0.918418 L0.376106 0.918418 L0.450067 0.883886 L0.525148 0.815809",r:"M0.107422 0.439941 L0.107422 0.960796 M0.107422 0.663164 L0.155824 0.551014 L0.252626 0.476607 L0.349428 0.439941 L0.49463 0.439941",s:"M0.475556 0.477535 L0.400757 0.439941 L0.276092 0.439941 L0.176361 0.477535 L0.101563 0.553823 L0.101563 0.630112 L0.176361 0.668808 L0.301024 0.668808 L0.425688 0.745099 L0.50049 0.821387 L0.50049 0.897677 L0.425688 0.93527 L0.325956 0.973965 L0.201295 0.973965 L0.126496 0.93527 L0.101563 0.858979",t:"M0.246032 0.297852 L0.246032 0.826549 L0.301023 0.919323 L0.411011 0.950848 L0.520997 0.950848 M0.081055 0.515799 L0.466004 0.515799",u:"M0.092041 0.454102 L0.092041 0.826134 L0.13018 0.937211 L0.205936 0.974954 L0.319832 0.974954 L0.396113 0.937211 L0.510011 0.826134 M0.510011 0.454102 L0.510011 0.974954",v:"M0.048828 0.453125 L0.301026 0.961719 M0.553224 0.453125 L0.301026 0.961719",w:"M0 0.453125 L0.150512 0.961719 M0.301024 0.453125 L0.150512 0.961719 M0.301024 0.453125 L0.451539 0.961719 M0.602052 0.453125 L0.451539 0.961719",x:"M0.03711 0.453125 L0.564943 0.961719 M0.564943 0.453125 L0.03711 0.961719",y:"M0.084618 0.453125 L0.320232 0.921476 M0.55713 0.453125 L0.320232 0.921476 L0.242119 1.055289 L0.163369 1.122196 L0.084618 1.155166 L0.044922 1.155166",z:"M0.505373 0.452148 L0.09668 0.961651 M0.09668 0.452148 L0.505373 0.452148 M0.09668 0.961651 L0.505373 0.961651"},d_t={};for(const t in g_t){d_t[t]=[];const e=g_t[t].split("M").slice(1).map(n=>n.split("L").map(o=>o.trim().split(" ").map(parseFloat)));for(const n of e)for(let o=0;o<n.length-1;o++)d_t[t].push({x1:n[o][0],y1:1-n[o][1],x2:n[o+1][0],y2:1-n[o+1][1]})}var MD=(t,e)=>({...t,rects:[...t.rects??[],...e.rects??[]],points:[...t.points??[],...e.points??[]],lines:[...t.lines??[],...e.lines??[]],infiniteLines:[...t.infiniteLines??[],...e.infiniteLines??[]],polygons:[...t.polygons??[],...e.polygons??[]],circles:[...t.circles??[],...e.circles??[]],arrows:[...t.arrows??[],...e.arrows??[]],texts:[...t.texts??[],...e.texts??[]]});function s7e(t,e){if(t.points)for(const n of t.points)n.step=e;if(t.lines)for(const n of t.lines)n.step=e;if(t.infiniteLines)for(const n of t.infiniteLines)n.step=e;if(t.polygons)for(const n of t.polygons)n.step=e;if(t.rects)for(const n of t.rects)n.step=e;if(t.circles)for(const n of t.circles)n.step=e;if(t.texts)for(const n of t.texts)n.step=e;if(t.arrows)for(const n of t.arrows)n.step=e;return t}var zA=class{MAX_ITERATIONS=1e5;solved=!1;failed=!1;iterations=0;progress=0;error=null;activeSubSolver;failedSubSolvers;timeToSolve;stats={};_setupDone=!1;getSolverName(){return this.constructor.name}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.getSolverName()} error: ${e}`,this.failed=!0,e}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.getSolverName()} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){const e=Date.now();for(;!this.solved&&!this.failed;)this.step();const n=Date.now();this.timeToSolve=n-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function eh(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved}}var n7=class extends zA{startTimeOfStage={};endTimeOfStage={};timeSpentOnStage={};firstIterationOfStage={};currentPipelineStageIndex=0;inputProblem;pipelineOutputs={};constructor(e){super(),this.inputProblem=e,this.MAX_ITERATIONS=1e6}_step(){const e=this.pipelineDef[this.currentPipelineStageIndex];if(!e)return void(this.solved=!0);if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfStage[e.solverName]=performance.now(),this.timeSpentOnStage[e.solverName]=this.endTimeOfStage[e.solverName]-this.startTimeOfStage[e.solverName];const o=this.activeSubSolver.getOutput();o!==null&&(this.pipelineOutputs[e.solverName]=o),e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStageIndex++}else this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}const n=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...n),this[e.solverName]=this.activeSubSolver,this.timeSpentOnStage[e.solverName]=0,this.startTimeOfStage[e.solverName]=performance.now(),this.firstIterationOfStage[e.solverName]=this.iterations}solveUntilStage(e){for(;this.getCurrentStageName().toLowerCase()!==e.toLowerCase()&&(this.step(),!this.failed&&!this.solved););}getCurrentStageName(){return this.pipelineDef[this.currentPipelineStageIndex]?.solverName??"none"}getStageProgress(){const e=this.pipelineDef.length;if(e===0)return 1;const n=this.activeSubSolver?.progress??0;return(this.currentPipelineStageIndex+n)/e}getStageStats(){const e={};for(const n of this.pipelineDef){const o=this.timeSpentOnStage[n.solverName]||0,i=this.firstIterationOfStage[n.solverName]||0,r=this.iterations,s=n.solverName===this.getCurrentStageName()?r-i:0,a=this.currentPipelineStageIndex>this.pipelineDef.findIndex(A=>A.solverName===n.solverName);e[n.solverName]={timeSpent:o,iterations:s,completed:a}}return e}initialVisualize(){return null}finalVisualize(){return null}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let e=0;const n=this.initialVisualize();n&&(s7e(n,0),e=1);let o=null;this.solved&&(o=this.finalVisualize());const i=[n].filter(Boolean).concat(this.pipelineDef.map((r,s)=>{const a=this[r.solverName],A=a?.visualize();return A?(s7e(A,s+e),A):null}).filter(Boolean));return i.length===0?{points:[],rects:[],lines:[],circles:[],texts:[]}:(this.solved&&o&&(s7e(o,i.length+e+1),i.push(o)),i.length===1?i[0]:{points:i.flatMap(r=>r.points||[]),rects:i.flatMap(r=>r.rects||[]),lines:i.flatMap(r=>r.lines||[]),circles:i.flatMap(r=>r.circles||[]),texts:i.flatMap(r=>r.texts||[])})}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}computeProgress(){return this.getStageProgress()}getStageOutput(e){return this.pipelineOutputs[e]}getAllOutputs(){return{...this.pipelineOutputs}}hasStageOutput(e){return e in this.pipelineOutputs}getSolver(e){return this[e]}},dqn=class{constructor(e=1/0,n=Float64Array,o=Uint32Array){const i=e!==1/0;this.ids=i?new o(e):[],this.values=i?new n(e):[],this.capacity=e,this.length=0}clear(){this.length=0}push(e,n){if(this.length===this.capacity)throw new RangeError("Queue is at capacity.");let o=this.length++;for(;o>0;){const i=o-1>>1,r=this.values[i];if(n>=r)break;this.ids[o]=this.ids[i],this.values[o]=r,o=i}this.ids[o]=e,this.values[o]=n}pop(){if(this.length===0)return;const e=this.ids,n=this.values,o=e[0],i=--this.length;if(i>0){const r=e[i],s=n[i];let a=0;const A=i>>1;for(;a<A;){const c=1+(a<<1),l=c+1,u=c+(+(l<i)&+(n[l]<n[c]));if(n[u]>=s)break;e[a]=e[u],n[a]=n[u],a=u}e[a]=r,n[a]=s}return o}peek(){return this.length>0?this.ids[0]:void 0}peekValue(){return this.length>0?this.values[0]:void 0}shrink(){Array.isArray(this.ids)&&(this.ids.length=this.length),Array.isArray(this.values)&&(this.values.length=this.length)}},h_t=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],X4=class ZEn{static from(e,n=0){if(n%8!=0)throw new Error("byteOffset must be 8-byte aligned.");if(!e||e.byteLength===void 0||"buffer"in e)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");const[o,i]=new Uint8Array(e,n+0,2);if(o!==251)throw new Error("Data does not appear to be in a Flatbush format.");const r=i>>4;if(r!==3)throw new Error(`Got v${r} data when expected v3.`);const s=h_t[15&i];if(!s)throw new Error("Unrecognized array type.");const[a]=new Uint16Array(e,n+2,1),[A]=new Uint32Array(e,n+4,1);return new ZEn(A,a,s,void 0,e,n)}constructor(e,n=16,o=Float64Array,i=ArrayBuffer,r,s=0){if(e===void 0)throw new Error("Missing required argument: numItems.");if(isNaN(e)||e<=0)throw new Error(`Unexpected numItems value: ${e}.`);this.numItems=+e,this.nodeSize=Math.min(Math.max(+n,2),65535),this.byteOffset=s;let a=e,A=a;this._levelBounds=[4*a];do a=Math.ceil(a/this.nodeSize),A+=a,this._levelBounds.push(4*A);while(a!==1);this.ArrayType=o,this.IndexArrayType=A<16384?Uint16Array:Uint32Array;const c=h_t.indexOf(o),l=4*A*o.BYTES_PER_ELEMENT;if(c<0)throw new Error(`Unexpected typed array class: ${o}.`);const u=o,g=this.IndexArrayType;if(r)this.data=r,this._boxes=new u(r,s+8,4*A),this._indices=new g(r,s+8+l,A),this._pos=4*A,this.minX=this._boxes[this._pos-4],this.minY=this._boxes[this._pos-3],this.maxX=this._boxes[this._pos-2],this.maxY=this._boxes[this._pos-1];else{const h=this.data=new i(8+l+A*this.IndexArrayType.BYTES_PER_ELEMENT);this._boxes=new u(h,8,4*A),this._indices=new g(h,8+l,A),this._pos=0,this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,new Uint8Array(h,0,2).set([251,48+c]),new Uint16Array(h,2,1)[0]=n,new Uint32Array(h,4,1)[0]=e}this._queue=new dqn}add(e,n,o=e,i=n){const r=this._pos,s=r>>2,a=this._boxes;return this._indices[s]=s,a[r]=e,a[r+1]=n,a[r+2]=o,a[r+3]=i,this._pos=r+4,e<this.minX&&(this.minX=e),n<this.minY&&(this.minY=n),o>this.maxX&&(this.maxX=o),i>this.maxY&&(this.maxY=i),s}finish(){if(this._pos>>2!==this.numItems)throw new Error(`Added ${this._pos>>2} items when expected ${this.numItems}.`);const e=this._boxes;if(this.numItems<=this.nodeSize)return e[this._pos++]=this.minX,e[this._pos++]=this.minY,e[this._pos++]=this.maxX,void(e[this._pos++]=this.maxY);const{numItems:n,minX:o,minY:i,nodeSize:r,_indices:s,_levelBounds:a}=this,A=this.maxX-o||1,c=this.maxY-i||1,l=new Int32Array(n),u=65535/A,g=65535/c;for(let d=0,p=0;d<n;d++){const m=e[p++],_=e[p++],f=u*((m+e[p++])/2-o)|0,I=g*((_+e[p++])/2-i)|0;l[d]=mqn(f,I)}(function(d,p,m,_,f,I){const C=[_,f];for(;C.length;){const y=C.pop()||0,x=C.pop()||0;if(y-x<=I&&Math.floor(x/I)>=Math.floor(y/I))continue;const E=d[x],B=d[x+y>>1],S=d[y],Q=E>B!=E>S?E:B<E!=B<S?B:S;let w=x-1,M=y+1;for(;;){do w++;while(d[w]<Q);do M--;while(d[M]>Q);if(w>=M)break;pqn(d,p,m,w,M)}C.push(x,M,M+1,y)}})(l,e,s,0,n-1,r);let h=4*n;for(let d=0,p=0;d<a.length-1;d++){const m=a[d];for(;p<m;){const _=p;let f=e[p++],I=e[p++],C=e[p++],y=e[p++];for(let x=1;x<r&&p<m;x++)f=Math.min(f,e[p++]),I=Math.min(I,e[p++]),C=Math.max(C,e[p++]),y=Math.max(y,e[p++]);s[h>>2]=_,e[h++]=f,e[h++]=I,e[h++]=C,e[h++]=y}}this._pos=h}search(e,n,o,i,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");const{_boxes:s,_levelBounds:a,_indices:A,nodeSize:c}=this,l=4*this.numItems;let u=s.length-4,g=a.length-1;const h=[],d=[];let p=!1;for(;u!==void 0;){const m=Math.min(u+4*c,a[g]),_=u>=l;if(p)this._collectContained(u,m,g,l,d,r);else for(let f=u;f<m;f+=4){const I=s[f];if(o<I)continue;const C=s[f+1];if(i<C)continue;const y=s[f+2];if(e>y)continue;const x=s[f+3];if(n>x)continue;const E=0|A[f>>2];if(_){const B=+(e<=I&&n<=C&&o>=y&&i>=x);h.push(E|B,g-1)}else(r===void 0||r(E,I,C,y,x))&&d.push(E)}g=h.pop(),u=h.pop(),u!==void 0&&(p=!(1&~u),u&=-2)}return d}_collectContained(e,n,o,i,r,s){const a=this._boxes,A=this._indices;let c=e;for(let u=o;u>0;u--)c=A[c>>2];const l=Math.min(c+(n-e)*this.nodeSize**o,i);if(s===void 0)for(;c<l;c+=4)r.push(0|A[c>>2]);else for(;c<l;c+=4){const u=0|A[c>>2];s(u,a[c],a[c+1],a[c+2],a[c+3])&&r.push(u)}}neighbors(e,n,o=1/0,i=1/0,r){if(this._pos!==this._boxes.length)throw new Error("Data not yet indexed - call index.finish().");const{_boxes:s,_levelBounds:a,_indices:A,_queue:c,nodeSize:l}=this,u=4*this.numItems,g=4*l,h=[],d=o===1;let p=i*i;for(c.push(s.length-4<<1,0);c.length;){const m=c.ids[0];if(1&m){if(c.pop(),h.push(m>>1),h.length===o)break;continue}c.pop();const _=m>>1,f=_<u,I=Math.min(_+g,hqn(_,a));for(let C=_;C<I;C+=4){const y=s[C],x=s[C+1],E=s[C+2],B=s[C+3],S=Math.max(Math.max(y-e,e-E),0),Q=Math.max(Math.max(x-n,n-B),0),w=S*S+Q*Q;if(w>p)continue;const M=0|A[C>>2];f?(r===void 0||r(M))&&(c.push(M<<1|1,w),d&&w<p&&(p=w)):c.push(M<<1,w)}}return c.clear(),h}};function hqn(t,e){let n=0,o=e.length-1;for(;n<o;){const i=n+o>>1;e[i]>t?o=i:n=i+1}return e[n]}function pqn(t,e,n,o,i){const r=t[o];t[o]=t[i],t[i]=r;const s=4*o,a=4*i,A=e[s],c=e[s+1],l=e[s+2],u=e[s+3];e[s]=e[a],e[s+1]=e[a+1],e[s+2]=e[a+2],e[s+3]=e[a+3],e[a]=A,e[a+1]=c,e[a+2]=l,e[a+3]=u;const g=n[o];n[o]=n[i],n[i]=g}function mqn(t,e){let n=t^e,o=65535^n,i=65535^(t|e),r=t&(65535^e),s=n|o>>1,a=n>>1^n,A=i^i>>1^o&r>>1,c=r^n&i>>1^r>>1;return n=s&s>>2^a&a>>2,o=s&a>>2^a&(s^a)>>2,i=A^s&A>>2^a&c>>2,r=c^a&A>>2^(s^a)&c>>2,s=n&n>>4^o&o>>4,a=n&o>>4^o&(n^o)>>4,A=i^n&i>>4^o&r>>4,c=r^o&i>>4^(n^o)&r>>4,i=A^s&A>>8^a&c>>8,r=c^a&A>>8^(s^a)&c>>8,i^=i>>1,r^=r>>1,n=t^e,o=r|65535^(n|i),n=16711935&(n|n<<8),n=252645135&(n|n<<4),n=858993459&(n|n<<2),n=1431655765&(n|n<<1),o=16711935&(o|o<<8),o=252645135&(o|o<<4),o=858993459&(o|o<<2),o=1431655765&(o|o<<1),((o<<1|n)>>>0)-2147483648}var Z4=1e-4,bz=[{facingDirection:"x-",dx:-1,dy:0,startX:-.5,startY:.5,endX:-.5,endY:-.5},{facingDirection:"x+",dx:1,dy:0,startX:.5,startY:.5,endX:.5,endY:-.5},{facingDirection:"y-",dx:0,dy:-1,startX:-.5,startY:-.5,endX:.5,endY:-.5},{facingDirection:"y+",dx:0,dy:1,startX:.5,startY:.5,endX:-.5,endY:.5}],_qn={"x-":bz.find(t=>t.facingDirection==="x-"),"x+":bz.find(t=>t.facingDirection==="x+"),"y-":bz.find(t=>t.facingDirection==="y-"),"y+":bz.find(t=>t.facingDirection==="y+")},fqn={"x-":{x:-1,y:0},"x+":{x:1,y:0},"y-":{x:0,y:-1},"y+":{x:0,y:1}},a7e=(t,e)=>{const{dir:n,amt:o}=e,i=fqn[n];return t.map(r=>({x:r.x+i.x*o,y:r.y+i.y*o}))},Sz=1e-4;function p_t(t){const e=[];for(const n of t)for(const o of bz){let i={x:n.center.x+n.width*o.startX,y:n.center.y+n.height*o.startY},r={x:n.center.x+n.width*o.endX,y:n.center.y+n.height*o.endY};i.x>r.x&&([i,r]=[r,i]),Math.abs(i.x-r.x)<Sz&&i.y>r.y&&([i,r]=[r,i]);for(const s of n.availableZ)e.push({parent:n,start:i,end:r,facingDirection:o.facingDirection,z:s})}return e}var Iqn=class extends zA{constructor(e){super(),this.input=e;const n=this.input.targetMeshNodes??this.input.allMeshNodes,o=new Set(n.map(r=>r.capacityMeshNodeId)),i=this.input.allMeshNodes.filter(r=>!o.has(r.capacityMeshNodeId));this.unprocessedEdges=p_t(n),this.allEdges=[...this.unprocessedEdges,...p_t(i)],this.edgeSpatialIndex=new X4(this.allEdges.length);for(const r of this.allEdges)this.edgeSpatialIndex.add(r.start.x,r.start.y,r.end.x,r.end.y);this.edgeSpatialIndex.finish()}input;allEdges;unprocessedEdges=[];segmentsWithAdjacentEmptySpace=[];edgeSpatialIndex;lastCandidateEdge=null;lastOverlappingEdges=null;lastUncoveredSegments=null;_step(){if(this.unprocessedEdges.length===0)return this.solved=!0,this.lastCandidateEdge=null,this.lastOverlappingEdges=null,void(this.lastUncoveredSegments=null);const e=this.unprocessedEdges.shift();this.lastCandidateEdge=e;const n=this.edgeSpatialIndex.search(e.start.x-Sz,e.start.y-Sz,e.end.x+Sz,e.end.y+Sz).map(i=>this.allEdges[i]).filter(i=>i.z===e.z);this.lastOverlappingEdges=n;const o=(function(i,r){const s=Math.abs(i.start.y-i.end.y)<Z4,a=Math.abs(i.start.x-i.end.x)<Z4;if(!s&&!a)return[];const A=s?"x":"y",c=s?"y":"x",l=i.start[c],u=i.start[A],g=i.end[A],h=Math.min(u,g),d=Math.max(u,g),p=C=>Math.max(h,Math.min(d,C)),m=[];for(const C of r){if(C===i)continue;const y=Math.abs(C.start.y-C.end.y)<Z4,x=Math.abs(C.start.x-C.end.x)<Z4;if(A==="x"&&!y||A==="y"&&!x||Math.abs(C.start[c]-l)>Z4)continue;const E=Math.min(C.start[A],C.end[A]),B=Math.max(C.start[A],C.end[A]),S=p(E),Q=p(B);Q-S>Z4&&m.push({s:S,e:Q})}if(m.length===0)return[{...i,start:{...i.start},end:{...i.end}}];m.sort((C,y)=>C.s-y.s);const _=[];for(const C of m){const y=_[_.length-1];!y||C.s>y.e+Z4?_.push({...C}):y.e=Math.max(y.e,C.e)}const f=[];let I=h;for(const C of _)if(C.s>I+Z4&&f.push({s:I,e:C.s}),I=Math.max(I,C.e),I>=d-Z4)break;return d>I+Z4&&f.push({s:I,e:d}),f.length===0?[]:f.filter(C=>C.e-C.s>Z4).map(C=>{const y=A==="x"?{x:C.s,y:l}:{x:l,y:C.s},x=A==="x"?{x:C.e,y:l}:{x:l,y:C.e};return{parent:i.parent,facingDirection:i.facingDirection,start:y,end:x,z:i.z}})})(e,n);this.lastUncoveredSegments=o,this.segmentsWithAdjacentEmptySpace.push(...o)}getOutput(){return{segmentsWithAdjacentEmptySpace:this.segmentsWithAdjacentEmptySpace}}visualize(){const e={title:"FindSegmentsWithAdjacentEmptySpace",coordinateSystem:"cartesian",rects:[],points:[],lines:[],circles:[],infiniteLines:[],polygons:[],arrows:[],texts:[]};for(const n of this.input.allMeshNodes)e.rects.push({center:n.center,width:n.width,height:n.height,stroke:"rgba(0, 0, 0, 0.1)"});for(const n of this.unprocessedEdges)e.lines.push({points:a7e([n.start,n.end],{dir:n.facingDirection,amt:-.1}),strokeColor:"rgba(0, 0, 255, 0.5)",strokeDash:"5 5"});for(const n of this.segmentsWithAdjacentEmptySpace)e.lines.push({points:[n.start,n.end],strokeColor:"rgba(0,255,0, 0.5)"});if(this.lastCandidateEdge&&e.lines.push({points:[this.lastCandidateEdge.start,this.lastCandidateEdge.end],strokeColor:"blue"}),this.lastOverlappingEdges)for(const n of this.lastOverlappingEdges)e.lines.push({points:a7e([n.start,n.end],{dir:n.facingDirection,amt:.05}),strokeColor:"red",strokeDash:"2 2"});if(this.lastUncoveredSegments)for(const n of this.lastUncoveredSegments)e.lines.push({points:a7e([n.start,n.end],{dir:n.facingDirection,amt:-.05}),strokeColor:"green",strokeDash:"2 2"});return e}};function m_t(t,e,n=0,o=t.length-1,i=Cqn){for(;o>n;){if(o-n>600){const A=o-n+1,c=e-n+1,l=Math.log(A),u=.5*Math.exp(2*l/3),g=.5*Math.sqrt(l*u*(A-u)/A)*(c-A/2<0?-1:1);m_t(t,e,Math.max(n,Math.floor(e-c*u/A+g)),Math.min(o,Math.floor(e+(A-c)*u/A+g)),i)}const r=t[e];let s=n,a=o;for(Qz(t,n,e),i(t[o],r)>0&&Qz(t,n,o);s<a;){for(Qz(t,s,a),s++,a--;i(t[s],r)<0;)s++;for(;i(t[a],r)>0;)a--}i(t[n],r)===0?Qz(t,n,a):(a++,Qz(t,a,o)),a<=e&&(n=a+1),e<=a&&(o=a-1)}}function Qz(t,e,n){const o=t[e];t[e]=t[n],t[n]=o}function Cqn(t,e){return t<e?-1:t>e?1:0}var vz=class{constructor(e=9){this._maxEntries=Math.max(4,e),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(e){let n=this.data;const o=[];if(!Pse(e,n))return o;const i=this.toBBox,r=[];for(;n;){for(let s=0;s<n.children.length;s++){const a=n.children[s],A=n.leaf?i(a):a;Pse(e,A)&&(n.leaf?o.push(a):c7e(e,A)?this._all(a,o):r.push(a))}n=r.pop()}return o}collides(e){let n=this.data;if(!Pse(e,n))return!1;const o=[];for(;n;){for(let i=0;i<n.children.length;i++){const r=n.children[i],s=n.leaf?this.toBBox(r):r;if(Pse(e,s)){if(n.leaf||c7e(e,s))return!0;o.push(r)}}n=o.pop()}return!1}load(e){if(!e||!e.length)return this;if(e.length<this._minEntries){for(let o=0;o<e.length;o++)this.insert(e[o]);return this}let n=this._build(e.slice(),0,e.length-1,0);if(this.data.children.length)if(this.data.height===n.height)this._splitRoot(this.data,n);else{if(this.data.height<n.height){const o=this.data;this.data=n,n=o}this._insert(n,this.data.height-n.height-1,!0)}else this.data=n;return this}insert(e){return e&&this._insert(e,this.data.height-1),this}clear(){return this.data=JF([]),this}remove(e,n){if(!e)return this;let o=this.data;const i=this.toBBox(e),r=[],s=[];let a,A,c;for(;o||r.length;){if(o||(o=r.pop(),A=r[r.length-1],a=s.pop(),c=!0),o.leaf){const l=yqn(e,o.children,n);if(l!==-1)return o.children.splice(l,1),r.push(o),this._condense(r),this}c||o.leaf||!c7e(o,i)?A?(a++,o=A.children[a],c=!1):o=null:(r.push(o),s.push(a),a=0,A=o,o=o.children[0])}return this}toBBox(e){return e}compareMinX(e,n){return e.minX-n.minX}compareMinY(e,n){return e.minY-n.minY}toJSON(){return this.data}fromJSON(e){return this.data=e,this}_all(e,n){const o=[];for(;e;)e.leaf?n.push(...e.children):o.push(...e.children),e=o.pop();return n}_build(e,n,o,i){const r=o-n+1;let s,a=this._maxEntries;if(r<=a)return s=JF(e.slice(n,o+1)),zF(s,this.toBBox),s;i||(i=Math.ceil(Math.log(r)/Math.log(a)),a=Math.ceil(r/Math.pow(a,i-1))),s=JF([]),s.leaf=!1,s.height=i;const A=Math.ceil(r/a),c=A*Math.ceil(Math.sqrt(a));__t(e,n,o,c,this.compareMinX);for(let l=n;l<=o;l+=c){const u=Math.min(l+c-1,o);__t(e,l,u,A,this.compareMinY);for(let g=l;g<=u;g+=A){const h=Math.min(g+A-1,u);s.children.push(this._build(e,g,h,i-1))}}return zF(s,this.toBBox),s}_chooseSubtree(e,n,o,i){for(;i.push(n),!n.leaf&&i.length-1!==o;){let r,s=1/0,a=1/0;for(let A=0;A<n.children.length;A++){const c=n.children[A],l=A7e(c),u=Bqn(e,c)-l;u<a?(a=u,s=l<s?l:s,r=c):u===a&&l<s&&(s=l,r=c)}n=r||n.children[0]}return n}_insert(e,n,o){const i=o?e:this.toBBox(e),r=[],s=this._chooseSubtree(i,this.data,n,r);for(s.children.push(e),Pz(s,i);n>=0&&r[n].children.length>this._maxEntries;)this._split(r,n),n--;this._adjustParentBBoxes(i,r,n)}_split(e,n){const o=e[n],i=o.children.length,r=this._minEntries;this._chooseSplitAxis(o,r,i);const s=this._chooseSplitIndex(o,r,i),a=JF(o.children.splice(s,o.children.length-s));a.height=o.height,a.leaf=o.leaf,zF(o,this.toBBox),zF(a,this.toBBox),n?e[n-1].children.push(a):this._splitRoot(o,a)}_splitRoot(e,n){this.data=JF([e,n]),this.data.height=e.height+1,this.data.leaf=!1,zF(this.data,this.toBBox)}_chooseSplitIndex(e,n,o){let i,r=1/0,s=1/0;for(let a=n;a<=o-n;a++){const A=wz(e,0,a,this.toBBox),c=wz(e,a,o,this.toBBox),l=bqn(A,c),u=A7e(A)+A7e(c);l<r?(r=l,i=a,s=u<s?u:s):l===r&&u<s&&(s=u,i=a)}return i||o-n}_chooseSplitAxis(e,n,o){const i=e.leaf?this.compareMinX:xqn,r=e.leaf?this.compareMinY:Eqn;this._allDistMargin(e,n,o,i)<this._allDistMargin(e,n,o,r)&&e.children.sort(i)}_allDistMargin(e,n,o,i){e.children.sort(i);const r=this.toBBox,s=wz(e,0,n,r),a=wz(e,o-n,o,r);let A=wse(s)+wse(a);for(let c=n;c<o-n;c++){const l=e.children[c];Pz(s,e.leaf?r(l):l),A+=wse(s)}for(let c=o-n-1;c>=n;c--){const l=e.children[c];Pz(a,e.leaf?r(l):l),A+=wse(a)}return A}_adjustParentBBoxes(e,n,o){for(let i=o;i>=0;i--)Pz(n[i],e)}_condense(e){for(let n,o=e.length-1;o>=0;o--)e[o].children.length===0?o>0?(n=e[o-1].children,n.splice(n.indexOf(e[o]),1)):this.clear():zF(e[o],this.toBBox)}};function yqn(t,e,n){if(!n)return e.indexOf(t);for(let o=0;o<e.length;o++)if(n(t,e[o]))return o;return-1}function zF(t,e){wz(t,0,t.children.length,e,t)}function wz(t,e,n,o,i){i||(i=JF(null)),i.minX=1/0,i.minY=1/0,i.maxX=-1/0,i.maxY=-1/0;for(let r=e;r<n;r++){const s=t.children[r];Pz(i,t.leaf?o(s):s)}return i}function Pz(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function xqn(t,e){return t.minX-e.minX}function Eqn(t,e){return t.minY-e.minY}function A7e(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function wse(t){return t.maxX-t.minX+(t.maxY-t.minY)}function Bqn(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function bqn(t,e){const n=Math.max(t.minX,e.minX),o=Math.max(t.minY,e.minY),i=Math.min(t.maxX,e.maxX),r=Math.min(t.maxY,e.maxY);return Math.max(0,i-n)*Math.max(0,r-o)}function c7e(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function Pse(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function JF(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function __t(t,e,n,o,i){const r=[e,n];for(;r.length;){if((n=r.pop())-(e=r.pop())<=o)continue;const s=e+Math.ceil((n-e)/o/2)*o;m_t(t,s,e,n,i),r.push(e,s,s,n)}}var f_t=t=>({minX:Math.min(...t.map(e=>e.x)),minY:Math.min(...t.map(e=>e.y)),maxX:Math.max(...t.map(e=>e.x)),maxY:Math.max(...t.map(e=>e.y))});function Uh(t,e,n,o){const i=Mse(t,e,n),r=Mse(t,e,o),s=Mse(n,o,t),a=Mse(n,o,e);return i!==r&&s!==a||!(i!==0||!Dse(t,n,e))||!(r!==0||!Dse(t,o,e))||!(s!==0||!Dse(n,t,o))||!(a!==0||!Dse(n,e,o))}function Mse(t,e,n){const o=(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y);return o===0?0:o>0?1:2}function Dse(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function wc(t,e,n){const o=(n.x-e.x)**2+(n.y-e.y)**2;if(o===0)return no(t,e);let i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/o;return i=Math.max(0,Math.min(1,i)),no(t,{x:e.x+i*(n.x-e.x),y:e.y+i*(n.y-e.y)})}function no(t,e){const n=t.x-e.x,o=t.y-e.y;return Math.sqrt(n*n+o*o)}function DD(t,e,n,o){const i=e.x-t.x,r=e.y-t.y,s=o.x-n.x,a=o.y-n.y,A=t.x-n.x,c=t.y-n.y,l=i*a-r*s;if(Math.abs(l)<1e-10)return null;const u=(c*s-A*a)/l,g=(i*c-r*A)/l,h=1e-9;return u>=-1e-9&&u<=1+h&&g>=-1e-9&&g<=1+h?{x:t.x+u*i,y:t.y+u*r}:null}var I_t=t=>{if("minX"in t)return t;const e=t.width/2,n=t.height/2;return{minX:t.center.x-e,minY:t.center.y-n,maxX:t.center.x+e,maxY:t.center.y+n}},l7e=t=>[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}],C_t=t=>{const e=[];for(let n=0;n<t.length;n++){const o=t[n],i=t[(n+1)%t.length];e.push([o,i])}return e},Sqn=(t,e,n)=>{const o=(t.y-e.y)*(n.x-e.x)-(t.x-e.x)*(n.y-e.y);if(Math.abs(o)>1e-9)return!1;const i=(t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y);if(i<0)return!1;const r=(n.x-e.x)**2+(n.y-e.y)**2;return r!==0&&!(i>r)},y_t=(t,e)=>t.x>=e.minX&&t.x<=e.maxX&&t.y>=e.minY&&t.y<=e.maxY,Mz=(t,e)=>{if(e.length<3)return!1;const n=C_t(e);for(const[i,r]of n)if(Sqn(t,i,r))return!0;let o=!1;for(let i=0,r=e.length-1;i<e.length;r=i++){const s=e[i].x,a=e[i].y,A=e[r].x,c=e[r].y;a>t.y!=c>t.y&&t.x<(A-s)*(t.y-a)/(c-a)+s&&(o=!o)}return o},x_t=(t,e)=>{const n=l7e(t),o=[[n[0],n[1]],[n[1],n[2]],[n[2],n[3]],[n[3],n[0]]],i=C_t(e);for(const[r,s]of i)for(const[a,A]of o)if(Uh(r,s,a,A))return!0;return!1},Nse=(t,e)=>((n,o)=>!(o.length<3)&&(!!o.some(i=>y_t(i,n))||!!l7e(n).some(i=>Mz(i,o))||x_t(n,o)))(I_t(t),e),E_t=(t,e)=>((n,o)=>!(o.length<3)&&!!l7e(n).every(i=>Mz(i,o))&&!x_t(n,o))(I_t(t),e);function Is(t){const e=t.width/2,n=t.height/2;return{minX:t.center.x-e,maxX:t.center.x+e,minY:t.center.y-n,maxY:t.center.y+n}}function V3(t,e,n){return Math.max(e,Math.min(n,t))}function M5(t,e,n,o){if(t.x===e.x&&t.y===e.y)return wc(t,n,o);if(n.x===o.x&&n.y===o.y)return wc(n,t,e);if(Uh(t,e,n,o))return 0;const i=[wc(t,n,o),wc(e,n,o),wc(n,t,e),wc(o,t,e)];return Math.min(...i)}function Dz(t,e,n){const o={x:n.minX,y:n.minY},i={x:n.maxX,y:n.minY},r={x:n.minX,y:n.maxY},s={x:n.maxX,y:n.maxY};if(Uh(t,e,o,i)||Uh(t,e,i,s)||Uh(t,e,s,r)||Uh(t,e,r,o)||t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY&&e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY)return 0;const a=[wc(o,t,e),wc(i,t,e),wc(r,t,e),wc(s,t,e)];if(t.x>=n.minX&&t.x<=n.maxX&&t.y>=n.minY&&t.y<=n.maxY||e.x>=n.minX&&e.x<=n.maxX&&e.y>=n.minY&&e.y<=n.maxY)return 0;if(t.x<n.minX||t.x>n.maxX||t.y<n.minY||t.y>n.maxY){const A=V3(t.x,n.minX,n.maxX),c=V3(t.y,n.minY,n.maxY);a.push(no(t,{x:A,y:c}))}if(e.x<n.minX||e.x>n.maxX||e.y<n.minY||e.y>n.maxY){const A=V3(e.x,n.minX,n.maxX),c=V3(e.y,n.minY,n.maxY);a.push(no(e,{x:A,y:c}))}return Math.min(...a)}function K8(t,e,n){const o=n.width/2,i=n.height/2;return Dz(t,e,{minX:n.center.x-o,maxX:n.center.x+o,minY:n.center.y-i,maxY:n.center.y+i})}function Nz(t,e,n){const o={x:n.x,y:n.y};if(t.x===e.x&&t.y===e.y)return Math.max(0,no(t,o)-n.radius);const i=e.x-t.x,r=e.y-t.y,s=o.x-t.x,a=o.y-t.y,A=i*i+r*r,c=Math.max(0,Math.min(1,(i*s+r*a)/A)),l=no({x:t.x+c*i,y:t.y+c*r},o);return Math.max(0,l-n.radius)}function z_(t,e,n){const o=n.x-e.x,i=n.y-e.y,r=o*o+i*i;if(r===0)return{x:e.x,y:e.y};let s=((t.x-e.x)*o+(t.y-e.y)*i)/r;return s=Math.max(0,Math.min(1,s)),{x:e.x+s*o,y:e.y+s*i}}var u7e=(t,e)=>{const n=e.x-t.x,o=e.y-t.y,i=Math.sqrt(n**2+o**2);return{x:n/i,y:o/i}};function o7(t,e){const n=e.width/2,o=e.height/2,i=e.center.x-n,r=e.center.x+n,s=e.center.y-o,a=e.center.y+o;return t.x>=i&&t.x<=r&&t.y>=s&&t.y<=a?0:no(t,{x:V3(t.x,i,r),y:V3(t.y,s,a)})}function V8(t,e){return{x:(t.x+e.x)/2,y:(t.y+e.y)/2}}function B_t(t,e){const n=t.x-e.x,o=t.y-e.y;return n*n+o*o}var WF=(t,e)=>!(t.maxX<e.minX||e.maxX<t.minX||t.maxY<e.minY||e.maxY<t.minY),Pg=t=>{const{center:e,width:n,height:o}=t,i=n/2,r=o/2;return{minX:e.x-i,maxX:e.x+i,minY:e.y-r,maxY:e.y+r}},i7=1e-4,Qqn=class extends zA{constructor(e){super(),this.input=e,this.unprocessedSegments=[...this.input.segmentsWithAdjacentEmptySpace],this.rectSpatialIndex=new vz,this.rectSpatialIndex.load(this.input.boardVoid?.boardVoidRects.map((n,o)=>({capacityMeshNodeId:`void-rect-${o}`,center:{x:n.x+n.width/2,y:n.y+n.height/2},width:n.width,height:n.height,availableZ:Array.from({length:this.input.boardVoid?.layerCount||0},(i,r)=>r),layer:"void",minX:n.x,minY:n.y,maxX:n.x+n.width,maxY:n.y+n.height}))||[]),this.rectSpatialIndex.load(this.input.inputMeshNodes.map(n=>({...n,minX:n.center.x-n.width/2,minY:n.center.y-n.height/2,maxX:n.center.x+n.width/2,maxY:n.center.y+n.height/2})))}input;unprocessedSegments=[];expandedSegments=[];lastSegment=null;lastSearchBounds=null;lastCollidingNodes=null;lastSearchCorner1=null;lastSearchCorner2=null;lastExpandedSegment=null;rectSpatialIndex;_step(){if(this.unprocessedSegments.length===0)return void(this.solved=!0);const e=this.unprocessedSegments.shift();this.lastSegment=e;const{dx:n,dy:o}=_qn[e.facingDirection],i=e.end.x-e.start.x,r=e.end.y-e.start.y,s=Math.sqrt(i**2+r**2),a=i/s,A=r/s;let c=null,l=1;const u={x:e.start.x+n*i7+a*i7*10,y:e.start.y+o*i7+A*i7*10},g={x:e.end.x+n*i7-a*i7*10,y:e.end.y+o*i7-A*i7*10};for(this.lastSearchCorner1=u,this.lastSearchCorner2=g;(!c||c.length===0)&&l<1e3;){const C=f_t([u,g,{x:u.x+n*l,y:u.y+o*l},{x:g.x+n*l,y:g.y+o*l}]);this.lastSearchBounds=C,c=this.rectSpatialIndex.search(C).filter(y=>y.availableZ.includes(e.z)).filter(y=>y.capacityMeshNodeId!==e.parent.capacityMeshNodeId),l*=4}if(!c||c.length===0)return;this.lastCollidingNodes=c;let h=1/0;for(const C of c){const y=K8(e.start,e.end,C);y<h&&(h=y)}const d=h,p=f_t([e.start,e.end,{x:e.start.x+n*d,y:e.start.y+o*d},{x:e.end.x+n*d,y:e.end.y+o*d}]),m={x:(p.minX+p.maxX)/2,y:(p.minY+p.maxY)/2},_=p.maxX-p.minX,f=p.maxY-p.minY,I={segment:e,newNode:{capacityMeshNodeId:`new-${e.parent.capacityMeshNodeId}-${this.expandedSegments.length}`,center:m,width:_,height:f,availableZ:[e.z],layer:e.parent.layer}};this.lastExpandedSegment=I,_<i7||f<i7||(this.expandedSegments.push(I),this.rectSpatialIndex.insert({...I.newNode,...p}))}getOutput(){return{expandedSegments:this.expandedSegments}}visualize(){const e={title:"ExpandEdgesToEmptySpace",coordinateSystem:"cartesian",rects:[],points:[],lines:[],circles:[],infiniteLines:[],polygons:[],arrows:[],texts:[]};for(const n of this.input.inputMeshNodes)e.rects.push({center:n.center,width:n.width,height:n.height,stroke:"rgba(0, 0, 0, 0.1)",layer:`z${n.availableZ.join(",")}`,label:[`node ${n.capacityMeshNodeId}`,`z:${n.availableZ.join(",")}`].join(`
`)});for(const{newNode:n}of this.expandedSegments)e.rects.push({center:n.center,width:n.width,height:n.height,fill:"green",label:`expandedSegment (z=${n.availableZ.join(",")})`,layer:`z${n.availableZ.join(",")}`});if(this.lastSegment&&e.lines.push({points:[this.lastSegment.start,this.lastSegment.end],strokeColor:"rgba(0, 0, 255, 0.5)"}),this.lastSearchBounds&&e.rects.push({center:{x:(this.lastSearchBounds.minX+this.lastSearchBounds.maxX)/2,y:(this.lastSearchBounds.minY+this.lastSearchBounds.maxY)/2},width:this.lastSearchBounds.maxX-this.lastSearchBounds.minX,height:this.lastSearchBounds.maxY-this.lastSearchBounds.minY,fill:"rgba(0, 0, 255, 0.25)"}),this.lastSearchCorner1&&this.lastSearchCorner2&&(e.points.push({x:this.lastSearchCorner1.x,y:this.lastSearchCorner1.y,color:"rgba(0, 0, 255, 0.5)",label:["searchCorner1",`z=${this.lastSegment?.z}`].join(`
`)}),e.points.push({x:this.lastSearchCorner2.x,y:this.lastSearchCorner2.y,color:"rgba(0, 0, 255, 0.5)",label:["searchCorner2",`z=${this.lastSegment?.z}`].join(`
`)})),this.lastExpandedSegment&&e.rects.push({center:this.lastExpandedSegment.newNode.center,width:this.lastExpandedSegment.newNode.width,height:this.lastExpandedSegment.newNode.height,fill:"purple",label:`expandedSegment (z=${this.lastExpandedSegment.segment.z})`}),this.lastCollidingNodes)for(const n of this.lastCollidingNodes)e.rects.push({center:n.center,width:n.width,height:n.height,fill:"rgba(255, 0, 0, 0.5)"});return e}},vqn=class extends n7{findSegmentsWithAdjacentEmptySpaceSolver;expandEdgesToEmptySpaceSolver;outputNodes=[];passExpandedCounts=[];currentPassNodes=[];currentTargetNodes=[];currentPassIndex=0;expandedNodeIds=new Set;maxGapFillPasses=1;pipelineDef=[eh("findSegmentsWithAdjacentEmptySpaceSolver",Iqn,e=>[{allMeshNodes:e.currentPassNodes,targetMeshNodes:e.currentTargetNodes}],{onSolved:()=>{}}),eh("expandEdgesToEmptySpaceSolver",Qqn,e=>[{inputMeshNodes:e.currentPassNodes,segmentsWithAdjacentEmptySpace:e.findSegmentsWithAdjacentEmptySpaceSolver.getOutput().segmentsWithAdjacentEmptySpace,boardVoid:e.inputProblem.boardVoid}],{onSolved:e=>{e.completePass()}})];_setup(){this.outputNodes=[...this.inputProblem.meshNodes],this.currentPassNodes=[...this.inputProblem.meshNodes],this.currentTargetNodes=[...this.inputProblem.meshNodes],this.passExpandedCounts=[],this.currentPassIndex=0,this.expandedNodeIds.clear();const e=this.inputProblem.maxGapFillPasses;this.maxGapFillPasses=Number.isFinite(e)?Math.max(1,Math.floor(e)):1}completePass(){const e=(this.expandEdgesToEmptySpaceSolver?.getOutput().expandedSegments??[]).map(n=>n.newNode);for(const n of e)this.expandedNodeIds.add(n.capacityMeshNodeId);this.passExpandedCounts.push(e.length),this.currentPassNodes=[...this.currentPassNodes,...e],this.currentTargetNodes=e,this.outputNodes=this.currentPassNodes,e.length===0||this.currentPassIndex+1>=this.maxGapFillPasses||(this.currentPassIndex+=1,this.currentPipelineStageIndex=-1)}getOutput(){return{outputNodes:this.outputNodes.length?this.outputNodes:this.inputProblem.meshNodes}}initialVisualize(){const e={title:"GapFillSolverPipeline - Initial",coordinateSystem:"cartesian",rects:[],points:[],lines:[],circles:[],infiniteLines:[],polygons:[],arrows:[],texts:[]};for(const n of this.inputProblem.meshNodes)e.rects.push({center:n.center,width:n.width,height:n.height,stroke:"rgba(0, 0, 0, 0.3)",fill:"rgba(100, 100, 100, 0.1)",layer:`z${n.availableZ.join(",")}`,label:[`node ${n.capacityMeshNodeId}`,`z:${n.availableZ.join(",")}`].join(`
`)});return e}finalVisualize(){const e={title:"GapFillSolverPipeline - Final",coordinateSystem:"cartesian",rects:[],points:[],lines:[],circles:[],infiniteLines:[],polygons:[],arrows:[],texts:[]},{outputNodes:n}=this.getOutput();for(const o of n){const i=this.expandedNodeIds.has(o.capacityMeshNodeId);e.rects.push({center:o.center,width:o.width,height:o.height,stroke:i?"rgba(0, 128, 0, 0.8)":"rgba(0, 0, 0, 0.3)",fill:i?"rgba(0, 200, 0, 0.3)":"rgba(100, 100, 100, 0.1)",layer:`z${o.availableZ.join(",")}`,label:[`${i?"[expanded] ":""}node ${o.capacityMeshNodeId}`,`z:${o.availableZ.join(",")}`].join(`
`)})}return e}};function b_t(t){const e=t.toLowerCase();if(e==="top")return-1e6;if(e==="bottom")return 1e6;const n=/^inner(\d+)$/i.exec(e);return n?parseInt(n[1],10)||0:100+e.charCodeAt(0)}function g7e(t){const e=(function(c){return Array.from(new Set(c)).sort((l,u)=>{const g=b_t(l),h=b_t(u);return g!==h?g-h:l.localeCompare(u)})})((t.obstacles??[]).flatMap(c=>c.layers??[])),n=Math.max(1,t.layerCount||e.length||1),o=Array.from({length:n},(c,l)=>l===0?"top":l===n-1?"bottom":`inner${l}`),i=[],r=new Set,s=c=>{const l=c.toLowerCase();r.has(l)||(r.add(l),i.push(c))};o.forEach(s),e.forEach(s);const a=i.slice(0,n),A=new Map;return a.forEach((c,l)=>A.set(c.toLowerCase(),l)),i.slice(a.length).forEach(c=>{const l=c.toLowerCase();A.set(l,(u=>{if(a.length<=1||u==="top")return 0;if(u==="bottom")return a.length-1;const g=/^inner(\d+)$/i.exec(u);if(g){if(a.length<=2)return a.length-1;const h=parseInt(g[1],10),d=a.length-2;return Math.min(d,Math.max(1,Number.isFinite(h)?h:1))}return 0})(l))}),{layerNames:a,zIndexByName:A}}function d7e(t,e){if(t.zLayers?.length)return Array.from(new Set(t.zLayers)).sort((o,i)=>o-i);const n=(t.layers??[]).map(o=>e.get(o.toLowerCase())).filter(o=>typeof o=="number");return Array.from(new Set(n)).sort((o,i)=>o-i)}function h7e(t){const e=t.width,n=t.height;return typeof e!="number"||typeof n!="number"?null:{x:t.center.x-e/2,y:t.center.y-n/2,width:e,height:n}}var Rse=t=>{const e=[{fill:"#dbeafe",stroke:"#3b82f6"},{fill:"#fef3c7",stroke:"#f59e0b"},{fill:"#d1fae5",stroke:"#10b981"},{fill:"#e9d5ff",stroke:"#a855f7"},{fill:"#fed7aa",stroke:"#f97316"},{fill:"#fecaca",stroke:"#ef4444"}];return e[Math.min(...t)%e.length]},Fi=1e-9,S_t=(t,e)=>t>e+Fi,Q_t=(t,e)=>t>e-Fi,v_t=(t,e)=>t<e-Fi,w_t=(t,e)=>t<e+Fi;function Rz(t,e){return!(t.x+t.width<=e.x+Fi||e.x+e.width<=t.x+Fi||t.y+t.height<=e.y+Fi||e.y+e.height<=t.y+Fi)}function Tse(t,e){const n=e.x,o=e.x+e.width,i=e.y,r=e.y+e.height;if(t.x>=n&&t.x<=o&&t.y>=i&&t.y<=r)return Math.min(t.x-n,o-t.x,t.y-i,r-t.y);const s=t.x<n?n-t.x:t.x>o?t.x-o:0,a=t.y<i?i-t.y:t.y>r?t.y-r:0;return s===0?a:a===0?s:Math.hypot(s,a)}function P_t(t,e){const n=Math.max(t[0],e[0]),o=Math.min(t[1],e[1]);return o>n+Fi?[n,o]:null}function M_t(t,e){if(!Rz(t,e))return[t];const n=P_t([t.x,t.x+t.width],[e.x,e.x+e.width]),o=P_t([t.y,t.y+t.height],[e.y,e.y+e.height]);if(!n||!o)return[t];const[i,r]=n,[s,a]=o,A=[];i>t.x+Fi&&A.push({x:t.x,y:t.y,width:i-t.x,height:t.height}),t.x+t.width>r+Fi&&A.push({x:r,y:t.y,width:t.x+t.width-r,height:t.height});const c=Math.max(0,r-i);return c>Fi&&s>t.y+Fi&&A.push({x:i,y:t.y,width:c,height:s-t.y}),c>Fi&&t.y+t.height>a+Fi&&A.push({x:i,y:a,width:c,height:t.y+t.height-a}),A.filter(l=>l.width>Fi&&l.height>Fi)}var p7e=(t,e)=>!e||e<=0?t:{x:t.x-e,y:t.y-e,width:t.width+2*e,height:t.height+2*e},jF=t=>({x:t.center.x-t.width/2,y:t.center.y-t.height/2,width:t.width,height:t.height}),D_t=t=>t.width*t.height,m7e=t=>({...t,center:{...t.center},availableZ:[...t.availableZ]}),wqn=(t,e,n)=>({...t,capacityMeshNodeId:n,center:{x:e.x+e.width/2,y:e.y+e.height/2},width:e.width,height:e.height,availableZ:[...t.availableZ],layer:`z${t.availableZ.join(",")}`}),_7e=t=>!t._containsObstacle&&!t._containsTarget,N_t=(t,e)=>t.availableZ.length===1&&t.availableZ[0]===e,Pqn=(t,e)=>Math.abs(t.x-e.x)<=Fi&&Math.abs(t.y-e.y)<=Fi&&Math.abs(t.width-e.width)<=Fi&&Math.abs(t.height-e.height)<=Fi,R_t=(t,e)=>{let n=[t];for(const o of e){if(n.length===0)return n;const i=[];for(const r of n)i.push(...M_t(r,o));n=i}return n},T_t=(t,e)=>R_t(t,e).length===0,Mqn=class extends zA{constructor(e){super(),this.input=e}input;outputNodes=[];promotedNodeIds=new Set;residualNodeIds=new Set;_setup(){this.outputNodes=this.input.meshNodes.map(m7e),this.promotedNodeIds.clear(),this.residualNodeIds.clear()}_step(){this.outputNodes=this.processOuterLayerContainmentMerges(),this.solved=!0}processOuterLayerContainmentMerges(){const e=this.input.simpleRouteJson,n=Math.max(1,e.layerCount||1);if(n<3)return this.input.meshNodes.map(m7e);const o=n-1,i=Math.max(e.minViaDiameter??0,e.minTraceWidth||0),r=this.input.meshNodes.map(m7e),s=this.buildObstaclesByLayer(n),a=r.filter(p=>_7e(p)&&(N_t(p,0)||N_t(p,o))),A=r.filter(p=>!a.includes(p)),c=new Map;c.set(0,r.filter(p=>_7e(p)&&p.availableZ.includes(0)).map(jF)),c.set(o,r.filter(p=>_7e(p)&&p.availableZ.includes(o)).map(jF));const l=[],u=[],g=a.filter(p=>p.width+Fi>=i&&p.height+Fi>=i).sort((p,m)=>D_t(jF(m))-D_t(jF(p)));for(const p of g){const m=p.availableZ[0],_=m===0?o:0,f=jF(p),I=c.get(_)??[];this.isTransitCompatibleAcrossIntermediateLayers({rect:f,fromZ:m,toZ:_,obstaclesByLayer:s})&&T_t(f,I)&&(l.push({...p,availableZ:[0,o],layer:`z0,${o}`}),u.push(f),this.promotedNodeIds.add(p.capacityMeshNodeId))}let h=0;const d=[];for(const p of a){if(this.promotedNodeIds.has(p.capacityMeshNodeId))continue;const m=jF(p),_=R_t(m,u);if(_.length===1&&Pqn(_[0],m))d.push(p);else for(const f of _){const I=wqn(p,f,`${p.capacityMeshNodeId}-outer-merge-${h++}`);d.push(I),this.residualNodeIds.add(I.capacityMeshNodeId)}}return[...A,...l,...d]}buildObstaclesByLayer(e){const n=Array.from({length:e},()=>[]);for(const o of this.input.simpleRouteJson.obstacles??[]){const i=h7e(o);if(!i)continue;const r=p7e(i,this.input.obstacleClearance??0),s=d7e(o,this.input.zIndexByName);for(const a of s)a<0||a>=e||n[a].push({obstacle:o,rect:r})}return n}isTransitCompatibleAcrossIntermediateLayers(e){const{rect:n,fromZ:o,toZ:i,obstaclesByLayer:r}=e,s=Math.min(o,i),a=Math.max(o,i);if(a-s<2)return!1;for(let A=s+1;A<a;A++){const c=(r[A]??[]).filter(u=>Rz(u.rect,n));if(c.length===0||c.some(u=>!u.obstacle.isCopperPour))return!1;const l=c.filter(u=>u.obstacle.isCopperPour).map(u=>u.rect);if(!T_t(n,l))return!1}return!0}getOutput(){return{outputNodes:this.outputNodes}}visualize(){return{title:"OuterLayerContainmentMergeSolver",coordinateSystem:"cartesian",rects:this.outputNodes.map(e=>{const n=Rse(e.availableZ),o=this.promotedNodeIds.has(e.capacityMeshNodeId),i=this.residualNodeIds.has(e.capacityMeshNodeId);return{center:e.center,width:e.width,height:e.height,stroke:o?"rgba(22, 163, 74, 0.95)":i?"rgba(37, 99, 235, 0.95)":n.stroke,fill:e._containsObstacle?"rgba(239, 68, 68, 0.35)":o?"rgba(34, 197, 94, 0.28)":i?"rgba(59, 130, 246, 0.18)":n.fill,layer:`z${e.availableZ.join(",")}`,label:[`node ${e.capacityMeshNodeId}`,`z:${e.availableZ.join(",")}`].join(`
`)}}),points:[],lines:[],texts:[]}}},kse=1e-9,Dqn=t=>Math.abs(t.rect.x+t.rect.width/2-t.startX)<kse&&Math.abs(t.rect.y+t.rect.height/2-t.startY)<kse&&Math.abs(t.rect.width-t.initialW)<kse&&Math.abs(t.rect.height-t.initialH)<kse,Nqn=({rect:t,bounds:e})=>({x:t.x,y:t.y,width:e.x+e.width-t.x,height:t.height}),Rqn=({rect:t,bounds:e})=>({x:t.x,y:t.y,width:t.width,height:e.y+e.height-t.y}),Tqn=({rect:t,bounds:e})=>({x:e.x,y:t.y,width:t.x-e.x,height:t.height}),kqn=({rect:t,bounds:e})=>({x:t.x,y:e.y,width:t.width,height:t.y-e.y}),Fse=(t,e=1e-6)=>Math.round(t/e)*e,Fqn=t=>({x:Fse(t.x),y:Fse(t.y),width:Fse(t.width),height:Fse(t.height)});function Lqn(t){const{r:e,bounds:n,blockers:o,maxAspect:i}=t;let r=n.x+n.width-e.x;for(const a of o)if(e.y+e.height>a.y+Fi&&a.y+a.height>e.y+Fi){if(Q_t(a.x,e.x+e.width))r=Math.min(r,a.x-e.x);else if(a.x+a.width>e.x+e.width-Fi&&a.x<e.x+e.width+Fi)return 0}let s=Math.max(0,r-e.width);if(s<=0)return 0;if(i!=null){const a=e.width,A=e.height;a>=A&&(s=Math.min(s,i*A-a))}return Math.max(0,s)}function Hqn(t){const{r:e,bounds:n,blockers:o,maxAspect:i}=t;let r=n.y+n.height-e.y;for(const a of o)if(e.x+e.width>a.x+Fi&&a.x+a.width>e.x+Fi){if(Q_t(a.y,e.y+e.height))r=Math.min(r,a.y-e.y);else if(a.y+a.height>e.y+e.height-Fi&&a.y<e.y+e.height+Fi)return 0}let s=Math.max(0,r-e.height);if(s<=0)return 0;if(i!=null){const a=e.width,A=e.height;A>=a&&(s=Math.min(s,i*a-A))}return Math.max(0,s)}function Oqn(t){const{r:e,bounds:n,blockers:o,maxAspect:i}=t;let r=n.x;for(const a of o)if(e.y+e.height>a.y+Fi&&a.y+a.height>e.y+Fi){if(w_t(a.x+a.width,e.x))r=Math.max(r,a.x+a.width);else if(a.x<e.x+Fi&&a.x+a.width>e.x-Fi)return 0}let s=Math.max(0,e.x-r);if(s<=0)return 0;if(i!=null){const a=e.width,A=e.height;a>=A&&(s=Math.min(s,i*A-a))}return Math.max(0,s)}function Gqn(t){const{r:e,bounds:n,blockers:o,maxAspect:i}=t;let r=n.y;for(const a of o)if(e.x+e.width>a.x+Fi&&a.x+a.width>e.x+Fi){if(w_t(a.y+a.height,e.y))r=Math.max(r,a.y+a.height);else if(a.y<e.y+Fi&&a.y+a.height>e.y-Fi)return 0}let s=Math.max(0,e.y-r);if(s<=0)return 0;if(i!=null){const a=e.width,A=e.height;A>=a&&(s=Math.min(s,i*a-A))}return Math.max(0,s)}var k_t=t=>{const{rect:e,seen:n,blockers:o}=t;n.has(e)||(n.add(e),o.push(e))};function F_t(t){const{startX:e,startY:n,gridSize:o,bounds:i,obsticalIndexByLayer:r,placedIndexByLayer:s,initialCellRatio:a,maxAspectRatio:A,minReq:c}=t,l=Math.max(1e-9,o*a),u=Math.max(l,c.width),g=Math.max(l,c.height),h=[],d=new Set,p=s.length,m=C=>{const y=(x=>{const{bounds:E,rect:B}=x,S=Math.max(E.x,B.x),Q=Math.max(E.y,B.y),w=Math.min(E.x+E.width,B.x+B.width),M=Math.min(E.y+E.height,B.y+B.height);return w<=S+Fi||M<=Q+Fi?null:{minX:S,minY:Q,maxX:w,maxY:M}})({bounds:i,rect:C});if(y)for(const x of t.zLayers){const E=r[x];if(E)for(const S of E.search(y))k_t({rect:S,seen:d,blockers:h});const B=s[x];if(B)for(const S of B.search(y))S.zLayers.length>=p&&(Dqn({rect:S,startX:e,startY:n,initialW:u,initialH:g})||k_t({rect:S,seen:d,blockers:h}))}},_=[{ox:0,oy:0},{ox:-u,oy:0},{ox:0,oy:-g},{ox:-u,oy:-g},{ox:-u/2,oy:-g/2}];let f=null,I=0;e:for(const C of _){let y={x:e+C.ox,y:n+C.oy,width:u,height:g};if(m(y),v_t(y.x,i.x)||v_t(y.y,i.y)||S_t(y.x+y.width,i.x+i.width)||S_t(y.y+y.height,i.y+i.height))continue;for(const Q of h)if(Rz(y,Q))continue e;const x=1e-6,E=1e3;let B=!0,S=0;for(;B&&S<E;){S++,B=!1;const Q={bounds:i,blockers:h,maxAspect:A};m(Nqn({rect:y,bounds:i}));const w=Lqn({...Q,r:y});w>x&&(y={...y,width:y.width+w},m(y),B=!0),m(Rqn({rect:y,bounds:i}));const M=Hqn({...Q,r:y});M>x&&(y={...y,height:y.height+M},m(y),B=!0),m(Tqn({rect:y,bounds:i}));const k=Oqn({...Q,r:y});k>x&&(y={x:y.x-k,y:y.y,width:y.width+k,height:y.height},m(y),B=!0),m(kqn({rect:y,bounds:i}));const R=Gqn({...Q,r:y});R>x&&(y={x:y.x,y:y.y-R,width:y.width,height:y.height+R},m(y),B=!0)}if(y.width+Fi>=c.width&&y.height+Fi>=c.height){const Q=y.width*y.height;Q>I&&(f=Fqn(y),I=Q)}}return f}function Yqn(t){const e=Math.max(t.width,t.height);return[e/8,e/16,e/32]}function f7e(t){const e={minX:t.point.x,minY:t.point.y,maxX:t.point.x,maxY:t.point.y};for(let n=0;n<t.layerCount;n++){const o=t.obstacleIndexByLayer[n],i=!!o&&o.collides(e),r=t.placedIndexByLayer[n],s=!!r&&r.collides(e);if(!i&&!s)return!1}return!0}function I7e(t){const{x:e,y:n,z:o,layerCount:i,minSpan:r,maxSpan:s,obstacleIndexByLayer:a,additionalBlockersByLayer:A}=t,c=h=>{const d={minX:e,minY:n,maxX:e,maxY:n},p=a[h];return p&&p.collides(d)?!1:!(A?.[h]??[]).some(m=>{return(f={x:e,y:n}).x>=(_=m).x-Fi&&f.x<=_.x+_.width+Fi&&f.y>=_.y-Fi&&f.y<=_.y+_.height+Fi;var _,f})};let l=o,u=o;for(;l-1>=0&&c(l-1);)l--;for(;u+1<i&&c(u+1);)u++;if(typeof s=="number"){const h=((d,p,m)=>Math.max(p,Math.min(m,d)))(s,1,i);for(;u-l+1>h;)o-l>u-o?l++:u--}const g=[];for(let h=l;h<=u;h++)g.push(h);return g.length>=r?g:[]}var Uqn=(t,e=1e-6)=>Math.round(t/e)*e,eB=(t,e=1e-6)=>Math.round(t/e)*e,Kqn=t=>"minX"in t?{x:t.minX,y:t.minY,width:t.maxX-t.minX,height:t.maxY-t.minY}:t;function VQ(t){const{lineStart:e,lineEnd:n,coveringIntervals:o,minSegmentLength:i}=t,r=eB(e),s=eB(n),a=o.map(g=>{const h=eB(g.start),d=eB(g.end);return{start:Math.min(h,d),end:Math.max(h,d)}}).filter(g=>g.end>g.start+Fi);if(a.length===0)return[{start:r,end:s,center:(r+s)/2}];const A=[...a].sort((g,h)=>g.start-h.start),c=[];let l={...A[0]};for(let g=1;g<A.length;g++){const h=A[g];h.start<=l.end+Fi?l.end=Math.max(l.end,h.end):(c.push(l),l={...h})}c.push(l);const u=[];if(c[0].start>r+Fi){const g=r,h=c[0].start;h-g>=i&&u.push({start:g,end:h,center:(g+h)/2})}for(let g=0;g<c.length-1;g++){const h=c[g].end,d=c[g+1].start;d-h>=i&&u.push({start:h,end:d,center:(h+d)/2})}if(c[c.length-1].end<s-Fi){const g=c[c.length-1].end,h=s;h-g>=i&&u.push({start:g,end:h,center:(g+h)/2})}return u}function Vqn(t){const{bounds:e,minSize:n,layerCount:o,obstacleIndexByLayer:i,placedIndexByLayer:r,hardPlacedByLayer:s}=t,a=[],A=Math.max(.15*n,3*Fi),c=new Set,l=Array.from({length:o},(g,h)=>[...i[h]?.all()??[],...s[h]??[]].map(Kqn));function u(g){const h=eB(g.x),d=eB(g.y),{z:p}=g,m=h,_=d;if(m<e.x+Fi||_<e.y+Fi||m>e.x+e.width-Fi||_>e.y+e.height-Fi||(function(E){return f7e({layerCount:o,obstacleIndexByLayer:i,placedIndexByLayer:r,point:E})})({x:m,y:_}))return;const f=l[p]??[];let I=Tse({x:m,y:_},e);for(const E of f)I=Math.min(I,Tse({x:m,y:_},E));const C=eB(I),y=(E=>`${E.z}|${E.x.toFixed(6)}|${E.y.toFixed(6)}`)({x:m,y:_,z:p});if(c.has(y))return;c.add(y);const x=I7e({x:m,y:_,z:p,layerCount:o,minSpan:1,maxSpan:void 0,obstacleIndexByLayer:i,additionalBlockersByLayer:s});a.push({x:m,y:_,z:p,distance:C,zSpanLen:x.length,isEdgeSeed:!0})}for(let g=0;g<o;g++){const h=(l[g]??[]).map(w=>({x:eB(w.x),y:eB(w.y),width:eB(w.width),height:eB(w.height)})),d=[{x:e.x+A,y:e.y+A},{x:e.x+e.width-A,y:e.y+A},{x:e.x+A,y:e.y+e.height-A},{x:e.x+e.width-A,y:e.y+e.height-A}];for(const w of d)u({x:w.x,y:w.y,z:g});const p=e.y+A,m=h.filter(w=>w.y<=p&&w.y+w.height>=p).map(w=>({start:Math.max(e.x,w.x),end:Math.min(e.x+e.width,w.x+w.width)})),_=VQ({lineStart:e.x+A,lineEnd:e.x+e.width-A,coveringIntervals:m,minSegmentLength:.5*n});for(const w of _){const M=w.end-w.start;M>=n&&(u({x:w.center,y:p,z:g}),M>1.5*n&&(u({x:w.start+.4*n,y:p,z:g}),u({x:w.end-.4*n,y:p,z:g})))}const f=e.y+e.height-A,I=h.filter(w=>w.y<=f&&w.y+w.height>=f).map(w=>({start:Math.max(e.x,w.x),end:Math.min(e.x+e.width,w.x+w.width)})),C=VQ({lineStart:e.x+A,lineEnd:e.x+e.width-A,coveringIntervals:I,minSegmentLength:.5*n});for(const w of C){const M=w.end-w.start;M>=n&&(u({x:w.center,y:f,z:g}),M>1.5*n&&(u({x:w.start+.4*n,y:f,z:g}),u({x:w.end-.4*n,y:f,z:g})))}const y=e.x+A,x=h.filter(w=>w.x<=y&&w.x+w.width>=y).map(w=>({start:Math.max(e.y,w.y),end:Math.min(e.y+e.height,w.y+w.height)})),E=VQ({lineStart:e.y+A,lineEnd:e.y+e.height-A,coveringIntervals:x,minSegmentLength:.5*n});for(const w of E){const M=w.end-w.start;M>=n&&(u({x:y,y:w.center,z:g}),M>1.5*n&&(u({x:y,y:w.start+.4*n,z:g}),u({x:y,y:w.end-.4*n,z:g})))}const B=e.x+e.width-A,S=h.filter(w=>w.x<=B&&w.x+w.width>=B).map(w=>({start:Math.max(e.y,w.y),end:Math.min(e.y+e.height,w.y+w.height)})),Q=VQ({lineStart:e.y+A,lineEnd:e.y+e.height-A,coveringIntervals:S,minSegmentLength:.5*n});for(const w of Q){const M=w.end-w.start;M>=n&&(u({x:B,y:w.center,z:g}),M>1.5*n&&(u({x:B,y:w.start+.4*n,z:g}),u({x:B,y:w.end-.4*n,z:g})))}for(const w of h){const M=w.x-A;if(M>e.x+Fi&&M<e.x+e.width-Fi){const O=h.filter(Y=>Y!==w&&Y.x<=M&&Y.x+Y.width>=M).map(Y=>({start:Math.max(w.y,Y.y),end:Math.min(w.y+w.height,Y.y+Y.height)})),U=VQ({lineStart:w.y,lineEnd:w.y+w.height,coveringIntervals:O,minSegmentLength:.5*n});for(const Y of U)u({x:M,y:Y.center,z:g})}const k=w.x+w.width+A;if(k>e.x+Fi&&k<e.x+e.width-Fi){const O=h.filter(Y=>Y!==w&&Y.x<=k&&Y.x+Y.width>=k).map(Y=>({start:Math.max(w.y,Y.y),end:Math.min(w.y+w.height,Y.y+Y.height)})),U=VQ({lineStart:w.y,lineEnd:w.y+w.height,coveringIntervals:O,minSegmentLength:.5*n});for(const Y of U)u({x:k,y:Y.center,z:g})}const R=w.y-A;if(R>e.y+Fi&&R<e.y+e.height-Fi){const O=h.filter(Y=>Y!==w&&Y.y<=R&&Y.y+Y.height>=R).map(Y=>({start:Math.max(w.x,Y.x),end:Math.min(w.x+w.width,Y.x+Y.width)})),U=VQ({lineStart:w.x,lineEnd:w.x+w.width,coveringIntervals:O,minSegmentLength:.5*n});for(const Y of U)u({x:Y.center,y:R,z:g})}const F=w.y+w.height+A;if(F>e.y+Fi&&F<e.y+e.height-Fi){const O=h.filter(Y=>Y!==w&&Y.y<=F&&Y.y+Y.height>=F).map(Y=>({start:Math.max(w.x,Y.x),end:Math.min(w.x+w.width,Y.x+Y.width)})),U=VQ({lineStart:w.x,lineEnd:w.x+w.width,coveringIntervals:O,minSegmentLength:.5*n});for(const Y of U)u({x:Y.center,y:F,z:g})}}}return a.sort((g,h)=>h.zSpanLen-g.zSpanLen||h.distance-g.distance||g.z-h.z||g.x-h.x||g.y-h.y),a}function zqn(t){const e=Array.from({length:t.layerCount},()=>[]);for(const n of t.placed)if(n.zLayers.length>=t.layerCount)for(const o of n.zLayers)e[o].push(n.rect);return e}var $F=(t,e)=>({...t,minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height,zLayers:e.zLayers});function L_t(t,e){const n=t.placed[e],{rect:o,zLayers:i}=n,r=t.layerCount,s=[],a=[];for(let c=0;c<t.placed.length;c++){if(c===e)continue;const l=t.placed[c];if(l.zLayers.length>=r)continue;const u=l.zLayers.filter(m=>i.includes(m));if(u.length===0||!Rz(l.rect,o))continue;const g=M_t(l.rect,o);s.push(c);const h=l.zLayers.filter(m=>!i.includes(m));h.length>0&&a.push({rect:l.rect,zLayers:h});const d=Math.min(t.options.minSingle.width,t.options.minMulti.width),p=Math.min(t.options.minSingle.height,t.options.minMulti.height);for(const m of g)m.width+Fi>=d&&m.height+Fi>=p&&a.push({rect:m,zLayers:u.slice()})}const A=(c,l)=>c.minX===l.minX&&c.minY===l.minY&&c.maxX===l.maxX&&c.maxY===l.maxY;s.sort((c,l)=>l-c).forEach(c=>{const l=t.placed.splice(c,1)[0];if(t.placedIndexByLayer)for(const u of l.zLayers){const g=t.placedIndexByLayer[u];g&&g.remove($F(l.rect,{zLayers:l.zLayers}),A)}});for(const c of a){t.placed.push(c);for(const l of c.zLayers)if(t.placedIndexByLayer){const u=t.placedIndexByLayer[l];u&&u.insert($F(c.rect,{zLayers:c.zLayers.slice()}))}}}var Jqn=class extends zA{constructor(e){super(),this.input=e}input;srj;layerNames;layerCount;bounds;options;boardVoidRects;gridIndex;candidates;placed;placedIndexByLayer;hardPlacedByLayer;expansionIndex;edgeAnalysisDone;totalSeedsThisGrid;consumedSeedsThisGrid;_setup(){const e=this.input.simpleRouteJson,n=this.input.gridOptions??{},o=this.input.layerNames&&this.input.zIndexByName,{layerNames:i}=o?{layerNames:this.input.layerNames,zIndexByName:this.input.zIndexByName}:g7e({obstacles:e.obstacles,layerCount:e.layerCount}),r=Math.max(1,i.length,e.layerCount||1),s={x:e.bounds.minX,y:e.bounds.minY,width:e.bounds.maxX-e.bounds.minX,height:e.bounds.maxY-e.bounds.minY},a=Math.max(.01,e.minTraceWidth||.15),A={gridSizes:[],initialCellRatio:.2,maxAspectRatio:3,minSingle:{width:2*a,height:2*a},minMulti:{width:4*a,height:4*a,minLayers:Math.min(2,Math.max(1,e.layerCount||1))},preferMultiLayer:!0,maxMultiLayerSpan:void 0,...n,gridSizes:n.gridSizes??Yqn(s)};this.srj=e,this.layerNames=i,this.layerCount=r,this.bounds=s,this.options=A,this.boardVoidRects=this.input.boardVoidRects,this.gridIndex=0,this.candidates=[],this.placed=[],this.placedIndexByLayer=Array.from({length:r},()=>new vz),this.hardPlacedByLayer=Array.from({length:r},()=>[]),this.expansionIndex=0,this.edgeAnalysisDone=!1,this.totalSeedsThisGrid=0,this.consumedSeedsThisGrid=0,this.stats={gridIndex:this.gridIndex}}_step(){this._stepGrid(),this.stats.gridIndex=this.gridIndex,this.stats.placed=this.placed.length}_stepGrid(){const{gridSizes:e,initialCellRatio:n,maxAspectRatio:o,minSingle:i,minMulti:r,preferMultiLayer:s,maxMultiLayerSpan:a}=this.options,A=e[this.gridIndex];if(this.candidates.length===0&&this.consumedSeedsThisGrid===0&&(this.candidates=(function(h){const{bounds:d,gridSize:p,layerCount:m,obstacleIndexByLayer:_,placedIndexByLayer:f,hardPlacedByLayer:I}=h,C=new Map,y=Array.from({length:m},(E,B)=>[..._[B]?.all()??[],...I[B]??[]]);for(let E=d.x;E<d.x+d.width;E+=p)for(let B=d.y;B<d.y+d.height;B+=p){if(Math.abs(E-d.x)<Fi||Math.abs(B-d.y)<Fi||E>d.x+d.width-p-Fi||B>d.y+d.height-p-Fi||f7e({layerCount:m,obstacleIndexByLayer:_,placedIndexByLayer:f,point:{x:E,y:B}}))continue;let S=[],Q=0;for(let Y=0;Y<m;Y++){const W=I7e({x:E,y:B,z:Y,layerCount:m,minSpan:1,maxSpan:void 0,obstacleIndexByLayer:_,additionalBlockersByLayer:I});W.length>S.length&&(S=W,Q=Y)}const w=S.length?S[Math.floor(S.length/2)]:Q,M=y[w]??[];let k=Tse({x:E,y:B},d);for(const Y of M)k=Math.min(k,Tse({x:E,y:B},Y));const R=Uqn(k),F=`${E.toFixed(6)}|${B.toFixed(6)}`,O={x:E,y:B,z:w,distance:R,zSpanLen:S.length},U=C.get(F);(!U||O.zSpanLen>(U.zSpanLen??0)||O.zSpanLen===U.zSpanLen&&O.distance>U.distance)&&C.set(F,O)}const x=Array.from(C.values());return x.sort((E,B)=>B.zSpanLen-E.zSpanLen||B.distance-E.distance||E.z-B.z||E.x-B.x||E.y-B.y),x})({bounds:this.bounds,gridSize:A,layerCount:this.layerCount,hardPlacedByLayer:this.hardPlacedByLayer,obstacleIndexByLayer:this.input.obstacleIndexByLayer,placedIndexByLayer:this.placedIndexByLayer}),this.totalSeedsThisGrid=this.candidates.length,this.consumedSeedsThisGrid=0),this.consumedSeedsThisGrid>=this.candidates.length){if(this.gridIndex+1<e.length)return this.gridIndex+=1,this.candidates=[],this.totalSeedsThisGrid=0,void(this.consumedSeedsThisGrid=0);if(!this.edgeAnalysisDone){const h=Math.min(i.width,i.height);return this.candidates=Vqn({bounds:this.bounds,minSize:h,layerCount:this.layerCount,obstacleIndexByLayer:this.input.obstacleIndexByLayer,placedIndexByLayer:this.placedIndexByLayer,hardPlacedByLayer:this.hardPlacedByLayer}),this.edgeAnalysisDone=!0,this.totalSeedsThisGrid=this.candidates.length,void(this.consumedSeedsThisGrid=0)}return this.candidates=[],this.solved=!0,void(this.expansionIndex=0)}const c=this.candidates[this.consumedSeedsThisGrid++];if(f7e({layerCount:this.layerCount,obstacleIndexByLayer:this.input.obstacleIndexByLayer,placedIndexByLayer:this.placedIndexByLayer,point:{x:c.x,y:c.y}}))return;const l=I7e({x:c.x,y:c.y,z:c.z,layerCount:this.layerCount,minSpan:r.minLayers,maxSpan:a,obstacleIndexByLayer:this.input.obstacleIndexByLayer,additionalBlockersByLayer:this.hardPlacedByLayer}),u=[];l.length>=r.minLayers&&u.push({kind:"multi",layers:l,minReq:{width:r.width,height:r.height}}),u.push({kind:"single",layers:[c.z],minReq:{width:i.width,height:i.height}});const g=s?u:u.reverse();for(const h of g){const d=F_t({startX:c.x,startY:c.y,gridSize:A,bounds:this.bounds,obsticalIndexByLayer:this.input.obstacleIndexByLayer,placedIndexByLayer:this.placedIndexByLayer,initialCellRatio:n,maxAspectRatio:o,minReq:h.minReq,zLayers:h.layers});if(!d)continue;const p={rect:d,zLayers:[...h.layers]},m=this.placed.push(p)-1;for(const _ of h.layers){const f=this.placedIndexByLayer[_];f&&f.insert($F(d,{zLayers:p.zLayers}))}return L_t({layerCount:this.layerCount,placed:this.placed,options:this.options,placedIndexByLayer:this.placedIndexByLayer},m),void(this.hardPlacedByLayer=zqn({layerCount:this.layerCount,placed:this.placed}))}}computeProgress(){if(this.solved)return 1;const e=this.options.gridSizes.length,n=this.gridIndex/(e+1),o=Math.max(1,this.totalSeedsThisGrid),i=o?this.consumedSeedsThisGrid/o:1;return Math.min(.999,n+i*(1/(e+1)))}getOutput(){return{layerNames:this.layerNames,layerCount:this.layerCount,bounds:this.bounds,options:this.options,boardVoidRects:this.boardVoidRects,gridIndex:this.gridIndex,candidates:this.candidates,placed:this.placed,expansionIndex:this.expansionIndex,edgeAnalysisDone:this.edgeAnalysisDone,totalSeedsThisGrid:this.totalSeedsThisGrid,consumedSeedsThisGrid:this.consumedSeedsThisGrid,obstacles:this.srj.obstacles,obstacleClearance:this.input.obstacleClearance}}visualize(){const e=[],n=[],o=[],i=this.srj??this.input.simpleRouteJson,r=i.bounds.minX,s=i.bounds.maxX,a=i.bounds.minY,A=i.bounds.maxY;i.outline&&i.outline.length>1?o.push({points:[...i.outline,i.outline[0]],strokeColor:"#111827",strokeWidth:.01,label:"outline"}):e.push({center:{x:(r+s)/2,y:(a+A)/2},width:s-r,height:A-a,fill:"none",stroke:"#111827",label:"board"});for(const c of i.obstacles??[])c.type!=="rect"&&c.type!=="oval"||e.push({center:{x:c.center.x,y:c.center.y},width:c.width,height:c.height,fill:"#fee2e2",stroke:"#ef4444",layer:"obstacle",label:"obstacle"});if(this.boardVoidRects){let c=null;if(i.outline&&i.outline.length>0){const l=i.outline.map(d=>d.x),u=i.outline.map(d=>d.y),g=Math.min(...l),h=Math.min(...u);c={x:g,y:h,width:Math.max(...l)-g,height:Math.max(...u)-h}}for(const l of this.boardVoidRects)c&&!Rz(l,c)||e.push({center:{x:l.x+l.width/2,y:l.y+l.height/2},width:l.width,height:l.height,fill:"rgba(0, 0, 0, 0.5)",stroke:"none",label:"void"})}if(this.candidates?.length)for(const c of this.candidates)n.push({x:c.x,y:c.y,label:`z:${c.z}`});if(this.placed?.length)for(const c of this.placed){const l=Rse(c.zLayers);e.push({center:{x:c.rect.x+c.rect.width/2,y:c.rect.y+c.rect.height/2},width:c.rect.width,height:c.rect.height,fill:l.fill,stroke:l.stroke,layer:`z${c.zLayers.join(",")}`,label:`free
z:${c.zLayers.join(",")}`})}return{title:"RectDiff Grid",coordinateSystem:"cartesian",rects:e,points:n,lines:o}}},Wqn=(t,e)=>t.minX===e.minX&&t.minY===e.minY&&t.maxX===e.maxX&&t.maxY===e.maxY,jqn=class extends zA{constructor(e){super(),this.input=e}input;placedIndexByLayer=[];_meshNodes=[];_setup(){this.stats={gridIndex:this.input.gridIndex},this.placedIndexByLayer=Array.from({length:this.input.layerCount},()=>new vz);for(const e of this.input.placed)for(const n of e.zLayers){const o=this.placedIndexByLayer[n];o&&o.insert($F(e.rect,{zLayers:e.zLayers}))}}_step(){this.solved||(this._stepExpansion(),this.stats.gridIndex=this.input.gridIndex,this.stats.placed=this.input.placed.length,this.input.expansionIndex>=this.input.placed.length&&this.finalizeIfNeeded())}_stepExpansion(){if(this.input.expansionIndex>=this.input.placed.length)return;const e=this.input.expansionIndex,n=this.input.placed[e],o=this.input.options.gridSizes[this.input.options.gridSizes.length-1],i=n.rect,r=F_t({startX:n.rect.x+n.rect.width/2,startY:n.rect.y+n.rect.height/2,gridSize:o,bounds:this.input.bounds,obsticalIndexByLayer:this.input.obstacleIndexByLayer,placedIndexByLayer:this.placedIndexByLayer,initialCellRatio:0,maxAspectRatio:null,minReq:{width:n.rect.width,height:n.rect.height},zLayers:n.zLayers});if(r){this.input.placed[e]={rect:r,zLayers:n.zLayers};for(const s of n.zLayers){const a=this.placedIndexByLayer[s];a&&(a.remove($F(i,{zLayers:n.zLayers}),Wqn),a.insert($F(r,{zLayers:n.zLayers})))}L_t({layerCount:this.input.layerCount,placed:this.input.placed,options:this.input.options,placedIndexByLayer:this.placedIndexByLayer},e)}this.input.expansionIndex+=1}finalizeIfNeeded(){if(this.solved)return;const e=(function(n){const o=n.placed.map(i=>({minX:i.rect.x,minY:i.rect.y,maxX:i.rect.x+i.rect.width,maxY:i.rect.y+i.rect.height,zLayers:[...i.zLayers].sort((r,s)=>r-s)}));for(const i of n.obstacles??[]){const r=h7e(i);if(!r)continue;const s=n.obstacleClearance?{x:r.x-n.obstacleClearance,y:r.y-n.obstacleClearance,width:r.width+2*n.obstacleClearance,height:r.height+2*n.obstacleClearance}:r,a=i.zLayers?.length&&i.zLayers.length>0?i.zLayers:d7e(i,n.zIndexByName);o.push({minX:s.x,minY:s.y,maxX:s.x+s.width,maxY:s.y+s.height,zLayers:[...new Set(a)].sort((A,c)=>A-c),isObstacle:!0,connectedTo:[...i.connectedTo]})}return o})({placed:this.input.placed,obstacles:this.input.obstacles,zIndexByName:this.input.zIndexByName,boardVoidRects:this.input.boardVoidRects,obstacleClearance:this.input.obstacleClearance});this._meshNodes=(function(n){let o=0;const i=[];for(const r of n){const s=Math.max(0,r.maxX-r.minX),a=Math.max(0,r.maxY-r.minY);s<=0||a<=0||r.zLayers.length===0||i.push({capacityMeshNodeId:"cmn_"+o++,center:{x:(r.minX+r.maxX)/2,y:(r.minY+r.maxY)/2},width:s,height:a,layer:"top",availableZ:r.zLayers.slice(),_containsObstacle:r.isObstacle,_containsTarget:r.isObstacle,...r.connectedTo?.length?{_connectedTo:[...r.connectedTo]}:{}})}return i})(e),this.solved=!0}computeProgress(){if(this.solved)return 1;const e=this.input.options.gridSizes.length,n=e/(e+1),o=Math.max(1,this.input.placed.length),i=o?this.input.expansionIndex/o:1;return Math.min(.999,n+i*(1/(e+1)))}getOutput(){return this.solved?{meshNodes:this._meshNodes}:{meshNodes:this.input.placed.map((e,n)=>({capacityMeshNodeId:`expand-preview-${n}`,center:{x:e.rect.x+e.rect.width/2,y:e.rect.y+e.rect.height/2},width:e.rect.width,height:e.rect.height,availableZ:e.zLayers.slice(),layer:`z${e.zLayers.join(",")}`}))}}visualize(){const e=[];for(const n of this.input.placed??[])e.push({center:{x:n.rect.x+n.rect.width/2,y:n.rect.y+n.rect.height/2},width:n.rect.width,height:n.rect.height,stroke:"rgba(37, 99, 235, 0.9)",fill:"rgba(191, 219, 254, 0.5)",layer:`z${n.zLayers.join(",")}`,label:`expanded
z:${n.zLayers.join(",")}`});return{title:"RectDiff Expansion",coordinateSystem:"cartesian",rects:e,points:[],lines:[]}}},$qn=class extends n7{rectDiffSeedingSolver;rectDiffExpansionSolver;obstacleIndexByLayer;layerNames;zIndexByName;constructor(e){super(e);const{obstacleIndexByLayer:n,layerNames:o,zIndexByName:i}=(r=>{const{srj:s,boardVoidRects:a,obstacleClearance:A}=r,{layerNames:c,zIndexByName:l}=g7e({obstacles:s.obstacles,layerCount:s.layerCount}),u=Math.max(1,c.length,s.layerCount||1),g=(s.bounds.minX,s.bounds.minY,s.bounds.maxX,s.bounds.minX,s.bounds.maxY,s.bounds.minY,Array.from({length:u},()=>new vz)),h=(d,p)=>{const m={...d,minX:d.x,minY:d.y,maxX:d.x+d.width,maxY:d.y+d.height,zLayers:[p]};g[p]?.insert(m)};if(s.outline&&s.outline.length>2)for(const d of a??[])for(let p=0;p<u;p++)h(d,p);for(const d of s.obstacles??[]){const p=h7e(d);if(!p)continue;const m=p7e(p,A??0),_=d7e(d,l),f=_.filter(I=>I<0||I>=u);if(f.length)throw new Error(`RectDiff: obstacle uses z-layer indices ${f.join(",")} outside 0-${u-1}`);d.zLayers&&d.zLayers.length!==0||!_.length||(d.zLayers=_);for(const I of _)h(m,I)}return{obstacleIndexByLayer:g,layerNames:c,zIndexByName:l}})({srj:{bounds:e.bounds,obstacles:e.obstacles,connections:e.connections,outline:e.outline?.outline,layerCount:e.layerCount,minTraceWidth:e.minTraceWidth},boardVoidRects:e.boardVoidRects,obstacleClearance:e.obstacleClearance});this.obstacleIndexByLayer=n,this.layerNames=e.layerNames??o,this.zIndexByName=e.zIndexByName??i}pipelineDef=[eh("rectDiffSeedingSolver",Jqn,e=>[{simpleRouteJson:{bounds:e.inputProblem.bounds,obstacles:e.inputProblem.obstacles,connections:e.inputProblem.connections,outline:e.inputProblem.outline?.outline,layerCount:e.inputProblem.layerCount,minTraceWidth:e.inputProblem.minTraceWidth},gridOptions:e.inputProblem.gridOptions,obstacleIndexByLayer:e.obstacleIndexByLayer,boardVoidRects:e.inputProblem.boardVoidRects,layerNames:e.layerNames,zIndexByName:e.zIndexByName,obstacleClearance:e.inputProblem.obstacleClearance}]),eh("rectDiffExpansionSolver",jqn,e=>{const n=e.rectDiffSeedingSolver?.getOutput();if(!n)throw new Error("RectDiffSeedingSolver did not produce output");return[{layerNames:n.layerNames??[],boardVoidRects:e.inputProblem.boardVoidRects??[],layerCount:e.inputProblem.layerCount,bounds:n.bounds,candidates:n.candidates,consumedSeedsThisGrid:n.placed.length,totalSeedsThisGrid:n.candidates.length,placed:n.placed,edgeAnalysisDone:n.edgeAnalysisDone,gridIndex:n.gridIndex,expansionIndex:n.expansionIndex,obstacleIndexByLayer:e.obstacleIndexByLayer,options:n.options,zIndexByName:e.zIndexByName,layerNamesCanonical:e.layerNames,obstacles:e.inputProblem.obstacles,obstacleClearance:e.inputProblem.obstacleClearance}]})];getConstructorParams(){return[this.inputProblem]}getOutput(){return this.rectDiffExpansionSolver?this.rectDiffExpansionSolver.getOutput():this.rectDiffSeedingSolver?{meshNodes:this.rectDiffSeedingSolver.getOutput().placed.map((e,n)=>({capacityMeshNodeId:`grid-${n}`,center:{x:e.rect.x+e.rect.width/2,y:e.rect.y+e.rect.height/2},width:e.rect.width,height:e.rect.height,availableZ:e.zLayers,layer:`z${e.zLayers.join(",")}`}))}:{meshNodes:[]}}visualize(){return this.rectDiffExpansionSolver?this.rectDiffExpansionSolver.visualize():this.rectDiffSeedingSolver?this.rectDiffSeedingSolver.visualize():{title:"RectDiff Grid Pipeline",coordinateSystem:"cartesian",rects:[],points:[],lines:[]}}},H_t=t=>{const{srj:e,clearance:n}=t,o=n??0;if(o<=0)return{title:"Obstacle Clearance",coordinateSystem:"cartesian",rects:[]};const i=[];for(const r of e.obstacles??[]){if(r.type!=="rect"&&r.type!=="oval")continue;const s={x:r.center.x-r.width/2-o,y:r.center.y-r.height/2-o,width:r.width+2*o,height:r.height+2*o};i.push({center:{x:s.x+s.width/2,y:s.y+s.height/2},width:s.width,height:s.height,stroke:"rgba(202, 138, 4, 0.9)",fill:"rgba(234, 179, 8, 0.15)",layer:"obstacle-clearance",label:`clearance
z:${(r.zLayers??[]).join(",")||"all"}`})}return{title:"Obstacle Clearance",coordinateSystem:"cartesian",rects:i}};function qqn(t,e,n={}){if(!e||e.length<3)return[];const o=e.length>120,i=o?(function(h,d){const p=f=>Math.round(f/d)*d,m=new Set,_=[];for(const f of h){const I=p(f.x),C=p(f.y),y=`${I},${C}`;m.has(y)||(m.add(y),_.push({x:I,y:C}))}return _})(e,Math.max(t.width,t.height)/120):e,r=new Set([t.x,t.x+t.width]),s=new Set([t.y,t.y+t.height]);for(const h of i)r.add(h.x),s.add(h.y);(function({polygon:h,xs:d,ys:p,minGridSize:m}){const _=[];let f=0;for(let C=0;C<h.length;C++){const y=h[C],x=h[(C+1)%h.length],E=Math.abs(x.x-y.x),B=Math.abs(x.y-y.y);if(E<=Fi||B<=Fi)continue;const S=Math.max(E,B);_.push({start:y,end:x,span:S}),f+=S}if(_.length===0)return;const I=Math.max(m,f/256);for(const{start:C,end:y,span:x}of _){const E=Math.max(1,Math.ceil(x/I));for(let B=1;B<E;B++){const S=B/E;d.add(C.x+(y.x-C.x)*S),p.add(C.y+(y.y-C.y)*S)}}})({polygon:i,xs:r,ys:s,minGridSize:Math.max(Fi,n.minGridSize??Math.max(t.width,t.height)/256)});const a=Array.from(r).sort((h,d)=>h-d),A=Array.from(s).sort((h,d)=>h-d),c=[];for(let h=0;h<a.length-1;h++)for(let d=0;d<A.length-1;d++){const p=a[h],m=a[h+1],_=A[d],f=A[d+1],I=(p+m)/2,C=(_+f)/2;I>=t.x&&I<=t.x+t.width&&C>=t.y&&C<=t.y+t.height&&((o?[{x:I,y:C}]:[{x:I,y:C},{x:p,y:_},{x:m,y:_},{x:p,y:f},{x:m,y:f}]).every(y=>Mz(y,e))||c.push({x:p,y:_,width:m-p,height:f-_}))}const l=[];c.sort((h,d)=>Math.abs(h.y-d.y)>Fi?h.y-d.y:h.x-d.x);let u=null;for(const h of c){if(!u){u=h;continue}const d=Math.abs(u.y-h.y)<Fi,p=Math.abs(u.height-h.height)<Fi,m=Math.abs(u.x+u.width-h.x)<Fi;d&&p&&m?u.width+=h.width:(l.push(u),u=h)}u&&l.push(u),l.sort((h,d)=>Math.abs(h.x-d.x)>Fi?h.x-d.x:h.y-d.y);const g=[];u=null;for(const h of l){if(!u){u=h;continue}const d=Math.abs(u.x-h.x)<Fi,p=Math.abs(u.width-h.width)<Fi,m=Math.abs(u.y+u.height-h.y)<Fi;d&&p&&m?u.height+=h.height:(g.push(u),u=h)}return u&&g.push(u),g}var qF=class extends n7{rectDiffGridSolverPipeline;gapFillSolver;outerLayerContainmentMergeSolver;boardVoidRects;zIndexByName;layerNames;pipelineDef=[eh("rectDiffGridSolverPipeline",$qn,e=>[{bounds:e.inputProblem.simpleRouteJson.bounds,obstacles:e.inputProblem.simpleRouteJson.obstacles,connections:e.inputProblem.simpleRouteJson.connections,outline:e.inputProblem.simpleRouteJson.outline?{outline:e.inputProblem.simpleRouteJson.outline}:void 0,layerCount:e.inputProblem.simpleRouteJson.layerCount,gridOptions:e.inputProblem.gridOptions,boardVoidRects:e.boardVoidRects,layerNames:e.layerNames,zIndexByName:e.zIndexByName,minTraceWidth:e.inputProblem.simpleRouteJson.minTraceWidth,obstacleClearance:e.inputProblem.obstacleClearance}]),eh("gapFillSolver",vqn,e=>[{meshNodes:e.rectDiffGridSolverPipeline?.getOutput().meshNodes??[],boardVoid:{boardVoidRects:e.boardVoidRects||[],layerCount:e.inputProblem.simpleRouteJson.layerCount||0},maxGapFillPasses:e.inputProblem.maxGapFillPasses}]),eh("outerLayerContainmentMergeSolver",Mqn,e=>[{meshNodes:e.gapFillSolver?.getOutput().outputNodes??e.rectDiffGridSolverPipeline?.getOutput().meshNodes??[],simpleRouteJson:e.inputProblem.simpleRouteJson,zIndexByName:e.zIndexByName??new Map,obstacleClearance:e.inputProblem.obstacleClearance}])];_setup(){const{zIndexByName:e,layerNames:n}=g7e({obstacles:this.inputProblem.simpleRouteJson.obstacles,layerCount:this.inputProblem.simpleRouteJson.layerCount});if(this.zIndexByName=e,this.layerNames=n,this.inputProblem.simpleRouteJson.outline){const o=Math.max(0,this.inputProblem.simpleRouteJson.minBoardEdgeClearance??0);this.boardVoidRects=qqn({x:this.inputProblem.simpleRouteJson.bounds.minX-o,y:this.inputProblem.simpleRouteJson.bounds.minY-o,width:this.inputProblem.simpleRouteJson.bounds.maxX-this.inputProblem.simpleRouteJson.bounds.minX+2*o,height:this.inputProblem.simpleRouteJson.bounds.maxY-this.inputProblem.simpleRouteJson.bounds.minY+2*o},this.inputProblem.simpleRouteJson.outline??[],{minGridSize:this.inputProblem.simpleRouteJson.minTraceWidth}).map(i=>p7e(i,o))}}getConstructorParams(){return[this.inputProblem]}getOutput(){const e=this.outerLayerContainmentMergeSolver?.getOutput();if(e)return{meshNodes:e.outputNodes};const n=this.gapFillSolver?.getOutput();return n?{meshNodes:n.outputNodes}:this.rectDiffGridSolverPipeline?this.rectDiffGridSolverPipeline.getOutput():{meshNodes:[]}}initialVisualize(){const e=(function(i,r="RectDiff"){const s=[],a=[],A=i.bounds.minX,c=i.bounds.maxX,l=i.bounds.minY,u=i.bounds.maxY;i.outline&&i.outline.length>1?a.push({points:[...i.outline,i.outline[0]],strokeColor:"#111827",strokeWidth:.01,label:"outline"}):s.push({center:{x:(A+c)/2,y:(l+u)/2},width:c-A,height:u-l,fill:"none",stroke:"#111827",label:"board"});for(const g of i.obstacles??[])if(g.type==="rect"||g.type==="oval"){const h=(g.zLayers??[]).join(",")||"all";s.push({center:{x:g.center.x,y:g.center.y},width:g.width,height:g.height,fill:"#fee2e2",stroke:"#ef4444",layer:"obstacle",label:`obstacle
z:${h}`})}return{title:r,coordinateSystem:"cartesian",rects:s,points:[],lines:a}})(this.inputProblem.simpleRouteJson,"RectDiffPipeline - Initial"),n=H_t({srj:this.inputProblem.simpleRouteJson,clearance:this.inputProblem.obstacleClearance}),o={rects:(this.rectDiffGridSolverPipeline?.getOutput().meshNodes??[]).map(i=>({center:i.center,width:i.width,height:i.height,stroke:"rgba(0, 0, 0, 0.3)",fill:"rgba(100, 100, 100, 0.1)",layer:`z${i.availableZ.join(",")}`,label:[`node ${i.capacityMeshNodeId}`,`z:${i.availableZ.join(",")}`].join(`
`)}))};return MD(MD(e,n),o)}finalVisualize(){return(({srj:e,meshNodes:n,obstacleClearance:o})=>{const i=(({srj:a})=>({title:"SimpleRoute Outline",coordinateSystem:"cartesian",lines:a.outline&&a.outline.length>1?[{points:[...a.outline,a.outline[0]],strokeColor:"#111827",strokeWidth:.1,label:"outline"}]:[{points:[{x:a.bounds.minX,y:a.bounds.minY},{x:a.bounds.maxX,y:a.bounds.minY},{x:a.bounds.maxX,y:a.bounds.maxY},{x:a.bounds.minX,y:a.bounds.maxY},{x:a.bounds.minX,y:a.bounds.minY}],strokeColor:"#111827",strokeWidth:.1,label:"bounds"}]}))({srj:e}),r=H_t({srj:e,clearance:o}),s=n.map(a=>({center:a.center,width:a.width,height:a.height,stroke:Rse(a.availableZ).stroke,fill:a._containsObstacle?"#fca5a5":Rse(a.availableZ).fill,layer:`z${a.availableZ.join(",")}`,label:`node ${a.capacityMeshNodeId}
z:${a.availableZ.join(",")}`}));return MD(MD({title:"RectDiffPipeline - Final",coordinateSystem:"cartesian",rects:s,lines:[],points:[],texts:[]},i),r)})({srj:this.inputProblem.simpleRouteJson,meshNodes:this.getOutput().meshNodes,obstacleClearance:this.inputProblem.obstacleClearance})}},Xqn=class{cacheHitsByPrefix={};cacheMissesByPrefix={};isSyncCache=!0;cacheHits=0;cacheMisses=0;cache=new Map;getCachedSolutionSync(e){const n=this.cache.get(e);if(n!==void 0){this.cacheHits++;const o=e.split(":")[0];return this.cacheHitsByPrefix[o]=(this.cacheHitsByPrefix[o]||0)+1,structuredClone(n)}{this.cacheMisses++;const o=e.split(":")[0];return void(this.cacheMissesByPrefix[o]=(this.cacheMissesByPrefix[o]||0)+1)}}async getCachedSolution(e){return this.getCachedSolutionSync(e)}setCachedSolutionSync(e,n){this.cache.set(e,structuredClone(n))}async setCachedSolution(e,n){this.setCachedSolutionSync(e,n)}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0,this.cacheHitsByPrefix={},this.cacheMissesByPrefix={}}getAllCacheKeys(){return Array.from(this.cache.keys())}},C7e="tscircuit_autorouter_cache_",Zqn=class{isSyncCache=!0;cacheHits=0;cacheMisses=0;cacheHitsByPrefix={};cacheMissesByPrefix={};constructor(){}getKey(e){return`${C7e}${e}`}getCachedSolutionSync(e){if(typeof localStorage>"u")return;const n=this.getKey(e);try{const o=localStorage.getItem(n);if(o!==null){const i=JSON.parse(o);this.cacheHits++;const r=e.split(":")[0];return this.cacheHitsByPrefix[r]=(this.cacheHitsByPrefix[r]||0)+1,i}{this.cacheMisses++;const i=e.split(":")[0];return void(this.cacheMissesByPrefix[i]=(this.cacheMissesByPrefix[i]||0)+1)}}catch(o){console.error(`Error getting cached solution sync for ${n}:`,o),this.cacheMisses++;const i=e.split(":")[0];return void(this.cacheMissesByPrefix[i]=(this.cacheMissesByPrefix[i]||0)+1)}}async getCachedSolution(e){return this.getCachedSolutionSync(e)}setCachedSolutionSync(e,n){if(typeof localStorage>"u")return;const o=this.getKey(e);try{const i=JSON.stringify(n);localStorage.setItem(o,i)}catch(i){console.error(`Error setting cached solution sync for ${o}:`,i),i instanceof DOMException&&(i.name==="QuotaExceededError"||i.name==="NS_ERROR_DOM_QUOTA_REACHED")&&console.warn(`LocalStorage quota exceeded. Failed to cache solution for ${o}. Consider clearing the cache.`)}}async setCachedSolution(e,n){this.setCachedSolutionSync(e,n)}clearCache(){if(typeof localStorage<"u")try{const e=[];for(let n=0;n<localStorage.length;n++){const o=localStorage.key(n);o?.startsWith(C7e)&&e.push(o)}e.forEach(n=>localStorage.removeItem(n)),console.log(`Cleared ${e.length} items from LocalStorage cache.`)}catch(e){console.error("Error clearing LocalStorage cache:",e)}finally{this.cacheHits=0,this.cacheMisses=0,this.cacheHitsByPrefix={},this.cacheMissesByPrefix={}}}getAllCacheKeys(){const e=[];for(let n=0;n<1e4;n++){const o=localStorage.key(n);if(!o)break;o.includes(C7e)&&e.push(o)}return e}};function eXn(){return globalThis.TSCIRCUIT_AUTOROUTER_LOCAL_STORAGE_CACHE||Lse(),globalThis.TSCIRCUIT_AUTOROUTER_LOCAL_STORAGE_CACHE}function tB(){return globalThis.TSCIRCUIT_AUTOROUTER_IN_MEMORY_CACHE||Lse(),globalThis.TSCIRCUIT_AUTOROUTER_IN_MEMORY_CACHE}function Lse(){globalThis.TSCIRCUIT_AUTOROUTER_LOCAL_STORAGE_CACHE??=new Zqn,globalThis.TSCIRCUIT_AUTOROUTER_IN_MEMORY_CACHE??=new Xqn}function Tz(t){const e={minX:t.center.x-t.width/2,maxX:t.center.x+t.width/2,minY:t.center.y-t.height/2,maxY:t.center.y+t.height/2};for(const n of t.portPoints)n.x<e.minX&&(e.minX=n.x),n.x>e.maxX&&(e.maxX=n.x),n.y<e.minY&&(e.minY=n.y),n.y>e.maxY&&(e.maxY=n.y);return e}var O_t=(t,e)=>t<=e?[t,e]:[e,t],y7e=t=>`${t[0]}|${t[1]}`,tXn=({portPointId:t,currentNodeId:e,inputNodes:n})=>{let o;if(t)for(const s of n){const a=s.portPoints.find(A=>A.portPointId===t);if(a?.connectionNodeIds){o=a.connectionNodeIds;break}}if(!o||o.length!==2)return[e,e];const[i,r]=o;return i&&r?O_t(i,r):[e,e]},x7e=1e-6,zQ=(t,e)=>Math.abs(t-e)<=x7e,nXn=({nodeAId:t,nodeBId:e,nodeBounds:n})=>{if(t===e)return null;const o=n.get(t),i=n.get(e);if(!o||!i)return null;const r=O_t(t,e),s=y7e(r);if(zQ(o.maxX,i.minX)||zQ(i.maxX,o.minX)){const a=Math.max(o.minY,i.minY),A=Math.min(o.maxY,i.maxY),c=A-a;if(c>x7e){const l=zQ(o.maxX,i.minX)?o.maxX:o.minX;return{ownerNodeIds:r,ownerPairKey:s,orientation:"vertical",x1:l,y1:a,x2:l,y2:A,center:{x:l,y:(a+A)/2},length:c,nodeSideByOwnerId:zQ(o.maxX,i.minX)?{[t]:"right",[e]:"left"}:{[t]:"left",[e]:"right"}}}}if(zQ(o.maxY,i.minY)||zQ(i.maxY,o.minY)){const a=Math.max(o.minX,i.minX),A=Math.min(o.maxX,i.maxX),c=A-a;if(c>x7e){const l=zQ(o.maxY,i.minY)?o.maxY:o.minY;return{ownerNodeIds:r,ownerPairKey:s,orientation:"horizontal",x1:a,y1:l,x2:A,y2:l,center:{x:(a+A)/2,y:l},length:c,nodeSideByOwnerId:zQ(o.maxY,i.minY)?{[t]:"top",[e]:"bottom"}:{[t]:"bottom",[e]:"top"}}}}return null},oXn=({portPoint:t,ownerNodeIds:e,inputNodes:n})=>{for(const o of e){const i=n.find(s=>s.capacityMeshNodeId===o);if(i?._containsTarget||i?.portPoints.find(s=>s.portPointId===t.portPointId)?.connectionNodeIds?.some(s=>n.find(a=>a.capacityMeshNodeId===s)?._containsTarget))return!0}return!1},XF=1e-6,kz=class extends zA{constructor(e){super(),this.input=e;for(const o of e.nodeWithPortPoints)this.mapOfNodeIdToBounds.set(o.capacityMeshNodeId,Tz(o));const n=new Map;for(const o of e.nodeWithPortPoints)for(const i of o.portPoints){if(!i.portPointId)continue;const r=tXn({portPointId:i.portPointId,currentNodeId:o.capacityMeshNodeId,inputNodes:e.inputNodesWithPortPoints}),s=y7e(r),a=this.mapOfOwnerPairToPortPoints.get(s)??[];a.some(A=>A.portPointId&&A.portPointId===i.portPointId)||a.push({...i,ownerNodeIds:r,ownerPairKey:s}),this.mapOfOwnerPairToPortPoints.set(s,a),n.set(s,r)}this.mapOfOwnerPairToSharedEdge=(({ownerPairs:o,nodeBounds:i})=>{const r=new Map;for(const s of o){const[a,A]=s;if(a===A)continue;const c=nXn({nodeAId:a,nodeBId:A,nodeBounds:i});c&&r.set(y7e(s),c)}return r})({ownerPairs:Array.from(n.values()),nodeBounds:this.mapOfNodeIdToBounds}),this.ownerPairsToProcess=Array.from(this.mapOfOwnerPairToSharedEdge.keys()),this.ownerPairsToProcess.sort((o,i)=>{const r=this.mapOfOwnerPairToSharedEdge.get(o),s=this.mapOfOwnerPairToSharedEdge.get(i);return r.center.x-s.center.x||r.center.y-s.center.y})}input;getSolverName(){return"UniformPortDistributionSolver"}mapOfNodeIdToBounds=new Map;mapOfOwnerPairToPortPoints=new Map;mapOfOwnerPairToSharedEdge=new Map;ownerPairsToProcess=[];currentOwnerPairBeingProcessed=null;redistributedNodes=[];step(){if(this.ownerPairsToProcess.length===0)return this.rebuildNodes(),void(this.solved=!0);this.currentOwnerPairBeingProcessed=this.ownerPairsToProcess.shift();const e=this.currentOwnerPairBeingProcessed,n=this.mapOfOwnerPairToSharedEdge.get(e);if(!n||(({sharedEdge:s,obstacles:a})=>{for(const A of a){const c=A.center.x-A.width/2,l=A.center.x+A.width/2,u=A.center.y-A.height/2,g=A.center.y+A.height/2;if(s.orientation!=="vertical"){if(Math.abs(s.y1-u)<XF||Math.abs(s.y1-g)<XF){const h=Math.max(s.x1,c);if(Math.min(s.x2,l)-h>XF)return!0}}else if(Math.abs(s.x1-c)<XF||Math.abs(s.x1-l)<XF){const h=Math.max(s.y1,u);if(Math.min(s.y2,g)-h>XF)return!0}}return!1})({sharedEdge:n,obstacles:this.input.obstacles}))return;const o=this.mapOfOwnerPairToPortPoints.get(e)??[],i=[];for(const s of o)oXn({portPoint:s,ownerNodeIds:s.ownerNodeIds,inputNodes:this.input.inputNodesWithPortPoints})||i.push(s);const r=(({sharedEdge:s,portPoints:a})=>{if(a.length===0)return[];const A=new Map;for(const u of a){const g=u.z??0,h=A.get(g)??[];h.push(u),A.set(g,h)}const c=[],l=Array.from(A.keys()).sort((u,g)=>u-g);for(const u of l){const g=A.get(u),h=g.length;g.sort((d,p)=>s.orientation==="horizontal"?d.x-p.x:d.y-p.y);for(let d=0;d<h;d++){const p=(2*d+1)/(2*h),m=s.orientation==="horizontal"?s.x1+s.length*p:s.x1,_=s.orientation==="horizontal"?s.y1:s.y1+s.length*p;c.push({...g[d],x:m,y:_})}}return c})({sharedEdge:n,portPoints:i});this.mapOfOwnerPairToPortPoints.set(e,r)}rebuildNodes(){const e=new Map;for(const o of this.mapOfOwnerPairToPortPoints.values())for(const i of o)i.portPointId&&e.set(i.portPointId,{x:i.x,y:i.y});const n=o=>{if(o.portPointId&&e.has(o.portPointId)){const i=e.get(o.portPointId);return{...o,x:i.x,y:i.y}}return o};this.redistributedNodes=this.input.nodeWithPortPoints.map(o=>({...o,portPoints:o.portPoints.map(n),portPointsInPairs:o.portPointsInPairs?.map(([i,r])=>[n(i),n(r)])}))}getOutput=()=>this.redistributedNodes;visualize(){return(({obstacles:e,nodeWithPortPoints:n,mapOfOwnerPairToPortPoints:o,mapOfOwnerPairToSharedEdge:i,ownerPairsToProcess:r,currentOwnerPairBeingProcessed:s,mapOfNodeIdToBounds:a})=>{const A=e.filter(p=>!p.isCopperPour).map(p=>({...p,fill:"#ec000070"})),c=[],l=[],u=new Map,g=new Map,h=new Map,d=p=>p.portPointId?u.get(p.portPointId)??{x:p.x,y:p.y}:{x:p.x,y:p.y};for(const p of n)for(const m of p.portPoints)m.portPointId&&(u.set(m.portPointId,{x:m.x,y:m.y}),g.set(m.portPointId,m.z??0));for(const p of o.values())for(const m of p)m.portPointId&&(u.set(m.portPointId,{x:m.x,y:m.y}),g.set(m.portPointId,m.z??0),h.set(m.portPointId,`${m.ownerNodeIds[0]}&${m.ownerNodeIds[1]}`));n.forEach(p=>{const m=a.get(p.capacityMeshNodeId);if(m){const _=(m.minX+m.maxX)/2,f=(m.minY+m.maxY)/2,I=m.maxX-m.minX,C=m.maxY-m.minY;A.push({center:{x:_,y:f},width:I,height:C,fill:"#00000030",label:`${p.capacityMeshNodeId}`})}p.portPoints.forEach(_=>{if(!_.portPointId)return;const f=u.get(_.portPointId),I=g.get(_.portPointId)??0,C=h.get(_.portPointId)??`${p.capacityMeshNodeId}&${p.capacityMeshNodeId}`;c.push({x:f.x,y:f.y,label:`z:${I}
o:${C}`}),p.portPointsInPairs?.length||p.portPoints.forEach(y=>{if(y.portPointId&&_!==y&&_.connectionName===y.connectionName){const x=u.get(y.portPointId);l.push({points:[f,x],strokeColor:"#fff822c9"})}})}),p.portPointsInPairs?.forEach(([_,f])=>{l.push({points:[d(_),d(f)],strokeColor:"#fff822c9"})})});for(const p of r){const m=i.get(p);m&&l.push({points:[{x:m.x1,y:m.y1},{x:m.x2,y:m.y2}],strokeColor:"orange",strokeWidth:.01})}if(s){const p=i.get(s);p&&(l.push({points:[{x:p.x1,y:p.y1},{x:p.x2,y:p.y2}],strokeColor:"red",strokeWidth:.03}),c.push({x:p.center.x,y:p.center.y,label:p.ownerPairKey}))}for(const p of i.values())l.push({points:[{x:p.x1,y:p.y1},{x:p.x2,y:p.y2}],strokeColor:"#33b5ff80",strokeWidth:.006});return{rects:A,lines:l,points:c}})({obstacles:this.input.obstacles,nodeWithPortPoints:this.input.nodeWithPortPoints,mapOfOwnerPairToPortPoints:this.mapOfOwnerPairToPortPoints,mapOfOwnerPairToSharedEdge:this.mapOfOwnerPairToSharedEdge,ownerPairsToProcess:this.ownerPairsToProcess,currentOwnerPairBeingProcessed:this.currentOwnerPairBeingProcessed,mapOfNodeIdToBounds:this.mapOfNodeIdToBounds})}},Hse=(t,e,n)=>t.connectedTo.some(o=>o===e.connectionName||o===e.rootConnectionName||(n?.areIdsConnected(e.connectionName,o)??!1)||e.rootConnectionName!==void 0&&(n?.areIdsConnected(e.rootConnectionName,o)??!1));function E7e(t){return"layers"in t&&Array.isArray(t.layers)}function ND(t){return"layer"in t&&typeof t.layer=="string"}function tI(t){return E7e(t)?t.layers[0]:t.layer}function RD(t){return E7e(t)?t.layers:[t.layer]}var Kh=(t,e)=>{if(t===1&&e===1)return"inner1";if(t<0||t>=e)throw new Error(`Invalid z "${t}" for layer count: ${e}`);return t===0?"top":t===e-1?"bottom":`inner${t}`},iXn=(t,e)=>!!t&&!!e&&Math.abs(t.x-e.x)<=1e-12&&Math.abs(t.y-e.y)<=1e-12,Ose=(t,e)=>o7(t,e)<=1e-6,rXn=(t,e,n,o)=>e.toNextSegmentType==="through_obstacle"||(o.connectedMultilayerObstacles?o.connectedMultilayerObstacles.some(i=>Ose(e,i)&&Ose(n,i)):o.obstacles?.some(i=>(r=>(r.__zLayers?.length??r.layers?.length??0)>1)(i)&&Ose(e,i)&&Ose(n,i)&&Hse(i,t,o.connMap))??!1),G_t=({endpoint:t,endpointLayer:e,connectionPoints:n,tolerance:o})=>{let i;for(const r of n){if(!ND(r)||!r.terminalVia||r.layer!==e)continue;const s=no(r,t);s>o||(!i||s<i.distance)&&(i={point:r,distance:s})}return i?.point},nB=(t,e,n={})=>{const o=[];if(t.route.length===0)return o;let i=[],r=t.route[0].z;for(let a=0;a<t.route.length;a++){const A=t.route[a];if(A.z!==r){const c=i[i.length-1],l=Kh(r,e);for(const g of i)o.push({route_type:"wire",x:g.x,y:g.y,width:g.traceThickness??t.traceThickness,layer:l});const u=Kh(A.z,e);c&&rXn(t,c,A,n)?o.push({route_type:"through_obstacle",start:{x:c.x,y:c.y},end:{x:A.x,y:A.y},from_layer:l,to_layer:u,width:c.traceThickness??t.traceThickness,...c.toNextSegmentCircuitJsonMetadata?{circuitJsonMetadata:c.toNextSegmentCircuitJsonMetadata}:{}}):t.vias.some(g=>Math.abs(g.x-A.x)<.001&&Math.abs(g.y-A.y)<.001)&&o.push({route_type:"via",x:A.x,y:A.y,from_layer:l,to_layer:u,via_diameter:t.viaDiameter,...n.defaultViaHoleDiameter!==void 0?{via_hole_diameter:n.defaultViaHoleDiameter}:{}}),i=[A],r=A.z}else iXn(i[i.length-1],A)||i.push(A)}const s=Kh(r,e);for(const a of i)o.push({route_type:"wire",x:a.x,y:a.y,width:a.traceThickness??t.traceThickness,layer:s});if(t.jumpers&&t.jumpers.length>0){const a=Kh(t.route[0]?.z??0,e);for(const A of t.jumpers)o.push({route_type:"jumper",start:A.start,end:A.end,footprint:A.footprint,layer:a})}return(({route:a,hdRoute:A,layerCount:c,connectionPoints:l=[],tolerance:u=.25,defaultViaHoleDiameter:g})=>{if(a.length===0||A.route.length===0||!l.length||!l.some(w=>ND(w)&&w.terminalVia))return a;const h=a.filter(w=>w.route_type!=="jumper"),d=a.filter(w=>w.route_type==="jumper");if(h.length===0)return a;const p=A.route[0],m=A.route[A.route.length-1],_=Kh(p.z,c),f=Kh(m.z,c),I=G_t({endpoint:p,endpointLayer:_,connectionPoints:l,tolerance:u}),C=G_t({endpoint:m,endpointLayer:f,connectionPoints:l,tolerance:u}),y=[],x=[],E=h[0],B=h[h.length-1],S=p.traceThickness??A.traceThickness,Q=m.traceThickness??A.traceThickness;return I?.terminalVia&&(y.push({route_type:"via",x:I.x,y:I.y,from_layer:I.layer,to_layer:I.terminalVia.toLayer,via_diameter:I.terminalVia.viaDiameter??A.viaDiameter,...g!==void 0?{via_hole_diameter:g}:{}}),E?.route_type==="wire"&&E.layer===I.layer&&no(E,I)<=.001||y.push({route_type:"wire",x:I.x,y:I.y,width:S,layer:I.layer})),C?.terminalVia&&(B?.route_type==="wire"&&B.layer===C.layer&&no(B,C)<=.001||x.push({route_type:"wire",x:C.x,y:C.y,width:Q,layer:C.layer}),x.push({route_type:"via",x:C.x,y:C.y,from_layer:C.layer,to_layer:C.terminalVia.toLayer,via_diameter:C.terminalVia.viaDiameter??A.viaDiameter,...g!==void 0?{via_hole_diameter:g}:{}})),[...y,...h,...x,...d]})({route:o,hdRoute:t,layerCount:e,connectionPoints:n.connectionPoints,tolerance:n.terminalViaAttachTolerance,defaultViaHoleDiameter:n.defaultViaHoleDiameter})},Y_t=["blue","orange","purple","cyan","magenta","yellowgreen","darkgoldenrod","deeppink"],Jf=(t,e)=>{const n={};for(let o=0;o<t.connections.length;o++){const i=t.connections[o],r=e?.getNetConnectedToId(i.name);r&&!n[r]&&(n[r]=`hsl(${300*o/t.connections.length}, 100%, 50%)`),n[i.name]=(r?n[r]:null)??`hsl(${340*o/t.connections.length}, 100%, 50%)`}return n},Es=(t,e)=>{try{return Bz(e,t)}catch(n){return console.error(n),t}},Fz=(t,e=1)=>{if(!t)return"rgba(0, 0, 0, 0.5)";const n=300*t.split("").reduce((o,i)=>o+i.charCodeAt(0),0)/t.length%360;return e<1?`hsla(${n}, 100%, 50%, ${e})`:`hsl(${n}, 100%, 50%)`},U_t=t=>{const e=new Set;return t.filter(n=>!e.has(n)&&(e.add(n),!0))},Lz=(t,e,n)=>{if(!e)return;const o=t.get(e);o?o.includes(n)||o.push(n):t.set(e,[n])},z8=t=>{const e=new Map;for(const n of t.connections){const o=n.__rootConnectionNames??[n.name];for(const i of o){Lz(e,n.name,i),Lz(e,i,i),Lz(e,n.__netConnectionName,i);for(const r of n.pointsToConnect)Lz(e,r.pointId,i),Lz(e,r.pcb_port_id,i)}}return n=>((o,i=[])=>{const r=U_t(i).join(", ");return o.layers.map(s=>r?`${s}
${r}`:s).join(`
`)})(n,((o,i)=>U_t([...o.connectedTo.flatMap(r=>i.get(r)??[]),...(o.offBoardConnectsTo??[]).flatMap(r=>i.get(r)??[])]))(n,e))},Kr=(t,e)=>t==="top"?0:t==="bottom"?e-1:parseInt(t.slice(5));function Hz(t,e){return[...new Set(t)].filter(n=>Number.isInteger(n)&&n>=0&&n<e).sort((n,o)=>n-o)}function Oz(t,e){return Hz(t.map(n=>Kr(n,e)),e)}var Gz=(t,e)=>`z${Oz(t,e).join(",")}`,J8=(t,e)=>Gz(RD(t),e),K_t=(t,e)=>t.__zLayers&&t.__zLayers.length>0?Hz(t.__zLayers,e):Oz(t.layers,e),r7=(t,e)=>`z${K_t(t,e).join(",")}`,V_t=(...t)=>t.find(e=>typeof e=="number"&&Number.isFinite(e)),om=t=>{const e=V_t(t.min_via_hole_diameter,t.minViaHoleDiameter),n=V_t(t.min_via_pad_diameter,t.minViaPadDiameter,t.minViaDiameter),o=Math.max(n??t.minViaDiameter??.3,e??0);return{padDiameter:o,holeDiameter:e??.5*o}},W8={"0603":{length:1.65,width:.95,padLength:.8,padWidth:.95},1206:{length:3.2,width:1.6,padLength:.6,padWidth:1.6},"1206x4_pair":{length:2.7,width:.5,padLength:.8,padWidth:.5}},z_t={top:"red",bottom:"blue",inner1:"green",inner2:"yellow",inner3:"orange",inner4:"purple",inner5:"cyan",inner6:"magenta",inner7:"lime",inner8:"brown"};function J_t(t){if(Object.hasOwn(z_t,t))return z_t[t];const e=/^inner([1-9]\d*)$/.exec(t);if(e)return`hsl(${137*Number(e[1])%360}, 70%, 45%)`;throw new Error(`No visualization color for layer "${t}"`)}var mx=(t,e={})=>{const n=[],o=[],i=[],r=[],s=Jf(t),a=e.traceColorMode??"layer",A=t.layerCount,c=om(t),l=z8(t);if(t.connections)for(const u of t.connections)for(const g of u.pointsToConnect){const h=RD(g),d=u.__rootConnectionNames??[u.name];i.push({x:g.x,y:g.y,color:s[u.name],layer:J8(g,A),label:[u.name,d.join(", "),h.join(",")].join(`
`)})}if(t.traces)for(const u of t.traces){let g=t.minTraceWidth;const h=u.route.filter(m=>m.route_type==="jumper"),d=(m,_)=>{for(const I of h){const C=Math.abs(m.x-I.start.x)<.01&&Math.abs(m.y-I.start.y)<.01&&Math.abs(_.x-I.end.x)<.01&&Math.abs(_.y-I.end.y)<.01,y=Math.abs(m.x-I.end.x)<.01&&Math.abs(m.y-I.end.y)<.01&&Math.abs(_.x-I.start.x)<.01&&Math.abs(_.y-I.start.y)<.01;if(C||y)return!0}return!1};for(const m of u.route)if(m.route_type==="via"){const _=Kr(m.from_layer,A),f=Kr(m.to_layer,A),I=(m.via_diameter??c.padDiameter)/2,C=Array.from({length:Math.abs(f-_)+1},(y,x)=>Math.min(_,f)+x);o.push({center:{x:m.x,y:m.y},radius:I,fill:a==="net"?s[u.connection_name]:"blue",stroke:"none",layer:`z${C.join(",")}`})}else if(m.route_type==="through_obstacle"){const _=s[u.connection_name]??"purple";n.push({points:[m.start,m.end],strokeColor:Es(_,.35),strokeWidth:m.width,strokeDash:[.1,.1],layer:Gz([m.from_layer,m.to_layer],A),label:`${u.connection_name} through_obstacle`})}let p;for(let m=0;m<u.route.length-1;m++){const _=u.route[m],f=u.route[m+1];if(_.route_type==="jumper"){p=void 0;const I=s[u.connection_name]??"rgba(255, 165, 0, 0.8)",C=_.footprint,y=W8[C==="1206x4_pair"?"1206x4_pair":"0603"]??W8["0603"],x=_.end.x-_.start.x,E=_.end.y-_.start.y,B=Math.abs(x)>Math.abs(E),S=B?y.padLength:y.padWidth,Q=B?y.padWidth:y.padLength;r.push({center:_.start,width:S,height:Q,fill:Es(I,.5),stroke:"rgba(0, 0, 0, 0.5)",layer:Gz([_.layer],A)}),r.push({center:_.end,width:S,height:Q,fill:Es(I,.5),stroke:"rgba(0, 0, 0, 0.5)",layer:Gz([_.layer],A)}),n.push({points:[_.start,_.end],strokeColor:"rgba(100, 100, 100, 0.8)",strokeWidth:.3*y.padWidth,layer:Gz([_.layer],A)})}else if(_.route_type==="wire"&&f.route_type==="wire"&&f.layer===_.layer){if(d({x:_.x,y:_.y},{x:f.x,y:f.y})){p=void 0;continue}g=_.width;const I=_.layer==="top",C=a==="net"?s[u.connection_name]:J_t(_.layer),y=`z${Kr(_.layer,A)}`;if(p&&p.layer===y&&p.strokeWidth===g){p.points.push({x:f.x,y:f.y});continue}p={points:[{x:_.x,y:_.y},{x:f.x,y:f.y}],layer:y,strokeWidth:g,strokeColor:I?C:Es(C,.5),...a==="net"?{label:u.connection_name}:{},...I?{}:{strokeDash:[.2,.2]}},n.push(p)}else p=void 0}}for(const u of t.obstacles){if(u.isCopperPour)continue;const g=K_t(u,A);if(g.length===0)throw new Error(`Cannot visualize obstacle "${u.obstacleId??"unknown"}" without a valid layer: layers=${u.layers.join(",")}, __zLayers=${u.__zLayers?.join(",")??"unset"}, layerCount=${A}`);const h=J_t((g.length===1?Kh(g[0],A):null)==="bottom"?"bottom":"top"),d=.5**g.length;r.push({center:u.center,width:u.width,height:u.height,ccwRotationDegrees:u.ccwRotationDegrees,fill:Es(h,d),layer:r7(u,A),label:l(u)})}if(t.jumpers)for(const u of t.jumpers)for(const g of u.pads)r.push({center:g.center,width:g.width,height:g.height,ccwRotationDegrees:g.ccwRotationDegrees,fill:"rgba(255, 165, 0, 0.3)",stroke:"rgba(255, 165, 0, 0.8)",layer:r7(g,A)});return{rects:r,circles:o,lines:n,points:i}};function sXn([t,e],[n,o],{lineThickness:i=0}={}){return i===0?W_t(t,e,n,o):(function(s,a,A,c){if(s.x===a.x&&s.y===a.y)return ZF(s,A,c);if(A.x===c.x&&A.y===c.y)return ZF(A,s,a);if(W_t(s,a,A,c))return 0;const l=[ZF(s,A,c),ZF(a,A,c),ZF(A,s,a),ZF(c,s,a)];return Math.min(...l)})(t,e,n,o)<=i}function W_t(t,e,n,o){const i=Gse(t,e,n),r=Gse(t,e,o),s=Gse(n,o,t),a=Gse(n,o,e);return i!==r&&s!==a||!(i!==0||!Yse(t,n,e))||!(r!==0||!Yse(t,o,e))||!(s!==0||!Yse(n,t,o))||!(a!==0||!Yse(n,e,o))}function Gse(t,e,n){const o=(e.y-t.y)*(n.x-e.x)-(e.x-t.x)*(n.y-e.y);return o===0?0:o>0?1:2}function Yse(t,e,n){return e.x<=Math.max(t.x,n.x)&&e.x>=Math.min(t.x,n.x)&&e.y<=Math.max(t.y,n.y)&&e.y>=Math.min(t.y,n.y)}function ZF(t,e,n){const o=(n.x-e.x)**2+(n.y-e.y)**2;if(o===0)return j_t(t,e);let i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/o;return i=Math.max(0,Math.min(1,i)),j_t(t,{x:e.x+i*(n.x-e.x),y:e.y+i*(n.y-e.y)})}function j_t(t,e){const n=t.x-e.x,o=t.y-e.y;return Math.sqrt(n*n+o*o)}function $_t(t){const e=new Map;let n=0;function o(i){for(const[,s]of e)if(s.has(i))return s;const r=new Set;return e.set("connectivity_net"+n++,r),r}for(const i of t){let r=null;for(const s of i){if(r){if(!r.has(s)){const a=o(s);if(a!==r){for(const A of a)r.add(A);e.delete(Array.from(e.entries()).find(([,A])=>A===a)[0])}}}else r=o(s);r.add(s)}}return Object.fromEntries(Array.from(e.entries()).map(([i,r])=>[i,Array.from(r)]))}var TD=class{netMap;idToNetMap;constructor(e){this.netMap=e,this.idToNetMap={};for(const[n,o]of Object.entries(e))for(const i of o)this.idToNetMap[i]=n}addConnections(e){for(const n of e){const o=new Set;for(const r of n){const s=this.idToNetMap[r];s&&o.add(s)}let i;if(o.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(o.size===1)i=o.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=o.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(const r of o)if(r!==i){this.netMap[i].push(...this.netMap[r]),this.netMap[r]=this.netMap[i];for(const s of this.netMap[i])this.idToNetMap[s]=i}}for(const r of n)this.netMap[i].includes(r)||this.netMap[i].push(r),this.idToNetMap[r]=i}}getIdsConnectedToNet(e){return this.netMap[e]||[]}getNetConnectedToId(e){return this.idToNetMap[e]}areIdsConnected(e,n){if(e===n)return!0;const o=this.getNetConnectedToId(e);if(!o)return!1;const i=this.getNetConnectedToId(n);return!!i&&(o===i||i===e||i===e)}areAllIdsConnected(e){const n=this.getNetConnectedToId(e[0]);for(const o of e){const i=this.getNetConnectedToId(o);if(i===void 0||i!==n)return!1}return!0}},eL=t=>{const e=[];for(const o of t)if(o.type==="source_trace")e.push([o.source_trace_id,...o.connected_source_port_ids??[],...o.connected_source_net_ids??[]].filter(Boolean));else if(o.type==="pcb_port"){const{pcb_port_id:i,source_port_id:r}=o;r&&i&&e.push([r,i])}else if(o.type==="pcb_smtpad"){const{pcb_smtpad_id:i,pcb_port_id:r}=o;r&&i&&e.push([i,r])}else if(o.type==="pcb_plated_hole"){const{pcb_plated_hole_id:i,pcb_port_id:r}=o;r&&i&&e.push([i,r])}else if(o.type==="pcb_trace"){const{pcb_trace_id:i,source_trace_id:r}=o;r&&i&&e.push([i,r])}const n=$_t(e);return new TD(n)},aXn=class{circuitJson;traceIdToElm;portIdToElm;connMap;constructor(e){this.circuitJson=e||[],this.traceIdToElm=new Map,this.portIdToElm=new Map,e?(this._buildTraceMap(),this._buildPortMap(),this.connMap=this._buildTraceConnectivityMap()):this.connMap=new TD({})}_buildPortMap(){for(const e of this.circuitJson)e.type==="pcb_port"&&this.portIdToElm.set(e.pcb_port_id,e)}_buildTraceMap(){for(const e of this.circuitJson)e.type==="pcb_trace"&&this.traceIdToElm.set(e.pcb_trace_id,e)}_buildTraceConnectivityMap(){const e=[],n=Array.from(this.traceIdToElm.keys());for(let o=0;o<n.length;o++)for(let i=o+1;i<n.length;i++){const r=this.traceIdToElm.get(n[o]),s=this.traceIdToElm.get(n[i]);this._arePcbTracesConnected(r,s)&&e.push([n[o],n[i]])}for(const o of this.portIdToElm.values())for(const i of this.traceIdToElm.values())for(const r of i.route)r.route_type==="wire"&&(r.start_pcb_port_id===o.pcb_port_id?e.push([o.pcb_port_id,i.pcb_trace_id]):r.end_pcb_port_id===o.pcb_port_id&&e.push([i.pcb_trace_id,o.pcb_port_id]));return new TD($_t(e))}addTrace(e){this.traceIdToElm.set(e.pcb_trace_id,e);const n=[];for(const o of e.route)o.route_type==="wire"&&(o.start_pcb_port_id&&n.push([o.start_pcb_port_id,e.pcb_trace_id]),o.end_pcb_port_id&&n.push([o.end_pcb_port_id,e.pcb_trace_id]));this.connMap.addConnections(n)}_arePcbTracesConnected(e,n){for(let o=0;o<e.route.length-1;o++){const i=e.route[o],r=e.route[o+1];if(i.route_type==="wire"&&r.route_type==="wire")for(let s=0;s<n.route.length-1;s++){const a=n.route[s],A=n.route[s+1];if(a.route_type==="wire"&&A.route_type==="wire"&&sXn([i,r],[a,A],{lineThickness:(i.width+a.width)/2}))return!0}}return!1}areTracesConnected(e,n){return this.connMap.areIdsConnected(e,n)}getAllTracesConnectedToTrace(e){const n=this.connMap.getNetConnectedToId(e);return n?this.connMap.getIdsConnectedToNet(n).filter(o=>this.traceIdToElm.has(o)).map(o=>this.traceIdToElm.get(o)):[]}getAllTracesConnectedToPort(e){const n=this.connMap.getNetConnectedToId(e);return n?this.connMap.getIdsConnectedToNet(n).filter(o=>this.traceIdToElm.has(o)).map(o=>this.traceIdToElm.get(o)):[]}},q_t=t=>`${Math.round(100*t.x)},${Math.round(100*t.y)}`,Jm=t=>{const e=new TD({});for(const n of t.connections){for(const o of n.__rootConnectionNames??[])e.addConnections([[n.name,o]]);n.__netConnectionName&&e.addConnections([[n.name,n.__netConnectionName]]);for(const o of n.pointsToConnect)e.addConnections([[n.name,`${q_t(o)}:${"layers"in o?o.layers.map(i=>Kr(i,t.layerCount)).sort().join("-"):Kr(o.layer,t.layerCount)}`]]),"pcb_port_id"in o&&o.pcb_port_id&&e.addConnections([[n.name,o.pcb_port_id]]),o.pointId&&e.addConnections([[n.name,o.pointId]])}for(const n of t.obstacles){const o=n.offBoardConnectsTo??[],i=Array.from(new Set([n.obstacleId,...n.connectedTo,...o,`${q_t(n.center)}:${n.layers.map(r=>Kr(r,t.layerCount)).sort().join("-")}`].filter(Boolean)));i.length>0&&e.addConnections([i])}for(const n of t.traces??[]){const o=Array.from(new Set([n.pcb_trace_id,n.connection_name,...n.connectsTo??[]].filter(Boolean)));o.length>0&&e.addConnections([o])}return e},JQ=t=>{const e=new TD({});for(const n of t.connections){const o=n.externallyConnectedPointIds??[];e.addConnections(o)}for(const n of t.traces??[]){const o=n.connectsTo??[];o.length!==0&&e.addConnections([[n.pcb_trace_id,...o]])}return e},yr=class{MAX_ITERATIONS=1e3;solved=!1;failed=!1;iterations=0;progress=0;error=null;activeSubSolver;failedSubSolvers;timeToSolve;stats={};pendingEffects;cacheHit;cacheKey;cacheToSolveSpaceTransform;getSolverName(){return this.constructor.name}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.getSolverName()} error: ${e}`,console.error(this.error),this.failed=!0,e}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.getSolverName()} ran out of iterations (MAX_ITERATIONS=${this.MAX_ITERATIONS})`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){const e=Date.now();for(;!this.solved&&!this.failed;)this.step();const n=Date.now();this.timeToSolve=n-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function tL(t){const e=new Map;for(const n of t)for(const o of n.nodeIds)e.set(o,[...e.get(o)??[],n]);return e}var kD=class extends yr{getSolverName(){return"AvailableSegmentPointSolver"}nodes;edges;traceWidth;obstacleMargin;minPortSpacing;nodeMap;nodeEdgeMap;sharedEdgeSegments=[];edgeSegmentMap=new Map;portPointMap=new Map;colorMap;shouldReturnCrampedPortPoints;constructor({nodes:e,edges:n,traceWidth:o,obstacleMargin:i,colorMap:r,shouldReturnCrampedPortPoints:s}){super(),this.nodes=e,this.edges=n,this.traceWidth=o,this.obstacleMargin=i??.15,this.shouldReturnCrampedPortPoints=s,this.minPortSpacing=this.traceWidth+this.obstacleMargin,this.colorMap=r??{},this.nodeMap=new Map(e.map(a=>[a.capacityMeshNodeId,a])),this.nodeEdgeMap=tL(n),this.MAX_ITERATIONS=1}_step(){this.computeAllSharedEdgeSegments(),this.solved=!0}computeAllSharedEdgeSegments(){for(const e of this.edges){const[n,o]=e.nodeIds,i=this.nodeMap.get(n),r=this.nodeMap.get(o);if(!i||!r)continue;const s=this.computeSharedEdgeSegment(e,i,r);if(s){this.sharedEdgeSegments.push(s),this.edgeSegmentMap.set(e.capacityMeshEdgeId,s);for(const a of s.portPoints)this.portPointMap.set(a.segmentPortPointId,a)}}}computeSharedEdgeSegment(e,n,o){const i=this.findOverlappingSegment(n,o);if(!i)return null;const r=n.availableZ.filter(f=>o.availableZ.includes(f));if(r.length===0)return null;const s=Math.sqrt((i.end.x-i.start.x)**2+(i.end.y-i.start.y)**2),a=!!(n._isNarrowQfpPadGap||o._isNarrowQfpPadGap),A=3*this.minPortSpacing/4,c=Math.max(0,s-2*A);if(c<=0&&!n._containsTarget&&!o._containsTarget){if(!this.shouldReturnCrampedPortPoints)return null;const f=[];for(const I of r)f.push({segmentPortPointId:`${e.capacityMeshEdgeId}_pp0_z${I}_cramped`,x:(i.start.x+i.end.x)/2,y:(i.start.y+i.end.y)/2,availableZ:[I],nodeIds:[n.capacityMeshNodeId,o.capacityMeshNodeId],edgeId:e.capacityMeshEdgeId,connectionName:null,distToCentermostPortOnZ:0,cramped:!0});return{edgeId:e.capacityMeshEdgeId,nodeIds:[n.capacityMeshNodeId,o.capacityMeshNodeId],start:i.start,end:i.end,availableZ:r,portPoints:f}}let l=Math.max(1,Math.floor(c/this.minPortSpacing)+1);if(n._offBoardConnectionId||o._offBoardConnectionId){if(n._offBoardConnectionId&&!o._offBoardConnectionId){if(this.shouldSkipOffBoardPortPoint(n,o))return null}else if(o._offBoardConnectionId&&!n._offBoardConnectionId&&this.shouldSkipOffBoardPortPoint(o,n))return null;l=1}const u=[],g=i.end.x-i.start.x,h=i.end.y-i.start.y,d=(i.start.x+i.end.x)/2,p=(i.start.y+i.end.y)/2;l>5&&(l=5+Math.floor(l/4));const m=[];for(let f=0;f<l;f++){let I;I=s===0||l===1?.5:(A+c*f/(l-1))/s;const C=i.start.x+g*I,y=i.start.y+h*I,x=Math.sqrt((C-d)**2+(y-p)**2);m.push({x:C,y,distToCenter:x})}const _=m.reduce((f,I)=>I.distToCenter<f.distToCenter?I:f);for(let f=0;f<l;f++){const{x:I,y:C}=m[f],y=Math.sqrt((I-_.x)**2+(C-_.y)**2);for(const x of r){const E={segmentPortPointId:`${e.capacityMeshEdgeId}_pp${f}_z${x}`,x:I,y:C,availableZ:[x],nodeIds:[n.capacityMeshNodeId,o.capacityMeshNodeId],edgeId:e.capacityMeshEdgeId,connectionName:null,distToCentermostPortOnZ:y,cramped:a};u.push(E)}}return{edgeId:e.capacityMeshEdgeId,nodeIds:[n.capacityMeshNodeId,o.capacityMeshNodeId],start:i.start,end:i.end,availableZ:r,portPoints:u}}shouldSkipOffBoardPortPoint(e,n){const o=this.nodeEdgeMap.get(n.capacityMeshNodeId)??[];for(const i of o){const r=i.nodeIds[0]===n.capacityMeshNodeId?i.nodeIds[1]:i.nodeIds[0];if(r===e.capacityMeshNodeId)continue;const s=this.nodeMap.get(r);if(s?._offBoardConnectionId!==e._offBoardConnectionId||this.nodes.filter(A=>A._offBoardConnectionId===e._offBoardConnectionId).length!==2)continue;const a={x:(e.center.x+s.center.x)/2,y:(e.center.y+s.center.y)/2};if(a.x>=n.center.x-n.width/2&&a.x<=n.center.x+n.width/2&&a.y>=n.center.y-n.height/2&&a.y<=n.center.y+n.height/2)return!0}return!1}findOverlappingSegment(e,n){const o={start:Math.max(e.center.x-e.width/2,n.center.x-n.width/2),end:Math.min(e.center.x+e.width/2,n.center.x+n.width/2)},i={start:Math.max(e.center.y-e.height/2,n.center.y-n.height/2),end:Math.min(e.center.y+e.height/2,n.center.y+n.height/2)},r=o.end-o.start,s=i.end-i.start;if(r<-1e-4||s<-1e-4)return null;if(r<s){const a=(o.start+o.end)/2;return{start:{x:a,y:i.start},end:{x:a,y:i.end}}}{const a=(i.start+i.end)/2;return{start:{x:o.start,y:a},end:{x:o.end,y:a}}}}getAvailablePortPointsBetweenNodes(e,n){const o=this.edges.find(r=>r.nodeIds[0]===e&&r.nodeIds[1]===n||r.nodeIds[0]===n&&r.nodeIds[1]===e);if(!o)return[];const i=this.edgeSegmentMap.get(o.capacityMeshEdgeId);return i?i.portPoints.filter(r=>r.connectionName===null):[]}getPortPointsForEdge(e,n){const o=this.edges.find(r=>r.nodeIds[0]===e&&r.nodeIds[1]===n||r.nodeIds[0]===n&&r.nodeIds[1]===e);return o?this.edgeSegmentMap.get(o.capacityMeshEdgeId)?.portPoints??[]:[]}assignPortPoint(e,n,o){const i=this.portPointMap.get(e);return!!i&&i.connectionName===null&&(i.connectionName=n,i.rootConnectionName=o,!0)}releasePortPoint(e){const n=this.portPointMap.get(e);return!!n&&(n.connectionName=null,n.rootConnectionName=void 0,!0)}getAvailablePortCountForEdge(e,n){return this.getAvailablePortPointsBetweenNodes(e,n).length}getOutput(){return this.sharedEdgeSegments}visualize(){const e={lines:[],points:[],rects:[],circles:[]};for(const n of this.sharedEdgeSegments){e.lines.push({points:[n.start,n.end],strokeColor:"rgba(100, 100, 100, 0.5)"});for(const o of n.portPoints){const i=o.connectionName?this.colorMap[o.connectionName]??"blue":"rgba(0, 200, 0, 0.7)";o.cramped?e.rects.push({center:{x:o.x,y:o.y},width:.1,height:.1,fill:i,layer:`z${o.availableZ.join(",")}`,label:`cramped ${o.segmentPortPointId}`}):e.circles.push({center:{x:o.x,y:o.y},radius:this.traceWidth/2,fill:i,layer:`z${o.availableZ.join(",")}`,label:[o.segmentPortPointId,o.connectionName,o.availableZ.join(","),`cd: ${o.distToCentermostPortOnZ}`,`connects: ${o.nodeIds.join(",")}`].filter(Boolean).join(`
`)})}}return e}};function Use(t,e){const n=t.center.x-t.width/2,o=t.center.x+t.width/2,i=t.center.y-t.height/2,r=t.center.y+t.height/2,s=e.center.x-e.width/2,a=e.center.x+e.width/2,A=e.center.y-e.height/2,c=e.center.y+e.height/2,l=.001,u=(Math.abs(o-s)<l||Math.abs(n-a)<l)&&Math.min(r,c)-Math.max(i,A)>=l,g=(Math.abs(r-A)<l||Math.abs(i-c)<l)&&Math.min(o,a)-Math.max(n,s)>=l;return u||g}var AXn=class extends yr{constructor(e){super(),this.nodes=e,this.edges=[]}nodes;getSolverName(){return"CapacityMeshEdgeSolver"}edges;nodeMap;getNextCapacityMeshEdgeId(){return`ce${this.edges.length}`}_step(){this.edges=[];for(let e=0;e<this.nodes.length;e++)for(let n=e+1;n<this.nodes.length;n++)!(this.nodes[e]._strawNode&&this.nodes[n]._strawNode&&this.nodes[e]._strawParentCapacityMeshNodeId===this.nodes[n]._strawParentCapacityMeshNodeId)&&Use(this.nodes[e],this.nodes[n])&&this.doNodesHaveSharedLayer(this.nodes[e],this.nodes[n])&&this.edges.push({capacityMeshEdgeId:this.getNextCapacityMeshEdgeId(),nodeIds:[this.nodes[e].capacityMeshNodeId,this.nodes[n].capacityMeshNodeId]});this.handleTargetNodes(),this.solved=!0}handleTargetNodes(){const e=this.nodes.filter(o=>o._containsTarget),n=new Map(this.nodes.map(o=>[o.capacityMeshNodeId,o]));for(let o=0;o<e.length;o++)for(let i=o+1;i<e.length;i++){const r=e[o],s=e[i];this.doNodesHaveSharedLayer(r,s)&&this.doNodesTouchOrOverlap(r,s)&&(this.hasEdgeBetween(r,s)||this.edges.push({capacityMeshEdgeId:this.getNextCapacityMeshEdgeId(),nodeIds:[r.capacityMeshNodeId,s.capacityMeshNodeId]}))}for(const o of e)if(!(!o._containsObstacle||!o._targetConnectionName)&&!this.edges.some(i=>{if(!i.nodeIds.includes(o.capacityMeshNodeId))return!1;const r=i.nodeIds[0]===o.capacityMeshNodeId?i.nodeIds[1]:i.nodeIds[0],s=n.get(r);return!!s&&!s._containsObstacle&&!s._containsTarget&&this.doNodesHaveSharedLayer(o,s)}))throw new Error(`Target obstacle region "${o.capacityMeshNodeId}" for connection "${o._targetConnectionName}" has no bordering routing edge`)}doNodesHaveSharedLayer(e,n){return e.availableZ.some(o=>n.availableZ.includes(o))}hasEdgeBetween(e,n){return this.edges.some(o=>o.nodeIds.includes(e.capacityMeshNodeId)&&o.nodeIds.includes(n.capacityMeshNodeId))}doNodesTouchOrOverlap(e,n){const i=e.center.x-e.width/2,r=e.center.x+e.width/2,s=e.center.y-e.height/2,a=e.center.y+e.height/2,A=n.center.x-n.width/2,c=n.center.x+n.width/2,l=n.center.y-n.height/2,u=n.center.y+n.height/2;return i<=c+.001&&r+.001>=A&&s<=u+.001&&a+.001>=l}visualize(){const e=new Map;for(const o of this.edges)for(const i of o.nodeIds)e.set(i,1+(e.get(i)??0));const n={lines:[],points:[],rects:this.nodes.map(o=>{const i=Math.min(...o.availableZ);return{width:Math.max(o.width-2,.8*o.width),height:Math.max(o.height-2,.8*o.height),center:{x:o.center.x+i*o.width*.05,y:o.center.y-i*o.width*.05},fill:o._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[o.availableZ.join(",")]??"rgba(0,200,200,0.1)",label:[o.capacityMeshNodeId,`availableZ: ${o.availableZ.join(",")}`,`target? ${o._containsTarget??!1}`,`obs? ${o._containsObstacle??!1}`,`conn: ${e.get(o.capacityMeshNodeId)??0}`].join(`
`),layer:`z${o.availableZ.join(",")}`}}),circles:[]};if(!this.nodeMap){this.nodeMap=new Map;for(const o of this.nodes)this.nodeMap.set(o.capacityMeshNodeId,o)}for(const o of this.edges){const i=this.nodeMap.get(o.nodeIds[0]),r=this.nodeMap.get(o.nodeIds[1]);if(i?.center&&r?.center){const s=Math.min(...i.availableZ),a=Math.min(...r.availableZ),A={x:i.center.x+s*i.width*.05,y:i.center.y-s*i.width*.05},c={x:r.center.x+a*r.width*.05,y:r.center.y-a*r.width*.05},l=Array.from(new Set([...i.availableZ,...r.availableZ])).sort();n.lines.push({layer:`z${l.join(",")}`,points:[A,c],strokeDash:i.availableZ.join(",")===r.availableZ.join(",")?void 0:"10 5"})}}return n}},B7e=class{constructor(e){this.nodes=e,this.buckets=new Map;for(const n of e){const o=n.center.x-n.width/2,i=n.center.y-n.height/2,r=n.center.x+n.width/2,s=n.center.y+n.height/2,a=Math.floor(o/this.CELL_SIZE),A=Math.floor(r/this.CELL_SIZE),c=Math.floor(i/this.CELL_SIZE),l=Math.floor(s/this.CELL_SIZE);for(let u=a;u<=A;u++)for(let g=c;g<=l;g++){const h=`${u}x${g}`,d=this.buckets.get(h);d?d.push(n):this.buckets.set(h,[n])}}}nodes;buckets;CELL_SIZE=.4;getBucketKey(e,n){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(n/this.CELL_SIZE)}`}getNodesInArea(e,n,o,i){const r=[],s=new Set,a=e-o/2,A=n-i/2,c=e+o/2,l=n+i/2,u=Math.floor(a/this.CELL_SIZE),g=Math.floor(c/this.CELL_SIZE),h=Math.floor(A/this.CELL_SIZE),d=Math.floor(l/this.CELL_SIZE);for(let p=u;p<=g;p++)for(let m=h;m<=d;m++){const _=`${p}x${m}`,f=this.buckets.get(_)||[];for(const I of f)s.has(I.capacityMeshNodeId)||(s.add(I.capacityMeshNodeId),r.push(I))}return r}},WQ=class extends AXn{constructor(e){super(e),this.nodes=e,this.MAX_ITERATIONS=1e7,this.nodeTree=new B7e(this.nodes),this.currentNodeIndex=0,this.edgeSet=new Set}nodes;getSolverName(){return"CapacityMeshEdgeSolver2_NodeTreeOptimization"}nodeTree;currentNodeIndex;edgeSet;_step(){if(this.currentNodeIndex>=this.nodes.length)return this.handleTargetNodes(),void(this.solved=!0);const e=this.nodes[this.currentNodeIndex],n=this.nodeTree.getNodesInArea(e.center.x,e.center.y,2*e.width,2*e.height);for(const o of n){if(!Use(e,o))continue;const i=e._strawNode&&o._strawNode&&e._strawParentCapacityMeshNodeId===o._strawParentCapacityMeshNodeId;e.capacityMeshNodeId===o.capacityMeshNodeId||i||!this.doNodesHaveSharedLayer(e,o)||this.edgeSet.has(`${e.capacityMeshNodeId}-${o.capacityMeshNodeId}`)||(this.edgeSet.add(`${e.capacityMeshNodeId}-${o.capacityMeshNodeId}`),this.edgeSet.add(`${o.capacityMeshNodeId}-${e.capacityMeshNodeId}`),this.edges.push({capacityMeshEdgeId:this.getNextCapacityMeshEdgeId(),nodeIds:[e.capacityMeshNodeId,o.capacityMeshNodeId]}))}this.currentNodeIndex++}},Il=(...t)=>{const e={points:[],lines:[],circles:[],rects:[],polygons:[],infiniteLines:[],arrows:[],texts:[]};return t.forEach((n,o)=>{n&&(n.lines&&(e.lines=[...e.lines||[],...n.lines.map(i=>({...i,step:o}))]),n.points&&(e.points=[...e.points||[],...n.points.map(i=>({...i,step:o}))]),n.circles&&(e.circles=[...e.circles||[],...n.circles.map(i=>({...i,step:o}))]),n.rects&&(e.rects=[...e.rects||[],...n.rects.map(i=>({...i,step:o}))]),n.polygons&&(e.polygons=[...e.polygons||[],...n.polygons.map(i=>({...i,step:o}))]),n.infiniteLines&&(e.infiniteLines=[...e.infiniteLines||[],...n.infiniteLines.map(i=>({...i,step:o}))]),n.arrows&&(e.arrows=[...e.arrows||[],...n.arrows.map(i=>({...i,step:o}))]),n.texts&&(e.texts=[...e.texts||[],...n.texts.map(i=>({...i,step:o}))]))}),e};function Kse(t,e,n){const o=[];let i=null;for(let r=0;r<t.length;r++){const s=t[r];i?i.z===s.z?i.points.push({x:s.x,y:s.y}):(o.push(i),i={points:[{x:s.x,y:s.y}],z:s.z,connectionName:e,color:n}):i={points:[{x:s.x,y:s.y}],z:s.z,connectionName:e,color:n},r===t.length-1&&i&&o.push(i)}return o}function s7(t,e){return{x:t.a*e.x+t.b*e.y+t.c,y:t.d*e.x+t.e*e.y+t.f}}var b7e=(t,e,n)=>{const[o,i]=t;if(o===i)return;const r=((s,a)=>{const A=s.portPointId??`${s.connectionName}:${s.x}:${s.y}:${s.z}`,c=a.portPointId??`${a.connectionName}:${a.x}:${a.y}:${a.z}`;return A<c?`${A}|${c}`:`${c}|${A}`})(o,i);e.has(r)||(e.add(r),n.push(t))},X_t=(t,e,n)=>{for(let o=0;o<t.length-1;o++)b7e([t[o],t[o+1]],e,n)},Z_t=t=>{const e=[],n=new Set,o=(s=>{const a=new Map;for(const A of s)A.portPointId&&a.set(A.portPointId,A);return a})(t);for(const s of t){if(s.prevPortPointId){const a=o.get(s.prevPortPointId);a&&a.connectionName===s.connectionName&&b7e([a,s],n,e)}if(s.nextPortPointId){const a=o.get(s.nextPortPointId);a&&a.connectionName===s.connectionName&&b7e([s,a],n,e)}}if(e.length===0)return X_t(t,n,e),e;const i=(s=>{const a=new Set;for(const[A,c]of s)A.portPointId&&a.add(A.portPointId),c.portPointId&&a.add(c.portPointId);return a})(e),r=t.filter(s=>!s.portPointId||!i.has(s.portPointId));return X_t(r,n,e),e};function Vse(t,e,n){return Math.max(e,Math.min(n,t))}function eft(t){const e=t.planeSize*t.layers,n=t.connectionCount,o=Math.sqrt(n),i=Math.max(1,t.maxIterations),r=Vse(Math.round(e*(8+1.2*o)),15e4,12e6),s=Vse(Math.round(r*t.effort),15e4,12e6),a=Vse(Math.round(.2*i),15e4,2e6);return{maxIterationsIters:Math.max(1,Math.min(i,Math.max(a,s))),baseSearchBudgetIters:Vse(Math.round(e*(10+.8*o)*t.effort),5e4,4e6)}}function tft(t,e){for(let n=t;n;n=n.prev)if(n.id===e)return!0;return!1}var cXn=class{f=[];seq=[];id=[];n=0;push(e,n,o){let i=this.n++;for(this.f[i]=e,this.seq[i]=n,this.id[i]=o;i>0;){const r=i-1>>1;if(this.less(r,i))break;this.swap(i,r),i=r}}pop(){const e=this.id[0];return this.n--,this.n>0&&(this.f[0]=this.f[this.n],this.seq[0]=this.seq[this.n],this.id[0]=this.id[this.n],this.siftDown(0)),e}get size(){return this.n}clear(){this.n=0}siftDown(e){for(;;){const n=2*e+1,o=n+1;if(n>=this.n)return;let i=n;if(o<this.n&&!this.less(n,o)&&(i=o),this.less(e,i))return;this.swap(e,i),e=i}}less(e,n){const o=this.f[e],i=this.f[n];return o!==i?o<i:this.seq[e]<this.seq[n]}swap(e,n){const o=this.f[e];this.f[e]=this.f[n],this.f[n]=o;const i=this.seq[e];this.seq[e]=this.seq[n],this.seq[n]=i;const r=this.id[e];this.id[e]=this.id[n],this.id[n]=r}},lXn=[-1,-1,-1,0,0,1,1,1],uXn=[-1,0,1,-1,1,-1,0,1],S7e=class extends zA{getSolverName(){return"HighDensitySolverA01"}nodeWithPortPoints;cellSizeMm;viaDiameter;MAX_RIPS;maxCellCount;traceThickness;traceMargin;viaMinDistFromBorder;showPenaltyMap;showUsedCellMap;effort;stepMultiplier;hyperParameters;initialPenaltyFn;rows;cols;layers;gridOrigin;gridToBoundsTransform;availableZ;zToLayer;layerToZ;connNameToId;connIdToName;connIdToRootNet;overlapFriendlyRootNets;planeSize;usedCellsFlat;portOwnerFlat;usedDiagFlat;penalty2d;visitedStamp;sharedCrossRootPortCells;stamp=0;viaOffsetsDr;viaOffsetsDc;viaOffsetsLen;minViaRow;maxViaRow;minViaCol;maxViaCol;usedIndicesByConn;usedDiagIndicesByConn;unsolvedSegs;solvedRoutes;activeConnSeg=null;activeConnId=-1;crossLayerSearch=!1;nodePool;heap;seqCounter=0;_viaOccs=[];ripCount;totalRipEvents=0;searchIterations=0;consecutiveSkips=0;penaltyCap;baseSearchBudgetIters;_moveCost=0;_moveRipped=null;get unsolvedConnections(){return this.unsolvedSegs}get solvedConnectionsMap(){return this.solvedRoutes}get activeConnection(){if(!this.activeConnSeg)return null;const e=this.activeConnSeg;return{connectionName:this.connIdToName[e.connId]??"",start:{row:e.startRow,col:e.startCol,z:e.startZ,x:0,y:0},end:{row:e.endRow,col:e.endCol,z:e.endZ,x:0,y:0}}}get openSet(){return{length:this.heap?.size??0}}get gridStats(){return{cells:this.planeSize||0,layers:this.layers||0,states:(this.planeSize||0)*(this.layers||0)}}constructor(e){super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.cellSizeMm=e.cellSizeMm,this.viaDiameter=e.viaDiameter,this.maxCellCount=e.maxCellCount,this.traceThickness=e.traceThickness??.1,this.traceMargin=e.traceMargin??.15,this.viaMinDistFromBorder=e.viaMinDistFromBorder??.15,this.showPenaltyMap=e.showPenaltyMap??!1,this.showUsedCellMap=e.showUsedCellMap??!1,this.effort=e.effort??1,this.stepMultiplier=Math.max(1,Math.floor(e.stepMultiplier??1)),this.hyperParameters={shuffleSeed:0,ripCost:10,ripTracePenalty:.5,ripViaPenalty:.75,viaBaseCost:.1,greedyMultiplier:1.5,...e.hyperParameters},this.MAX_ITERATIONS=1e8,this.MAX_RIPS=200,this.initialPenaltyFn=e.initialPenaltyFn}getConstructorParams(){return[{nodeWithPortPoints:this.nodeWithPortPoints,cellSizeMm:this.cellSizeMm,viaDiameter:this.viaDiameter,maxCellCount:this.maxCellCount,stepMultiplier:this.stepMultiplier,traceThickness:this.traceThickness,traceMargin:this.traceMargin,viaMinDistFromBorder:this.viaMinDistFromBorder,showPenaltyMap:this.showPenaltyMap,showUsedCellMap:this.showUsedCellMap,effort:this.effort,hyperParameters:this.hyperParameters,initialPenaltyFn:this.initialPenaltyFn}]}_setup(){const{nodeWithPortPoints:e,cellSizeMm:n}=this,{width:o,height:i,center:r}=e;this.availableZ=e.availableZ??[...new Set(e.portPoints.map(d=>d.z))].sort((d,p)=>d-p),this.rows=Math.floor(i/n),this.cols=Math.floor(o/n),this.layers=this.availableZ.length,this.planeSize=this.rows*this.cols;const s=this.layers*this.planeSize;if(this.maxCellCount!==void 0&&s>this.maxCellCount)return this.error=`Cell count ${s} exceeds maxCellCount ${this.maxCellCount}`,void(this.failed=!0);const a=this.layers*Math.max(0,this.rows-1)*Math.max(0,this.cols-1)*2;this.zToLayer=new Map,this.layerToZ=new Map;for(let d=0;d<this.availableZ.length;d++){const p=this.availableZ[d];this.zToLayer.set(p,d),this.layerToZ.set(d,p)}if(this.gridOrigin={x:r.x-o/2,y:r.y-i/2},this.gridToBoundsTransform=(function(d){const{originX:p,originY:m,rows:_,cols:f,cellSizeMm:I,width:C,height:y}=d;let x,E,B,S;return f>1?(x=C/((f-1)*I),E=p*(1-x)-.5*I*x):(x=1,E=p+C/2-(p+.5*I)),_>1?(B=y/((_-1)*I),S=m*(1-B)-.5*I*B):(B=1,S=m+y/2-(m+.5*I)),{a:x,b:0,c:E,d:0,e:B,f:S}})({originX:this.gridOrigin.x,originY:this.gridOrigin.y,rows:this.rows,cols:this.cols,cellSizeMm:n,width:o,height:i}),this.connNameToId=new Map,this.connIdToName=[],this.connIdToRootNet=[],this.overlapFriendlyRootNets=new Set,this.penalty2d=new Float64Array(this.planeSize),this.initialPenaltyFn)for(let d=0;d<this.rows;d++){const p=d*this.cols;for(let m=0;m<this.cols;m++){const _=this.gridOrigin.x+(m+.5)*n,f=this.gridOrigin.y+(d+.5)*n,I=(m+.5)/this.cols,C=(d+.5)/this.rows;this.penalty2d[p+m]=this.initialPenaltyFn({x:_,y:f,px:I,py:C,row:d,col:m})}}this.usedCellsFlat=new Int32Array(s).fill(-1),this.portOwnerFlat=new Int32Array(s).fill(-1),this.usedDiagFlat=new Int32Array(a).fill(-1),this.visitedStamp=new Uint32Array(s),this.stamp=0;const A=Math.ceil(this.viaDiameter/2/n),c=A*A,l=[],u=[];for(let d=-A;d<=A;d++)for(let p=-A;p<=A;p++)d*d+p*p<=c&&(l.push(d),u.push(p));if(this.viaOffsetsLen=l.length,this.viaOffsetsDr=new Int32Array(l),this.viaOffsetsDc=new Int32Array(u),this.viaMinDistFromBorder>0){const d=Math.ceil(this.viaMinDistFromBorder/n);this.minViaRow=d,this.maxViaRow=this.rows-1-d,this.minViaCol=d,this.maxViaCol=this.cols-1-d}else this.minViaRow=0,this.maxViaRow=this.rows-1,this.minViaCol=0,this.maxViaCol=this.cols-1;this.unsolvedSegs=this.buildConnectionSegs(),this.sharedCrossRootPortCells=new Set;const g=new Map;for(const d of this.nodeWithPortPoints.portPoints){const p=this.connNameToId.get(d.connectionName);if(p===void 0)continue;const m=this.pointToCell(d),_=(m.z*this.rows+m.row)*this.cols+m.col,f=this.connIdToRootNet[p],I=g.get(_);I===void 0?g.set(_,f):I!==f&&this.sharedCrossRootPortCells.add(_);const C=this.portOwnerFlat[_];this.portOwnerFlat[_]=C===-1||C===p?p:-2}this.solvedRoutes=new Map,this.usedIndicesByConn=[],this.usedDiagIndicesByConn=[],this.ripCount=[],this.consecutiveSkips=0,this.penaltyCap=.5*this.hyperParameters.ripCost,this.shuffleConnections();const h=eft({planeSize:this.planeSize,layers:this.layers,connectionCount:this.unsolvedSegs.length,effort:this.effort,maxIterations:this.MAX_ITERATIONS});this.baseSearchBudgetIters=h.baseSearchBudgetIters,this.MAX_ITERATIONS=h.maxIterationsIters,this.activeConnSeg=null,this.activeConnId=-1,this.nodePool=[],this.heap=new cXn,this.seqCounter=0}_step(){for(let e=0;e<this.stepMultiplier;e++){if(this.solved||this.failed)return;this.stepOnce()}}stepOnce(){if(!this.activeConnSeg){if(this.unsolvedSegs.length===0)return void(this.solved=!0);const C=this.unsolvedSegs.shift();this.activeConnSeg=C,this.activeConnId=C.connId,this.crossLayerSearch=C.startZ!==C.endZ,this.nodePool=[],this.heap.clear(),this.seqCounter=0,this.searchIterations=0,this.nextStamp();const y=this.computeH(C.startZ,C.startRow,C.startCol,C.endZ,C.endRow,C.endCol)*this.hyperParameters.greedyMultiplier;return this.nodePool.push({z:C.startZ,row:C.startRow,col:C.startCol,g:0,f:y,parentIdx:-1,ripped:null}),void this.heap.push(y,this.seqCounter++,0)}this.searchIterations++;const e=this.ripCount[this.activeConnId]??0,n=Math.round(this.baseSearchBudgetIters*(1+.25*Math.min(e,10)));if(this.searchIterations>n){const C=this.penalty2d;for(let y=0;y<C.length;y++)C[y]=.9*C[y];return this.unsolvedSegs.push(this.activeConnSeg),this.activeConnSeg=null,this.activeConnId=-1,this.heap.clear(),this.nodePool=[],this.consecutiveSkips++,void(this.consecutiveSkips>=3*this.unsolvedSegs.length&&(this.error=`Convergence failure: ${this.unsolvedSegs.length} connections stuck`,this.failed=!0))}if(this.heap.size===0)return this.error=`No path found for ${this.connIdToName[this.activeConnId]}`,void(this.failed=!0);const o=this.heap.pop(),i=this.nodePool[o],{z:r,row:s,col:a,g:A,ripped:c}=i,l=(r*this.rows+s)*this.cols+a;if(this.visitedStamp[l]===this.stamp)return;this.visitedStamp[l]=this.stamp;const u=this.activeConnSeg;if(r===u.endZ&&s===u.endRow&&a===u.endCol)return this.finalizeRoute(o),this.activeConnSeg=null,void(this.activeConnId=-1);const g=u.endZ,h=u.endRow,d=u.endCol,p=this.activeConnId,m=this.rows,_=this.cols,f=(this.cellSizeMm,this.visitedStamp),I=this.stamp;for(let C=0;C<8;C++){const y=s+lXn[C],x=a+uXn[C];if(y<0||y>=m||x<0||x>=_||f[(r*m+y)*_+x]===I||(this.computeMoveCostAndRips(p,r,s,a,r,y,x,c),this._moveCost<0))continue;const E=A+this._moveCost,B=E+this.computeH(r,y,x,g,h,d)*this.hyperParameters.greedyMultiplier,S=this.nodePool.length;this.nodePool.push({z:r,row:y,col:x,g:E,f:B,parentIdx:o,ripped:this._moveRipped}),this.heap.push(B,this.seqCounter++,S)}if(s>=this.minViaRow&&s<=this.maxViaRow&&a>=this.minViaCol&&a<=this.maxViaCol)for(let C=0;C<this.layers;C++){if(C===r||f[(C*m+s)*_+a]===I||(this.computeMoveCostAndRips(p,r,s,a,C,s,a,c),this._moveCost<0))continue;const y=A+this._moveCost,x=y+this.computeH(C,s,a,g,h,d)*this.hyperParameters.greedyMultiplier,E=this.nodePool.length;this.nodePool.push({z:C,row:s,col:a,g:y,f:x,parentIdx:o,ripped:this._moveRipped}),this.heap.push(x,this.seqCounter++,E)}}computeMoveCostAndRips(e,n,o,i,r,s,a,A){let c=0,l=A;const u=this.cols;if(n!==r){c+=this.hyperParameters.viaBaseCost,c+=Math.min(this.penalty2d[s*u+a],this.penaltyCap);const g=(r*this.rows+s)*u+a,h=this.portOwnerFlat[g],d=this.connIdToRootNet[h]===this.connIdToRootNet[e]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[e]),p=this.activeConnSeg,m=!!p&&r===p.endZ&&s===p.endRow&&a===p.endCol;if(h>=0&&h!==e&&!d&&!m)return this._moveCost=-1,void(this._moveRipped=l);this.fillViaOccupants(s,a,e);const _=this._viaOccs;for(let f=0;f<_.length;f++){const I=_[f];tft(l,I)||(c+=this.hyperParameters.ripCost,l={id:I,prev:l}),c+=this.hyperParameters.ripViaPenalty}}else{const g=o>s?o-s:s-o,h=i>a?i-a:a-i;c+=(g+h>1?Math.SQRT2:1)*this.cellSizeMm,c+=Math.min(this.penalty2d[s*u+a],this.penaltyCap);const d=(r*this.rows+s)*u+a,p=this.portOwnerFlat[d],m=this.connIdToRootNet[p]===this.connIdToRootNet[e]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[e]),_=this.activeConnSeg,f=!!_&&r===_.endZ&&s===_.endRow&&a===_.endCol;if(p>=0&&p!==e&&!m&&!f)return this._moveCost=-1,void(this._moveRipped=l);const I=this.usedCellsFlat[d],C=this.connIdToRootNet[I]===this.connIdToRootNet[e]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[e]);if(I===-1||I===e||C||(tft(l,I)||(c+=this.hyperParameters.ripCost,l={id:I,prev:l}),c+=this.hyperParameters.ripTracePenalty),g===1&&h===1){const y=o<s?o:s,x=i<a?i:a,E=1^(o<s&&i<a||o>s&&i>a?0:1),B=this.cols-1,S=2*((r*(this.rows-1)+y)*B+x),Q=this.usedDiagFlat[S+E],w=this.connIdToRootNet[Q]===this.connIdToRootNet[e]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[e]);if(Q!==-1&&Q!==e&&!w)return this._moveCost=-1,void(this._moveRipped=l)}}this._moveCost=c,this._moveRipped=l}fillViaOccupants(e,n,o){const i=this._viaOccs;i.length=0;const r=this.rows,s=this.cols,a=this.viaOffsetsDr,A=this.viaOffsetsDc,c=this.viaOffsetsLen,l=this.usedCellsFlat;for(let u=0;u<this.layers;u++){const g=u*this.planeSize;for(let h=0;h<c;h++){const d=e+a[h],p=n+A[h];if(d<0||p<0||d>=r||p>=s)continue;const m=l[g+d*s+p];if(m===-1||m===o||this.connIdToRootNet[m]===this.connIdToRootNet[o]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[o]))continue;let _=!1;for(let f=0;f<i.length;f++)if(i[f]===m){_=!0;break}_||i.push(m)}}}shouldSkipFixedPortHalo(e,n){const o=this.portOwnerFlat[e];return o===n?!1:o===-2?!0:o<0?!1:!(this.connIdToRootNet[o]===this.connIdToRootNet[n]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[n]))}nextStamp(){this.stamp=this.stamp+1>>>0,this.stamp===0&&(this.visitedStamp.fill(0),this.stamp=1)}computeH(e,n,o,i,r,s){const a=Math.abs(n-r)+Math.abs(o-s);if(e===i)return a*this.cellSizeMm;if(!this.crossLayerSearch)return a*this.cellSizeMm+this.hyperParameters.viaBaseCost;const A=Math.max(this.minViaRow,Math.min(this.maxViaRow,n)),c=Math.max(this.minViaCol,Math.min(this.maxViaCol,o)),l=Math.max(this.minViaRow,Math.min(this.maxViaRow,r)),u=Math.max(this.minViaCol,Math.min(this.maxViaCol,s)),g=Math.abs(n-A)+Math.abs(o-c)+Math.abs(A-r)+Math.abs(c-s),h=Math.abs(n-l)+Math.abs(o-u)+Math.abs(l-r)+Math.abs(u-s);return Math.max(Math.min(g,h),a)*this.cellSizeMm+this.hyperParameters.viaBaseCost}internConn(e,n){const o=this.connNameToId.get(e);if(o!==void 0)return o;const i=this.connIdToName.length;var r;return this.connIdToName.push(e),this.connIdToRootNet.push((r=e,n??r.replace(/_mst\d+$/,""))),this.connNameToId.set(e,i),i}buildConnectionSegs(){const e=new Map;for(const i of this.nodeWithPortPoints.portPoints){const r=i.connectionName;e.has(r)||e.set(r,{points:[],rootConnectionName:i.rootConnectionName}),e.get(r).points.push(i)}const n=[],o=new Set;for(const[i,r]of e){const s=r.points,a=Z_t(s);if(a.length===0)continue;const A=this.internConn(i,r.rootConnectionName);for(const[c,l]of a){const u=this.pointToCell(c),g=this.pointToCell(l),h=`${u.z}:${u.row}:${u.col}`,d=`${g.z}:${g.row}:${g.col}`,p=h<d?`${h}|${d}`:`${d}|${h}`,m=r.rootConnectionName??i,_=`${m}|${p}`;o.has(_)?this.overlapFriendlyRootNets.add(m):(o.add(_),n.push({connId:A,startZ:u.z,startRow:u.row,startCol:u.col,startPoint:c,endZ:g.z,endRow:g.row,endCol:g.col,endPoint:l}))}}return n}pointToCell(e){const n=Math.max(0,Math.min(this.cols-1,Math.round((e.x-this.gridOrigin.x)/this.cellSizeMm-.5))),o=Math.max(0,Math.min(this.rows-1,Math.round((e.y-this.gridOrigin.y)/this.cellSizeMm-.5)));return{z:this.zToLayer.get(e.z)??0,row:o,col:n}}shuffleConnections(){const e=this.unsolvedSegs;let n=this.hyperParameters.shuffleSeed;const o=()=>(n=1664525*n+1013904223&4294967295,(n>>>0)/4294967295);for(let i=e.length-1;i>0;i--){const r=Math.floor(o()*(i+1)),s=e[i];e[i]=e[r],e[r]=s}}finalizeRoute(e){this.consecutiveSkips=Math.max(0,this.consecutiveSkips-1);const n=[];let o=e;for(;o>=0;){const E=this.nodePool[o];n.push({z:E.z,row:E.row,col:E.col}),o=E.parentIdx}for(n.reverse();n.length>1;){const E=n[0],B=(E.z*this.rows+E.row)*this.cols+E.col;if(!this.sharedCrossRootPortCells.has(B))break;n.shift()}for(;n.length>1;){const E=n[n.length-1],B=(E.z*this.rows+E.row)*this.cols+E.col;if(!this.sharedCrossRootPortCells.has(B))break;n.pop()}const i=[];for(let E=1;E<n.length;E++)n[E].z!==n[E-1].z&&i.push({row:n[E].row,col:n[E].col});const r=n[0],s=n[n.length-1],a=this.activeConnId,A=[];for(let E=this.nodePool[e].ripped;E;E=E.prev)A.push(E.id);for(let E=0;E<A.length;E++)if(this.ripTrace(A[E]),this.failed)return;const c=Math.ceil(this.traceMargin/this.cellSizeMm),l=[],u=this.rows,g=this.cols,h=this.usedCellsFlat;for(let E=0;E<n.length;E++){const B=n[E];for(let S=-c;S<=c;S++)for(let Q=-c;Q<=c;Q++){const w=B.row+S,M=B.col+Q;if(w<0||w>=u||M<0||M>=g)continue;const k=(B.z*u+w)*g+M;if((w!==B.row||M!==B.col)&&this.shouldSkipFixedPortHalo(k,a))continue;const R=h[k],F=this.connIdToRootNet[R]===this.connIdToRootNet[a]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[a]);(R===-1||R===a||F)&&(h[k]=a,l.push(k))}}const d=[],p=this.viaOffsetsDr,m=this.viaOffsetsDc,_=this.viaOffsetsLen;for(let E=0;E<i.length;E++){const B=i[E];for(let S=0;S<this.layers;S++){const Q=S*this.planeSize;for(let w=0;w<_;w++){const M=B.row+p[w],k=B.col+m[w];if(M<0||M>=u||k<0||k>=g)continue;const R=Q+M*g+k;if((M!==B.row||k!==B.col)&&this.shouldSkipFixedPortHalo(R,a))continue;const F=h[R],O=this.connIdToRootNet[F]===this.connIdToRootNet[a]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[a]);if(F!==-1&&F!==a&&!O){let U=!1;for(let Y=0;Y<d.length;Y++)if(d[Y]===F){U=!0;break}U||d.push(F)}h[R]=a,l.push(R)}}}const f=[],I=this.cols-1;for(let E=1;E<n.length;E++){const B=n[E-1],S=n[E];if(B.z!==S.z)continue;const Q=B.row>S.row?B.row-S.row:S.row-B.row,w=B.col>S.col?B.col-S.col:S.col-B.col;if(Q!==1||w!==1)continue;const M=B.row<S.row?B.row:S.row,k=B.col<S.col?B.col:S.col,R=B.row<S.row&&B.col<S.col||B.row>S.row&&B.col>S.col?0:1,F=1^R,O=2*((B.z*(this.rows-1)+M)*I+k),U=O+F,Y=this.usedDiagFlat[U],W=this.connIdToRootNet[Y]===this.connIdToRootNet[a]&&this.overlapFriendlyRootNets.has(this.connIdToRootNet[a]);if(Y!==-1&&Y!==a&&!W)continue;const te=O+R;this.usedDiagFlat[te]=a,f.push(te)}for(;this.usedIndicesByConn.length<=a;)this.usedIndicesByConn.push([]);const C=this.usedIndicesByConn[a]??[];for(C.push(...l),this.usedIndicesByConn[a]=C;this.usedDiagIndicesByConn.length<=a;)this.usedDiagIndicesByConn.push([]);const y=this.usedDiagIndicesByConn[a]??[];y.push(...f),this.usedDiagIndicesByConn[a]=y;const x=this.solvedRoutes.get(a)??[];x.push({connId:a,startZ:r.z,startRow:r.row,startCol:r.col,startPoint:this.activeConnSeg.startPoint,endZ:s.z,endRow:s.row,endCol:s.col,endPoint:this.activeConnSeg.endPoint,cells:n,viaCells:i}),this.solvedRoutes.set(a,x);for(let E=0;E<d.length;E++)if(this.ripTrace(d[E]),this.failed)return;if(A.length>0||d.length>0){const E=this.penalty2d,B=this.penaltyCap;if(this.totalRipEvents>50)for(let S=0;S<E.length;S++)E[S]=.99*E[S];else for(let S=0;S<E.length;S++)E[S]>B&&(E[S]=.5*E[S])}}ripTrace(e){for(;this.ripCount.length<=e;)this.ripCount.push(0);if(this.ripCount[e]++,this.totalRipEvents++,this.totalRipEvents>=this.MAX_RIPS)return this.error=`Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`,void(this.failed=!0);const n=this.solvedRoutes.get(e)??[];if(n.length>0){const r=this.cols;for(const s of n){for(let a=0;a<s.cells.length;a++){const A=s.cells[a],c=A.row*r+A.col;this.penalty2d[c]=this.penalty2d[c]+this.hyperParameters.ripTracePenalty}for(let a=0;a<s.viaCells.length;a++){const A=s.viaCells[a],c=A.row*r+A.col;this.penalty2d[c]=this.penalty2d[c]+this.hyperParameters.ripViaPenalty}}}const o=this.usedIndicesByConn[e];if(o){const r=this.usedCellsFlat;for(let s=0;s<o.length;s++){const a=o[s];r[a]===e&&(r[a]=-1)}this.usedIndicesByConn[e]=[]}const i=this.usedDiagIndicesByConn[e];if(i){const r=this.usedDiagFlat;for(let s=0;s<i.length;s++){const a=i[s];r[a]===e&&(r[a]=-1)}this.usedDiagIndicesByConn[e]=[]}if(n.length>0){this.solvedRoutes.delete(e);for(const r of n)this.unsolvedSegs.push({connId:e,startZ:r.startZ,startRow:r.startRow,startCol:r.startCol,startPoint:r.startPoint,endZ:r.endZ,endRow:r.endRow,endCol:r.endCol,endPoint:r.endPoint})}}visualize(){const e=["red","blue","orange","green"],n=[],o=[],i=[],r=[],{width:s,height:a,center:A}=this.nodeWithPortPoints;r.push({center:{x:A.x,y:A.y},width:s,height:a,stroke:"gray"});const c=this.gridToBoundsTransform;if(this.showPenaltyMap&&this.penalty2d){let g=0;for(let h=0;h<this.penalty2d.length;h++)this.penalty2d[h]>g&&(g=this.penalty2d[h]);if(g>0)for(let h=0;h<this.rows;h++)for(let d=0;d<this.cols;d++){const p=this.penalty2d[h*this.cols+d];if(p<=0)continue;const m=Math.min(.6,p/g*.6),_=s7(c,{x:this.gridOrigin.x+(d+.5)*this.cellSizeMm,y:this.gridOrigin.y+(h+.5)*this.cellSizeMm});r.push({center:_,width:this.cellSizeMm*c.a,height:this.cellSizeMm*c.e,fill:`rgba(255,165,0,${m.toFixed(3)})`})}}if(this.showUsedCellMap&&this.usedCellsFlat)for(let g=0;g<this.layers;g++)for(let h=0;h<this.rows;h++)for(let d=0;d<this.cols;d++){if(this.usedCellsFlat[(g*this.rows+h)*this.cols+d]===-1)continue;const p=s7(c,{x:this.gridOrigin.x+(d+.5)*this.cellSizeMm,y:this.gridOrigin.y+(h+.5)*this.cellSizeMm});r.push({center:p,width:this.cellSizeMm*c.a,height:this.cellSizeMm*c.e,fill:"rgba(0,0,255,0.5)"})}for(const g of this.nodeWithPortPoints.portPoints)n.push({x:g.x,y:g.y,color:e[g.z]??"gray",label:g.connectionName});const l=["rgba(255,0,0,0.75)","rgba(0,0,255,0.75)","rgba(255,165,0,0.75)","rgba(0,128,0,0.75)"],u=this.getOutput();for(const g of u){if(g.route.length<2)continue;let h=0;for(let d=1;d<g.route.length;d++){const p=g.route[d-1];g.route[d].z!==p.z&&(d-h>=2&&o.push({points:g.route.slice(h,d).map(m=>({x:m.x,y:m.y})),strokeColor:l[p.z]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness}),h=d)}if(g.route.length-h>=2){const d=g.route[h].z;o.push({points:g.route.slice(h).map(p=>({x:p.x,y:p.y})),strokeColor:l[d]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness})}}for(const g of u)for(const h of g.vias)i.push({center:{x:h.x,y:h.y},radius:this.viaDiameter/2,fill:"rgba(0,0,0,0.3)",stroke:"black"});if(this.activeConnSeg&&this.visitedStamp){const g=this.stamp;for(let h=0;h<this.layers;h++)for(let d=0;d<this.rows;d++)for(let p=0;p<this.cols;p++){if(this.visitedStamp[(h*this.rows+d)*this.cols+p]!==g)continue;const m=s7(c,{x:this.gridOrigin.x+(p+.5)*this.cellSizeMm,y:this.gridOrigin.y+(d+.5)*this.cellSizeMm});n.push({x:m.x,y:m.y,color:"rgba(0,0,255,0.2)"})}}return{points:n,lines:o,circles:i,rects:r,coordinateSystem:"cartesian",title:`HighDensityA01 [${this.solvedRoutes?.size??0} solved, ${this.unsolvedSegs?.length??0} remaining]`}}getOutput(){const e=this.gridToBoundsTransform,n=[];for(const[o,i]of this.solvedRoutes??[]){const r=this.connIdToName[o];for(const s of i){const a=s.cells.map(A=>{const c=this.gridOrigin.x+(A.col+.5)*this.cellSizeMm,l=this.gridOrigin.y+(A.row+.5)*this.cellSizeMm,u=s7(e,{x:c,y:l});return{x:u.x,y:u.y,z:this.layerToZ.get(A.z)??A.z}});a.length>0&&(a[0]={...s.startPoint},a.length>1&&(a[a.length-1]={...s.endPoint})),n.push({connectionName:r,rootConnectionName:this.connIdToRootNet[o],regionId:this.nodeWithPortPoints.capacityMeshNodeId,traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,route:a,vias:s.viaCells.map(A=>{const c=this.gridOrigin.x+(A.col+.5)*this.cellSizeMm,l=this.gridOrigin.y+(A.row+.5)*this.cellSizeMm;return s7(e,{x:c,y:l})})})}}return n}},Q7e=["left","top","right","bottom","middle"],gXn=class{f=new Float64Array(1024);seq=new Uint32Array(1024);id=new Int32Array(1024);n=0;push(e,n,o){this.ensureCapacity(this.n+1);let i=this.n++;for(this.f[i]=e,this.seq[i]=n,this.id[i]=o;i>0;){const r=i-1>>1;if(this.less(r,i))break;this.swap(i,r),i=r}}pop(){const e=this.id[0];return this.n--,this.n>0&&(this.f[0]=this.f[this.n],this.seq[0]=this.seq[this.n],this.id[0]=this.id[this.n],this.siftDown(0)),e}get size(){return this.n}clear(){this.n=0}ensureCapacity(e){if(e<=this.f.length)return;let n=this.f.length;for(;n<e;)n*=2;const o=new Float64Array(n);o.set(this.f),this.f=o;const i=new Uint32Array(n);i.set(this.seq),this.seq=i;const r=new Int32Array(n);r.set(this.id),this.id=r}siftDown(e){for(;;){const n=2*e+1,o=n+1;if(n>=this.n)return;let i=n;if(o<this.n&&!this.less(n,o)&&(i=o),this.less(e,i))return;this.swap(e,i),e=i}}less(e,n){const o=this.f[e],i=this.f[n];return o!==i?o<i:this.seq[e]<this.seq[n]}swap(e,n){const o=this.f[e];this.f[e]=this.f[n],this.f[n]=o;const i=this.seq[e];this.seq[e]=this.seq[n],this.seq[n]=i;const r=this.id[e];this.id[e]=this.id[n],this.id[n]=r}},dXn=class{z=new Int32Array(1024);cellId=new Int32Array(1024);g=new Float64Array(1024);parent=new Int32Array(1024);ripHead=new Int32Array(1024).fill(-1);ripCount=new Int32Array(1024);length=0;clear(){this.length=0}push(e,n,o,i,r,s){this.ensureCapacity(this.length+1);const a=this.length++;return this.z[a]=e,this.cellId[a]=n,this.g[a]=o,this.parent[a]=i,this.ripHead[a]=r,this.ripCount[a]=s,a}ensureCapacity(e){if(e<=this.z.length)return;let n=this.z.length;for(;n<e;)n*=2;const o=new Int32Array(n);o.set(this.z),this.z=o;const i=new Int32Array(n);i.set(this.cellId),this.cellId=i;const r=new Float64Array(n);r.set(this.g),this.g=r;const s=new Int32Array(n);s.set(this.parent),this.parent=s;const a=new Int32Array(n);a.fill(-1),a.set(this.ripHead.subarray(0,this.length)),this.ripHead=a;const A=new Int32Array(n);A.set(this.ripCount.subarray(0,this.length)),this.ripCount=A}},hXn=class{connId=new Int32Array(1024);prev=new Int32Array(1024).fill(-1);length=0;clear(){this.length=0}append(e,n){this.ensureCapacity(this.length+1);const o=this.length++;return this.connId[o]=n,this.prev[o]=e,o}contains(e,n){for(let o=e;o>=0;o=this.prev[o])if(this.connId[o]===n)return!0;return!1}collect(e,n){n.length=0;for(let o=e;o>=0;o=this.prev[o])n.push(this.connId[o])}ensureCapacity(e){if(e<=this.connId.length)return;let n=this.connId.length;for(;n<e;)n*=2;const o=new Int32Array(n);o.set(this.connId),this.connId=o;const i=new Int32Array(n);i.fill(-1),i.set(this.prev.subarray(0,this.length)),this.prev=i}};function a7(t,e,n){return Math.max(e,Math.min(n,t))}function zse(t,e){for(let n=0;n<t.length;n++)if(t[n]===e)return;t.push(e)}function nft(t,e){for(let n=0;n<t.length;n++)if(t[n].cellId===e.cellId)return;t.push(e)}function v7e(t,e,n,o,i,r,s){const a=t-a7(t,o,r),A=e-a7(e,i,s);return a*a+A*A<=n*n}var w7e=class extends zA{getSolverName(){return"HighDensitySolverA03"}nodeWithPortPoints;highResolutionCellSize;highResolutionCellThickness;lowResolutionCellSize;viaDiameter;MAX_RIPS;maxCellCount;traceThickness;traceMargin;viaMinDistFromBorder;showPenaltyMap;showUsedCellMap;effort;stepMultiplier;hyperParameters;initialPenaltyFn;boundsMinX;boundsMaxX;boundsMinY;boundsMaxY;gridToBoundsTransform;availableZ;zToLayer;layerToZ;layers;fineRows;fineCols;lowScale;bandRows;bandCols;regions;planeSize;cellCenterX;cellCenterY;cellMinX;cellMinY;cellMaxX;cellMaxY;cellWidth;cellHeight;cellRegion;cellRow;cellCol;viaAllowed;neighborOffset;neighborIds;neighborCosts;usedCellsFlat;sharedCellsFlat;portOwnerFlat;penalty2d;ripStateBuckets;visitedStamp;bestGStamp;bestGValue;visitedFlatStamp;sharedCrossRootPortFlat;stamp=0;connNameToId;connIdToName;connIdToRootNet;overlapFriendlyRootNets;usedIndicesByConn;unsolvedSegs;solvedRoutes;activeConnSeg=null;activeConnId=-1;nodePool;heap;ripChain;seqCounter=0;_viaOccs=[];_cellOccs=[];_rippedIds=[];ripCount;totalRipEvents=0;searchIterations=0;consecutiveSkips=0;penaltyCap;baseSearchBudgetIters;_moveCost=0;_moveRippedHead=-1;_moveRipCount=0;traceKeepoutRadius;viaKeepoutRadius;get unsolvedConnections(){return this.unsolvedSegs}get solvedConnectionsMap(){const e=new Map;for(let n=0;n<this.solvedRoutes.length;n++){const o=this.getSolvedRoutesForConn(n);o.length>0&&e.set(n,o)}return e}get activeConnection(){if(!this.activeConnSeg)return null;const e=this.activeConnSeg.startCellId,n=this.activeConnSeg.endCellId;return{connectionName:this.connIdToName[this.activeConnSeg.connId]??"",start:{cellId:e,region:Q7e[this.cellRegion[e]],row:this.cellRow[e],col:this.cellCol[e],x:this.cellCenterX[e],y:this.cellCenterY[e],z:this.activeConnSeg.startZ},end:{cellId:n,region:Q7e[this.cellRegion[n]],row:this.cellRow[n],col:this.cellCol[n],x:this.cellCenterX[n],y:this.cellCenterY[n],z:this.activeConnSeg.endZ}}}get openSet(){return{length:this.heap?.size??0}}get gridStats(){return{cells:this.planeSize||0,layers:this.layers||0,states:(this.planeSize||0)*(this.layers||0),ripStateBuckets:this.ripStateBuckets||0,neighborEdges:this.neighborIds?.length??0,regionCounts:this.regions?Object.fromEntries(this.regions.map(e=>[e.name,e.rows*e.cols])):{}}}constructor(e){super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.highResolutionCellSize=e.highResolutionCellSize??.1,this.highResolutionCellThickness=Math.max(1,Math.floor(e.highResolutionCellThickness??8)),this.lowResolutionCellSize=e.lowResolutionCellSize??.4,this.viaDiameter=e.viaDiameter,this.maxCellCount=e.maxCellCount,this.traceThickness=e.traceThickness??.1,this.traceMargin=e.traceMargin??.15,this.viaMinDistFromBorder=e.viaMinDistFromBorder??.15,this.showPenaltyMap=e.showPenaltyMap??!1,this.showUsedCellMap=e.showUsedCellMap??!1,this.effort=e.effort??1,this.stepMultiplier=Math.max(1,Math.floor(e.stepMultiplier??1)),this.hyperParameters={shuffleSeed:0,ripCost:8,ripTracePenalty:.5,ripViaPenalty:.75,viaBaseCost:.1,greedyMultiplier:1.5,...e.hyperParameters},this.MAX_ITERATIONS=1e8,this.MAX_RIPS=200,this.initialPenaltyFn=e.initialPenaltyFn}getConstructorParams(){return[{nodeWithPortPoints:this.nodeWithPortPoints,highResolutionCellSize:this.highResolutionCellSize,highResolutionCellThickness:this.highResolutionCellThickness,lowResolutionCellSize:this.lowResolutionCellSize,viaDiameter:this.viaDiameter,maxCellCount:this.maxCellCount,stepMultiplier:this.stepMultiplier,traceThickness:this.traceThickness,traceMargin:this.traceMargin,viaMinDistFromBorder:this.viaMinDistFromBorder,showPenaltyMap:this.showPenaltyMap,showUsedCellMap:this.showUsedCellMap,effort:this.effort,hyperParameters:this.hyperParameters,initialPenaltyFn:this.initialPenaltyFn}]}_setup(){const{nodeWithPortPoints:e}=this,{width:n,height:o,center:i}=e,r=this.lowResolutionCellSize/this.highResolutionCellSize,s=Math.round(r);if(!Number.isFinite(r)||r<=0||Math.abs(r-s)>1e-9)return this.error="lowResolutionCellSize must be a positive integer multiple of highResolutionCellSize",void(this.failed=!0);this.lowScale=Math.max(1,s),this.availableZ=e.availableZ??[...new Set(e.portPoints.map(h=>h.z))].sort((h,d)=>h-d),this.layers=this.availableZ.length,this.zToLayer=new Map,this.layerToZ=new Map;for(let h=0;h<this.availableZ.length;h++){const d=this.availableZ[h];this.zToLayer.set(d,h),this.layerToZ.set(h,d)}this.boundsMinX=i.x-n/2,this.boundsMaxX=i.x+n/2,this.boundsMinY=i.y-o/2,this.boundsMaxY=i.y+o/2,this.traceKeepoutRadius=this.traceMargin+this.traceThickness/2,this.viaKeepoutRadius=this.viaDiameter/2+this.traceKeepoutRadius,this.buildFiveRegionGrid(n,o),this.gridToBoundsTransform=this.computeGridToBoundsTransform();const a=this.layers*this.planeSize;if(this.maxCellCount!==void 0&&a>this.maxCellCount)return this.error=`Cell count ${a} exceeds maxCellCount ${this.maxCellCount}`,void(this.failed=!0);this.connNameToId=new Map,this.connIdToName=[],this.connIdToRootNet=[],this.overlapFriendlyRootNets=new Set,this.unsolvedSegs=this.buildConnectionSegs(),this.penalty2d=new Float64Array(this.planeSize);const A=n>0?1/n:0,c=o>0?1/o:0;for(let h=0;h<this.planeSize;h++){let d=0;this.initialPenaltyFn&&(d+=this.initialPenaltyFn({x:this.cellCenterX[h],y:this.cellCenterY[h],px:(this.cellCenterX[h]-this.boundsMinX)*A,py:(this.cellCenterY[h]-this.boundsMinY)*c,cellId:h,region:Q7e[this.cellRegion[h]],row:this.cellRow[h],col:this.cellCol[h]})),this.penalty2d[h]=d}this.usedCellsFlat=new Int32Array(a).fill(-1),this.sharedCellsFlat=Array.from({length:a},()=>{}),this.portOwnerFlat=new Int32Array(a).fill(-1),this.sharedCrossRootPortFlat=new Uint8Array(a),this.ripStateBuckets=1;const l=a;this.visitedStamp=new Uint32Array(l),this.bestGStamp=new Uint32Array(l),this.bestGValue=new Float64Array(l),this.visitedFlatStamp=new Uint32Array(a),this.stamp=0;const u=new Map;for(const h of this.nodeWithPortPoints.portPoints){const d=this.connNameToId.get(h.connectionName);if(d===void 0)continue;const p=this.pointToCell(h),m=p.z*this.planeSize+p.cellId,_=this.connIdToRootNet[d],f=u.get(m);f===void 0?u.set(m,_):f!==_&&(this.sharedCrossRootPortFlat[m]=1);const I=this.portOwnerFlat[m];this.portOwnerFlat[m]=I===-1||I===d?d:-2}this.solvedRoutes=[],this.usedIndicesByConn=[],this.ripCount=[],this.consecutiveSkips=0,this.penaltyCap=.5*this.hyperParameters.ripCost,this.shuffleConnections();const g=eft({planeSize:this.planeSize,layers:this.layers,connectionCount:this.unsolvedSegs.length,effort:this.effort,maxIterations:this.MAX_ITERATIONS});this.baseSearchBudgetIters=g.baseSearchBudgetIters,this.MAX_ITERATIONS=g.maxIterationsIters,this.activeConnSeg=null,this.activeConnId=-1,this.nodePool=new dXn,this.heap=new gXn,this.ripChain=new hXn,this.seqCounter=0}_step(){for(let e=0;e<this.stepMultiplier;e++){if(this.solved||this.failed)return;this.stepOnce()}}buildFiveRegionGrid(e,n){this.fineCols=Math.max(1,Math.ceil(e/this.highResolutionCellSize)),this.fineRows=Math.max(1,Math.ceil(n/this.highResolutionCellSize)),this.bandCols=Math.min(this.highResolutionCellThickness,Math.floor(this.fineCols/2)),this.bandRows=Math.min(this.highResolutionCellThickness,Math.floor(this.fineRows/2));const o=Math.max(0,this.fineCols-2*this.bandCols),i=Math.max(0,this.fineRows-2*this.bandRows),r=o,s=o;this.regions=[{id:0,name:"left",fineOriginRow:0,fineOriginCol:0,fineRows:this.fineRows,fineCols:this.bandCols,cellScale:1,rows:this.fineRows,cols:this.bandCols,offset:0},{id:1,name:"top",fineOriginRow:0,fineOriginCol:this.bandCols,fineRows:this.bandRows,fineCols:r,cellScale:1,rows:this.bandRows,cols:r,offset:0},{id:2,name:"right",fineOriginRow:0,fineOriginCol:this.fineCols-this.bandCols,fineRows:this.fineRows,fineCols:this.bandCols,cellScale:1,rows:this.fineRows,cols:this.bandCols,offset:0},{id:3,name:"bottom",fineOriginRow:this.fineRows-this.bandRows,fineOriginCol:this.bandCols,fineRows:this.bandRows,fineCols:s,cellScale:1,rows:this.bandRows,cols:s,offset:0},{id:4,name:"middle",fineOriginRow:this.bandRows,fineOriginCol:this.bandCols,fineRows:i,fineCols:o,cellScale:this.lowScale,rows:i>0?Math.ceil(i/this.lowScale):0,cols:o>0?Math.ceil(o/this.lowScale):0,offset:0}];let a=0;for(let y=0;y<this.regions.length;y++)this.regions[y].offset=a,a+=this.regions[y].rows*this.regions[y].cols;this.planeSize=a,this.cellCenterX=new Float64Array(this.planeSize),this.cellCenterY=new Float64Array(this.planeSize),this.cellMinX=new Float64Array(this.planeSize),this.cellMinY=new Float64Array(this.planeSize),this.cellMaxX=new Float64Array(this.planeSize),this.cellMaxY=new Float64Array(this.planeSize),this.cellWidth=new Float64Array(this.planeSize),this.cellHeight=new Float64Array(this.planeSize),this.cellRegion=new Uint8Array(this.planeSize),this.cellRow=new Int32Array(this.planeSize),this.cellCol=new Int32Array(this.planeSize),this.viaAllowed=new Uint8Array(this.planeSize);for(let y=0;y<this.regions.length;y++){const x=this.regions[y];for(let E=0;E<x.rows;E++){const B=x.fineOriginRow+E*x.cellScale,S=Math.min(x.fineOriginRow+x.fineRows,B+x.cellScale),Q=this.boundsMinY+B*this.highResolutionCellSize,w=Math.min(this.boundsMaxY,this.boundsMinY+S*this.highResolutionCellSize);for(let M=0;M<x.cols;M++){const k=x.fineOriginCol+M*x.cellScale,R=Math.min(x.fineOriginCol+x.fineCols,k+x.cellScale),F=this.boundsMinX+k*this.highResolutionCellSize,O=Math.min(this.boundsMaxX,this.boundsMinX+R*this.highResolutionCellSize),U=this.cellIdFor(x.id,E,M);this.cellCenterX[U]=(F+O)/2,this.cellCenterY[U]=(Q+w)/2,this.cellMinX[U]=F,this.cellMinY[U]=Q,this.cellMaxX[U]=O,this.cellMaxY[U]=w,this.cellWidth[U]=O-F,this.cellHeight[U]=w-Q,this.cellRegion[U]=x.id,this.cellRow[U]=E,this.cellCol[U]=M;const Y=Math.min(this.cellCenterX[U]-this.boundsMinX,this.boundsMaxX-this.cellCenterX[U],this.cellCenterY[U]-this.boundsMinY,this.boundsMaxY-this.cellCenterY[U]);this.viaAllowed[U]=Y>=this.viaMinDistFromBorder?1:0}}}const A=Array.from({length:this.planeSize},()=>[]),c=(y,x)=>{if(y===x||y<0||x<0)return;const E=this.cellCenterX[y]-this.cellCenterX[x],B=this.cellCenterY[y]-this.cellCenterY[x],S=Math.hypot(E,B);nft(A[y],{cellId:x,cost:S}),nft(A[x],{cellId:y,cost:S})};for(let y=0;y<this.regions.length;y++){const x=this.regions[y];for(let E=0;E<x.rows;E++)for(let B=0;B<x.cols;B++){const S=this.cellIdFor(x.id,E,B);E+1<x.rows&&c(S,this.cellIdFor(x.id,E+1,B)),B+1<x.cols&&c(S,this.cellIdFor(x.id,E,B+1))}}const l=this.regions[0],u=this.regions[1],g=this.regions[2],h=this.regions[3],d=this.regions[4],p=l.rows>0&&l.cols>0,m=u.rows>0&&u.cols>0,_=g.rows>0&&g.cols>0,f=h.rows>0&&h.cols>0,I=d.rows>0&&d.cols>0;if(p&&m)for(let y=0;y<this.bandRows;y++)c(this.cellIdFor(0,y,l.cols-1),this.cellIdFor(1,y,0));if(m&&_)for(let y=0;y<this.bandRows;y++)c(this.cellIdFor(1,y,u.cols-1),this.cellIdFor(2,y,0));if(p&&f)for(let y=this.fineRows-this.bandRows;y<this.fineRows;y++)c(this.cellIdFor(0,y,l.cols-1),this.cellIdFor(3,y-(this.fineRows-this.bandRows),0));if(f&&_)for(let y=this.fineRows-this.bandRows;y<this.fineRows;y++)c(this.cellIdFor(3,y-(this.fineRows-this.bandRows),h.cols-1),this.cellIdFor(2,y,0));if(p&&I)for(let y=this.bandRows;y<this.fineRows-this.bandRows;y++)c(this.cellIdFor(0,y,l.cols-1),this.cellIdFor(4,Math.floor((y-this.bandRows)/this.lowScale),0));if(_&&I)for(let y=this.bandRows;y<this.fineRows-this.bandRows;y++)c(this.cellIdFor(4,Math.floor((y-this.bandRows)/this.lowScale),d.cols-1),this.cellIdFor(2,y,0));if(m&&I)for(let y=this.bandCols;y<this.fineCols-this.bandCols;y++)c(this.cellIdFor(1,u.rows-1,y-this.bandCols),this.cellIdFor(4,0,Math.floor((y-this.bandCols)/this.lowScale)));if(f&&I)for(let y=this.bandCols;y<this.fineCols-this.bandCols;y++)c(this.cellIdFor(4,d.rows-1,Math.floor((y-this.bandCols)/this.lowScale)),this.cellIdFor(3,0,y-this.bandCols));if(!I&&!m&&!f&&p&&_)for(let y=0;y<Math.min(l.rows,g.rows);y++)c(this.cellIdFor(0,y,l.cols-1),this.cellIdFor(2,y,0));if(!I&&!p&&!_&&m&&f)for(let y=0;y<Math.min(u.cols,h.cols);y++)c(this.cellIdFor(1,u.rows-1,y),this.cellIdFor(3,0,y));const C=this.flattenNeighborLists(A);this.neighborOffset=C.offset,this.neighborIds=C.ids,this.neighborCosts=C.costs}cellIdFor(e,n,o){const i=this.regions[e];return i.offset+n*i.cols+o}stepOnce(){if(!this.activeConnSeg){if(this.unsolvedSegs.length===0)return void(this.solved=!0);const I=this.unsolvedSegs.shift();this.activeConnSeg=I,this.activeConnId=I.connId,this.nodePool.clear(),this.ripChain.clear(),this.heap.clear(),this.seqCounter=0,this.searchIterations=0,this.nextStamp();const C=this.computeH(I.startZ,I.startCellId,I.endZ,I.endCellId)*this.hyperParameters.greedyMultiplier,y=this.nodePool.push(I.startZ,I.startCellId,0,-1,-1,0),x=I.startZ*this.planeSize+I.startCellId,E=this.getSearchStateIdx(x,0);return this.bestGStamp[E]=this.stamp,this.bestGValue[E]=0,void this.heap.push(C,this.seqCounter++,y)}this.searchIterations++;const e=this.ripCount[this.activeConnId]??0,n=Math.round(this.baseSearchBudgetIters*(1+.25*Math.min(e,10)));if(this.searchIterations>n){const I=this.penalty2d;for(let C=0;C<I.length;C++)I[C]=.9*I[C];return this.unsolvedSegs.push(this.activeConnSeg),this.activeConnSeg=null,this.activeConnId=-1,this.heap.clear(),this.nodePool.clear(),this.consecutiveSkips++,void(this.consecutiveSkips>=Math.max(3,3*this.unsolvedSegs.length)&&(this.error=`Convergence failure: ${this.unsolvedSegs.length} connections stuck`,this.failed=!0))}if(this.heap.size===0)return this.error=`No path found for ${this.connIdToName[this.activeConnId]}`,void(this.failed=!0);const o=this.heap.pop(),i=this.nodePool.z[o],r=this.nodePool.cellId[o],s=this.nodePool.g[o],a=this.nodePool.ripHead[o],A=this.nodePool.ripCount[o],c=i*this.planeSize+r,l=this.getSearchStateIdx(c,A);if(this.visitedStamp[l]===this.stamp)return;this.visitedStamp[l]=this.stamp,this.visitedFlatStamp[c]=this.stamp;const u=this.activeConnSeg;if(i===u.endZ&&r===u.endCellId)return this.finalizeRoute(o),this.activeConnSeg=null,void(this.activeConnId=-1);const g=this.visitedStamp,h=this.stamp,d=this.activeConnId,p=u.endZ,m=u.endCellId,_=this.neighborOffset[r],f=this.neighborOffset[r+1];for(let I=_;I<f;I++){const C=this.neighborIds[I],y=i*this.planeSize+C;if(this.computeMoveCostAndRips(d,i,C,!1,a,A,this.neighborCosts[I]),this._moveCost<0)continue;const x=this.getSearchStateIdx(y,this._moveRipCount);if(g[x]===h)continue;const E=s+this._moveCost;if(this.bestGStamp[x]===h&&E>=this.bestGValue[x])continue;this.bestGStamp[x]=h,this.bestGValue[x]=E;const B=E+this.computeH(i,C,p,m)*this.hyperParameters.greedyMultiplier,S=this.nodePool.push(i,C,E,o,this._moveRippedHead,this._moveRipCount);this.heap.push(B,this.seqCounter++,S)}if(this.viaAllowed[r])for(let I=0;I<this.layers;I++){if(I===i)continue;const C=I*this.planeSize+r;if(this.computeMoveCostAndRips(d,I,r,!0,a,A,0),this._moveCost<0)continue;const y=this.getSearchStateIdx(C,this._moveRipCount);if(g[y]===h)continue;const x=s+this._moveCost;if(this.bestGStamp[y]===h&&x>=this.bestGValue[y])continue;this.bestGStamp[y]=h,this.bestGValue[y]=x;const E=x+this.computeH(I,r,p,m)*this.hyperParameters.greedyMultiplier,B=this.nodePool.push(I,r,x,o,this._moveRippedHead,this._moveRipCount);this.heap.push(E,this.seqCounter++,B)}}computeMoveCostAndRips(e,n,o,i,r,s,a){let A=0,c=r,l=s;const u=n*this.planeSize+o;if(i){A+=this.hyperParameters.viaBaseCost,A+=Math.min(this.penalty2d[o],this.penaltyCap);const g=this.portOwnerFlat[u],h=this.allowSharedUse(e,g),d=this.activeConnSeg,p=!!d&&n===d.endZ&&o===d.endCellId;if(g>=0&&g!==e&&!h&&!p)return this._moveCost=-1,void(this._moveRippedHead=c);this.fillViaOccupants(o,e);const m=this._viaOccs;for(let _=0;_<m.length;_++){const f=m[_];this.ripChain.contains(c,f)||(A+=this.hyperParameters.ripCost,c=this.ripChain.append(c,f),l++),A+=this.hyperParameters.ripViaPenalty}}else{A+=a,A+=Math.min(this.penalty2d[o],this.penaltyCap);const g=this.portOwnerFlat[u],h=this.allowSharedUse(e,g),d=this.activeConnSeg,p=!!d&&n===d.endZ&&o===d.endCellId;if(g>=0&&g!==e&&!h&&!p)return this._moveCost=-1,void(this._moveRippedHead=c);this.fillTraceOccupants(u,e,this._cellOccs);for(let m=0;m<this._cellOccs.length;m++){const _=this._cellOccs[m];this.ripChain.contains(c,_)||(A+=this.hyperParameters.ripCost,c=this.ripChain.append(c,_),l++),A+=this.hyperParameters.ripTracePenalty}}this._moveCost=A,this._moveRippedHead=c,this._moveRipCount=l}fillViaOccupants(e,n){const o=this._viaOccs;o.length=0;const i=this.cellCenterX[e],r=this.cellCenterY[e];this.forEachCellNearCircle(i,r,this.viaKeepoutRadius,s=>{if(v7e(i,r,this.viaKeepoutRadius,this.cellMinX[s],this.cellMinY[s],this.cellMaxX[s],this.cellMaxY[s]))for(let a=0;a<this.layers;a++)this.pushFlatOccupants(a*this.planeSize+s,n,o)})}fillTraceOccupants(e,n,o){o.length=0,this.pushFlatOccupants(e,n,o)}pushFlatOccupants(e,n,o){const i=this.usedCellsFlat[e];i===-1||i===n||this.allowSharedUse(n,i)||zse(o,i);const r=this.sharedCellsFlat[e];if(r)for(let s=0;s<r.length;s++){const a=r[s];a!==n&&(this.allowSharedUse(n,a)||zse(o,a))}}addSharedOccupant(e,n){if(this.usedCellsFlat[e]===n)return;let o=this.sharedCellsFlat[e];o||(o=[],this.sharedCellsFlat[e]=o),zse(o,n)}replaceOccupants(e,n){this.usedCellsFlat[e]=n,this.sharedCellsFlat[e]=void 0}removeOccupant(e,n){const o=this.sharedCellsFlat[e];if(this.usedCellsFlat[e]===n)return void(o&&o.length>0?(this.usedCellsFlat[e]=o.pop(),o.length===0&&(this.sharedCellsFlat[e]=void 0)):this.usedCellsFlat[e]=-1);if(!o)return;const i=o.indexOf(n);i!==-1&&(o.splice(i,1),o.length===0&&(this.sharedCellsFlat[e]=void 0))}allowSharedUse(e,n){return n<0?!1:this.connIdToRootNet[n]===this.connIdToRootNet[e]}shouldSkipFixedPortHalo(e,n){const o=this.portOwnerFlat[e];return o!==n&&(o===-2||!(o<0)&&!this.allowSharedUse(n,o))}nextStamp(){this.stamp=this.stamp+1>>>0,this.stamp===0&&(this.visitedStamp.fill(0),this.bestGStamp.fill(0),this.visitedFlatStamp.fill(0),this.stamp=1)}getSearchStateIdx(e,n){return e}computeH(e,n,o,i){const r=Math.hypot(this.cellCenterX[n]-this.cellCenterX[i],this.cellCenterY[n]-this.cellCenterY[i]);return e===o?r:r+this.hyperParameters.viaBaseCost}internConn(e,n){const o=this.connNameToId.get(e);if(o!==void 0)return o;const i=this.connIdToName.length;var r;return this.connIdToName.push(e),this.connIdToRootNet.push((r=e,n??r.replace(/_mst\d+$/,""))),this.connNameToId.set(e,i),i}buildConnectionSegs(){const e=new Map;for(const i of this.nodeWithPortPoints.portPoints){const r=i.connectionName;e.has(r)||e.set(r,{points:[],rootConnectionName:i.rootConnectionName}),e.get(r).points.push(i)}const n=[],o=new Set;for(const[i,r]of e){const s=r.points,a=Z_t(s);if(a.length===0)continue;const A=this.internConn(i,r.rootConnectionName);for(const[c,l]of a){const u=this.pointToCell(c),g=this.pointToCell(l),h=`${u.z}:${u.cellId}`,d=`${g.z}:${g.cellId}`,p=h<d?`${h}|${d}`:`${d}|${h}`,m=r.rootConnectionName??i,_=`${m}|${p}`;o.has(_)?this.overlapFriendlyRootNets.add(m):(o.add(_),n.push({connId:A,startZ:u.z,startCellId:u.cellId,startPoint:c,endZ:g.z,endCellId:g.cellId,endPoint:l}))}}return n}pointToCell(e){const n=a7(Math.floor((e.x-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),o=a7(Math.floor((e.y-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1);let i=4;n<this.bandCols?i=0:n>=this.fineCols-this.bandCols?i=2:o<this.bandRows?i=1:o>=this.fineRows-this.bandRows&&(i=3);const r=this.regions[i],s=o-r.fineOriginRow,a=n-r.fineOriginCol,A=a7(Math.floor(s/r.cellScale),0,Math.max(0,r.rows-1)),c=a7(Math.floor(a/r.cellScale),0,Math.max(0,r.cols-1));return{z:this.zToLayer.get(e.z)??0,cellId:this.cellIdFor(i,A,c)}}shuffleConnections(){const e=this.unsolvedSegs;let n=this.hyperParameters.shuffleSeed>>>0;const o=()=>(n=Math.imul(n,1664525)+1013904223>>>0,n/4294967295);for(let i=e.length-1;i>0;i--){const r=Math.floor(o()*(i+1)),s=e[i];e[i]=e[r],e[r]=s}}finalizeRoute(e){this.consecutiveSkips=Math.max(0,this.consecutiveSkips-1);const n=[];let o=e;for(;o>=0;){const l=this.nodePool.z[o],u=this.nodePool.cellId[o];n.push(l*this.planeSize+u),o=this.nodePool.parent[o]}for(n.reverse();n.length>1&&this.sharedCrossRootPortFlat[n[0]];)n.shift();for(;n.length>1&&this.sharedCrossRootPortFlat[n[n.length-1]];)n.pop();const i=this.extractViaCellIds(n),r=this.activeConnId;this.ripChain.collect(this.nodePool.ripHead[e],this._rippedIds);for(let l=0;l<this._rippedIds.length;l++)if(this.ripTrace(this._rippedIds[l]),this.failed)return;const s=[];for(let l=0;l<n.length;l++){const u=n[l],g=Math.floor(u/this.planeSize),h=u-g*this.planeSize;this.markTraceFootprint(r,g,h,s)}const a=[];for(let l=0;l<i.length;l++)this.markViaFootprint(r,i[l],s,a);for(;this.usedIndicesByConn.length<=r;)this.usedIndicesByConn.push(void 0);const A=this.usedIndicesByConn[r]??[];for(A.push(...s),this.usedIndicesByConn[r]=A;this.solvedRoutes.length<=r;)this.solvedRoutes.push(void 0);const c=this.solvedRoutes[r]??[];c.push({connId:r,states:Int32Array.from(n),viaCellIds:Int32Array.from(i),startPoint:this.activeConnSeg.startPoint,endPoint:this.activeConnSeg.endPoint}),this.solvedRoutes[r]=c;for(let l=0;l<a.length;l++)if(this.ripTrace(a[l]),this.failed)return;if(this._rippedIds.length>0||a.length>0){const l=this.penalty2d,u=this.penaltyCap;if(this.totalRipEvents>50)for(let g=0;g<l.length;g++)l[g]=.99*l[g];else for(let g=0;g<l.length;g++)l[g]>u&&(l[g]=.5*l[g])}}extractViaCellIds(e){const n=[];for(let o=1;o<e.length;o++){const i=e[o-1],r=e[o],s=Math.floor(i/this.planeSize),a=Math.floor(r/this.planeSize);s!==a&&n.push(r-a*this.planeSize)}return n}markTraceFootprint(e,n,o,i){const r=this.cellCenterX[o],s=this.cellCenterY[o];this.forEachCellNearCircle(r,s,this.traceKeepoutRadius,a=>{if(!v7e(r,s,this.traceKeepoutRadius,this.cellMinX[a],this.cellMinY[a],this.cellMaxX[a],this.cellMaxY[a]))return;const A=n*this.planeSize+a;if(a!==o&&this.shouldSkipFixedPortHalo(A,e))return;const c=this.usedCellsFlat[A],l=this.allowSharedUse(e,c);(c===-1||c===e||l)&&(c!==-1&&c!==e?this.addSharedOccupant(A,e):this.usedCellsFlat[A]=e,i.push(A))})}markViaFootprint(e,n,o,i){const r=this.cellCenterX[n],s=this.cellCenterY[n];this.forEachCellNearCircle(r,s,this.viaKeepoutRadius,a=>{if(v7e(r,s,this.viaKeepoutRadius,this.cellMinX[a],this.cellMinY[a],this.cellMaxX[a],this.cellMaxY[a]))for(let A=0;A<this.layers;A++){const c=A*this.planeSize+a;if(a!==n&&this.shouldSkipFixedPortHalo(c,e))continue;if(this.fillTraceOccupants(c,e,this._cellOccs),this._cellOccs.length>0){for(let u=0;u<this._cellOccs.length;u++)zse(i,this._cellOccs[u]);this.replaceOccupants(c,e),o.push(c);continue}const l=this.usedCellsFlat[c];l!==-1&&l!==e?this.addSharedOccupant(c,e):this.usedCellsFlat[c]=e,o.push(c)}})}forEachCellNearCircle(e,n,o,i){const r=a7(Math.floor((e-o-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),s=a7(Math.floor((e+o-this.boundsMinX)/this.highResolutionCellSize),0,this.fineCols-1),a=a7(Math.floor((n-o-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1),A=a7(Math.floor((n+o-this.boundsMinY)/this.highResolutionCellSize),0,this.fineRows-1);for(let c=0;c<this.regions.length;c++){const l=this.regions[c];if(l.rows===0||l.cols===0)continue;const u=Math.max(a,l.fineOriginRow),g=Math.min(A,l.fineOriginRow+l.fineRows-1),h=Math.max(r,l.fineOriginCol),d=Math.min(s,l.fineOriginCol+l.fineCols-1);if(u>g||h>d)continue;const p=Math.floor((u-l.fineOriginRow)/l.cellScale),m=Math.floor((g-l.fineOriginRow)/l.cellScale),_=Math.floor((h-l.fineOriginCol)/l.cellScale),f=Math.floor((d-l.fineOriginCol)/l.cellScale);for(let I=p;I<=m;I++)for(let C=_;C<=f;C++)i(this.cellIdFor(l.id,I,C))}}ripTrace(e){for(;this.ripCount.length<=e;)this.ripCount.push(0);if(this.ripCount[e]++,this.totalRipEvents++,this.totalRipEvents>=this.MAX_RIPS)return this.error=`Convergence failure: exceeded MAX_RIPS ${this.MAX_RIPS}`,void(this.failed=!0);const n=this.getSolvedRoutesForConn(e);if(n.length>0)for(const i of n){for(let r=0;r<i.states.length;r++){const s=i.states[r]%this.planeSize;this.penalty2d[s]=this.penalty2d[s]+this.hyperParameters.ripTracePenalty}for(let r=0;r<i.viaCellIds.length;r++){const s=i.viaCellIds[r];this.penalty2d[s]=this.penalty2d[s]+this.hyperParameters.ripViaPenalty}}const o=this.usedIndicesByConn[e];if(o){for(let i=0;i<o.length;i++)this.removeOccupant(o[i],e);this.usedIndicesByConn[e]=void 0}if(n.length>0){this.solvedRoutes[e]=void 0;for(const i of n){const r=i.states[0],s=i.states[i.states.length-1],a=Math.floor(r/this.planeSize),A=Math.floor(s/this.planeSize);this.unsolvedSegs.push({connId:e,startZ:a,startCellId:r-a*this.planeSize,startPoint:i.startPoint,endZ:A,endCellId:s-A*this.planeSize,endPoint:i.endPoint})}}}flattenNeighborLists(e){const n=new Int32Array(e.length+1);let o=0;for(let a=0;a<e.length;a++)n[a]=o,o+=e[a].length;n[e.length]=o;const i=new Int32Array(o),r=new Float32Array(o);let s=0;for(let a=0;a<e.length;a++){const A=e[a];for(let c=0;c<A.length;c++){const l=A[c];i[s]=l.cellId,r[s]=l.cost,s++}}return{offset:n,ids:i,costs:r}}visualize(){const e=["red","blue","orange","green"],n=this.gridToBoundsTransform,o=[],i=[],r=[],s=[];if(s.push({center:{x:this.nodeWithPortPoints.center.x,y:this.nodeWithPortPoints.center.y},width:this.nodeWithPortPoints.width,height:this.nodeWithPortPoints.height,stroke:"gray"}),this.showPenaltyMap&&this.penalty2d){let c=0;for(let l=0;l<this.penalty2d.length;l++)this.penalty2d[l]>c&&(c=this.penalty2d[l]);if(c>0)for(let l=0;l<this.planeSize;l++){const u=this.penalty2d[l];if(u<=0)continue;const g=s7(n,{x:this.cellCenterX[l],y:this.cellCenterY[l]}),h=Math.min(.6,u/c*.6);s.push({center:g,width:this.cellWidth[l]*n.a,height:this.cellHeight[l]*n.e,fill:`rgba(255,165,0,${h.toFixed(3)})`})}}if(this.showUsedCellMap&&this.usedCellsFlat)for(let c=0;c<this.layers;c++){const l=c*this.planeSize;for(let u=0;u<this.planeSize;u++){if(this.usedCellsFlat[l+u]===-1)continue;const g=s7(n,{x:this.cellCenterX[u],y:this.cellCenterY[u]});s.push({center:g,width:this.cellWidth[u]*n.a,height:this.cellHeight[u]*n.e,fill:"rgba(0,0,255,0.5)"})}}for(const c of this.nodeWithPortPoints.portPoints)o.push({x:c.x,y:c.y,color:e[c.z]??"gray",label:c.connectionName});const a=["rgba(255,0,0,0.75)","rgba(0,0,255,0.75)","rgba(255,165,0,0.75)","rgba(0,128,0,0.75)"],A=this.getOutput();for(const c of A){if(c.route.length<2)continue;let l=0;for(let u=1;u<c.route.length;u++){const g=c.route[u-1];c.route[u].z!==g.z&&(u-l>=2&&i.push({points:c.route.slice(l,u).map(h=>({x:h.x,y:h.y})),strokeColor:a[g.z]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness}),l=u)}if(c.route.length-l>=2){const u=c.route[l].z;i.push({points:c.route.slice(l).map(g=>({x:g.x,y:g.y})),strokeColor:a[u]??"rgba(128,128,128,0.75)",strokeWidth:this.traceThickness})}}for(const c of A)for(const l of c.vias)r.push({center:{x:l.x,y:l.y},radius:this.viaDiameter/2,fill:"rgba(0,0,0,0.3)",stroke:"black"});if(this.activeConnSeg&&this.visitedFlatStamp){const c=this.stamp;for(let l=0;l<this.layers;l++){const u=l*this.planeSize;for(let g=0;g<this.planeSize;g++){if(this.visitedFlatStamp[u+g]!==c)continue;const h=s7(n,{x:this.cellCenterX[g],y:this.cellCenterY[g]});o.push({x:h.x,y:h.y,color:"rgba(0,0,255,0.2)"})}}}return{points:o,lines:i,circles:r,rects:s,coordinateSystem:"cartesian",title:`HighDensityA03 [${this.getSolvedRouteCount()} solved, ${this.unsolvedSegs?.length??0} remaining]`}}getOutput(){const e=this.gridToBoundsTransform,n=[];for(let o=0;o<this.solvedRoutes.length;o++){const i=this.getSolvedRoutesForConn(o);if(i.length===0)continue;const r=this.connIdToName[o];for(const s of i){const a=Array.from(s.states,A=>{const c=Math.floor(A/this.planeSize),l=A-c*this.planeSize,u=s7(e,{x:this.cellCenterX[l],y:this.cellCenterY[l]});return{x:u.x,y:u.y,z:this.layerToZ.get(c)??c}});a.length>0&&(a[0]={...s.startPoint},a.length>1&&(a[a.length-1]={...s.endPoint})),n.push({connectionName:r,regionId:this.nodeWithPortPoints.capacityMeshNodeId,traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,route:a,vias:Array.from(s.viaCellIds,A=>s7(e,{x:this.cellCenterX[A],y:this.cellCenterY[A]}))})}}return n}getSolvedRoutesForConn(e){const n=this.solvedRoutes[e];return n?Array.isArray(n)?n:[n]:[]}getSolvedRouteCount(){let e=0;for(let n=0;n<this.solvedRoutes.length;n++)e+=this.getSolvedRoutesForConn(n).length;return e}computeGridToBoundsTransform(){let e=1/0,n=-1/0,o=1/0,i=-1/0;for(let u=0;u<this.planeSize;u++){const g=this.cellCenterX[u],h=this.cellCenterY[u];g<e&&(e=g),g>n&&(n=g),h<o&&(o=h),h>i&&(i=h)}const r=n-e,s=i-o,a=this.boundsMaxX-this.boundsMinX,A=this.boundsMaxY-this.boundsMinY,c=r>0?a/r:1,l=s>0?A/s:1;return{a:c,b:0,c:r>0?this.boundsMinX-c*e:(this.boundsMinX+this.boundsMaxX)/2-e,d:0,e:l,f:s>0?this.boundsMinY-l*o:(this.boundsMinY+this.boundsMaxY)/2-o}}},P7e=t=>({minX:Math.min(t[0].x,t[1].x),maxX:Math.max(t[0].x,t[1].x),minY:Math.min(t[0].y,t[1].y),maxY:Math.max(t[0].y,t[1].y)});function Jse(t,e){const n=t.x-e.x,o=t.y-e.y;return n*n+o*o}function nL(t,e,n){const o=Jse(e,n);if(o===0)return Jse(t,e);let i=((t.x-e.x)*(n.x-e.x)+(t.y-e.y)*(n.y-e.y))/o;return i=Math.max(0,Math.min(1,i)),Jse(t,{x:e.x+i*(n.x-e.x),y:e.y+i*(n.y-e.y)})}function pXn(t,e,n,o){if(Uh(t,e,n,o))return 0;const i={x:t.x,y:t.y},r={x:e.x,y:e.y},s={x:n.x,y:n.y},a={x:o.x,y:o.y};return Math.min(nL(i,s,a),nL(r,s,a),nL(s,i,r),nL(a,i,r))}var oB=class{segmentBuckets;viaBuckets;CELL_SIZE;maximumCopperRadius=0;constructor(e,n=1){this.segmentBuckets=new Map,this.viaBuckets=new Map,this.CELL_SIZE=n;for(const o of e)if(o&&o.connectionName){if(this.maximumCopperRadius=Math.max(this.maximumCopperRadius,o.traceThickness/2,o.viaDiameter/2),o.route&&o.route.length>=2)for(let i=0;i<o.route.length-1;i++){const r=o.route[i],s=o.route[i+1];if(r.x===s.x&&r.y===s.y||r.insideJumperPad&&s.insideJumperPad)continue;const a=[r,s],A=P7e(a),c={segmentId:`${o.connectionName}-seg-${i}`,segment:a,parentRoute:o},l=Math.floor(A.minX/this.CELL_SIZE),u=Math.floor((A.maxX+1e-9)/this.CELL_SIZE),g=Math.floor(A.minY/this.CELL_SIZE),h=Math.floor((A.maxY+1e-9)/this.CELL_SIZE);for(let d=l;d<=u;d++)for(let p=g;p<=h;p++){const m=`${d}x${p}`;let _=this.segmentBuckets.get(m);_||(_=[],this.segmentBuckets.set(m,_)),_.push(c)}}if(o.vias&&o.vias.length>0)for(let i=0;i<o.vias.length;i++){const r=o.vias[i];if(r==null)continue;const s={viaId:`${o.connectionName}-via-${i}`,x:r.x,y:r.y,parentRoute:o},a=`${Math.floor(r.x/this.CELL_SIZE)}x${Math.floor(r.y/this.CELL_SIZE)}`;let A=this.viaBuckets.get(a);A||(A=[],this.viaBuckets.set(a,A)),A.push(s)}}else console.warn("Skipping route with missing data:",o)}getConflictingRoutesForSegment(e,n,o){const i=P7e([e,n]),r=o+this.maximumCopperRadius,s=i.minX-r,a=i.minY-r,A=i.maxX+r,c=i.maxY+r,l=Math.floor(s/this.CELL_SIZE),u=Math.floor((A+1e-9)/this.CELL_SIZE),g=Math.floor(a/this.CELL_SIZE),h=Math.floor((c+1e-9)/this.CELL_SIZE),d=new Map,p=new Set,m=new Set,_={x:e.x,y:e.y},f={x:n.x,y:n.y};for(let C=l;C<=u;C++)for(let y=g;y<=h;y++){const x=`${C}x${y}`,E=this.segmentBuckets.get(x);if(E)for(const S of E){if(p.has(S.segmentId))continue;p.add(S.segmentId);const Q=S.parentRoute,[w,M]=S.segment;if(e.z!==n.z||w.z!==M.z||w.z!==e.z)continue;const k=o+Q.traceThickness/2,R=k*k,F=pXn(e,n,w,M);if(F<R){const O=Q.connectionName,U=d.get(O);(!U||F<U.minDistSq)&&d.set(O,{route:Q,minDistSq:F})}}const B=this.viaBuckets.get(x);if(B)for(const S of B){if(m.has(S.viaId))continue;m.add(S.viaId);const Q=S.parentRoute,w={x:S.x,y:S.y},M=o+Q.viaDiameter/2,k=M*M,R=nL(w,_,f);if(R<k){const F=Q.connectionName,O=d.get(F);(!O||R<O.minDistSq)&&d.set(F,{route:Q,minDistSq:R})}}}const I=[];for(const C of d.values())I.push({conflictingRoute:C.route,distance:Math.sqrt(C.minDistSq)});return I}removeRoute(e){for(const[n,o]of this.segmentBuckets){const i=o.filter(r=>r.parentRoute.connectionName!==e);i.length===0?this.segmentBuckets.delete(n):i.length!==o.length&&this.segmentBuckets.set(n,i)}for(const[n,o]of this.viaBuckets){const i=o.filter(r=>r.parentRoute.connectionName!==e);i.length===0?this.viaBuckets.delete(n):i.length!==o.length&&this.viaBuckets.set(n,i)}}addRoute(e){if(!e||!e.connectionName)return void console.warn("Skipping route with missing data:",e);if(this.maximumCopperRadius=Math.max(this.maximumCopperRadius,e.traceThickness/2,e.viaDiameter/2),e.route&&e.route.length>=2)for(let n=0;n<e.route.length-1;n++){const o=e.route[n],i=e.route[n+1];if(o.x===i.x&&o.y===i.y||o.insideJumperPad&&i.insideJumperPad)continue;const r=[o,i],s=P7e(r),a={segmentId:`${e.connectionName}-seg-${n}`,segment:r,parentRoute:e},A=Math.floor(s.minX/this.CELL_SIZE),c=Math.floor((s.maxX+1e-9)/this.CELL_SIZE),l=Math.floor(s.minY/this.CELL_SIZE),u=Math.floor((s.maxY+1e-9)/this.CELL_SIZE);for(let g=A;g<=c;g++)for(let h=l;h<=u;h++){const d=`${g}x${h}`;let p=this.segmentBuckets.get(d);p||(p=[],this.segmentBuckets.set(d,p)),p.push(a)}}if(e.vias&&e.vias.length>0)for(let n=0;n<e.vias.length;n++){const o=e.vias[n];if(o==null)continue;const i={viaId:`${e.connectionName}-via-${n}`,x:o.x,y:o.y,parentRoute:e},r=`${Math.floor(o.x/this.CELL_SIZE)}x${Math.floor(o.y/this.CELL_SIZE)}`;let s=this.viaBuckets.get(r);s||(s=[],this.viaBuckets.set(r,s)),s.push(i)}}getConflictingRoutesNearPoint(e,n){const o=n+this.maximumCopperRadius,i=e.x-o,r=e.y-o,s=e.x+o,a=e.y+o,A=Math.floor(i/this.CELL_SIZE),c=Math.floor((s+1e-9)/this.CELL_SIZE),l=Math.floor(r/this.CELL_SIZE),u=Math.floor((a+1e-9)/this.CELL_SIZE),g=new Map,h=new Set,d=new Set;for(let m=A;m<=c;m++)for(let _=l;_<=u;_++){const f=`${m}x${_}`,I=this.segmentBuckets.get(f);if(I)for(const y of I){if(h.has(y.segmentId))continue;h.add(y.segmentId);const x=y.segment[0],E=y.segment[1];if(x.z!==E.z||x.z!==e.z)continue;const B=y.parentRoute,S={x:y.segment[0].x,y:y.segment[0].y},Q={x:y.segment[1].x,y:y.segment[1].y},w=n+B.traceThickness/2,M=w*w,k=nL(e,S,Q);if(k<M){const R=B.connectionName,F=g.get(R);(!F||k<F.minDistSq)&&g.set(R,{route:B,minDistSq:k})}}const C=this.viaBuckets.get(f);if(C)for(const y of C){if(d.has(y.viaId))continue;d.add(y.viaId);const x=y.parentRoute,E={x:y.x,y:y.y},B=n+x.viaDiameter/2,S=B*B,Q=Jse(e,E);if(Q<S){const w=x.connectionName,M=g.get(w);(!M||Q<M.minDistSq)&&g.set(w,{route:x,minDistSq:Q})}}}const p=[];for(const m of g.values())p.push({conflictingRoute:m.route,distance:Math.sqrt(m.minDistSq)});return p}};function M7e(t){let e=t;for(let i=0;i<10;i++)e=16807*e%2147483647;let n=e;e=(69069*t+1)%2147483647;for(let i=0;i<10;i++)e=48271*e%2147483647;let o=e;return()=>{let i=n;n=o,i^=i<<23,i^=i>>>17,i^=o,i^=o>>>26,o=i;const r=(n+o)/4294967296;return r-Math.floor(r)}}var mXn={1:[[0]],2:[[0,1],[1,0]],3:[[0,1,2],[2,0,1],[1,0,2],[0,2,1],[1,2,0],[2,1,0]],4:[[0,1,2,3],[2,0,1,3],[1,3,2,0],[3,0,1,2],[0,2,1,3],[2,1,3,0],[3,0,2,1],[1,2,0,3],[3,1,0,2],[0,3,2,1],[2,3,0,1],[2,3,1,0],[1,2,3,0],[3,1,2,0],[0,1,3,2],[0,2,3,1],[0,3,1,2],[1,0,2,3],[1,0,3,2],[1,3,0,2],[2,0,3,1],[2,1,0,3],[3,2,0,1],[3,2,1,0]]};function D5(t,e){if(e===0||t.length===0)return t;if(t.length<=4){const i=mXn[t.length];return i[e%i.length].map(r=>t[r])}const n=M7e(e),o=t.slice();for(let i=0;i<o.length;i++){const r=Math.floor(n()*o.length),s=Math.floor(n()*(i+1));[o[r],o[s]]=[o[s],o[r]]}return o}var _Xn=t=>{let e=1/0;const n=t.portPoints;for(let o=0;o<n.length;o++)for(let i=o+1;i<n.length;i++){const r=n[o],s=n[i];if(r.z!==s.z||r.rootConnectionName&&r.rootConnectionName===s.rootConnectionName)continue;const a=Math.sqrt((r.x-s.x)**2+(r.y-s.y)**2);e=Math.min(e,a)}return e===1/0?0:e},fXn=class{heap=[];constructor(e){this.heap=[];for(const n of e)this.enqueue(n)}dequeue(){if(this.heap.length===0)return null;const e=this.heap[0];return this.heap[0]=this.heap[this.heap.length-1],this.heap.pop(),this.heapifyDown(),e}peek(){return this.heap.length===0?null:this.heap[0]}enqueue(e){this.heap.push(e),this.heapifyUp()}heapifyUp(){let e=this.heap.length-1;const n=this.heap[e];for(;e>0;){const o=Math.floor((e-1)/2),i=this.heap[o];if(i.f<=n.f)break;this.heap[e]=i,e=o}this.heap[e]=n}heapifyDown(){let e=0;const n=this.heap.length,o=this.heap[e];if(o){for(;;){const i=2*e+1;if(i>=n)break;const r=i+1;let s=i;if(r<n&&this.heap[r].f<this.heap[i].f&&(s=r),o.f<this.heap[s].f)break;this.heap[e]=this.heap[s],e=s}this.heap[e]=o}}getTopN(e){return[...this.heap].sort((n,o)=>n.f-o.f).slice(0,e)}},oL=(t,e,n=[])=>[t,e?`rootConnectionName: ${e}`:void 0,...n].filter(Boolean).join(`
`),IXn=class extends yr{getSolverName(){return"SingleHighDensityRouteSolver"}obstacleRoutes;bounds;boundsSize;boundsCenter;A;B;straightLineDistance;viaDiameter;traceThickness;obstacleMargin;layerCount;availableZ;minCellSize=.05;cellStep=.05;GREEDY_MULTIPLER=1.1;numRoutes;VIA_PENALTY_FACTOR=.3;CELL_SIZE_FACTOR;NEARBY_SEGMENT_CLEARANCE;exploredNodes;viasInPathByNode=new WeakMap;gridMinXIndex;gridMinYIndex;gridWidth;gridHeight;candidates;connectionName;rootConnectionName;regionId;solvedPath=null;futureConnections;hyperParameters;connMap;obstacleSegments=[];obstacleSegmentIndex=null;obstacleSegmentsByLayer=new Map;obstacleSegmentIndexByLayer=new Map;obstacleVias=[];obstacleViaIndex=null;debug_exploredNodesOrdered;debug_nodesTooCloseToObstacle;debug_nodePathToParentIntersectsObstacle;debugEnabled;initialNodeGridOffset;constructor(e){super(),this.bounds=e.bounds,this.connMap=e.connMap,this.hyperParameters=e.hyperParameters??{},this.CELL_SIZE_FACTOR=this.hyperParameters.CELL_SIZE_FACTOR??1,this.boundsSize={width:this.bounds.maxX-this.bounds.minX,height:this.bounds.maxY-this.bounds.minY},this.boundsCenter={x:(this.bounds.minX+this.bounds.maxX)/2,y:(this.bounds.minY+this.bounds.maxY)/2},this.connectionName=e.connectionName,this.rootConnectionName=e.rootConnectionName,this.regionId=e.regionId,this.obstacleRoutes=e.obstacleRoutes,this.A=e.A,this.B=e.B,this.viaDiameter=e.viaDiameter??.3,this.traceThickness=e.traceThickness??.15,this.obstacleMargin=e.obstacleMargin??.15,this.layerCount=e.layerCount??2,this.availableZ=e.availableZ&&e.availableZ.length>0?[...new Set(e.availableZ)].sort((g,h)=>g-h):Array.from({length:this.layerCount},(g,h)=>h),this.exploredNodes=new Set,this.straightLineDistance=no(this.A,this.B),this.futureConnections=e.futureConnections??[],this.NEARBY_SEGMENT_CLEARANCE=e.nearbySegmentClearance??.15,this.debugEnabled=e.captureSearchDebug??!0,this.MAX_ITERATIONS=1e4,this.debug_exploredNodesOrdered=[],this.debug_nodesTooCloseToObstacle=new Set,this.debug_nodePathToParentIntersectsObstacle=new Set,this.numRoutes=this.obstacleRoutes.length+this.futureConnections.length,this.buildObstacleIndexes();const n=Math.ceil(5*(this.numRoutes+1));let o=this.boundsSize.width/this.cellStep,i=this.boundsSize.height/this.cellStep;for(;o*i>n**2&&!(2*this.cellStep>e.minDistBetweenEnteringPoints);)this.cellStep*=2,o=this.boundsSize.width/this.cellStep,i=this.boundsSize.height/this.cellStep;this.cellStep*=this.CELL_SIZE_FACTOR,this.gridMinXIndex=Math.round(this.bounds.minX/this.cellStep)-1,this.gridMinYIndex=Math.round(this.bounds.minY/this.cellStep)-1;const r=Math.round(this.bounds.maxX/this.cellStep)+1,s=Math.round(this.bounds.maxY/this.cellStep)+1;this.gridWidth=r-this.gridMinXIndex+1,this.gridHeight=s-this.gridMinYIndex+1;const a=Math.abs(this.A.x-this.bounds.minX)<.001&&Math.abs(this.B.x-this.bounds.minX)<.001||Math.abs(this.A.x-this.bounds.maxX)<.001&&Math.abs(this.B.x-this.bounds.maxX)<.001||Math.abs(this.A.y-this.bounds.minY)<.001&&Math.abs(this.B.y-this.bounds.minY)<.001||Math.abs(this.A.y-this.bounds.maxY)<.001&&Math.abs(this.B.y-this.bounds.maxY)<.001;this.futureConnections&&this.futureConnections.length===0&&this.obstacleRoutes.length===0&&!a&&this.handleSimpleCases();const A={x:Math.round(e.A.x/(this.cellStep/2))*(this.cellStep/2),y:Math.round(e.A.y/(this.cellStep/2))*(this.cellStep/2)};this.initialNodeGridOffset={x:A.x-Math.round(e.A.x/this.cellStep)*this.cellStep,y:A.y-Math.round(e.A.y/this.cellStep)*this.cellStep};const c={...e.A,z:e.A.z??0,g:0,h:0,f:0,parent:null},l={...e.A,...A,z:e.A.z??0,g:0,h:0,f:0,parent:c},u=(Math.abs(l.x-e.A.x)>1e-9||Math.abs(l.y-e.A.y)>1e-9)&&(this.isNodeTooCloseToObstacle(l)||this.isNodeTooCloseToEdge(l,!1)||this.doesPathToParentIntersectObstacle(l));this.candidates=new fXn([u?c:l])}handleSimpleCases(){this.solved=!0;const{A:e,B:n}=this,o=e.z===n.z?[e,n]:[e,{...this.boundsCenter,z:this.A.z},{...this.boundsCenter,z:n.z},n];this.solvedPath={connectionName:this.connectionName,rootConnectionName:this.rootConnectionName,regionId:this.regionId,route:o,traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:this.A.z===this.B.z?[]:[this.boundsCenter]}}get viaPenaltyDistance(){return this.cellStep+this.straightLineDistance*this.VIA_PENALTY_FACTOR}isNodeTooCloseToObstacle(e,n,o,i){if(n??=this.obstacleMargin,o&&e.parent){const c=this.getViasInNodePath(e.parent);for(const l of c)if(no(e,l)<this.viaDiameter/2+n)return!0}const r=this.traceThickness+n,s=i?.segments??(o?this.obstacleSegments:this.obstacleSegmentsByLayer.get(e.z)),a=i?.segmentIds??(o?this.obstacleSegmentIndex:this.obstacleSegmentIndexByLayer.get(e.z))?.search(e.x-r,e.y-r,e.x+r,e.y+r)??[];if(s)for(const c of a){const l=s[c];if(l&&!l.connectedToCurrentConnection&&(o||l.z===e.z)&&(!i||!(e.x+r<l.minX||e.y+r<l.minY||e.x-r>l.maxX||e.y-r>l.maxY))&&wc(e,l.A,l.B)<r)return!0}const A=this.viaDiameter/2+this.traceThickness/2+n;if(this.obstacleViaIndex){const c=this.obstacleViaIndex.search(e.x-A,e.y-A,e.x+A,e.y+A);for(const l of c){const u=this.obstacleVias[l];if(u&&no(e,u)<A)return!0}}return!1}isNodeTooCloseToEdge(e,n){const o=n?this.viaDiameter/2+this.obstacleMargin/2:this.obstacleMargin/2,i=e.x<this.bounds.minX+o||e.x>this.bounds.maxX-o||e.y<this.bounds.minY+o||e.y>this.bounds.maxY-o;return!(i&&!n&&(no(e,this.B)<2*o||no(e,this.A)<2*o))&&i}doesPathToParentIntersectObstacle(e,n){const o=e.parent;if(!o)return!1;const i=n?.segments??this.obstacleSegmentsByLayer.get(e.z);if(!i)return!1;const r=e.z===o.z&&this.obstacleSegments.length>0?this.NEARBY_SEGMENT_CLEARANCE:0,s=Math.min(e.x,o.x),a=Math.max(e.x,o.x),A=Math.min(e.y,o.y),c=Math.max(e.y,o.y),l=n?.segmentIds??this.obstacleSegmentIndexByLayer.get(e.z)?.search(s-r,A-r,a+r,c+r)??[];for(const u of l){const g=i[u];if(g&&!g.connectedToCurrentConnection&&!(g.z!==e.z||n&&(a+r<g.minX||c+r<g.minY||s-r>g.maxX||A-r>g.maxY))&&(Uh(e,o,g.A,g.B)||r>0&&yXn(e,o,g.A,g.B)<r))return!0}return!1}getPlanarObstacleQuery(e){const n=e.parent;if(!n)return;const o=this.obstacleSegmentIndexByLayer.get(e.z),i=this.obstacleSegmentsByLayer.get(e.z);if(!o||!i)return;const r=this.traceThickness+this.obstacleMargin,s=e.z===n.z&&this.obstacleSegments.length>0?this.NEARBY_SEGMENT_CLEARANCE:0;return{segments:i,segmentIds:o.search(Math.min(e.x-r,n.x-s),Math.min(e.y-r,n.y-s),Math.max(e.x+r,n.x+s),Math.max(e.y+r,n.y+s))}}buildObstacleIndexes(){if(this.obstacleRoutes.length===0)return this.obstacleSegmentIndex=null,this.obstacleSegmentsByLayer.clear(),this.obstacleSegmentIndexByLayer.clear(),void(this.obstacleViaIndex=null);const e=[],n=[];for(const o of this.obstacleRoutes){const i=this.connMap?.areIdsConnected?.(this.connectionName,o.connectionName)??!1;for(const r of CXn(o))e.push({...r,minX:Math.min(r.A.x,r.B.x),minY:Math.min(r.A.y,r.B.y),maxX:Math.max(r.A.x,r.B.x),maxY:Math.max(r.A.y,r.B.y),connectedToCurrentConnection:i});for(const r of o.vias)n.push(r)}if(this.obstacleSegments=e,this.obstacleVias=n,this.obstacleSegmentsByLayer.clear(),this.obstacleSegmentIndexByLayer.clear(),e.length>0){const o=new X4(e.length);for(const i of e)o.add(i.minX,i.minY,i.maxX,i.maxY);o.finish(),this.obstacleSegmentIndex=o;for(const i of e){if(i.connectedToCurrentConnection)continue;const r=this.obstacleSegmentsByLayer.get(i.z);r?r.push(i):this.obstacleSegmentsByLayer.set(i.z,[i])}for(const[i,r]of this.obstacleSegmentsByLayer){const s=new X4(r.length);for(const a of r)s.add(a.minX,a.minY,a.maxX,a.maxY);s.finish(),this.obstacleSegmentIndexByLayer.set(i,s)}}else this.obstacleSegmentIndex=null;if(n.length>0){const o=new X4(n.length);for(const i of n)o.add(i.x,i.y,i.x,i.y);o.finish(),this.obstacleViaIndex=o}else this.obstacleViaIndex=null}computeH(e){return no(e,this.B)+(e.z!==this.B.z?this.viaPenaltyDistance:0)}computeG(e){return(e.parent?.g??0)+(e.z===e.parent?.z?0:this.viaPenaltyDistance)+no(e,e.parent)}computeF(e,n){return e+n*this.GREEDY_MULTIPLER}setNodeCosts(e){e.g=this.computeG(e),e.h=this.computeH(e),e.f=this.computeF(e.g,e.h)}getNodeKey(e){const n=Math.round(e.x/this.cellStep)-this.gridMinXIndex,o=Math.round(e.y/this.cellStep)-this.gridMinYIndex;return(e.z*this.gridHeight+o)*this.gridWidth+n}getNeighbors(e){const n=[],{maxX:o,minX:i,maxY:r,minY:s}=this.bounds;for(let a=-1;a<=1;a++)for(let A=-1;A<=1;A++){if(a===0&&A===0)continue;const c={x:oft(e.x+a*this.cellStep,i,o),y:oft(e.y+A*this.cellStep,s,r),z:e.z,g:e.g,h:e.h,f:e.f,parent:e},l=this.getNodeKey(c);if(this.exploredNodes.has(l))continue;const u=this.getPlanarObstacleQuery(c);this.isNodeTooCloseToObstacle(c,void 0,!1,u)?(this.debugEnabled&&this.debug_nodesTooCloseToObstacle.add(l),this.exploredNodes.add(l)):this.isNodeTooCloseToEdge(c,!1)?this.exploredNodes.add(l):this.doesPathToParentIntersectObstacle(c,u)?(this.debugEnabled&&this.debug_nodePathToParentIntersectsObstacle.add(l),this.exploredNodes.add(l)):(this.setNodeCosts(c),n.push(c))}for(const a of this.availableZ){if(a===e.z)continue;const A={x:e.x,y:e.y,z:a,g:e.g,h:e.h,f:e.f,parent:e};this.exploredNodes.has(this.getNodeKey(A))||this.isNodeTooCloseToObstacle(A,this.viaDiameter/2+this.obstacleMargin/2,!0)||this.isNodeTooCloseToEdge(A,!0)||(this.setNodeCosts(A),n.push(A))}return n}getNodePath(e){const n=[];for(;e;)n.push(e),e=e.parent;return n}getViasInNodePath(e){const n=this.viasInPathByNode.get(e);if(n)return n;const o=e.parent,i=o?this.getViasInNodePath(o):[],r=o&&e.z!==o.z?[{x:e.x,y:e.y},...i]:i;return this.viasInPathByNode.set(e,r),r}setSolvedPath(e){const n=this.getNodePath(e);n.reverse();const o=[];for(let i=0;i<n.length-1;i++)n[i].z!==n[i+1].z&&o.push({x:n[i].x,y:n[i].y});this.solvedPath={connectionName:this.connectionName,rootConnectionName:this.rootConnectionName,regionId:this.regionId,traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,route:n.map(i=>({x:i.x,y:i.y,z:i.z})).concat([this.B]),vias:o}}computeProgress(e,n,o){if(n===void 0||o===void 0)return Number.NaN;o||(n+=this.viaPenaltyDistance);const i=1-n/this.straightLineDistance;return Math.max(this.progress||0,2/Math.PI*Math.atan(.112*i/(1-i)))}_step(){let e=this.candidates.dequeue(),n=e?this.getNodeKey(e):void 0;for(;e&&n&&this.exploredNodes.has(n);)e=this.candidates.dequeue(),n=e?this.getNodeKey(e):void 0;if(!e||!n)return this.failed=!0,void(this.error="Ran out of candidate nodes to explore");this.exploredNodes.add(n),this.debugEnabled&&this.debug_exploredNodesOrdered.push({key:n,x:Math.round(e.x/this.cellStep)*this.cellStep+this.initialNodeGridOffset.x,y:Math.round(e.y/this.cellStep)*this.cellStep+this.initialNodeGridOffset.y,z:e.z});const o=no(e,this.B);this.progress=this.computeProgress(e,o,e.z===this.B.z),o<=this.cellStep*Math.SQRT2&&e.z===this.B.z&&!this.doesPathToParentIntersectObstacle({...e,parent:e,x:this.B.x,y:this.B.y})&&(this.solved=!0,this.setSolvedPath(e));const i=this.getNeighbors(e);for(const r of i)this.candidates.enqueue(r)}visualize(){const e={lines:[],points:[],rects:[],circles:[]};e.points.push({x:this.A.x,y:this.A.y,label:oL(this.connectionName,this.rootConnectionName,["Input A",`z: ${this.A.z}`]),color:"orange"}),e.points.push({x:this.B.x,y:this.B.y,label:oL(this.connectionName,this.rootConnectionName,["Input B",`z: ${this.B.z}`]),color:"orange"}),e.lines.push({points:[this.A,this.B],strokeColor:"rgba(255, 0, 0, 0.5)",label:oL(this.connectionName,this.rootConnectionName,["Direct Input Connection"])});for(let n=0;n<this.obstacleRoutes.length;n++){const o=this.obstacleRoutes[n];for(let i=0;i<o.route.length-1;i++){const r=o.route[i].z;e.lines.push({points:[o.route[i],o.route[i+1]],strokeColor:r===0?"rgba(255, 0, 0, 0.75)":"rgba(255, 128, 0, 0.25)",strokeWidth:o.traceThickness,label:oL(o.connectionName,o.rootConnectionName,["Obstacle Route"]),layer:`obstacle${n.toString()}`})}}for(let n=0;n<this.debug_exploredNodesOrdered.length;n++){const{key:o,x:i,y:r,z:s}=this.debug_exploredNodesOrdered[n];this.debug_nodesTooCloseToObstacle.has(o)||this.debug_nodePathToParentIntersectsObstacle.has(o)||e.rects.push({center:{x:i+s*this.cellStep/20,y:r+s*this.cellStep/20},fill:s===0?`rgba(255,0,255,${.3-n/this.debug_exploredNodesOrdered.length*.2})`:`rgba(0,0,255,${.3-n/this.debug_exploredNodesOrdered.length*.2})`,width:.9*this.cellStep,height:.9*this.cellStep,label:`Explored (z=${s})`})}if(this.candidates.peek()){const n=this.candidates.peek();e.rects.push({center:{x:n.x+n.z*this.cellStep/20,y:n.y+n.z*this.cellStep/20},fill:"rgba(0, 255, 0, 0.8)",width:.9*this.cellStep,height:.9*this.cellStep,label:`Next (z=${n.z})`})}for(const n of this.obstacleRoutes)for(const o of n.vias)e.circles.push({center:{x:o.x,y:o.y},radius:this.viaDiameter/2,fill:"rgba(255, 0, 0, 0.5)",label:"Via"});if(this.solvedPath){e.lines.push({points:this.solvedPath.route,strokeColor:"green",label:oL(this.solvedPath.connectionName,this.solvedPath.rootConnectionName,["Solved Route"])});for(const n of this.solvedPath.vias)e.circles.push({center:n,radius:this.viaDiameter/2,fill:"green",label:oL(this.solvedPath.connectionName,this.solvedPath.rootConnectionName,["Via"])})}return e}};function CXn(t){const e=[];for(let n=0;n<t.route.length-1;n++)t.route[n].z===t.route[n+1].z&&e.push({z:t.route[n].z,A:t.route[n],B:t.route[n+1]});return e}function oft(t,e,n){return Math.max(e,Math.min(t,n))}function yXn(t,e,n,o){return Math.min(wc(t,n,o),wc(e,n,o),wc(n,t,e),wc(o,t,e))}var ift=class extends IXn{FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR=2;FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR=1;FUTURE_CONNECTION_PROXIMITY_VD=10;MISALIGNED_DIST_PENALTY_FACTOR=5;VIA_PENALTY_FACTOR_2=1;FLIP_TRACE_ALIGNMENT_DIRECTION=!1;FUTURE_CONNECTION_VIA_TRACE_CLEARANCE=.1;futureConnectionPoints;futureConnectionSegmentsCache=null;constructor(e){super({...e,nearbySegmentClearance:e.nearbySegmentClearance??(e.traceThickness??.15)/2+(e.obstacleMargin??.15)});for(const i in e.hyperParameters)this[i]=e.hyperParameters[i];const n=this.boundsSize.width/this.viaDiameter,o=Math.max(1,this.numRoutes);this.VIA_PENALTY_FACTOR=n/o*.3*this.VIA_PENALTY_FACTOR_2,this.futureConnectionPoints=this.futureConnections.flatMap(i=>i.points)}getClosestFutureConnectionPoint(e){let n=1/0,o=null;for(const i of this.futureConnectionPoints){const r=no(e,i)+(e.z!==i.z?this.viaPenaltyDistance:0);r<n&&(n=r,o=i)}return o}getFutureConnectionSegments(){if(this.futureConnectionSegmentsCache)return this.futureConnectionSegmentsCache;const e=[];for(const n of this.futureConnections){if(n.connectionName===this.connectionName||(this.connMap?.areIdsConnected?.(this.connectionName,n.connectionName)??!1))continue;const[o,...i]=n.points;if(o)for(const r of i)Math.abs(o.x-r.x)<1e-9&&Math.abs(o.y-r.y)<1e-9||e.push({connectionName:n.connectionName,start:o,end:r})}return this.futureConnectionSegmentsCache=e,e}isViaTooCloseToFutureConnectionTrace(e){const n=this.viaDiameter/2+this.traceThickness/2+this.FUTURE_CONNECTION_VIA_TRACE_CLEARANCE;for(const o of this.getFutureConnectionSegments())if(wc(e,o.start,o.end)<n)return!0;return!1}isNodeTooCloseToObstacle(e,n,o,i){return!!super.isNodeTooCloseToObstacle(e,n,o,i)||!(!o||!this.isViaTooCloseToFutureConnectionTrace(e))}diminishCloseToGoal(e){const n=no(e,this.B);return 1-Math.exp(-n/this.straightLineDistance*5)}getFutureConnectionPenalty(e,n){let o=0;const i=this.getClosestFutureConnectionPoint(e),r=no(e,this.B);if(i){const s=no(e,i);if(r<=s)return 0;const a=s/(this.viaDiameter*this.FUTURE_CONNECTION_PROXIMITY_VD);o=(n?this.straightLineDistance*this.FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR:this.straightLineDistance*this.FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR)*Math.exp(5*-a)}return o}computeH(e){const n=no(e,this.B)**1.6;return this.straightLineDistance,n+(e.z!==this.B.z?this.viaPenaltyDistance:0)+this.getFutureConnectionPenalty(e,e.z!==e.parent?.z)}computeG(e){const n=Math.abs(e.x-e.parent.x),o=Math.abs(e.y-e.parent.y),i=Math.sqrt(n**2+o**2),r=e.z%2==0,s=this.FLIP_TRACE_ALIGNMENT_DIRECTION?r?n:o:r?o:n;return(e.parent?.g??0)+(e.z===e.parent?.z?0:this.viaPenaltyDistance)+i+s*this.MISALIGNED_DIST_PENALTY_FACTOR+this.getFutureConnectionPenalty(e,e.z!==e.parent?.z)}setNodeCosts(e){const n=Math.abs(e.x-e.parent.x),o=Math.abs(e.y-e.parent.y),i=Math.sqrt(n**2+o**2),r=e.z%2==0,s=this.FLIP_TRACE_ALIGNMENT_DIRECTION?r?n:o:r?o:n,a=(e.parent?.g??0)+(e.z===e.parent?.z?0:this.viaPenaltyDistance)+i+s*this.MISALIGNED_DIST_PENALTY_FACTOR,A=no(e,this.B)**1.6+(e.z!==this.B.z?this.viaPenaltyDistance:0),c=this.getFutureConnectionPenalty(e,e.z!==e.parent?.z);e.g=a+c,e.h=A+c,e.f=this.computeF(e.g,e.h)}},D7e=(t,e,n=[])=>[t,e?`rootConnectionName: ${e}`:void 0,...n].filter(Boolean).join(`
`),xXn=t=>`${t.x.toFixed(6)},${t.y.toFixed(6)},${t.z}`,N7e=t=>{const e=new Set,n=[];for(const o of t){const i=xXn(o);e.has(i)||(e.add(i),n.push(o))}return n},Wse=class extends yr{getSolverName(){return"IntraNodeRouteSolver"}nodeWithPortPoints;colorMap;unsolvedConnections;originalConnectionPointsByName;rootConnectionNameByConnectionName;totalConnections;solvedRoutes;failedSubSolvers;hyperParameters;minDistBetweenEnteringPoints;viaDiameter;traceWidth;obstacleMargin;captureSearchDebug;rerouteAttemptsByConnection;POSTROUTE_VIA_TRACE_CLEARANCE=.1;MAX_POSTROUTE_REPAIR_ATTEMPTS=2;activeSubSolver=null;connMap;get failedSolvers(){return this.failedSubSolvers}get activeSolver(){return this.activeSubSolver}constructor(e){const{nodeWithPortPoints:n,colorMap:o}=e;super(),this.nodeWithPortPoints=n,this.colorMap=o??{},this.solvedRoutes=[],this.hyperParameters=e.hyperParameters??{},this.failedSubSolvers=[],this.connMap=e.connMap,this.viaDiameter=e.viaDiameter??.3,this.traceWidth=e.traceWidth??.15,this.obstacleMargin=e.obstacleMargin??.15,this.captureSearchDebug=e.captureSearchDebug??!0;const i=new Map;this.rootConnectionNameByConnectionName=new Map;for(const{connectionName:r,rootConnectionName:s,x:a,y:A,z:c}of n.portPoints)s&&this.rootConnectionNameByConnectionName.set(r,s),i.set(r,[...i.get(r)??[],{x:a,y:A,z:c??0}]);this.originalConnectionPointsByName=new Map(Array.from(i.entries()).map(([r,s])=>[r,N7e(s)])),this.unsolvedConnections=Array.from(i.entries().map(([r,s])=>({connectionName:r,rootConnectionName:this.rootConnectionNameByConnectionName.get(r),points:N7e(s)}))),this.rerouteAttemptsByConnection=new Map,this.hyperParameters.SHUFFLE_SEED&&(this.unsolvedConnections=D5(this.unsolvedConnections,this.hyperParameters.SHUFFLE_SEED??0),this.unsolvedConnections=this.unsolvedConnections.map(({points:r,...s},a)=>({...s,points:D5(r,7117*a+(this.hyperParameters.SHUFFLE_SEED??0))}))),this.totalConnections=this.unsolvedConnections.length,this.MAX_ITERATIONS=1e3*this.totalConnections**1.5,this.minDistBetweenEnteringPoints=_Xn(this.nodeWithPortPoints)}computeProgress(){return(this.solvedRoutes.length+(this.activeSubSolver?.progress||0))/this.totalConnections}getSingleRouteSolverOpts(e){const{connectionName:n,rootConnectionName:o,points:i}=e;return{connectionName:n,rootConnectionName:o,regionId:this.nodeWithPortPoints.capacityMeshNodeId,minDistBetweenEnteringPoints:this.minDistBetweenEnteringPoints,bounds:Tz(this.nodeWithPortPoints),A:{x:i[0].x,y:i[0].y,z:i[0].z},B:{x:i[i.length-1].x,y:i[i.length-1].y,z:i[i.length-1].z},obstacleRoutes:this.connMap?this.solvedRoutes.filter(r=>!this.connMap.areIdsConnected(r.connectionName,n)):this.solvedRoutes,futureConnections:this.unsolvedConnections,layerCount:this.nodeWithPortPoints.portPoints.reduce((r,s)=>Math.max(r,(s.z??0)+1),2),availableZ:this.nodeWithPortPoints.availableZ&&this.nodeWithPortPoints.availableZ.length>0?this.nodeWithPortPoints.availableZ:[...new Set(this.nodeWithPortPoints.portPoints.map(r=>r.z??0))].sort((r,s)=>r-s),hyperParameters:this.hyperParameters,connMap:this.connMap,viaDiameter:this.viaDiameter,traceThickness:this.traceWidth,obstacleMargin:this.obstacleMargin,captureSearchDebug:this.captureSearchDebug}}trySolveSamePointLayerChange(e){const n=this.getSingleRouteSolverOpts(e),o=new ift(n),{A:i,B:r}=n,s={x:i.x,y:i.y};if(!EXn(o,s,i))return!1;const a=[{x:i.x,y:i.y,z:i.z},{...s,z:i.z},{...s,z:r.z},{x:r.x,y:r.y,z:r.z}].filter((A,c,l)=>c===0||Math.abs(A.x-l[c-1].x)>1e-6||Math.abs(A.y-l[c-1].y)>1e-6||A.z!==l[c-1].z);return this.solvedRoutes.push({connectionName:e.connectionName,rootConnectionName:e.rootConnectionName,regionId:this.nodeWithPortPoints.capacityMeshNodeId,traceThickness:this.traceWidth,viaDiameter:this.viaDiameter,route:a,vias:[{x:s.x,y:s.y}]}),!0}queueExtraBranchesForMultiPointConnection(e){const[n,...o]=N7e(e.points);if(!n||o.length<=1)return!1;for(const i of o)this.unsolvedConnections.push({connectionName:e.connectionName,rootConnectionName:e.rootConnectionName,points:[n,i]});return!0}getAvailableZLayers(){return this.nodeWithPortPoints.availableZ&&this.nodeWithPortPoints.availableZ.length>0?[...new Set(this.nodeWithPortPoints.availableZ)].sort((e,n)=>e-n):[...new Set(this.nodeWithPortPoints.portPoints.map(e=>e.z??0))].sort((e,n)=>e-n)}getFirstSolvedViaTraceConflict(){if(this.solvedRoutes.length<2)return null;const e=new oB(this.solvedRoutes),n=this.getAvailableZLayers();for(const o of this.solvedRoutes){const i=o.viaDiameter/2+this.POSTROUTE_VIA_TRACE_CLEARANCE;for(const r of o.vias)for(const s of n){const a=e.getConflictingRoutesNearPoint({x:r.x,y:r.y,z:s},i).filter(({conflictingRoute:A})=>A.connectionName!==o.connectionName&&!this.connMap?.areIdsConnected(o.connectionName,A.connectionName));if(a.length>0)return{route:o,via:r,conflictingRoute:a[0].conflictingRoute}}}return null}queueConnectionForPostrouteRepair(e){const n=this.originalConnectionPointsByName.get(e);return!(!n||n.length<2)&&(this.solvedRoutes=this.solvedRoutes.filter(o=>o.connectionName!==e),this.unsolvedConnections.push({connectionName:e,rootConnectionName:this.rootConnectionNameByConnectionName.get(e),points:n.map(o=>({...o}))}),this.rerouteAttemptsByConnection.set(e,(this.rerouteAttemptsByConnection.get(e)??0)+1),!0)}_step(){if(this.activeSubSolver)return this.activeSubSolver.step(),this.progress=this.computeProgress(),void(this.activeSubSolver.solved?(this.solvedRoutes.push(this.activeSubSolver.solvedPath),this.activeSubSolver=null):this.activeSubSolver.failed&&(this.failedSubSolvers.push(this.activeSubSolver),this.activeSubSolver=null,this.error=this.failedSubSolvers.map(n=>n.error).join(`
`),this.failed=!0));const e=this.unsolvedConnections.pop();if(this.progress=this.computeProgress(),!e){const n=this.getFirstSolvedViaTraceConflict();if(n){if((this.rerouteAttemptsByConnection.get(n.route.connectionName)??0)>=this.MAX_POSTROUTE_REPAIR_ATTEMPTS)return this.error=["Post-route via/trace clearance repair exceeded retry budget",`route: ${n.route.connectionName}`,`conflicts with: ${n.conflictingRoute.connectionName}`,`via: (${n.via.x.toFixed(3)}, ${n.via.y.toFixed(3)})`].join(`
`),void(this.failed=!0);if(this.queueConnectionForPostrouteRepair(n.route.connectionName))return void(this.progress=this.computeProgress())}return void(this.solved=this.failedSubSolvers.length===0)}if(e.points.length!==1&&!(e.points.length>2&&this.queueExtraBranchesForMultiPointConnection(e))){if(e.points.length===2){const[n,o]=e.points,i=Math.abs(n.x-o.x)<1e-6,r=Math.abs(n.y-o.y)<1e-6;if(i&&r&&n.z===o.z||i&&r&&n.z!==o.z&&this.trySolveSamePointLayerChange(e))return}this.activeSubSolver=new ift(this.getSingleRouteSolverOpts(e))}}visualize(){const e={lines:[],points:[],rects:[],circles:[]};for(const a of this.nodeWithPortPoints.portPoints)e.points.push({x:a.x,y:a.y,label:D7e(a.connectionName,a.rootConnectionName,[`layer: ${a.z}`]),color:this.colorMap[a.connectionName]??"blue"});for(let a=0;a<this.solvedRoutes.length;a++){const A=this.solvedRoutes[a];if(A.route.length>0){const c=this.colorMap[A.connectionName]??"blue",l=A.rootConnectionName??this.rootConnectionNameByConnectionName.get(A.connectionName);for(let u=0;u<A.route.length-1;u++){const g=A.route[u],h=A.route[u+1];e.lines.push({points:[g,h],label:D7e(A.connectionName,l,[`layer: ${g.z}`]),strokeColor:g.z===0?Es(c,.2):Es(c,.8),layer:`route-layer-${g.z}`,step:a,strokeWidth:A.traceThickness})}for(const u of A.vias)e.circles.push({center:{x:u.x,y:u.y},radius:A.viaDiameter/2,fill:Es(c,.5),layer:"via",step:a,label:D7e(A.connectionName,l,["via"])})}}const n=Tz(this.nodeWithPortPoints),{minX:o,minY:i,maxX:r,maxY:s}=n;return e.lines.push({points:[{x:o,y:i},{x:r,y:i},{x:r,y:s},{x:o,y:s},{x:o,y:i}],strokeColor:"rgba(255, 0, 0, 0.25)",strokeDash:"4 4",layer:"border"}),e}},EXn=(t,e,n,o)=>{const i={x:e.x,y:e.y,z:n.z,parent:{x:n.x,y:n.y,z:n.z,g:0,h:0,f:0,parent:null},g:0,h:0,f:0};return!t.isNodeTooCloseToObstacle(i,t.viaDiameter/2+t.obstacleMargin/2,!0)&&!t.isNodeTooCloseToEdge(i,!0)},N5=t=>Math.round(200*t)/200,R7e=t=>typeof structuredClone=="function"?structuredClone(t):JSON.parse(JSON.stringify(t));Lse();var T7e=class extends Wse{getSolverName(){return"CachedIntraNodeRouteSolver"}cacheProvider;cacheHit=!1;hasAttemptedToUseCache=!1;initialUnsolvedConnections;constructor(e){super(e),this.cacheProvider=e.cacheProvider===void 0?tB():e.cacheProvider,this.initialUnsolvedConnections=R7e(this.unsolvedConnections),(this.solved||this.failed)&&this.cacheProvider&&!this.cacheHit&&this.saveToCacheSync()}_step(){if(!this.hasAttemptedToUseCache&&this.cacheProvider&&this.attemptToUseCacheSync())return;const e=this.solved,n=this.failed;super._step(),!this.cacheProvider||this.cacheHit||!this.solved&&!this.failed||e||n||this.saveToCacheSync()}computeCacheKeyAndTransform(){const e=this.nodeWithPortPoints.center,n=this.initialUnsolvedConnections.map(({connectionName:c,rootConnectionName:l,points:u})=>({connectionName:c,rootConnectionName:l,points:u.map(g=>({connectionName:c,x:N5(g.x-e.x),y:N5(g.y-e.y),z:g.z??0}))})),o=[...this.nodeWithPortPoints.portPoints].sort((c,l)=>c.connectionName!==l.connectionName?c.connectionName.localeCompare(l.connectionName):(c.portPointId??"")!==(l.portPointId??"")?(c.portPointId??"").localeCompare(l.portPointId??""):c.x!==l.x?c.x-l.x:c.y!==l.y?c.y-l.y:(c.z??0)-(l.z??0)).map(c=>({connectionName:c.connectionName,rootConnectionName:c.rootConnectionName,portPointId:c.portPointId,prevPortPointId:c.prevPortPointId,nextPortPointId:c.nextPortPointId,x:N5(c.x-e.x),y:N5(c.y-e.y),z:c.z??0})),i=Object.fromEntries(Object.entries(this.hyperParameters??{}).filter(([,c])=>c!==void 0).sort(([c],[l])=>c.localeCompare(l))),r=this.connMap?this.initialUnsolvedConnections.map(({connectionName:c})=>({connectionName:c,connectedIds:[...new Set(this.connMap.getIdsConnectedToNet(c)??[])].sort()})):void 0,s={cacheSchemaVersion:4,node:{width:N5(this.nodeWithPortPoints.width),height:N5(this.nodeWithPortPoints.height),center:{x:N5(this.nodeWithPortPoints.center.x),y:N5(this.nodeWithPortPoints.center.y)},availableZ:this.nodeWithPortPoints.availableZ?[...this.nodeWithPortPoints.availableZ].sort():void 0,portPoints:o},normalizedConnections:n,normalizedHyperParameters:i,minDistBetweenEnteringPoints:N5(this.minDistBetweenEnteringPoints),traceWidth:N5(this.traceWidth),viaDiameter:N5(this.viaDiameter),obstacleMargin:N5(this.obstacleMargin),normalizedConnMap:r},a=`intranode-solver:${$9e(s,{respectType:!1,unorderedObjects:!1})}`,A={};return this.cacheKey=a,this.cacheToSolveSpaceTransform=A,{cacheKey:a,cacheToSolveSpaceTransform:A}}applyCachedSolution(e){e.success?(this.solvedRoutes=R7e(e.solvedRoutes),this.solved=!0,this.failed=!1):(this.solvedRoutes=[],this.failedSubSolvers=[],this.solved=!1,this.failed=!0,this.error=e.error??this.error),this.unsolvedConnections=[],this.activeSubSolver=null,this.cacheHit=!0,this.progress=1}attemptToUseCacheSync(){if(this.hasAttemptedToUseCache=!0,!this.cacheProvider?.isSyncCache)return!1;if(!this.cacheKey)try{this.computeCacheKeyAndTransform()}catch(e){return console.error("Error computing cache key:",e),!1}if(!this.cacheKey)return console.error("Failed to compute cache key."),!1;try{const e=this.cacheProvider.getCachedSolutionSync(this.cacheKey);if(e!=null)return this.applyCachedSolution(e),!0}catch(e){console.error("Error attempting to use cache:",e)}return!1}saveToCacheSync(){if(!this.cacheProvider?.isSyncCache)return;if(!this.cacheKey)try{this.computeCacheKeyAndTransform()}catch(n){return void console.error("Error computing cache key during save:",n)}if(!this.cacheKey)return void console.error("Failed to compute cache key before saving.");const e=this.failed?{success:!1,error:this.error??void 0}:{success:!0,solvedRoutes:R7e(this.solvedRoutes)};try{this.cacheProvider.setCachedSolutionSync(this.cacheKey,e)}catch(n){console.error("Error saving solution to cache:",n)}}},rft=(t,e)=>{const n={};return t.portPoints.forEach((o,i)=>{n[o.connectionName]=`hsl(${360*i/t.portPoints.length}, 100%, 50%)`}),n},BXn=class extends yr{getSolverName(){return"ViaPossibilitiesSolver2"}bounds;maxViaCount;portPairMap;colorMap;nodeWidth;availableZ;hyperParameters;VIA_INTERSECTION_BUFFER_DISTANCE=.05;PLACEHOLDER_WALL_BUFFER_DISTANCE=.1;NEW_HEAD_WALL_BUFFER_DISTANCE=.05;viaDiameter;unprocessedConnections;completedPaths=new Map;placeholderPaths=new Map;currentHead;currentConnectionName;currentPath;currentViaCount;constructor({nodeWithPortPoints:e,colorMap:n,hyperParameters:o,viaDiameter:i}){super(),this.MAX_ITERATIONS=1e5,this.colorMap=n??rft(e),this.maxViaCount=5,this.bounds=Tz(e),this.nodeWidth=this.bounds.maxX-this.bounds.minX,this.portPairMap=(s=>{const a=new Map;return s.portPoints.forEach(A=>{a.has(A.connectionName)?a.get(A.connectionName).end=A:a.set(A.connectionName,{start:A,end:null,connectionName:A.connectionName})}),a})(e),this.stats.solutionsFound=0,this.availableZ=e.availableZ??[0,1],this.hyperParameters=o??{SHUFFLE_SEED:0},this.viaDiameter=i??.3,this.unprocessedConnections=Array.from(this.portPairMap.keys()).sort(),o?.SHUFFLE_SEED&&(this.unprocessedConnections=D5(this.unprocessedConnections,o.SHUFFLE_SEED));for(const[s,{start:a,end:A}]of this.portPairMap.entries())if(a.z===A.z){const c=Math.abs(a.x-A.x)<1e-9,l=Math.abs(a.y-A.y)<1e-9;c||l?this.placeholderPaths.set(s,[a,this._padByPlaceholderWallBuffer(a),this._padByPlaceholderWallBuffer(A),A]):this.placeholderPaths.set(s,[a,A])}else{const c=(a.x+A.x)/2,l=(a.y+A.y)/2,u=this._padByPlaceholderWallBuffer({x:c,y:l,z:a.z}),g=this._padByPlaceholderWallBuffer({x:c,y:l,z:A.z});this.placeholderPaths.set(s,[a,this._padByPlaceholderWallBuffer(a),u,g,this._padByPlaceholderWallBuffer(A),A])}this.currentConnectionName=this.unprocessedConnections.pop();const r=this.portPairMap.get(this.currentConnectionName).start;this.currentHead=this._padByNewHeadWallBuffer(r),this.currentPath=[r,this.currentHead],this.currentViaCount=0,this.placeholderPaths.delete(this.currentConnectionName)}_padByNewHeadWallBuffer(e){return{x:V3(e.x,this.bounds.minX+this.NEW_HEAD_WALL_BUFFER_DISTANCE,this.bounds.maxX-this.NEW_HEAD_WALL_BUFFER_DISTANCE),y:V3(e.y,this.bounds.minY+this.NEW_HEAD_WALL_BUFFER_DISTANCE,this.bounds.maxY-this.NEW_HEAD_WALL_BUFFER_DISTANCE),z:e.z}}_padByPlaceholderWallBuffer(e){return{x:V3(e.x,this.bounds.minX+this.PLACEHOLDER_WALL_BUFFER_DISTANCE,this.bounds.maxX-this.PLACEHOLDER_WALL_BUFFER_DISTANCE),y:V3(e.y,this.bounds.minY+this.PLACEHOLDER_WALL_BUFFER_DISTANCE,this.bounds.maxY-this.PLACEHOLDER_WALL_BUFFER_DISTANCE),z:e.z}}_step(){if(this.solved)return;const e=this.portPairMap.get(this.currentConnectionName).end,n=[this.currentHead,e];let o=null,i=null;const r=a=>{for(const A of a.values())for(let c=0;c<A.length-1;c++){const l=[A[c],A[c+1]];if(l[0].x===l[1].x&&l[0].y===l[1].y||l[0].z!==this.currentHead.z)continue;const u=DD(n[0],n[1],l[0],l[1]);if(u){const g=no(this.currentHead,u);if(g<1e-6)continue;(!o||g<o.dist)&&(o={point:u,dist:g},i=l[0].z)}}};r(this.completedPaths),r(this.placeholderPaths);const s=this.currentHead.z!==e.z;if((o||s)&&(this.currentViaCount++,this.currentViaCount>=this.maxViaCount))return this.failed=!0,void(this.error=`Exceeded max via count of ${this.maxViaCount}`);if(o){let a;const A=o.dist;if(A<=this.VIA_INTERSECTION_BUFFER_DISTANCE+1e-6)a=V8(this.currentHead,o.point);else{const g=o.point,h=g.x-this.currentHead.x,d=g.y-this.currentHead.y,p=(A-this.VIA_INTERSECTION_BUFFER_DISTANCE)/A;a={x:this.currentHead.x+h*p,y:this.currentHead.y+d*p}}const c=this.availableZ.find(g=>g!==i);if(c===void 0)return this.error="Could not determine next Z level for via placement!",void(this.failed=!0);const l={...a,z:this.currentHead.z},u={...a,z:c};this.currentPath.push(l,u),this.currentHead=u}else if(s){let a;const A=no(this.currentHead,e);if(A<this.VIA_INTERSECTION_BUFFER_DISTANCE)a=V8(this.currentHead,e);else{const g=e.x-this.currentHead.x,h=e.y-this.currentHead.y,d=(A-this.VIA_INTERSECTION_BUFFER_DISTANCE)/A;a={x:this.currentHead.x+g*d,y:this.currentHead.y+h*d}}const c=e.z,l={...a,z:this.currentHead.z},u={...a,z:c};this.currentPath.push(l,u),this.currentHead=u}else if(this.currentPath.push(e),this.completedPaths.set(this.currentConnectionName,this.currentPath),this.unprocessedConnections.length===0)this.solved=!0,this.stats.solutionsFound=1;else{this.currentConnectionName=this.unprocessedConnections.pop();const{start:a}=this.portPairMap.get(this.currentConnectionName);this.currentHead=this._padByNewHeadWallBuffer(a),this.currentPath=[a,this.currentHead],this.currentViaCount=0,this.placeholderPaths.delete(this.currentConnectionName)}}visualize(){const e={points:[],lines:[],circles:[],rects:[],title:"Via Possibilities Solver State",coordinateSystem:"cartesian"},n=this.colorMap;e.lines.push({points:[{x:this.bounds.minX,y:this.bounds.minY},{x:this.bounds.maxX,y:this.bounds.minY},{x:this.bounds.maxX,y:this.bounds.maxY},{x:this.bounds.minX,y:this.bounds.maxY},{x:this.bounds.minX,y:this.bounds.minY}],strokeColor:"gray",strokeWidth:.01});for(const[i,{start:r,end:s}]of this.portPairMap.entries()){const a=this.colorMap[i]??"black";e.points.push({x:r.x,y:r.y,color:a,label:`Port: ${i} Start (z${r.z})`}),e.points.push({x:s.x,y:s.y,color:a,label:`Port: ${i} End (z${s.z})`})}const o=(i,r)=>{for(const[s,a]of i.entries()){const A=n[s]??"black";for(let c=0;c<a.length-1;c++){const l=a[c],u=a[c+1];l.x===u.x&&l.y===u.y&&l.z!==u.z?e.circles.push({center:{x:l.x,y:l.y},radius:this.viaDiameter/2,fill:Es(A,.5),label:`${r}: ${s} Via (z${l.z}->z${u.z})`}):e.lines.push({points:[l,u],strokeColor:Es(A,.5),strokeDash:l.z===0?void 0:[.1,.1],strokeWidth:.1,label:`${r}: ${s} (z${l.z})`})}}};if(o(this.placeholderPaths,"Placeholder"),o(this.completedPaths,"Completed"),this.currentPath&&this.currentPath.length>0){const i=n[this.currentConnectionName]??"orange";for(let r=0;r<this.currentPath.length-1;r++){const s=this.currentPath[r],a=this.currentPath[r+1];s.x===a.x&&s.y===a.y&&s.z!==a.z?e.circles.push({center:{x:s.x,y:s.y},radius:this.viaDiameter/2,fill:Es(i,.5),label:`Current: ${this.currentConnectionName} Via (z${s.z}->z${a.z})`}):e.lines.push({points:[s,a],strokeColor:Es(i,.5),strokeWidth:.15,strokeDash:"2,2",label:`Current: ${this.currentConnectionName} (z${s.z})`})}e.points.push({x:this.currentHead.x,y:this.currentHead.y,color:"green",label:`Current Head: ${this.currentConnectionName} (z${this.currentHead.z})`})}return e}},jse=t=>Math.round(1e4*t),sft=t=>{let e=0,n=[];const o=[];for(const r of t.portPoints){if(n.some(a=>a.connectionName===r.connectionName)||o.some(a=>a.connectionName===r.connectionName))continue;const s={connectionName:r.connectionName,z:r.z,points:[{x:jse(r.x),y:jse(r.y),z:r.z}]};for(const a of t.portPoints)r.connectionName===a.connectionName&&(r.x===a.x&&r.y===a.y||s.points.push({x:jse(a.x),y:jse(a.y),z:a.z}));s.points.some(a=>a.z!==s.z)?o.push(s):n.push(s)}n=n.filter(r=>r.points.length>1);for(let r=0;r<n.length;r++)for(let s=r+1;s<n.length;s++){const a=n[r],A=n[s];a.z===A.z&&Uh(a.points[0],a.points[1],A.points[0],A.points[1])&&e++}let i=0;for(let r=0;r<o.length;r++)for(let s=r+1;s<o.length;s++){const a=o[r],A=o[s];Uh(a.points[0],a.points[1],A.points[0],A.points[1])&&i++}return{numSameLayerCrossings:e,numEntryExitLayerChanges:o.length,numTransitionPairCrossings:i}},bXn=t=>{const{start:e,end:n,segmentsPerPolyline:o,viaPositions:i,viaCount:r,availableZ:s}=t,a=(function(h,d){const p=new Array(h).fill(0);if(d===0)return p;if(d===h)return p.fill(1);if(d<=h/2){const m=Math.floor(h/d),_=Math.floor((h-(m*(d-1)+1))/2);for(let f=0;f<d;f++)p[_+f*m]=1}else{const m=h-d,_=Math.floor(h/m),f=Math.floor((h-(_*(m-1)+1))/2);p.fill(1);for(let I=0;I<m;I++)p[f+I*_]=0}return p})(o,r),A=a.map(()=>null);let c=0,l=e.z1;const u=s.indexOf(e.z1);for(let h=0;h<a.length;h++)if(a[h]===1){const d=s[(u+c+1)%s.length];A[h]={...i[c],z1:l,z2:d},l=d,c++}let g=e;for(let h=0;h<A.length;h++){if(A[h]){g=A[h];continue}let d=n,p=A.length;for(let I=h+1;I<A.length;I++)if(A[I]){d=A[I],p=I;break}const m=p-h,_=d.x-g.x,f=d.y-g.y;for(let I=1/(m+1),C=0;h+C!==p;I+=1/(m+1),C++)A[h+C]={x:g.x+_*I,y:g.y+f*I,z1:g.z2,z2:g.z2}}return A},iL=1e-9;function $se(t,e){return Math.abs(t-e)<iL}function k7e(t){return`${Math.round(t.x/iL)}:${Math.round(t.y/iL)}`}function F7e(t,e,n,o){return t*o-e*n}function SXn(t,e,n,o){const i={x:e.x-t.x,y:e.y-t.y},r={x:o.x-n.x,y:o.y-n.y},s=F7e(i.x,i.y,r.x,r.y),a={x:n.x-t.x,y:n.y-t.y};if($se(s,0))return null;const A=F7e(a.x,a.y,r.x,r.y)/s,c=F7e(a.x,a.y,i.x,i.y)/s;return A>=-1e-9&&A<=1+iL&&c>=-1e-9&&c<=1+iL?{x:t.x+A*i.x,y:t.y+A*i.y}:null}function aft(t,e,n){return $se(Math.hypot(t.x-e.x,t.y-e.y)+Math.hypot(t.x-n.x,t.y-n.y),Math.hypot(e.x-n.x,e.y-n.y))}function QXn(t,e){const n=[],o=new Map;for(const d of t){const p=[d.start,...d.mPoints,d.end];for(let _=0;_<p.length-1;_++){const f=p[_],I=p[_+1],C=f.z2;if(n.push({start:{x:f.x,y:f.y},end:{x:I.x,y:I.y},connectionName:d.connectionName,layer:C}),f.z1!==f.z2){const y=k7e(f);o.has(y)||o.set(y,{point:f,connectionName:d.connectionName})}}const m=p[p.length-1];if(m.z1!==m.z2){const _=k7e(m);o.has(_)||o.set(_,{point:m,connectionName:d.connectionName})}}const i=[{start:{x:e.minX,y:e.minY},end:{x:e.maxX,y:e.minY},connectionName:null,layer:0},{start:{x:e.maxX,y:e.minY},end:{x:e.maxX,y:e.maxY},connectionName:null,layer:0},{start:{x:e.maxX,y:e.maxY},end:{x:e.minX,y:e.maxY},connectionName:null,layer:0},{start:{x:e.minX,y:e.maxY},end:{x:e.minX,y:e.minY},connectionName:null,layer:0}];n.push(...i);const r=new Map;let s=0;function a(d,p){const m=k7e(d);let _=r.get(m);if(!_){const f=o.has(m);_={id:s++,x:d.x,y:d.y,isVia:f,connectionNames:new Set,outgoingEdges:[]},r.set(m,_),f&&o.get(m)&&_.connectionNames.add(o.get(m).connectionName)}return p&&_.connectionNames.add(p),_}for(const d of n)a(d.start,d.connectionName),a(d.end,d.connectionName);const A=new Map;for(const d of n)A.set(d,[]);for(let d=0;d<n.length;d++)for(let p=d+1;p<n.length;p++){if(n[d].layer!==n[p].layer)continue;const m=SXn(n[d].start,n[d].end,n[p].start,n[p].end);m&&(a(m),aft(m,n[d].start,n[d].end)&&A.get(n[d]).push(m),aft(m,n[p].start,n[p].end)&&A.get(n[p]).push(m))}const c=[];let l=0;for(const d of n){const p=[d.start,...A.get(d),d.end];p.sort((_,f)=>{const I=d.end.x-d.start.x,C=d.end.y-d.start.y;return Math.abs(I)>Math.abs(C)?(_.x-d.start.x)/I-(f.x-d.start.x)/I:Math.abs(C)<iL?0:(_.y-d.start.y)/C-(f.y-d.start.y)/C});const m=[];if(p.length>0){m.push(p[0]);for(let _=1;_<p.length;_++)$se(p[_].x,p[_-1].x)&&$se(p[_].y,p[_-1].y)||m.push(p[_])}for(let _=0;_<m.length-1;_++){const f=m[_],I=m[_+1],C=a(f,d.connectionName),y=a(I,d.connectionName);if(C===y)continue;const x={id:l++,origin:C,twin:null,next:null,face:null,connectionName:d.connectionName,layer:d.layer,visited:!1},E={id:l++,origin:y,twin:x,next:null,face:null,connectionName:d.connectionName,layer:d.layer,visited:!1};x.twin=E,c.push(x,E),C.outgoingEdges.push(x),y.outgoingEdges.push(E)}}for(const d of r.values()){d.outgoingEdges.sort((m,_)=>{const f=m.twin.origin,I=_.twin.origin;return Math.atan2(f.y-d.y,f.x-d.x)-Math.atan2(I.y-d.y,I.x-d.x)});const p=d.outgoingEdges.length;for(let m=0;m<p;m++){const _=d.outgoingEdges[m],f=d.outgoingEdges[(m-1+p)%p];_.twin&&(_.twin.next=f)}}let u=0,g=null,h=-1/0;for(const d of c){if(d.visited)continue;const p={id:u++,outerComponent:d,innerComponents:[],isOuterFace:!1};let m=d;const _=[],f=[],I=new Set;let C=0;do{if(!m||m.visited){console.warn("Face traversal encountered visited edge or null, breaking loop.",p.id),_.length=0;break}m.visited=!0,m.face=p,_.push(m),f.push(m.origin),m.connectionName!==null&&I.add(m.connectionName);const y=m.origin,x=m.twin.origin;C+=y.x*x.y-x.x*y.y,m=m.next}while(m!==d&&m!==null);if(m===d){if(C=.5*Math.abs(C),C>h&&(h=C,g&&(g.isOuterFace=!1),g=p,p.isOuterFace=!0),!p.isOuterFace&&_.length>0&&[...I].filter(y=>y!==null).length>1){let y=!1;for(const x of f)if(x.isVia){y=!0;break}if(!y)return!0}}else console.warn(`Face ${p.id} did not close properly.`),u--}return!1}var Aft=t=>{if(t.length===0)return[[]];const e=[];for(let n=0;n<t.length;n++){const o=t[n],i=[...t.slice(0,n),...t.slice(n+1)],r=Aft(i);for(const s of r)e.push([o,...s])}return e},L7e=1e-9;function qse(t,e,n=1e-9){return Math.abs(t-e)<n}function H7e(t,e,n,o){return t*o-e*n}function vXn(t,e,n,o){const i={x:e.x-t.x,y:e.y-t.y},r={x:o.x-n.x,y:o.y-n.y},s=H7e(i.x,i.y,r.x,r.y);if(qse(s,0))return null;const a={x:n.x-t.x,y:n.y-t.y},A=H7e(a.x,a.y,r.x,r.y)/s,c=H7e(a.x,a.y,i.x,i.y)/s;return A<-1e-9||A>1+L7e||c<-1e-9||c>1+L7e?null:{x:t.x+A*i.x,y:t.y+A*i.y}}function wXn(t){let e=0;for(let n=0,o=t.length;n<o;++n){const i=(n+1)%o;e+=t[n].x*t[i].y-t[i].x*t[n].y}return .5*e}function PXn(t){let e=0,n=0,o=0;for(let i=0,r=t.length;i<r;++i){const s=(i+1)%r,a=t[i].x*t[s].y-t[s].x*t[i].y;e+=a,n+=(t[i].x+t[s].x)*a,o+=(t[i].y+t[s].y)*a}return e*=.5,qse(e,0)?null:(n/=6*e,o/=6*e,{x:n,y:o})}var MXn=class{x;y;out;connectionNames;constructor(e,n){this.x=e,this.y=n,this.out=[],this.connectionNames=new Set}},cft=class{orig;dest;twin;next;visited;constructor(e,n){this.orig=e,this.dest=n,this.twin=null,this.next=null,this.visited=!1}};function DXn(t,e){const n=[...e,{start:{x:t.minX,y:t.minY},end:{x:t.maxX,y:t.minY}},{start:{x:t.maxX,y:t.minY},end:{x:t.maxX,y:t.maxY}},{start:{x:t.maxX,y:t.maxY},end:{x:t.minX,y:t.maxY}},{start:{x:t.minX,y:t.maxY},end:{x:t.minX,y:t.minY}}],o=n.map(()=>[]);for(let u=0;u<n.length;++u){const g=n[u];o[u].push(g.start,g.end)}for(let u=0;u<n.length;++u)for(let g=u+1;g<n.length;++g){const h=vXn(n[u].start,n[u].end,n[g].start,n[g].end);h&&(o[u].push(h),o[g].push(h))}const i=new Map,r=[];function s(u){const g=(function(h,d=1e-9){return`${Math.round(h.x/d)}:${Math.round(h.y/d)}`})(u);if(!i.has(g)){const h=r.length;return i.set(g,h),r.push(new MXn(u.x,u.y)),h}return i.get(g)}const a=[];for(let u=0;u<n.length;++u){const g=n[u],h=o[u].slice();h.sort((d,p)=>{const m=g.end.x-g.start.x,_=g.end.y-g.start.y;return(qse(Math.abs(m),0)?(d.y-g.start.y)/_:(d.x-g.start.x)/m)-(qse(Math.abs(m),0)?(p.y-g.start.y)/_:(p.x-g.start.x)/m)});for(let d=0;d<h.length-1;++d){const p=h[d],m=h[d+1],_=s(p),f=s(m);_!==f&&(a.push([_,f]),g.connectionName&&(r[_].connectionNames.add(g.connectionName),r[f].connectionNames.add(g.connectionName)))}}const A=[];for(const[u,g]of a){const h=new cft(u,g),d=new cft(g,u);h.twin=A.length+1,d.twin=A.length;const p=A.length;A.push(h,d),r[u].out.push(p),r[g].out.push(p+1)}for(let u=0;u<r.length;++u){const g=r[u];g.out.sort((d,p)=>{const m=A[d],_=A[p],f=r[m.dest],I=r[_.dest];return Math.atan2(f.y-g.y,f.x-g.x)-Math.atan2(I.y-g.y,I.x-g.x)});const h=g.out.length;for(let d=0;d<h;++d){const p=g.out[d],m=g.out[(d-1+h)%h],_=A[p];_.twin!==null&&(A[_.twin].next=m)}}const c=[],l=[];for(let u=0;u<A.length;++u){if(A[u].visited)continue;let g=u;const h=[];do{if(g===null)break;const d=A[g];d.visited=!0,h.push(r[d.orig]),g=d.next}while(g!==null&&g!==u&&!A[g].visited);if(!(h.length<3)&&wXn(h)>L7e){const d=PXn(h);d&&(c.push(d),l.push({vertices:h.map(p=>({x:p.x,y:p.y,connectionNames:p.connectionNames.size>0?p.connectionNames:void 0})),centroid:d}))}}return{centroids:c,faces:l,allVertices:r}}function NXn(t,e){if(t>e)throw new Error("oneCount cannot be greater than length");if(t<0||e<0)throw new Error("oneCount and length must be non-negative");const n=[];return(function o(i,r,s){s!==e?(i[s]=0,o(i,r,s+1),r>0&&(i[s]=1,o(i,r-1,s+1))):r===0&&n.push([...i])})(Array(e).fill(0),t,0),n}var RXn=class extends yr{getSolverName(){return"MultiHeadPolyLineIntraNodeSolver"}nodeWithPortPoints;colorMap;hyperParameters;connMap;candidates;bounds;solvedRoutes=[];unsolvedConnections=[];SEGMENTS_PER_POLYLINE;cellSize;MAX_CANDIDATES=5e4;viaDiameter=.3;obstacleMargin=.1;traceWidth=.15;availableZ=[];uniqueConnections=0;BOUNDARY_PADDING;lastCandidate=null;maxViaCount;minViaCount;phase="setup";progress=0;constructor(e){super(),this.MAX_ITERATIONS=1e4,this.nodeWithPortPoints=e.nodeWithPortPoints,this.colorMap=e.colorMap??rft(e.nodeWithPortPoints),this.hyperParameters=e.hyperParameters??{},this.SEGMENTS_PER_POLYLINE=e.hyperParameters?.SEGMENTS_PER_POLYLINE??3,this.BOUNDARY_PADDING=e.hyperParameters?.BOUNDARY_PADDING??.05,this.connMap=e.connMap,this.viaDiameter=e.viaDiameter??this.viaDiameter,this.cellSize=this.nodeWithPortPoints.width/1024,this.candidates=[],this.availableZ=this.nodeWithPortPoints.availableZ??[0,1],this.bounds={minX:this.nodeWithPortPoints.center.x-this.nodeWithPortPoints.width/2,maxX:this.nodeWithPortPoints.center.x+this.nodeWithPortPoints.width/2,minY:this.nodeWithPortPoints.center.y-this.nodeWithPortPoints.height/2,maxY:this.nodeWithPortPoints.center.y+this.nodeWithPortPoints.height/2};const n=this.nodeWithPortPoints.width*this.nodeWithPortPoints.height,o=(this.viaDiameter+2*this.obstacleMargin+this.traceWidth/2)**2,i=new Set(this.nodeWithPortPoints.portPoints.map(a=>a.connectionName)).size;this.uniqueConnections=i;const{numSameLayerCrossings:r,numEntryExitLayerChanges:s}=sft(this.nodeWithPortPoints);if(this.minViaCount=2*r+s,this.maxViaCount=Math.min(Math.floor(n/o),Math.ceil(1.5*i)),this.minViaCount>this.SEGMENTS_PER_POLYLINE*(i/2))return this.failed=!0,void(this.error=`Not possible to solve problem with given SEGMENTS_PER_POLYLINE (${this.SEGMENTS_PER_POLYLINE}), atleast ${this.minViaCount} vias are required`);this.maxViaCount>this.SEGMENTS_PER_POLYLINE&&(this.maxViaCount=this.SEGMENTS_PER_POLYLINE),this.maxViaCount<this.minViaCount&&(this.maxViaCount=this.minViaCount)}computeMinGapBtwPolyLines(e){const n=[],o=[],i=[];for(let r=0;r<e.length;r++){const s=e[r],a=[s.start,...s.mPoints,s.end],A=new Map(this.availableZ.map(c=>[c,[]]));for(let c=0;c<a.length-1;c++){const l=[a[c],a[c+1]],u=l[0].z2;A.has(u)||A.set(u,[]),A.get(u).push(l)}o.push(A),i.push(a.filter(c=>c.z1!==c.z2))}for(let r=0;r<e.length;r++){const s=o[r],a=i[r];for(let A=r+1;A<e.length;A++){if(this.connMap?.areIdsConnected(e[r].connectionName,e[A].connectionName))continue;const c=o[A],l=i[A];let u=1;for(const g of this.availableZ){const h=s.get(g)??[],d=c.get(g)??[];for(const p of h)for(const m of d)u=Math.min(u,M5(p[0],p[1],m[0],m[1])-this.traceWidth);for(const p of a)for(const m of d)u=Math.min(u,wc(p,m[0],m[1])-this.traceWidth/2-this.viaDiameter/2);for(const p of l)for(const m of h)u=Math.min(u,wc(p,m[0],m[1])-this.traceWidth/2-this.viaDiameter/2);for(const p of a)for(const m of l)u=Math.min(u,no(p,m)-this.viaDiameter)}n.push(u)}}return n}insertCandidate(e){let n=0,o=this.candidates.length-1;for(;n<=o;){const i=Math.floor((n+o)/2);this.candidates[i].f<e.f?n=i+1:o=i-1}this.candidates.splice(n,0,e)}setupInitialPolyLines(){const e=new Map;this.nodeWithPortPoints.portPoints.forEach(s=>{e.has(s.connectionName)?e.get(s.connectionName).end={...s,z1:s.z??0,z2:s.z??0}:e.set(s.connectionName,{start:{...s,z1:s.z??0,z2:s.z??0},end:null})});for(const[s,a]of e.entries())a.end===null&&e.delete(s);if(e.size===0)return this.failed=!0,void(this.error="No port pairs found, can't solve");const n=Array.from(e.entries()),o=((s,a,A,c)=>{const l=[];for(const[,g]of s){const h=g.start.z1!==g.end.z1,d=[];for(let p=0;p<=a;p++){const m=p%2!=0;h&&m?d.push(p):h||m||d.push(p)}l.push(d)}if(l.length===0)return[[]];let u=(g=>{if(!g||g.length===0)return[[]];let h=[[]];for(const d of g){const p=[];for(const m of h)for(const _ of d)p.push([...m,_]);h=p}return h})(l).filter(g=>{for(let h=0;h<g.length;h++)if(g.reduce((d,p)=>d+p,0)<c)return!1;return!0});return u=u.filter(g=>{for(let h=0;h<s.length;h++){const[,d]=s[h];if(d.start.z1!==d.start.z2&&g[h]===0)return!1}return!0}),u=u.filter(g=>{for(let h=0;h<s.length;h++){const[,d]=s[h];if(s[h][1].start.z1===s[h][1].start.z2)for(let p=h+1;p<s.length;p++){if(s[p][1].start.z1!==s[p][1].start.z2)continue;const[,m]=s[p];if(d.start.z1===d.end.z1&&m.start.z1===m.end.z1&&d.start.z1===m.start.z1&&Uh(d.start,d.end,m.start,m.end)&&g[h]+g[p]<2)return!1}}return!0}),u=u.filter(g=>!(g.reduce((h,d)=>h+d,0)>A)),u})(n,this.SEGMENTS_PER_POLYLINE,this.maxViaCount,this.minViaCount),i=(s=>{const{bounds:a,portPairsEntries:A,viaCountVariants:c}=s,{centroids:l}=DXn(a,A.map(([g,h])=>h)),u=[];for(const g of c){const h=g.reduce((m,_)=>m+_,0);let d=l;if(l.length<h){d=[];const m=Math.ceil(Math.sqrt(h)),_=m;for(let f=0;f<m;f++)for(let I=0;I<_;I++)d.push({x:a.minX+(I+1)/(_+1)*(a.maxX-a.minX),y:a.minY+(f+1)/(m+1)*(a.maxY-a.minY)})}const p=NXn(h,d.length);for(const m of p){const _=[];for(let f=0;f<m.length;f++)m[f]===1&&_.push(d[f]);u.push({viaPositions:_,viaCountVariant:g})}}return u})({portPairsEntries:n,viaCountVariants:o,bounds:this.bounds}),r=[];for(const{viaCountVariant:s,viaPositions:a}of i){const A=Aft(a);for(const c of A)r.push({viaCountVariant:s,viaPositions:c})}for(const{viaPositions:s,viaCountVariant:a}of r){const A=[];let c=0;for(let h=0;h<n.length;h++){const[d,p]=n[h],m=a[h],_=s.slice(c,c+m),f=bXn({start:p.start,end:p.end,segmentsPerPolyline:this.SEGMENTS_PER_POLYLINE,viaPositions:_,viaCount:m,availableZ:this.availableZ});c+=m,A.push({connectionName:d,start:p.start,end:p.end,mPoints:f})}if(QXn(A,this.bounds))continue;const l=this.computeMinGapBtwPolyLines(A),u=this.computeH({minGaps:l,forces:[]}),g={polyLines:A,g:0,h:u,f:u,viaCount:a.reduce((h,d)=>h+d,0),minGaps:l};if(this.checkIfSolved(g))return void(this.candidates=[g]);if(this.candidates.push(g),this.candidates.length>this.MAX_CANDIDATES)return}this.candidates.sort((s,a)=>s.f-a.f)}computeG(e,n){return n.g+5e-6+5e-6*n.viaCount*100}computeH(e){let n=0;for(const o of e.forces??[])for(const i of o)for(const r of i.values())n+=r.fx*r.fx+r.fy*r.fy;return n}getNeighbors(e){const{polyLines:n}=e,o=n.length,i=.02,r=.008,s=1e-6,a=Array.from({length:o},(d,p)=>Array.from({length:n[p].mPoints.length},()=>new Map)),A=(d,p,m,_,f)=>{if(p>0&&p<n[d].mPoints.length+1){const I=p-1,C=a[d][I],y=C.get(m)||{fx:0,fy:0};C.set(m,{fx:y.fx+_,fy:y.fy+f})}};for(let d=0;d<o;d++)for(let p=d+1;p<o;p++){const m=n[d],_=n[p],f=[m.start,...m.mPoints,m.end],I=[_.start,..._.mPoints,_.end],C=[],y=[];for(let B=0;B<f.length-1;B++)C.push({p1:f[B],p2:f[B+1],layer:f[B].z2,p1Idx:B,p2Idx:B+1});f.forEach((B,S)=>{B.z1!==B.z2&&y.push({point:B,layers:[B.z1,B.z2],index:S})});const x=[],E=[];for(let B=0;B<I.length-1;B++)x.push({p1:I[B],p2:I[B+1],layer:I[B].z2,p1Idx:B,p2Idx:B+1});I.forEach((B,S)=>{B.z1!==B.z2&&E.push({point:B,layers:[B.z1,B.z2],index:S})});for(const B of C)for(const S of x)if(B.layer===S.layer){if(M5(B.p1,B.p2,S.p1,S.p2)<s)continue;const Q={x:(B.p1.x+B.p2.x)/2,y:(B.p1.y+B.p2.y)/2},w={x:(S.p1.x+S.p2.x)/2,y:(S.p1.y+S.p2.y)/2},M=Q.x-w.x,k=Q.y-w.y;if(M*M+k*k>s){const F=`seg:${p}:${S.p1Idx}:${S.p2Idx}`,O=`seg:${d}:${B.p1Idx}:${B.p2Idx}`,U=(Y,W,te,j,J,oe,ie)=>{const ne=z_(Y,te.p1,te.p2),le=Y.x-ne.x,ge=Y.y-ne.y,_e=le*le+ge*ge;if(_e<=s)return;const ue=Math.sqrt(_e),fe=.02*Math.exp(-6*ue),pe=le/ue*fe,ye=ge/ue*fe;A(j,W,oe,pe,ye),A(J,te.p1Idx,ie,-pe/2,-ye/2),A(J,te.p2Idx,ie,-pe/2,-ye/2)};U(B.p1,B.p1Idx,S,d,p,F,O),U(B.p2,B.p2Idx,S,d,p,F,O),U(S.p1,S.p1Idx,B,p,d,O,F),U(S.p2,S.p2Idx,B,p,d,O,F)}}for(const B of y)for(const S of x)if(B.layers.includes(S.layer)){const Q=z_(B.point,S.p1,S.p2),w=B.point.x-Q.x,M=B.point.y-Q.y,k=w*w+M*M;if(k>s){const R=Math.sqrt(k);let F=2,O=R;R<this.viaDiameter/2?(F*=4,O=Math.max(s,R)):O=Math.max(s,R-this.viaDiameter/2);const U=F*i*Math.exp(-6*O),Y=w/R*U,W=M/R*U,te=`seg:${p}:${S.p1Idx}:${S.p2Idx}`;A(d,B.index,te,Y,W);const j=`via:${d}:${B.index}`;A(p,S.p1Idx,j,-Y/2,-W/2),A(p,S.p2Idx,j,-Y/2,-W/2)}}for(const B of E)for(const S of C)if(B.layers.includes(S.layer)){const Q=z_(B.point,S.p1,S.p2),w=B.point.x-Q.x,M=B.point.y-Q.y,k=w*w+M*M;if(k>s){const R=Math.sqrt(k);let F=2,O=R;R<this.viaDiameter/2?(F*=4,O=Math.max(s,R)):O=Math.max(s,R-this.viaDiameter/2);const U=F*i*Math.exp(-6*O),Y=w/R*U,W=M/R*U,te=`seg:${d}:${S.p1Idx}:${S.p2Idx}`;A(p,B.index,te,Y,W);const j=`via:${p}:${B.index}`;A(d,S.p1Idx,j,-Y/2,-W/2),A(d,S.p2Idx,j,-Y/2,-W/2)}}for(const B of y)for(const S of E)if(B.layers.filter(Q=>S.layers.includes(Q)).length>0){const Q=B.point.x-S.point.x,w=B.point.y-S.point.y,M=Q*Q+w*w;if(M>s){const k=Math.sqrt(M);let R=2,F=k;k<this.viaDiameter?(R*=4,F=Math.max(s,k)):F=Math.max(s,k-this.viaDiameter);const O=R*i*Math.exp(-6*F),U=Q/k*O,Y=w/k*O,W=`via:${p}:${S.index}`,te=`via:${d}:${B.index}`;A(d,B.index,W,U,Y),A(p,S.index,te,-U,-Y)}}}for(let d=0;d<o;d++){const p=n[d],m=[p.start,...p.mPoints,p.end],_=[];if(m.forEach((f,I)=>{f.z1!==f.z2&&_.push({point:f,layers:[f.z1,f.z2],index:I})}),!(_.length<2))for(let f=0;f<_.length;f++)for(let I=f+1;I<_.length;I++){const C=_[f],y=_[I],x=C.point.x-y.point.x,E=C.point.y-y.point.y,B=x*x+E*E;if(B>s){const S=Math.sqrt(B);let Q=2,w=S;S<this.viaDiameter?(Q*=4,w=Math.max(s,S)):w=Math.max(s,S-this.viaDiameter);const M=Q*i*Math.exp(-6*w),k=x/S*M,R=E/S*M,F=`via:${d}:${y.index}`,O=`via:${d}:${C.index}`;A(d,C.index,F,k,R),A(d,y.index,O,-k,-R)}}}const c=n.map(d=>({...d,mPoints:d.mPoints.map(p=>({...p}))}));let l=!1;for(let d=0;d<o;d++)for(let p=0;p<c[d].mPoints.length;p++){const m=c[d].mPoints[p],_=a[d][p],f={fx:0,fy:0};for(const x of _.values())f.fx+=x.fx,f.fy+=x.fy;const I=m.z1!==m.z2;let C=m.x+f.fx,y=m.y+f.fy;if(I){const x=this.viaDiameter/2;let E=0,B=0;const S=this.viaDiameter/2+this.BOUNDARY_PADDING,Q=this.bounds.minX+S,w=this.bounds.maxX-S,M=this.bounds.minY+S,k=this.bounds.maxY-S,R=Q+x-m.x,F=m.x-(w-x),O=M+x-m.y,U=m.y-(k-x);R>0?E=r*(Math.exp(R/(2*this.obstacleMargin))-1):F>0&&(E=-.008*(Math.exp(F/(2*this.obstacleMargin))-1)),O>0?B=r*(Math.exp(O/(2*this.obstacleMargin))-1):U>0&&(B=-.008*(Math.exp(U/(2*this.obstacleMargin))-1)),f.fx+=E,f.fy+=B,C=m.x+f.fx,y=m.y+f.fy}else{const x=this.traceWidth/2+this.BOUNDARY_PADDING;C=Math.max(this.bounds.minX+x,Math.min(this.bounds.maxX-x,C)),y=Math.max(this.bounds.minY+x,Math.min(this.bounds.maxY-x,y))}Math.abs(f.fx)<s&&Math.abs(f.fy)<s||(Math.abs(m.x-C)>s||Math.abs(m.y-y)>s)&&(m.x=C,m.y=y,l=!0)}if(!l)return[];const u=this.computeMinGapBtwPolyLines(c),g=this.computeG(c,e),h=this.computeH({minGaps:u,forces:a});return[{polyLines:c,g,h,f:Math.round(5*g)/5+h,minGaps:u,forces:a,viaCount:e.viaCount}]}checkIfSolved(e){const n=e.minGaps.every(i=>i>=this.obstacleMargin),o=e.polyLines.every(i=>i.mPoints.every(r=>{const s=(r.z1!==r.z2?this.viaDiameter/2:this.traceWidth/2)+this.BOUNDARY_PADDING;return((a,A,c=0)=>a.x>=A.minX+c&&a.x<=A.maxX-c&&a.y>=A.minY+c&&a.y<=A.maxY-c)(r,this.bounds,s)}));return n&&o}tryFinalAcceptance(){const e=this.hyperParameters?.MINIMUM_FINAL_ACCEPTANCE_GAP??void 0;if(!(e===void 0||this.lastCandidate===null||this.lastCandidate.minGaps.length===0))return Math.min(...this.lastCandidate.minGaps)>=e?(this.solved=!0,void this._setSolvedRoutes()):void 0}_step(){if(this.phase==="setup")return this.setupInitialPolyLines(),void(this.phase="solving");const e=this.candidates.shift();if(!e)return this.tryFinalAcceptance(),this.solved?void 0:(this.failed=!0,void(this.error="No candidates left"));if(this.lastCandidate=e,this.checkIfSolved(e))return this.solved=!0,void this._setSolvedRoutes();if(!e)return void(this.failed=!0);const n=this.getNeighbors(e);for(const o of n)this.insertCandidate(o)}visualize(){const e={points:[],lines:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"MultiHeadPolyLineIntraNodeSolver Visualization"};e.lines.push({points:[{x:this.bounds.minX,y:this.bounds.minY},{x:this.bounds.maxX,y:this.bounds.minY},{x:this.bounds.maxX,y:this.bounds.maxY},{x:this.bounds.minX,y:this.bounds.maxY},{x:this.bounds.minX,y:this.bounds.minY}],strokeColor:"gray"});const n=this.lastCandidate??this.candidates[0];if(n?.hasClosedSameLayerFace){const o=.1*(this.bounds.maxX-this.bounds.minX),i=.1*(this.bounds.maxY-this.bounds.minY);e.rects.push({center:{x:this.bounds.maxX+.6*o,y:this.bounds.maxY+.6*i},width:o,height:i,fill:"red",label:"HAS CLOSED FACE"})}for(const o of this.nodeWithPortPoints.portPoints)e.points.push({x:o.x,y:o.y,label:`${o.connectionName} (Port z=${o.z??0})`,color:this.colorMap[o.connectionName]??"blue"});return n&&n.polyLines.forEach((o,i)=>{const r=this.colorMap[o.connectionName]??"purple",s=[o.start,...o.mPoints,o.end];for(let a=0;a<s.length-1;a++){const A=s[a],c=s[a+1],l=A.z2,u=l===0,g=u?r:Es(r,.5);e.lines.push({points:[A,c],strokeColor:g,strokeWidth:this.traceWidth,strokeDash:u?void 0:[.15,.15],label:`${o.connectionName} segment (z=${l})`})}s.forEach((a,A)=>{const c=a.z1!==a.z2,l=a.z1,u=A>0&&A<s.length-1;let g="",h="";if(u){const d=A-1,p=n.forces?.[i]?.[d];if(p&&p.size>0){const m={fx:0,fy:0};p.forEach((_,f)=>{if(m.fx+=_.fx,m.fy+=_.fy,Math.abs(_.fx)>1e-6||Math.abs(_.fy)>1e-6){const I=f.split(":"),C=I[0],y=parseInt(I[1],10),x=n.polyLines[y],E=this.colorMap[x.connectionName]??"gray",B=20,S={x:a.x+_.fx*B,y:a.y+_.fy*B};let Q=x.connectionName;C==="via"?Q+=` Via ${parseInt(I[2],10)}`:C==="seg"&&(Q+=` Seg ${parseInt(I[2],10)}-${parseInt(I[3],10)}`),e.lines.push({points:[a,S],strokeColor:E,strokeWidth:.02,strokeDash:"2,2",label:`Force by ${Q} on ${o.connectionName} mPoint ${d}`})}}),(Math.abs(m.fx)>1e-6||Math.abs(m.fy)>1e-6)&&(h=`
Net Force: (${m.fx.toFixed(3)}, ${m.fy.toFixed(3)})`)}}if(c)g=`Via (${o.connectionName} z=${a.z1} -> z=${a.z2})${h}`,e.circles.push({center:a,radius:this.viaDiameter/2,fill:Es(r,.5),label:g});else if(u){const d=l===0?r:Es(r,.5);g=`mPoint (${o.connectionName} z=${l})${h}`,e.circles.push({center:a,radius:this.cellSize/8,fill:d,label:g})}})}),e}_setSolvedRoutes(){if(!this.solved||!this.lastCandidate)return[];const e=[];for(const n of this.lastCandidate.polyLines){const o=[],i=[],r=[n.start,...n.mPoints,n.end];for(let s=0;s<r.length;s++){const a=r[s];o.push({x:a.x,y:a.y,z:a.z1}),a.z1!==a.z2&&(i.push({x:a.x,y:a.y}),o.push({x:a.x,y:a.y,z:a.z2}))}e.push({connectionName:n.connectionName,regionId:this.nodeWithPortPoints.capacityMeshNodeId,traceThickness:this.traceWidth,viaDiameter:this.viaDiameter,route:o,vias:i})}this.solvedRoutes=e}},TXn=class extends RXn{getSolverName(){return"MultiHeadPolyLineIntraNodeSolver2"}computeG(e,n){return n.g+5e-6+5e-6*n.viaCount*100}computeH(e){const{minGaps:n}=e;let o=0;for(const i of n)i<0&&(o+=this.obstacleMargin),i<this.obstacleMargin&&(o+=this.obstacleMargin-i);return .011*o}_step(){if(this.phase==="setup")return this.setupInitialPolyLines(),void(this.phase="solving");const e=this.candidates.shift();if(!e)return this.tryFinalAcceptance(),this.solved?void 0:void(this.failed=!0);if(this.lastCandidate=e,this.checkIfSolved(e))return this.solved=!0,void this._setSolvedRoutes();let n=!1,o=0;const i=e.magForceApplied===void 0?1:10;for(let r=0;r<i;r++){const s=this.applyForcesToPolyLines(e.polyLines);if(o+=s.magForceApplied,n=s.lastStepMoved,!s.lastStepMoved)break}if(e.magForceApplied=o,e.minGaps=this.computeMinGapBtwPolyLines(e.polyLines),this.checkIfSolved(e))return this.solved=!0,void this._setSolvedRoutes();e.g=this.computeG(e.polyLines,e),e.h=this.computeH(e),e.f=e.g+e.h,n&&this.insertCandidate(e)}applyForcesToPolyLines(e){let n=0;const o=e.length,i=.02,r=.008,s=1e-6,a=Array.from({length:o},(u,g)=>Array.from({length:e[g].mPoints.length},()=>({fx:0,fy:0}))),A=(u,g,h,d)=>{if(g>0&&g<e[u].mPoints.length+1){const p=g-1;a[u][p].fx+=h,a[u][p].fy+=d}},c=(u,g,h,d,p)=>{const m=z_(u,h.p1,h.p2),_=u.x-m.x,f=u.y-m.y,I=_*_+f*f;if(I<=s)return;const C=Math.sqrt(I),y=.02*Math.exp(-6*C),x=_/C*y,E=f/C*y;A(d,g,x,E),A(p,h.p1Idx,-x/2,-E/2),A(p,h.p2Idx,-x/2,-E/2)};for(let u=0;u<o;u++)for(let g=u+1;g<o;g++){const h=e[u],d=e[g],p=[h.start,...h.mPoints,h.end],m=[d.start,...d.mPoints,d.end],_=[],f=[];for(let y=0;y<p.length-1;y++)_.push({p1:p[y],p2:p[y+1],layer:p[y].z2,p1Idx:y,p2Idx:y+1});p.forEach((y,x)=>{y.z1!==y.z2&&f.push({point:y,layers:[y.z1,y.z2],index:x})});const I=[],C=[];for(let y=0;y<m.length-1;y++)I.push({p1:m[y],p2:m[y+1],layer:m[y].z2,p1Idx:y,p2Idx:y+1});m.forEach((y,x)=>{y.z1!==y.z2&&C.push({point:y,layers:[y.z1,y.z2],index:x})});for(const y of _)for(const x of I)y.layer===x.layer&&(M5(y.p1,y.p2,x.p1,x.p2),c(y.p1,y.p1Idx,x,u,g),c(y.p2,y.p2Idx,x,u,g),c(x.p1,x.p1Idx,y,g,u),c(x.p2,x.p2Idx,y,g,u));for(const y of f)for(const x of I)if(y.layers.includes(x.layer)){const E=z_(y.point,x.p1,x.p2),B=y.point.x-E.x,S=y.point.y-E.y,Q=B*B+S*S;if(Q>s){const w=Math.sqrt(Q);let M=2,k=w;w<this.viaDiameter/2?(M*=4,k=Math.max(s,w)):k=Math.max(s,w-this.viaDiameter/2);const R=M*i*Math.exp(-6*k),F=B/w*R,O=S/w*R;A(u,y.index,F,O),A(g,x.p1Idx,-F/2,-O/2),A(g,x.p2Idx,-F/2,-O/2)}}for(const y of C)for(const x of _)if(y.layers.includes(x.layer)){const E=z_(y.point,x.p1,x.p2),B=y.point.x-E.x,S=y.point.y-E.y,Q=B*B+S*S;if(Q>s){const w=Math.sqrt(Q);let M=2,k=w;w<this.viaDiameter/2?(M*=4,k=Math.max(s,w)):k=Math.max(s,w-this.viaDiameter/2);const R=M*i*Math.exp(-6*k),F=B/w*R,O=S/w*R;A(g,y.index,F,O),A(u,x.p1Idx,-F/2,-O/2),A(u,x.p2Idx,-F/2,-O/2)}}for(const y of f)for(const x of C)if(y.layers.filter(E=>x.layers.includes(E)).length>0){const E=y.point.x-x.point.x,B=y.point.y-x.point.y,S=E*E+B*B;if(S>s){const Q=Math.sqrt(S);let w=2,M=Q;Q<this.viaDiameter?(w*=4,M=Math.max(s,Q)):M=Math.max(s,Q-this.viaDiameter);const k=w*i*Math.exp(-6*M),R=E/Q*k,F=B/Q*k;A(u,y.index,R,F),A(g,x.index,-R,-F)}}}for(let u=0;u<o;u++){const g=e[u],h=[g.start,...g.mPoints,g.end],d=[];if(h.forEach((p,m)=>{p.z1!==p.z2&&d.push({point:p,layers:[p.z1,p.z2],index:m})}),!(d.length<2))for(let p=0;p<d.length;p++)for(let m=p+1;m<d.length;m++){const _=d[p],f=d[m],I=_.point.x-f.point.x,C=_.point.y-f.point.y,y=I*I+C*C;if(y>s){const x=Math.sqrt(y);let E=2,B=x;x<this.viaDiameter?(E*=4,B=Math.max(s,x)):B=Math.max(s,x-this.viaDiameter);const S=E*i*Math.exp(-6*B),Q=I/x*S,w=C/x*S;A(u,_.index,Q,w),A(u,f.index,-Q,-w)}}}let l=!1;for(let u=0;u<o;u++)for(let g=0;g<e[u].mPoints.length;g++){const h=e[u].mPoints[g],d=a[u][g],p=h.z1!==h.z2;let m=d.fx,_=d.fy,f=h.x+m,I=h.y+_;if(p){const C=this.viaDiameter/2;let y=0,x=0;const E=this.viaDiameter/2+this.BOUNDARY_PADDING,B=this.bounds.minX+E,S=this.bounds.maxX-E,Q=this.bounds.minY+E,w=this.bounds.maxY-E,M=B+C-h.x,k=h.x-(S-C),R=Q+C-h.y,F=h.y-(w-C);M>0?y=r*(Math.exp(M/(2*this.obstacleMargin))-1):k>0&&(y=-.008*(Math.exp(k/(2*this.obstacleMargin))-1)),R>0?x=r*(Math.exp(R/(2*this.obstacleMargin))-1):F>0&&(x=-.008*(Math.exp(F/(2*this.obstacleMargin))-1)),m+=y,_+=x,f=h.x+m,I=h.y+_}else{const C=this.traceWidth/2+this.BOUNDARY_PADDING;f=Math.max(this.bounds.minX+C,Math.min(this.bounds.maxX-C,f)),I=Math.max(this.bounds.minY+C,Math.min(this.bounds.maxY-C,I))}Math.abs(m)<s&&Math.abs(_)<s||(n+=Math.sqrt(m*m+_*_),(Math.abs(h.x-f)>s||Math.abs(h.y-I)>s)&&(h.x=f,h.y=I,l=!0))}return{lastStepMoved:l,magForceApplied:n}}},kXn=t=>t.flatMap(e=>`${e.connectionName}-${e.mPoints.map(n=>`${n.x.toFixed(2)},${n.y.toFixed(2)},${n.z1},${n.z2}`)}`).sort().join("|"),FXn=class extends TXn{getSolverName(){return"MultiHeadPolyLineIntraNodeSolver3"}constructor(e){super(e),this.MAX_ITERATIONS=1e3}createInitialCandidateFromSeed(e){const n=new BXn({nodeWithPortPoints:this.nodeWithPortPoints,colorMap:this.colorMap,hyperParameters:{SHUFFLE_SEED:e},viaDiameter:this.viaDiameter});if(n.solve(),n.failed||!n.solved)return this.failed=!0,this.error=`ViaPossibilitiesSolver2 failed with: ${n.error}`,null;const o=[];let i=0;for(const[A,c]of n.completedPaths.entries()){if(c.length<2){console.warn(`Skipping connection "${A}" due to insufficient points (${c.length}) in ViaPossibilitiesSolver2 path.`);continue}const l=c[0],u=c[c.length-1],g=c.slice(1,-1),h=[];let d=0,p=l.z;for(let f=0;f<g.length;f++){const I=g[f],C=f+1<g.length?g[f+1]:u,y=p,x=f+1<g.length&&I.x===C.x&&I.y===C.y&&I.z!==C.z?C.z:I.z;h.push({x:I.x,y:I.y,z1:y,z2:x}),y!==x?(d++,f++,p=x):p=I.z}i+=d;const m=this.SEGMENTS_PER_POLYLINE;let _=h.length+1;for(;_<m;){let f=-1,I=-1,C=null,y=null;const x=[{...l,z1:l.z,z2:l.z,connectionName:A},...h,{...u,z1:u.z,z2:u.z,connectionName:A}];for(let w=0;w<x.length-1;w++){const M=x[w],k=x[w+1];if(M.x===k.x&&M.y===k.y)continue;const R=no(M,k);R>f&&(f=R,I=w,C=M,y=k)}if(I===-1||!C||!y){console.warn(`Could not find longest segment for ${A} while trying to reach ${m} segments.`);break}const E=(C.x+y.x)/2,B=(C.y+y.y)/2,S=C.z2,Q={x:E,y:B,z1:S,z2:S};h.splice(I,0,Q),_++}o.push({connectionName:A,start:{...l,z1:l.z,z2:l.z},end:{...u,z1:u.z,z2:u.z},mPoints:h})}if(o.length===0)return this.failed=!0,this.error="No valid polylines generated from ViaPossibilitiesSolver2.",console.error(this.error),null;const r=this.computeMinGapBtwPolyLines(o),s=this.computeH({minGaps:r,forces:[]}),a={polyLines:o,g:0,h:s,f:0+s,viaCount:i,minGaps:r};return a.g=this.computeG(o,a),a.f=a.g+a.h,a}setupInitialPolyLines(){this.candidates=[];const e=Math.min(2e3,(function(o){if(!Number.isInteger(o)||o<0)throw new RangeError("n must be a non-negative integer");let i=1;for(let r=2;r<=o;r++)i*=r;return i})(this.uniqueConnections)),n=new Set;for(let o=0;o<e;o++){const i=this.createInitialCandidateFromSeed(o);if(!i)continue;const r=kXn(i.polyLines);n.has(r)||(n.add(r),this.candidates.push(i))}this.candidates.sort((o,i)=>o.f-i.f)}},lft=t=>t.portPointId??`${t.connectionName}:${t.x}:${t.y}:${t.z}`,O7e=(t,e)=>{const[n,o]=t;if(n===o)return!1;const i=(r=>{const[s,a]=r,A=lft(s),c=lft(a);return A<c?`${A}|${c}`:`${c}|${A}`})(t);return!e.seenPairKeys.has(i)&&(e.seenPairKeys.add(i),e.pairs.push(t),!0)},uft=(t,e)=>{for(let n=0;n<t.length-1;n++)O7e([t[n],t[n+1]],e)},Yz=t=>{const e=[],n=new Set,o=new Map(t.filter(a=>typeof a.portPointId=="string").map(a=>[a.portPointId,a])),i={pairs:e,seenPairKeys:n};for(const a of t){if(a.prevPortPointId){const A=o.get(a.prevPortPointId);A&&A.connectionName===a.connectionName&&O7e([A,a],i)}if(a.nextPortPointId){const A=o.get(a.nextPortPointId);A&&A.connectionName===a.connectionName&&O7e([a,A],i)}}if(e.length===0)return uft(t,i),e;const r=new Set(e.flatMap(([a,A])=>[a.portPointId,A.portPointId]).filter(Boolean)),s=t.filter(a=>!a.portPointId||!r.has(a.portPointId));return uft(s,i),e},A7=1e-6,gft=.02,Uz=t=>`${t.x.toFixed(6)},${t.y.toFixed(6)}`,FD=(t,e)=>Math.abs(t.x-e.x)<A7&&Math.abs(t.y-e.y)<A7,dft=t=>({minX:t.center.x-t.width/2,maxX:t.center.x+t.width/2,minY:t.center.y-t.height/2,maxY:t.center.y+t.height/2}),LXn=(t,e)=>t.x>=e.minX-A7&&t.x<=e.maxX+A7&&t.y>=e.minY-A7&&t.y<=e.maxY+A7,HXn=(t,e,n)=>{for(const o of n)if(!FD(o,t)&&!FD(o,e)&&wc(o,t,e)<1e-4)return!0;return!1},OXn=(t,e,n)=>{for(const o of n)if(!(FD(t,o.A)||FD(t,o.B)||FD(e,o.A)||FD(e,o.B))&&Uh(t,e,o.A,o.B))return!0;return!1},GXn=(t,e)=>{const n=[];for(const o of t){const i=o.rootConnectionName??o.connectionName;if(i!==e)for(let r=0;r<o.route.length-1;r++){const s=o.route[r],a=o.route[r+1];s.z===a.z&&n.push({A:{x:s.x,y:s.y},B:{x:a.x,y:a.y},rootConnectionName:i})}}return n},YXn=(t,e)=>t.portPoints.filter(n=>(n.rootConnectionName??n.connectionName)!==e).map(n=>({x:n.x,y:n.y}));function*hft(t,e=t.length){if(e<=1)yield t.slice();else for(let n=0;n<e;n++)[t[n],t[e-1]]=[t[e-1],t[n]],yield*hft(t,e-1),[t[n],t[e-1]]=[t[e-1],t[n]]}var UXn=({A:t,B:e,bounds:n,obstacleSegments:o,foreignPorts:i})=>{const r=[{x:t.x,y:t.y},{x:e.x,y:e.y},{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2},{x:n.minX,y:n.minY},{x:n.maxX,y:n.minY},{x:n.maxX,y:n.maxY},{x:n.minX,y:n.maxY}],s=[...o.flatMap(m=>[m.A,m.B]),...i,{x:t.x,y:t.y},{x:e.x,y:e.y}];for(const m of s)for(const _ of[-.02,0,gft])for(const f of[-.02,0,gft]){const I={x:m.x+_,y:m.y+f};LXn(I,n)&&r.push(I)}const a=(m=>{const _=new Set,f=[];for(const I of m){const C=Uz(I);_.has(C)||(_.add(C),f.push(I))}return f})(r),A=Uz(t),c=Uz(e),l=new Map(a.map(m=>[Uz(m),m])),u=new Map,g=new Map,h=new Set;for(const m of a){const _=Uz(m);u.set(_,_===A?0:1/0),g.set(_,null),h.add(_)}for(;h.size>0;){let m=null,_=1/0;for(const I of h){const C=u.get(I)??1/0;(C<_-A7||Math.abs(C-_)<=A7&&(m===null||I<m))&&(_=C,m=I)}if(!m||_===1/0||(h.delete(m),m===c))break;const f=l.get(m);for(const I of h){const C=l.get(I);if(FD(f,C)||OXn(f,C,o)||HXn(f,C,i))continue;const y=_+no(f,C),x=u.get(I)??1/0,E=g.get(I);(y<x-A7||Math.abs(y-x)<=A7&&(E==null||m<E))&&(u.set(I,y),g.set(I,m))}}if((u.get(c)??1/0)===1/0)return null;const d=[];let p=c;for(;p;)d.push(l.get(p)),p=g.get(p)??null;return d.reverse(),d.map(m=>({x:m.x,y:m.y,z:t.z}))},pft=class extends yr{getSolverName(){return"SingleLayerNoDifferentRootIntersectionsIntraNodeSolver"}nodeWithPortPoints;traceWidth;viaDiameter;solvedRoutes=[];constructor(e){super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.traceWidth=e.traceWidth??.15,this.viaDiameter=e.viaDiameter??.3,this.MAX_ITERATIONS=1}static isApplicable(e){if((r=>r.availableZ?.length?[...new Set(r.availableZ)].sort((s,a)=>s-a):[...new Set(r.portPoints.map(s=>s.z??0))].sort((s,a)=>s-a))(e).length!==1||e.portPoints.length>12)return!1;const o=dft(e);if(e.portPoints.some(r=>((s,a)=>Math.abs(s.y-a.minY)<.001?"top":Math.abs(s.x-a.maxX)<.001?"right":Math.abs(s.y-a.maxY)<.001?"bottom":Math.abs(s.x-a.minX)<.001?"left":null)(r,o)===null))return!1;const i=new Map;for(const r of e.portPoints)i.set(r.connectionName,(i.get(r.connectionName)??0)+1);return[...i.values()].some(r=>r>2)}buildTaskGroups(){const e=new Map;for(const n of this.nodeWithPortPoints.portPoints){const o=e.get(n.connectionName)??[];o.push(n),e.set(n.connectionName,o)}return e}trySolveNode(){const e=dft(this.nodeWithPortPoints),n=this.buildTaskGroups(),o=Array.from(n.entries()).flatMap(([r,s])=>Yz(s).map(([a,A])=>({connectionName:r,rootConnectionName:a.rootConnectionName??A.rootConnectionName??r,A:a,B:A}))),i=o.length<=6?hft(o.slice()):[o];for(const r of i){const s=[];let a=!1;for(const A of r){const c=GXn(s,A.rootConnectionName),l=YXn(this.nodeWithPortPoints,A.rootConnectionName),u=UXn({A:A.A,B:A.B,bounds:e,obstacleSegments:c,foreignPorts:l});if(!u||u.length<2){a=!0;break}s.push({connectionName:A.connectionName,rootConnectionName:A.rootConnectionName,regionId:this.nodeWithPortPoints.capacityMeshNodeId,traceThickness:this.traceWidth,viaDiameter:this.viaDiameter,route:u,vias:[]})}if(!a)return s}return null}_step(){const e=this.trySolveNode();if(!e)return this.failed=!0,void(this.error="Failed to find a single-layer route set without different-root intersections");this.solvedRoutes=e,this.stats={routeCount:e.length,distinctRoots:new Set(e.map(n=>n.rootConnectionName??n.connectionName)).size},this.solved=!0}visualize(){return{lines:this.solvedRoutes.map(e=>({points:e.route,strokeColor:"cyan",strokeWidth:e.traceThickness,label:`${e.connectionName}
root: ${e.rootConnectionName??e.connectionName}`})),points:this.nodeWithPortPoints.portPoints.map(e=>({x:e.x,y:e.y,color:"blue",label:`${e.connectionName}
root: ${e.rootConnectionName??e.connectionName}`})),rects:[],circles:[]}}},mft=t=>t.min<=t.max?V3(t.value,t.min,t.max):t.value,KXn=class extends yr{getSolverName(){return"SingleTransitionIntraNodeSolver"}nodeWithPortPoints;routes;viaDiameter;traceThickness;obstacleMargin;solvedRoutes=[];bounds;constructor(e){if(super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.viaDiameter=e?.viaDiameter??.3,this.traceThickness=e?.traceThickness??.15,this.obstacleMargin=e?.obstacleMargin??.1,this.routes=this.extractRoutesFromNode(),this.bounds=this.calculateBounds(),this.routes.length!==1)return this.failed=!0,void(this.error=`Expected 1 route, but got ${this.routes.length}`);const n=this.routes[0];if(n.A.z===void 0||n.B.z===void 0)return this.failed=!0,void(this.error="Route points should have predefined z values");if(n.A.z===n.B.z)return this.failed=!0,void(this.error="Only one route provided, but it has no transition");const o=this.viaDiameter/2+this.obstacleMargin,i={x:mft({value:(n.A.x+n.B.x)/2,min:this.bounds.minX+o,max:this.bounds.maxX-o}),y:mft({value:(n.A.y+n.B.y)/2,min:this.bounds.minY+o,max:this.bounds.maxY-o})};this.solvedRoutes.push(this.createTransitionRoute({start:n.A,end:n.B,via:i,connectionName:n.connectionName})),this.solved=!0}extractRoutesFromNode(){const e=[],n=this.nodeWithPortPoints.portPoints,o=new Map;for(const i of n){const{connectionName:r}=i;o.has(r)||o.set(r,[]),o.get(r).push(i)}for(const[i,r]of o.entries())for(const[s,a]of Yz(r))e.push({A:{...s},B:{...a},connectionName:i});return e}calculateBounds(){return{minX:this.nodeWithPortPoints.center.x-this.nodeWithPortPoints.width/2,maxX:this.nodeWithPortPoints.center.x+this.nodeWithPortPoints.width/2,minY:this.nodeWithPortPoints.center.y-this.nodeWithPortPoints.height/2,maxY:this.nodeWithPortPoints.center.y+this.nodeWithPortPoints.height/2}}createTransitionRoute(e){const{start:n,end:o,via:i,connectionName:r}=e,s=[{x:n.x,y:n.y,z:n.z},{x:i.x,y:i.y,z:n.z},{x:i.x,y:i.y,z:o.z},{x:o.x,y:o.y,z:o.z}];return{connectionName:r,regionId:this.nodeWithPortPoints.capacityMeshNodeId,route:s,traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:[i]}}_step(){this.solved=!0}visualize(){const e={lines:[],points:[],rects:[],circles:[]};if(e.rects.push({center:{x:(this.bounds.minX+this.bounds.maxX)/2,y:(this.bounds.minY+this.bounds.maxY)/2},width:this.bounds.maxX-this.bounds.minX,height:this.bounds.maxY-this.bounds.minY,stroke:"rgba(0, 0, 0, 0.5)",fill:"rgba(240, 240, 240, 0.1)",label:"PCB Bounds"}),this.routes.length>0)for(const n of this.routes)e.points.push({x:n.A.x,y:n.A.y,label:`${n.connectionName} start (z=${n.A.z})`,color:"orange"}),e.points.push({x:n.B.x,y:n.B.y,label:`${n.connectionName} end (z=${n.B.z})`,color:"orange"}),e.lines.push({points:[n.A,n.B],strokeColor:"rgba(255, 0, 0, 0.5)",label:`${n.connectionName} direct`});for(let n=0;n<this.solvedRoutes.length;n++){const o=this.solvedRoutes[n],i="rgba(0, 255, 0, 0.75)";for(let r=0;r<o.route.length-1;r++){const s=o.route[r],a=o.route[r+1];e.lines.push({points:[s,a],strokeColor:i,strokeDash:s.z!==o.route[0].z?[.2,.2]:void 0,strokeWidth:o.traceThickness,label:`${o.connectionName} z=${s.z}`})}for(const r of o.vias)e.circles.push({center:r,radius:this.viaDiameter/2,fill:"rgba(0, 0, 255, 0.8)",stroke:"black",label:"Solved Via"}),e.circles.push({center:r,radius:this.viaDiameter/2+this.obstacleMargin,fill:"rgba(0, 0, 255, 0.3)",stroke:"black",label:"Via Margin"})}return e}},c7=(t,e=2)=>{const n=Array.from({length:e},(o,i)=>i);return t.map(o=>{const i=Hz(o.__zLayers??(o.layers?Oz(o.layers,e):void 0)??n,e);return{...o,__zLayers:i.length>0?i:n}})},_ft=1e-6,fft=t=>{const{point:e,obstacle:n}=t,o=n.width/2+_ft,i=n.height/2+_ft;return Math.abs(e.x-n.center.x)<=o&&Math.abs(e.y-n.center.y)<=i},VXn=class e5n extends yr{getSolverName(){return"SingleTransitionThroughObstacleIntraNodeSolver"}nodeWithPortPoints;routes;obstacles;viaDiameter;traceThickness;connMap;solvedRoutes=[];constructor(e){if(super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.obstacles=c7(e.obstacles??[],e.layerCount??2),this.connMap=e.connMap,this.viaDiameter=e.viaDiameter??.3,this.traceThickness=e.traceThickness??.15,this.routes=this.extractRoutesFromNode(),this.routes.length===0)return this.failed=!0,void(this.error="Expected at least 1 route");if(this.routes.some(o=>o.A.z===void 0||o.B.z===void 0))return this.failed=!0,void(this.error="Route points should have predefined z values");if(!this.routes.some(o=>o.A.z!==o.B.z))return this.failed=!0,void(this.error="No route transitions through an obstacle");const n=this.routes.map(o=>this.getContainingThroughObstacle(o));if(n.some(o=>!o))return this.failed=!0,void(this.error="No same-net multilayer obstacle contains every route");this.solvedRoutes.push(...this.routes.map((o,i)=>({connectionName:o.connectionName,rootConnectionName:o.rootConnectionName,regionId:this.nodeWithPortPoints.capacityMeshNodeId,route:[{x:o.A.x,y:o.A.y,z:o.A.z,...o.A.z!==o.B.z?{toNextSegmentType:"through_obstacle",...n[i].circuitJsonMetadata?{toNextSegmentCircuitJsonMetadata:n[i].circuitJsonMetadata}:{}}:{}},{x:o.B.x,y:o.B.y,z:o.B.z}],traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:[]}))),this.solved=!0}static isApplicable(e){return new e5n(e).solved}extractRoutesFromNode(){const e=[],n=new Map;for(const o of this.nodeWithPortPoints.portPoints){const{connectionName:i}=o;n.has(i)||n.set(i,[]),n.get(i).push(o)}for(const[o,i]of n.entries())for(const[r,s]of Yz(i))e.push({A:{...r},B:{...s},connectionName:o,rootConnectionName:r.rootConnectionName??s.rootConnectionName});return e}getContainingThroughObstacle(e){const n=e.A.z,o=e.B.z;return n===void 0||o===void 0?null:this.obstacles.find(i=>{return!(i.__zLayers.length<2)&&!(!i.__zLayers.includes(n)||!i.__zLayers.includes(o))&&!!(r={obstacle:i,connectionName:e.connectionName,connMap:this.connMap}).obstacle.connectedTo.some(s=>s===r.connectionName||(r.connMap?.areIdsConnected(r.connectionName,s)??!1))&&fft({point:e.A,obstacle:i})&&fft({point:e.B,obstacle:i});var r})??null}_step(){this.solved=!0}visualize(){const e={lines:[],points:[],rects:[],circles:[]};for(const n of this.obstacles)e.rects.push({center:n.center,width:n.width,height:n.height,fill:"rgba(128, 0, 128, 0.2)",stroke:"rgba(128, 0, 128, 0.6)",label:`through obstacle candidate
z: ${n.__zLayers.join(",")}`});for(const n of this.solvedRoutes){e.lines.push({points:n.route,strokeColor:"rgba(0, 180, 0, 0.8)",strokeDash:"4, 3",strokeWidth:n.traceThickness,label:`${n.connectionName} through_obstacle`});for(const o of n.route)e.points.push({x:o.x,y:o.y,color:"green",label:`${n.connectionName}
z: ${o.z}`})}return e}},R5=1e-6,Ift=({value:t,min:e,max:n})=>t>=e&&t<=n,Xse=({value:t,target:e,epsilon:n})=>Math.abs(t-e)<=n,Cft=({point:t,bounds:e,epsilon:n=1e-6})=>{if(![t.x,t.y,e.minX,e.maxX,e.minY,e.maxY].every(u=>(({value:g})=>Number.isFinite(g))({value:u}))||t.x<e.minX-n||t.x>e.maxX+n||t.y<e.minY-n||t.y>e.maxY+n)return"outside";const o=Xse({value:t.x,target:e.minX,epsilon:n}),i=Xse({value:t.x,target:e.maxX,epsilon:n}),r=Xse({value:t.y,target:e.minY,epsilon:n}),s=Xse({value:t.y,target:e.maxY,epsilon:n}),a=o||i,A=r||s;if(a&&A)return"on-boundary";const c=Ift({value:t.y,min:e.minY,max:e.maxY}),l=Ift({value:t.x,min:e.minX,max:e.maxX});return a&&c||A&&l?"on-boundary":"inside"};function zXn(t,e,n,o,i){const r={x:(t.x+e.x+n.x)/3,y:(t.y+e.y+n.y)/3},s=(f,I)=>Math.sqrt((I.x-f.x)**2+(I.y-f.y)**2),a=f=>{const I=s(f,t),C=s(f,e),y=s(f,n),x=f.x>=i.minX&&f.x<=i.maxX&&f.y>=i.minY&&f.y<=i.maxY;return I>=o&&C>=o&&y>=o&&x};if(a(r))return r;const A=(f,I,C)=>{const y=f.x-I.x,x=f.y-I.y,E=Math.sqrt(y*y+x*x);return E<1e-10?{x:I.x+C,y:I.y}:{x:I.x+y/E*C,y:I.y+x/E*C}},c=(f,I,C)=>{const y=I.x-f.x,x=I.y-f.y,E=Math.sqrt(y*y+x*x);if(E>2*C-1e-10||E<1e-10)return[];const B=E*E/(2*E),S=Math.sqrt(Math.max(0,C*C-B*B)),Q=f.x+y*B/E,w=f.y+x*B/E,M={x:Q+S*x/E,y:w-S*y/E},k={x:Q-S*x/E,y:w+S*y/E},R=[],F=1e-6;return Math.abs(s(M,f)-C)<F&&Math.abs(s(M,I)-C)<F&&R.push(M),Math.abs(s(k,f)-C)<F&&Math.abs(s(k,I)-C)<F&&R.push(k),R},l=[A(r,t,o),A(r,e,o),A(r,n,o),...c(t,e,o),...c(e,n,o),...c(n,t,o)],u=l.filter(a);if(u.length>0){const f=u.filter(I=>!(C=>Math.abs(C.x-i.minX)<1e-6||Math.abs(C.x-i.maxX)<1e-6||Math.abs(C.y-i.minY)<1e-6||Math.abs(C.y-i.maxY)<1e-6)(I));if(f.length>0)return f.sort((I,C)=>s(I,r)-s(C,r)),f[0]}let g=null,h=1/0;for(let f=i.minX+1;f<i.maxX;f+=5)for(let I=i.minY+1;I<i.maxY;I+=5){const C={x:f,y:I};if(a(C)){const y=s(C,r);y<h&&(h=y,g=C)}}if(g!==null)return g;const d=[];for(let f=0;f<=100;f++){const I=f/100;d.push({x:i.minX+I*(i.maxX-i.minX),y:i.minY}),d.push({x:i.maxX,y:i.minY+I*(i.maxY-i.minY)}),d.push({x:i.maxX-I*(i.maxX-i.minX),y:i.maxY}),d.push({x:i.minX,y:i.maxY-I*(i.maxY-i.minY)})}const p=d.filter(a);if(p.length>0)return p.sort((f,I)=>s(f,r)-s(I,r)),p[0];let m=1/0,_={x:i.minX,y:i.minY};for(const f of[...l,...d])if(f.x>=i.minX&&f.x<=i.maxX&&f.y>=i.minY&&f.y<=i.maxY){const I=Math.max(0,o-s(f,t))+Math.max(0,o-s(f,e))+Math.max(0,o-s(f,n));I<m&&(m=I,_=f)}return _}function LD(t,e,n){const o=yft(e,t,n.center,n.radius),i=yft(t,e,n.center,n.radius),r=jQ(o,e),s=jQ(t,i),a=1e-6;let A;if(r>a&&s>a){A={x:(o.x+i.x)/2,y:(o.y+i.y)/2};const c=jQ(o,A),l=jQ(i,A);if(Math.abs(c-l)>.5*Math.min(c,l)){const g=jQ(t,o),h=jQ(e,i),d=g+h;if(d>a){const p=h/d,m=g/d;A={x:o.x*p+i.x*m,y:o.y*p+i.y*m}}}const u=jQ(A,n.center);if(u<1.05*n.radius){const g={x:(A.x-n.center.x)/u,y:(A.y-n.center.y)/u};A={x:n.center.x+g.x*n.radius*1.2,y:n.center.y+g.y*n.radius*1.2}}}else{const c={x:(t.x+e.x)/2,y:(t.y+e.y)/2},l=jQ(c,n.center);if(l<1.1*n.radius){const u={x:(c.x-n.center.x)/l,y:(c.y-n.center.y)/l};A={x:n.center.x+u.x*n.radius*1.2,y:n.center.y+u.y*n.radius*1.2}}else A=c}return{B:o,D:i,E:A}}function yft(t,e,n,o){const i=[n.x-t.x,n.y-t.y],r=Math.sqrt(i[0]*i[0]+i[1]*i[1]);if(r<=o){if(r<1e-8){const m=[e.x-t.x,e.y-t.y],_=Math.sqrt(m[0]*m[0]+m[1]*m[1]);return _<1e-8?{x:n.x+o,y:n.y}:{x:n.x+m[0]/_*o,y:n.y+m[1]/_*o}}const p=[i[0]/r,i[1]/r];return{x:n.x-p[0]*o,y:n.y-p[1]*o}}const s=[e.x-t.x,e.y-t.y],a=Math.sqrt(r*r-o*o),A=[i[0]/r,i[1]/r],c=[-A[1],A[0]],l=[A[1],-A[0]],u=s[0]*c[0]+s[1]*c[1]>s[0]*l[0]+s[1]*l[1]?c:l,g=o/r,h=a/r,d=[A[0]*h+u[0]*g,A[1]*h+u[1]*g];return{x:t.x+a*d[0],y:t.y+a*d[1]}}function jQ(t,e){const n=e.x-t.x,o=e.y-t.y;return Math.sqrt(n*n+o*o)}var pC=1e-9;function xft(t,e,n,o="cw"){const i=Kz(t,n),r=Kz(e,n);return Math.abs(r-i)<pC?{left:0,top:0,right:0,bottom:0}:(function(s,a,A,c){const l=A.maxX-A.minX,u=A.maxY-A.minY;if(l<pC&&u<pC)return{left:0,top:0,right:0,bottom:0};const g=2*(l+u);if(g<pC)return{left:0,top:0,right:0,bottom:0};const h=l/g*(2*Math.PI),d=(l+u)/g*(2*Math.PI),p=(l+l+u)/g*(2*Math.PI),m=2*Math.PI,_=[{name:"top",start:0,end:h,length:l},{name:"right",start:h,end:d,length:u},{name:"bottom",start:d,end:p,length:l},{name:"left",start:p,end:m,length:u}],f={left:0,top:0,right:0,bottom:0},I=(C,y,x,E,B)=>{const S=y>2*Math.PI-pC?2*Math.PI:y;if(S<=C+pC)return 0;if(B){const Q=Math.max(C,x),w=Math.min(S,2*Math.PI),M=Math.max(0,w-Q),k=Math.max(C,0),R=Math.min(S,E);return M+Math.max(0,R-k)}{const Q=Math.max(C,x),w=Math.min(S,E);return Math.max(0,w-Q)}};for(const C of _){const y=C.end-C.start;if(y<pC||C.length<pC)continue;let x=0;if(c==="cw"){const E=s>a+pC;x=I(C.start,C.end,s,a,E)}else{const E=a>s+pC;x=I(C.start,C.end,a,s,E)}if(x>pC){const E=x/y;f[C.name]+=Math.max(0,Number.isFinite(E)?E:0)}}for(const C in f)f[C]=Math.max(0,Math.min(1,f[C]));return f})(i,r,n,o)}function Kz(t,e){const n=e.maxX-e.minX,o=e.maxY-e.minY;if(n<pC&&o<pC)return 0;const i=2*(n+o);if(i<pC)return 0;let r=0;if(Math.abs(t.y-e.maxY)<=R5&&t.x>=e.minX-R5&&t.x<=e.maxX+R5)r=Math.max(0,Math.min(n,t.x-e.minX));else if(Math.abs(t.x-e.maxX)<=R5&&t.y>=e.minY-R5&&t.y<=e.maxY+R5)r=n+Math.max(0,Math.min(o,e.maxY-t.y));else if(Math.abs(t.y-e.minY)<=R5&&t.x>=e.minX-R5&&t.x<=e.maxX+R5)r=n+o+Math.max(0,Math.min(n,e.maxX-t.x));else{if(!(Math.abs(t.x-e.minX)<=R5&&t.y>=e.minY-R5&&t.y<=e.maxY+R5))throw new Error(`Point (${t.x}, ${t.y}) does not lie on the boundary defined by ${JSON.stringify(e)}`);r=n+o+n+Math.max(0,Math.min(o,t.y-e.minY))}return r=Math.max(0,Math.min(i,r)),i>pC?r/i*(2*Math.PI):0}function JXn(t,e,n,o){return(function({angleA:i,angleB:r,angleC:s}){const a=Math.cos(i),A=Math.sin(i),c=Math.cos(r),l=Math.sin(r),u=Math.cos(s);return(c-a)*(Math.sin(s)-A)-(l-A)*(u-a)<0?"ccw":"cw"})({angleA:Kz(t,o),angleB:Kz(e,o),angleC:Kz(n,o)})}var WXn=class extends yr{getSolverName(){return"SingleTransitionCrossingRouteSolver"}nodeWithPortPoints;routes;viaDiameter;traceThickness;obstacleMargin;layerCount=2;debugViaPositions;solvedRoutes=[];bounds;constructor(e){if(super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.viaDiameter=e?.viaDiameter??.3,this.traceThickness=e?.traceThickness??.15,this.obstacleMargin=e?.obstacleMargin??.1,this.layerCount=e?.layerCount??2,this.debugViaPositions=[],this.routes=this.extractRoutesFromNode(),this.bounds=this.calculateBounds(),this.routes.length!==2)return this.failed=!0,void(this.error=`Expected 2 routes, but got ${this.routes.length}`);const n=this.routes.flatMap(a=>[a.A,a.B]).map(a=>this.getPortPointBoundsPosition(a));if(n.includes("outside"))return this.failed=!0,void(this.error="Invalid route input: SingleTransitionCrossingRouteSolver received port point(s) outside node bounds");if(n.includes("inside"))return void(this.failed=!0);this.routes=this.routes.map(a=>({...a,A:this.snapPortPointToBounds(a.A),B:this.snapPortPointToBounds(a.B)}));const[o,i]=this.routes,r=o.A.z!==o.B.z,s=i.A.z!==i.B.z;return r&&s||!r&&!s?(this.failed=!0,void(this.error="Exactly one route must have a layer transition")):void 0}extractRoutesFromNode(){const e=[],n=this.nodeWithPortPoints.portPoints,o=new Map;for(const i of n){const{connectionName:r}=i;o.has(r)||o.set(r,[]),o.get(r)?.push(i)}for(const[i,r]of o.entries())r.length===2&&e.push({A:{...r[0],z:r[0].z??0},B:{...r[1],z:r[1].z??0},connectionName:i});return e}calculateBounds(){return{minX:this.nodeWithPortPoints.center.x-this.nodeWithPortPoints.width/2,maxX:this.nodeWithPortPoints.center.x+this.nodeWithPortPoints.width/2,minY:this.nodeWithPortPoints.center.y-this.nodeWithPortPoints.height/2,maxY:this.nodeWithPortPoints.center.y+this.nodeWithPortPoints.height/2}}getPortPointBoundsPosition(e){return Cft({point:e,bounds:this.bounds})}snapPortPointToBounds(e){const n=V3(e.x,this.bounds.minX,this.bounds.maxX),o=V3(e.y,this.bounds.minY,this.bounds.maxY);return[{distance:Math.abs(e.y-this.bounds.maxY),point:{...e,x:n,y:this.bounds.maxY}},{distance:Math.abs(e.x-this.bounds.maxX),point:{...e,x:this.bounds.maxX,y:o}},{distance:Math.abs(e.y-this.bounds.minY),point:{...e,x:n,y:this.bounds.minY}},{distance:Math.abs(e.x-this.bounds.minX),point:{...e,x:this.bounds.minX,y:o}}].reduce((i,r)=>r.distance<i.distance?r:i).point}doRoutesCross(e,n){return Uh(e.A,e.B,n.A,n.B)}calculateViaPosition(e,n){const o=n.A.z,i=e.A.z!==o?e.A:e.B,r=2*this.obstacleMargin+this.viaDiameter/2+this.traceThickness,s=this.obstacleMargin+this.viaDiameter/2,a=n.A,A=i,c=n.B,l=JXn(a,A,c,this.bounds),u=(function(h,d,p,m,_){const f=xft(h,d,m,_),I=xft(d,p,m,_),C={left:Math.min(1,f.left+I.left),top:Math.min(1,f.top+I.top),right:Math.min(1,f.right+I.right),bottom:Math.min(1,f.bottom+I.bottom)};for(const y in C)Math.abs(C[y])<pC&&(C[y]=0);return C})(a,A,c,this.bounds,l),g={minX:this.bounds.minX+(u.left>.5?r:s),minY:this.bounds.minY+(u.bottom>.5?r:s),maxX:this.bounds.maxX-(u.right>.5?r:s),maxY:this.bounds.maxY-(u.top>.5?r:s)};return g.maxY<g.minY&&(g.minY=(g.minY+g.maxY)/2,g.maxY=g.minY),g.maxX<g.minX&&(g.minX=(g.minX+g.maxX)/2,g.maxX=g.minX),zXn(a,A,c,r,g)}createTransitionRoute(e,n,o,i){const r=[{x:e.x,y:e.y,z:e.z??0},{x:o.x,y:o.y,z:e.z??0},{x:o.x,y:o.y,z:n.z??0},{x:n.x,y:n.y,z:n.z??0}];return{connectionName:i,regionId:this.nodeWithPortPoints.capacityMeshNodeId,route:r,traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:[o]}}createFlatRoute(e,n,o,i,r,s){i.z,e.z;const a=this.viaDiameter/2+this.traceThickness/2+this.obstacleMargin,A=((_,f,I,C)=>{const y=I.x-_.x,x=I.y-_.y;return((E,B)=>({x:(E.x+B.x)/2,y:(E.y+B.y)/2}))({x:_.x+y*f,y:_.y+x*f},{x:I.x-y*C,y:I.y-x*C})})(o,this.viaDiameter,i.z!==e.z?i:r,this.traceThickness),c={center:{x:o.x,y:o.y},radius:a},l=LD(e,A,c).E,u=LD(A,n,c).E,g=LD(e,l,c).E,h=LD(l,A,c).E,d=LD(A,u,c).E,p=LD(u,n,c).E,m=LD(h,d,c).E;return{connectionName:s,regionId:this.nodeWithPortPoints.capacityMeshNodeId,route:[{x:e.x,y:e.y,z:e.z??0},{x:g.x,y:g.y,z:e.z??0},{x:l.x,y:l.y,z:e.z??0},{x:h.x,y:h.y,z:e.z??0},{x:m.x,y:m.y,z:e.z??0},{x:d.x,y:d.y,z:e.z??0},{x:u.x,y:u.y,z:e.z??0},{x:p.x,y:p.y,z:e.z??0},{x:n.x,y:n.y,z:n.z??0}],traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:[]}}trySolve(){const[e,n]=this.routes,o=e.A.z!==e.B.z,i=o?e:n,r=o?n:e,s=this.calculateViaPosition(i,r);if(!s)return!1;this.debugViaPositions.push({via:s});const a=this.createTransitionRoute(i.A,i.B,s,i.connectionName),A=this.createFlatRoute(r.A,r.B,s,i.A,i.B,r.connectionName);return this.solvedRoutes.push(a,A),!0}_step(){if(!this.doRoutesCross(this.routes[0],this.routes[1]))return this.failed=!0,void(this.error="Can only solve routes that have a single transition crossing");this.trySolve()?this.solved=!0:(this.failed=!0,this.error="Failed to find a valid via position and route path")}visualize(){const e={lines:[],points:[],rects:[],circles:[]};e.rects.push({center:{x:(this.bounds.minX+this.bounds.maxX)/2,y:(this.bounds.minY+this.bounds.maxY)/2},width:this.bounds.maxX-this.bounds.minX,height:this.bounds.maxY-this.bounds.minY,stroke:"rgba(0, 0, 0, 0.5)",fill:"rgba(240, 240, 240, 0.1)",label:"PCB Bounds"});for(const n of this.routes)e.points.push({x:n.A.x,y:n.A.y,label:`${n.connectionName} start (z=${n.A.z})`,color:"orange"}),e.points.push({x:n.B.x,y:n.B.y,label:`${n.connectionName} end (z=${n.B.z})`,color:"orange"}),e.lines.push({points:[n.A,n.B],strokeColor:"rgba(255, 0, 0, 0.5)",label:`${n.connectionName} direct`});for(let n=0;n<this.debugViaPositions.length;n++){const{via:o}=this.debugViaPositions[n];e.circles.push({center:o,radius:this.viaDiameter/2,fill:"rgba(255, 165, 0, 0.7)",stroke:"rgba(0, 0, 0, 0.5)",label:`Computed Via (attempt ${n+1})`});const i=this.viaDiameter/2+this.obstacleMargin;e.circles.push({center:o,radius:i,stroke:"rgba(255, 165, 0, 0.7)",fill:"rgba(0, 0, 0, 0)",label:"Safety Margin"})}for(let n=0;n<this.solvedRoutes.length;n++){const o=this.solvedRoutes[n],i=n%2==0?"rgba(0, 255, 0, 0.75)":"rgba(255, 0, 255, 0.75)";for(let r=0;r<o.route.length-1;r++){const s=o.route[r],a=o.route[r+1];e.lines.push({points:[s,a],strokeColor:i,strokeDash:s.z!==o.route[0].z?[.2,.2]:void 0,strokeWidth:o.traceThickness,label:`${o.connectionName} z=${s.z}`})}for(const r of o.vias)e.circles.push({center:r,radius:this.viaDiameter/2,fill:"rgba(0, 0, 255, 0.8)",stroke:"black",label:"Solved Via"}),e.circles.push({center:r,radius:this.viaDiameter/2+this.obstacleMargin,fill:"rgba(0, 0, 255, 0.3)",stroke:"black",label:"Via Margin"})}return e}getSolvedRoutes(){return this.solvedRoutes}};function jXn({A:t,B:e,C:n,D:o,E:i,F:r,radius:s,margin:a,subdivisions:A=0}){const c=(E,B)=>({x:(E.x+B.x)/2,y:(E.y+B.y)/2}),l=(E,B,S)=>{const Q=B.x-E.x,w=B.y-E.y,M=Math.sqrt(Q*Q+w*w),k=Q/M,R=w/M,F=-R,O=k;return{midpoint:{x:(E.x+B.x)/2,y:(E.y+B.y)/2},A_Opp:{x:E.x-k*S,y:E.y-R*S},A_Right:{x:E.x+F*S,y:E.y+O*S},A_Left:{x:E.x-F*S,y:E.y-O*S},B_Opp:{x:B.x+k*S,y:B.y+R*S},B_Right:{x:B.x+F*S,y:B.y+O*S},B_Left:{x:B.x-F*S,y:B.y-O*S}}},u=(E,B)=>{const S=no(E,B.start),Q=no(E,B.end),w=no(B.start,B.end);return Math.abs(S+Q-w)<1e-4},g=(E,B)=>{const{start:S,end:Q}=E,{start:w,end:M}=B;if(u(S,B)||u(Q,B)||u(w,E)||u(M,E))return!0;const k=Q.x-S.x,R=Q.y-S.y,F=M.x-w.x,O=M.y-w.y,U=k*O-R*F;if(Math.abs(U)<1e-4)return!1;const Y=w.x-S.x,W=w.y-S.y,te=(Y*O-W*F)/U,j=(Y*R-W*k)/U;return te>0&&te<1&&j>0&&j<1},h=(E,B)=>{const S=[];for(let w=0;w<E.length-1;w++)S.push({start:E[w],end:E[w+1]});const Q=[];for(let w=0;w<B.length-1;w++)Q.push({start:B[w],end:B[w+1]});for(const w of S)for(const M of Q)if(g(w,M))return!0;return!1},d=E=>{let B=0;for(let S=1;S<E.length;S++){const Q=E[S].x-E[S-1].x,w=E[S].y-E[S-1].y;B+=Math.sqrt(Q*Q+w*w)}return B},p=(E,B)=>{const{start:S,end:Q}=E,w=Q.x-S.x,M=Q.y-S.y,k=w*w+M*M;if(k===0)return{...S,t:0};const R=Math.max(0,Math.min(1,((B.x-S.x)*w+(B.y-S.y)*M)/k));return{x:S.x+R*w,y:S.y+R*M,t:R}},m=(E,B,S)=>{const Q=p(E,B);if(no(Q,B)>=S)return Q;const w=Q.x-B.x,M=Q.y-B.y,k=Math.sqrt(w*w+M*M);if(k===0){const R=E.end.x-E.start.x,F=E.end.y-E.start.y,O=Math.sqrt(R*R+F*F);return{x:B.x+S*R/O,y:B.y+S*F/O,t:Q.t,isSpecial:!0,specialType:B===t?"A":"B"}}return{x:B.x+S*w/k,y:B.y+S*M/k,t:Q.t,isSpecial:!0,specialType:B===t?"A":"B"}},_=l(t,e,s),f=l(t,e,s+a),I=(E,B,S,Q,w)=>{const M=E.points;if(M.length<2)return M;const k=S+Q,R=[M[0]];for(let F=0;F<M.length-1;F++){const O={start:M[F],end:M[F+1]};if(wc(B,O.start,O.end)<k){const U=p(O,B),Y=U.x-B.x,W=U.y-B.y,te=Math.sqrt(Y*Y+W*W);let j=null;if(te>1e-6)j={x:B.x+k*Y/te,y:B.y+k*W/te};else{const J=O.end.x-O.start.x,oe=O.end.y-O.start.y,ie=Math.sqrt(J*J+oe*oe);ie>1e-6&&(j={x:B.x+k*J/ie,y:B.y+k*oe/ie})}j&&no(O.start,j)>s/10&&R.push(j)}no(R[R.length-1],O.end)>s/10&&R.push(O.end)}if(R.length>1){const F=[R[0]];for(let O=1;O<R.length;O++)no(F[F.length-1],R[O])>s/10&&F.push(R[O]);return F}return R},C=(()=>{const E=[[n,_.B_Left,_.B_Opp,_.B_Right,c(_.midpoint,c(_.B_Right,_.A_Right)),c(_.midpoint,c(_.A_Left,_.B_Left)),_.A_Left,_.A_Opp,_.A_Right,o],[n,_.B_Right,_.B_Opp,_.B_Left,c(_.midpoint,c(_.A_Left,_.B_Left)),c(_.midpoint,c(_.A_Right,_.B_Right)),_.A_Right,_.A_Opp,_.A_Left,o],[o,_.B_Left,_.B_Opp,_.B_Right,c(_.midpoint,c(_.A_Right,_.B_Right)),c(_.midpoint,c(_.A_Left,_.B_Left)),_.A_Left,_.A_Opp,_.A_Right,n],[o,_.B_Right,_.B_Opp,_.B_Left,c(_.midpoint,c(_.A_Left,_.B_Left)),c(_.midpoint,c(_.A_Right,_.B_Right)),_.A_Right,_.A_Opp,_.A_Left,n]],B=[];for(let W=0;W<E.length;W++){const te=E[W],j={start:te[0],end:te[1]},J={start:te[te.length-2],end:te[te.length-1]},oe={start:te[3],end:te[4]};g(j,J)||g(j,oe)||g(J,oe)||B.push({index:W+1,path:te,length:d(te)})}if(B.length===0)return{index:0,path:[]};const S=B.sort((W,te)=>W.length-te.length)[0],Q=[...S.path],w=Q[0],M=no(w,Q[2]),k=no(w,Q[3]),R=M<k?2:3;(M<no(w,Q[1])||k<no(w,Q[1]))&&Q.splice(1,R-1);const F=Q[Q.length-1],O=no(F,Q[Q.length-3]),U=no(F,Q[Q.length-4]),Y=O<U?Q.length-3:Q.length-4;return(O<no(F,Q[Q.length-2])||U<no(F,Q[Q.length-2]))&&Q.splice(Y+1,Q.length-Y-2),{index:S.index,path:Q,startsAt:Q[0]===n?"C":"D",goesTo:Q[Q.length-1]===n?"C":"D"}})(),y=A>0?((E,B)=>{if(E.length<2)return E;const S=[E[0]];for(let Q=0;Q<E.length-1;Q++){const w={start:E[Q],end:E[Q+1]},M={x:(w.start.x+w.end.x)/2,y:(w.start.y+w.end.y)/2},k=no(M,t),R=no(M,e);if((k<=s||R<=s)&&Math.abs(k-R)>1e-4){const F=p(w,t),O=p(w,e),U=no(F,t),Y=no(O,e)<s,W=U<s?m(w,t,s):null,te=Y?m(w,e,s):null;let j=[];if(no(w.start,w.end)>s/2&&B>0)for(let J=1;J<=B;J++){const oe=J/(B+1),ie={x:w.start.x+oe*(w.end.x-w.start.x),y:w.start.y+oe*(w.end.y-w.start.y),t:oe,isSpecial:!1},ne=no(ie,t),le=no(ie,e);ne<s||le<s||W&&Math.abs(ie.t-W.t)<.1||te&&Math.abs(ie.t-te.t)<.1||j.push(ie)}if(W&&j.push(W),te&&j.push(te),j.sort((J,oe)=>J.t-oe.t),j.length>1){const J=[j[0]];for(let oe=1;oe<j.length;oe++){const ie=J[J.length-1],ne=j[oe];no(ie,ne)>s/10&&J.push(ne)}j=J}j.forEach(J=>S.push(J))}S.push(E[Q+1])}if(S.length>1){const Q=[S[0]];for(let w=1;w<S.length;w++){const M=Q[Q.length-1],k=S[w];no(M,k)>s/10&&Q.push(k)}return Q}return S})(C.path,A):C.path;let x=(()=>{if(C.path.length===0)return null;const E=(()=>{const M=c(_.A_Right,_.B_Right),k=c(_.B_Left,_.A_Left);return[{startsAt:"E",goesTo:"B",points:[i,e]},{startsAt:"E",goesTo:"A",points:[i,t]},{startsAt:"F",goesTo:"B",points:[r,e]},{startsAt:"F",goesTo:"A",points:[r,t]},{startsAt:"E",goesTo:"B",points:[i,M,e]},{startsAt:"E",goesTo:"A",points:[i,M,t]},{startsAt:"F",goesTo:"B",points:[r,M,e]},{startsAt:"F",goesTo:"A",points:[r,M,t]},{startsAt:"E",goesTo:"B",points:[i,k,e]},{startsAt:"E",goesTo:"A",points:[i,k,t]},{startsAt:"F",goesTo:"B",points:[r,k,e]},{startsAt:"F",goesTo:"A",points:[r,k,t]},{startsAt:"E",goesTo:"B",points:[i,f.A_Right,M,e]},{startsAt:"F",goesTo:"B",points:[r,f.B_Right,M,e]},{startsAt:"E",goesTo:"A",points:[i,f.B_Left,k,t]},{startsAt:"F",goesTo:"A",points:[r,f.A_Left,k,t]},{startsAt:"E",goesTo:"B",points:[i,f.A_Left,k,e]},{startsAt:"E",goesTo:"A",points:[i,f.B_Right,M,t]},{startsAt:"E",goesTo:"B",points:[i,f.A_Opp,f.A_Right,M,e]},{startsAt:"E",goesTo:"A",points:[i,f.B_Opp,f.B_Left,k,t]},{startsAt:"F",goesTo:"B",points:[r,f.A_Opp,f.A_Left,k,e]},{startsAt:"F",goesTo:"A",points:[r,f.B_Opp,f.B_Right,M,t]},{startsAt:"F",goesTo:"A",points:[r,f.B_Opp,f.B_Left,k,t]},{startsAt:"E",goesTo:"B",points:[i,f.A_Opp,f.A_Left,k,e]},{startsAt:"E",goesTo:"A",points:[i,f.B_Opp,f.B_Right,M,t]},{startsAt:"E",goesTo:"B",points:[i,f.A_Left,f.A_Opp,f.A_Right,M,e]},{startsAt:"E",goesTo:"A",points:[i,f.B_Right,f.B_Opp,f.B_Left,k,t]},{startsAt:"F",goesTo:"B",points:[r,f.A_Right,f.A_Opp,f.A_Left,k,e]},{startsAt:"F",goesTo:"A",points:[r,f.B_Left,f.B_Opp,f.B_Right,M,t]},{startsAt:"F",goesTo:"A",points:[r,f.B_Right,f.B_Opp,f.B_Left,k,t]},{startsAt:"E",goesTo:"B",points:[i,f.A_Right,f.A_Opp,f.A_Left,k,e]},{startsAt:"E",goesTo:"A",points:[i,f.B_Left,f.B_Opp,f.B_Right,M,t]}].map((R,F)=>({...R,index:F}))})(),B=E.filter(M=>M.startsAt==="E"),S=E.filter(M=>M.startsAt==="F"),Q=[],w=[];for(const M of B)if(!h(M.points,C.path)){Q.push(M);break}for(const M of S)if(!h(M.points,C.path)){w.push(M);break}return Q.length===0||w.length===0?null:{line1:Q[0],line2:w[0]}})();if(x){const E=x.line1.goesTo==="A"?e:t,B=x.line2.goesTo==="A"?e:t,S=I(x.line1,E,s,a),Q=I(x.line2,B,s,a);x={line1:{...x.line1,points:S},line2:{...x.line2,points:Q}}}return{jPair:x,optimalPath:{startsAt:C.startsAt,goesTo:C.goesTo,points:y}}}var $Xn=class extends yr{getSolverName(){return"TwoCrossingRoutesHighDensitySolver"}nodeWithPortPoints;routes;viaDiameter;traceThickness;obstacleMargin;layerCount=2;debugViaPositions;escapeLayer=1;solvedRoutes=[];bounds;constructor(e){if(super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.viaDiameter=e?.viaDiameter??.3,this.traceThickness=e?.traceThickness??.15,this.obstacleMargin=e?.obstacleMargin??.1,this.layerCount=e?.layerCount??2,this.debugViaPositions=[],this.routes=this.extractRoutesFromNode(),this.bounds=this.calculateBounds(),this.routes.length!==2)return this.failed=!0,void(this.error=`Expected 2 routes, but got ${this.routes.length}`);const[n,o]=this.routes;if(n.startPort.z!==n.endPort.z)return this.failed=!0,void(this.error="Route A must start and end on the same layer");if(o.startPort.z!==o.endPort.z)return this.failed=!0,void(this.error="Route B must start and end on the same layer");if(n.startPort.z!==o.startPort.z)return this.failed=!0,void(this.error="Both routes must be on the same layer");n.startPort.z===0?this.escapeLayer=1:this.escapeLayer=0}extractRoutesFromNode(){const e=[],n=this.nodeWithPortPoints.portPoints,o=new Map;for(const i of n){const{connectionName:r}=i;o.has(r)||o.set(r,[]),o.get(r)?.push(i)}for(const[i,r]of o.entries())r.length===2&&e.push({startPort:{...r[0],z:r[0].z??0},endPort:{...r[1],z:r[1].z??0},connectionName:i});return e}calculateBounds(){return{minX:this.nodeWithPortPoints.center.x-this.nodeWithPortPoints.width/2,maxX:this.nodeWithPortPoints.center.x+this.nodeWithPortPoints.width/2,minY:this.nodeWithPortPoints.center.y-this.nodeWithPortPoints.height/2,maxY:this.nodeWithPortPoints.center.y+this.nodeWithPortPoints.height/2}}doRoutesCross(e,n){return Uh(e.startPort,e.endPort,n.startPort,n.endPort)}calculateViaPositions(e,n){const o=this.bounds.maxX-this.bounds.minX,i=this.bounds.maxY-this.bounds.minY,r=this.bounds.minX,s=this.bounds.minY,a={width:o-2*this.obstacleMargin-this.viaDiameter,height:i-2*this.obstacleMargin-this.viaDiameter,x:r+this.obstacleMargin+this.viaDiameter/2,y:s+this.obstacleMargin+this.viaDiameter/2},A=this.viaDiameter+this.obstacleMargin,c=n.startPort,l=n.endPort,u=[{x:a.x,y:a.y},{x:a.x+a.width,y:a.y},{x:a.x+a.width,y:a.y+a.height},{x:a.x,y:a.y+a.height}],g=(C,y)=>no(C,y),h=[];u.forEach((C,y)=>{g(C,c)>=A&&g(C,l)>=A&&h.push({...C,type:"corner",index:y})});const d=[{p1:u[0],p2:u[1]},{p1:u[1],p2:u[2]},{p1:u[2],p2:u[3]},{p1:u[3],p2:u[0]}];if([c,l].forEach((C,y)=>{d.forEach((x,E)=>{((B,S)=>{const Q=B.x,w=B.y,M=B.r,k=S.p1.x,R=S.p1.y,F=S.p2.x,O=S.p2.y;if(Math.abs(F-k)<.001){const ge=k,_e=M*M-(ge-Q)**2;if(_e<0)return[];if(Math.abs(_e)<.001){const ye=w;return ye>=Math.min(R,O)&&ye<=Math.max(R,O)?[{x:ge,y:ye}]:[]}const ue=w+Math.sqrt(_e),fe=w-Math.sqrt(_e),pe=[];return ue>=Math.min(R,O)&&ue<=Math.max(R,O)&&pe.push({x:ge,y:ue}),fe>=Math.min(R,O)&&fe<=Math.max(R,O)&&pe.push({x:ge,y:fe}),pe}const U=(O-R)/(F-k),Y=R-U*k,W=1+U*U,te=2*(U*Y-U*w-Q),j=te*te-4*W*(Q*Q+(Y-w)*(Y-w)-M*M);if(j<0)return[];if(Math.abs(j)<.001){const ge=-te/(2*W),_e=U*ge+Y;return ge>=Math.min(k,F)&&ge<=Math.max(k,F)&&_e>=Math.min(R,O)&&_e<=Math.max(R,O)?[{x:ge,y:_e}]:[]}const J=(-te+Math.sqrt(j))/(2*W),oe=(-te-Math.sqrt(j))/(2*W),ie=U*J+Y,ne=U*oe+Y,le=[];return J>=Math.min(k,F)&&J<=Math.max(k,F)&&ie>=Math.min(R,O)&&ie<=Math.max(R,O)&&le.push({x:J,y:ie}),oe>=Math.min(k,F)&&oe<=Math.max(k,F)&&ne>=Math.min(R,O)&&ne<=Math.max(R,O)&&le.push({x:oe,y:ne}),le})({...C,r:A},x).forEach(B=>{g(B,y===0?l:c)>=A&&h.push({...B,type:"intersection",circle:y,edge:E})})})}),h.length<2){const C=.8*A;if(u.forEach((y,x)=>{g(y,c)>=C&&g(y,l)>=C&&!h.some(E=>E.x===y.x&&E.y===y.y)&&h.push({...y,type:"relaxed_corner",index:x})}),h.length<2){const y=[...u].sort((x,E)=>{const B=Math.min(g(x,c),g(x,l));return Math.min(g(E,c),g(E,l))-B});for(const x of y)if(!h.some(E=>E.x===x.x&&E.y===x.y)&&(h.push({...x,type:"forced_corner"}),h.length>=2))break}}if(h.length<2)return null;let p=0,m=[h[0],h[h.length>1?1:0]];for(let C=0;C<h.length;C++)for(let y=C+1;y<h.length;y++){const x=g(h[C],h[y]);x>p&&(p=x,m=[h[C],h[y]])}let _={x:m[0].x,y:m[0].y},f={x:m[1].x,y:m[1].y};const I=no(_,e.startPort);return no(f,e.startPort)<I&&([_,f]=[f,_]),{via1:_,via2:f}}trySolveAOverB(e,n,o=!1){const i=o?this.calculateViaPositions(e,n):this.calculateViaPositions(n,e);if(!i)return!1;this.debugViaPositions.push(i);const{via1:r,via2:s}=this.pushViasFromEndpoints(this.moveViasAsCloseAsPossible(i));this.debugViaPositions.push({via1:r,via2:s});const{jPair:a,optimalPath:A}=jXn({A:r,B:s,C:e.startPort,D:e.endPort,E:n.startPort,F:n.endPort,radius:this.viaDiameter/2+this.obstacleMargin+this.traceThickness/2*1.5,margin:2*this.obstacleMargin+this.traceThickness/2*1.5,subdivisions:1});if(!a)return!1;const c={connectionName:e.connectionName,regionId:this.nodeWithPortPoints.capacityMeshNodeId,route:A.points.map(u=>({x:u.x,y:u.y,z:e.startPort.z??0})),traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:[]};a.line2.points.reverse();const l={connectionName:n.connectionName,regionId:this.nodeWithPortPoints.capacityMeshNodeId,route:[...a.line1.points.map(u=>({x:u.x,y:u.y,z:n.startPort.z??0})),{...a.line1.points[a.line1.points.length-1],z:this.escapeLayer},{...a.line2.points[0],z:this.escapeLayer},...a.line2.points.map(u=>({x:u.x,y:u.y,z:n.startPort.z??0}))],traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:[r,s]};return this.solvedRoutes.push(c,l),!0}pushViasFromEndpoints(e){const n={...e.via1},o={...e.via2},i=[this.routes[0].startPort,this.routes[0].endPort,this.routes[1].startPort,this.routes[1].endPort],r=this.getMinDistanceBetweenViaCenters(),s=this.viaDiameter/2+2*this.traceThickness+2*this.obstacleMargin;for(let A=0;A<10;A++){let c=!1,l=!1;const u=.9**A;for(const h of i){const d=no(n,h);if(d<s){const m=(s-d)*u,_=n.x-h.x,f=n.y-h.y,I=Math.sqrt(_*_+f*f);I>1e-6&&(n.x+=_/I*m,n.y+=f/I*m,c=!0)}const p=no(o,h);if(p<s){const m=(s-p)*u,_=o.x-h.x,f=o.y-h.y,I=Math.sqrt(_*_+f*f);I>1e-6&&(o.x+=_/I*m,o.y+=f/I*m,l=!0)}}const g=no(n,o);if(g<r){const h=(r-g)/2,d=o.x-n.x,p=o.y-n.y,m=Math.sqrt(d*d+p*p);m>1e-6?(n.x-=d/m*h,n.y-=p/m*h,o.x+=d/m*h,o.y+=p/m*h,c=!0,l=!0):(n.x-=h,o.x+=h,c=!0,l=!0)}if(!c&&!l)break}const a=no(n,o);if(a<r){const A=(r-a)/2,c=o.x-n.x,l=o.y-n.y,u=Math.sqrt(c*c+l*l);u>1e-6?(n.x-=c/u*A,n.y-=l/u*A,o.x+=c/u*A,o.y+=l/u*A):(n.x-=A,o.x+=A)}return{via1:n,via2:o}}getMinDistanceBetweenViaCenters(){return this.viaDiameter+this.traceThickness+2*this.obstacleMargin}moveViasAsCloseAsPossible(e){const{via1:n,via2:o}=e,i=this.getMinDistanceBetweenViaCenters(),r=no(n,o);if(r<=i)return e;const s=o.x-n.x,a=o.y-n.y,A=Math.sqrt(s*s+a*a),c=s/A,l=a/A,u=(n.x,o.x,n.y,o.y,(r-i)/2);return{via1:{x:n.x+c*u,y:n.y+l*u},via2:{x:o.x-c*u,y:o.y-l*u}}}handleRoutesDontCross(){const[e,n]=this.routes,o={connectionName:e.connectionName,regionId:this.nodeWithPortPoints.capacityMeshNodeId,route:[{x:e.startPort.x,y:e.startPort.y,z:e.startPort.z??0},{x:e.endPort.x,y:e.endPort.y,z:e.endPort.z??0}],traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:[]},i={connectionName:n.connectionName,regionId:this.nodeWithPortPoints.capacityMeshNodeId,route:[{x:n.startPort.x,y:n.startPort.y,z:n.startPort.z??0},{x:n.endPort.x,y:n.endPort.y,z:n.endPort.z??0}],traceThickness:this.traceThickness,viaDiameter:this.viaDiameter,vias:[]};this.solvedRoutes.push(o,i),this.solved=!0}_step(){if(this.routes.length!==2)return void(this.failed=!0);const[e,n]=this.routes;this.doRoutesCross(e,n)?this.trySolveAOverB(e,n)||this.trySolveAOverB(n,e)||this.trySolveAOverB(e,n,!0)||this.trySolveAOverB(n,e,!0)?this.solved=!0:(this.failed=!0,this.error="All crossover strategies failed"):this.handleRoutesDontCross()}visualize(){const e={lines:[],points:[],rects:[],circles:[]};e.rects.push({center:{x:(this.bounds.minX+this.bounds.maxX)/2,y:(this.bounds.minY+this.bounds.maxY)/2},width:this.bounds.maxX-this.bounds.minX,height:this.bounds.maxY-this.bounds.minY,stroke:"rgba(0, 0, 0, 0.5)",fill:"rgba(240, 240, 240, 0.1)"});for(const[n,o]of[["Route A",this.routes[0]],["Route B",this.routes[1]]])e.points.push({x:o.startPort.x,y:o.startPort.y,label:`${n}
${o.connectionName} start`,color:"orange"}),e.points.push({x:o.endPort.x,y:o.endPort.y,label:`${n}
${o.connectionName} end`,color:"orange"}),e.lines.push({points:[o.startPort,o.endPort],strokeColor:"rgba(255, 0, 0, 0.5)",label:`${n}
${o.connectionName} direct`});for(let n=0;n<this.debugViaPositions.length;n++){const{via1:o,via2:i}=this.debugViaPositions[n],r=["rgba(255, 165, 0, 0.3)","rgba(128, 0, 128, 0.3)"],s=r[n%r.length];e.circles.push({center:o,radius:this.viaDiameter/2,fill:s,stroke:"rgba(0, 0, 0, 0.3)",label:`Computed Via A (attempt ${n+1})`}),e.circles.push({center:i,radius:this.viaDiameter/2,fill:s,stroke:"rgba(0, 0, 0, 0.3)",label:`Computed Via B (attempt ${n+1})`});const a=this.viaDiameter/2+this.obstacleMargin;e.circles.push({center:o,radius:a,stroke:s,fill:"rgba(0, 0, 0, 0)",label:`Debug Via 1 Safety Margin (attempt ${n+1})`}),e.circles.push({center:i,radius:a,stroke:s,fill:"rgba(0, 0, 0, 0)",label:`Debug Via 2 Safety Margin (attempt ${n+1})`}),e.lines.push({points:[this.routes[n%2].startPort,o,i,this.routes[n%2].endPort],strokeColor:`${s.substring(0,s.lastIndexOf(","))}, 0.3)`,strokeDash:[5,5],label:`Potential Route (attempt ${n+1})`})}for(let n=0;n<this.solvedRoutes.length;n++){const o=this.solvedRoutes[n],i=n%2==0?"rgba(0, 255, 0, 0.75)":"rgba(255, 0, 255, 0.75)";for(let r=0;r<o.route.length-1;r++){const s=o.route[r],a=o.route[r+1];e.lines.push({points:[s,a],strokeColor:i,strokeDash:s.z===1?[.2,.2]:void 0,strokeWidth:o.traceThickness,label:`${o.connectionName} z=${s.z}`}),s._label&&e.points.push({x:s.x,y:s.y,label:s._label})}for(const r of o.vias)e.circles.push({center:r,radius:this.viaDiameter/2,fill:"rgba(0, 0, 255, 0.8)",stroke:"black",label:"Solved Via"}),e.circles.push({center:r,radius:this.viaDiameter/2+this.obstacleMargin,fill:"rgba(0, 0, 255, 0.3)",stroke:"black",label:"Solved Via Margin"})}return e}getSolvedRoutes(){return this.solvedRoutes}},Zse=class extends yr{getSolverName(){return"HyperParameterSupervisorSolver"}GREEDY_MULTIPLIER=1.2;MIN_SUBSTEPS=1;supervisedSolvers;winningSolver;getHyperParameterDefs(){throw new Error("Not implemented")}getCombinationDefs(){return null}getHyperParameterCombinations(e){e||(e=this.getHyperParameterDefs());const n=[];if(e.length===0)return[{}];const[o,...i]=e,r=this.getHyperParameterCombinations(i);return o.possibleValues.forEach(s=>{r.forEach(a=>{n.push({...a,...s})})}),n}initializeSolvers(){const e=this.getHyperParameterDefs(),n=this.getCombinationDefs()??[e.map(o=>o.name)];this.supervisedSolvers=[];for(const o of n){const i=this.getHyperParameterCombinations(e.filter(r=>o.includes(r.name)));for(const r of i){const s=this.generateSolver(r),a=this.computeG(s);this.supervisedSolvers.push({hyperParameters:r,solver:s,h:0,g:a,f:a})}}}generateSolver(e){throw new Error("Not implemented")}computeG(e){return e.iterations/e.MAX_ITERATIONS}computeH(e){return 1-(e.progress||0)}computeF(e,n){return e+n*this.GREEDY_MULTIPLIER}getSupervisedSolverWithBestFitness(){let e=1/0,n=null;for(const o of this.supervisedSolvers??[]){if(o.solver.solved)return o;if(o.solver.failed)continue;const i=o.f;i<e&&(e=i,n=o)}return n}getFailureMessage(){return`All solvers failed in hyper solver. Example failures: ${this.supervisedSolvers?.sort((e,n)=>n.f-e.f)?.slice(0,5).map(e=>e.solver.error).join(", ")}`}_step(){this.supervisedSolvers||this.initializeSolvers();const e=this.getSupervisedSolverWithBestFitness();if(!e)return this.failed=!0,void(this.error=this.getFailureMessage());for(let n=0;n<this.MIN_SUBSTEPS;n++)e.solver.step();this.activeSubSolver=e.solver,e.g=this.computeG(e.solver),e.h=this.computeH(e.solver),e.f=this.computeF(e.g,e.h),e.solver.solved&&(this.solved=!0,this.winningSolver=e.solver,this.onSolve?.(e))}onSolve(e){}visualize(){const e=this.getSupervisedSolverWithBestFitness();let n={lines:[],circles:[],points:[],rects:[]};return e&&(n=e.solver.visualize()),n}},z3=t=>`${t.x.toFixed(6)},${t.y.toFixed(6)},${t.z}`,qXn=t=>[t.route[0],t.route[t.route.length-1]],eae=(t,e,n)=>{const o=new Map,i=(a,A)=>{o.has(a)||o.set(a,new Set),o.has(A)||o.set(A,new Set),o.get(a).add(A),o.get(A).add(a)};for(const a of t)if(a.connectionName===e&&a.route.length!==0){if(a.route.length===1){const A=z3(a.route[0]);o.has(A)||o.set(A,new Set);continue}for(let A=0;A<a.route.length-1;A++)i(z3(a.route[A]),z3(a.route[A+1]))}const r=new Set([n]),s=[n];for(;s.length>0;){const a=s.pop();for(const A of o.get(a)??[])r.has(A)||(r.add(A),s.push(A))}return r},G7e=Array.from({length:6},(t,e)=>e),Vz=class extends Zse{getSolverName(){return"PortfolioSingleIntraNodeSolver"}constructorParams;solvedRoutes=[];nodeWithPortPoints;connMap;effort;adaptiveSearchExpanded=!1;getSolvedSegmentCount(e){const n=e.solvedConnectionsMap;if(!(n instanceof Map))return null;let o=0;for(const i of n.values())Array.isArray(i)&&(o+=i.length);return o}getNodeSegmentCount(){return Math.max(1,this.nodeWithPortPoints.portPointsInPairs?.length??new Set(this.nodeWithPortPoints.portPoints.map(e=>e.connectionName)).size)}getCandidateProgress(e){const n=this.getSolvedSegmentCount(e);return n!==null?Math.min(1,n/this.getNodeSegmentCount()):Math.max(0,Math.min(1,e.progress||0))}getTotalCandidateWork(){return(this.supervisedSolvers??[]).reduce((e,{solver:n})=>e+n.iterations,0)}getDynamicExpansionWorkBudget(){return Math.max(1,...(this.supervisedSolvers??[]).map(({solver:e})=>e.MAX_ITERATIONS))}constructor(e){super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.connMap=e.connMap,this.constructorParams=e,this.effort=e.effort??1,this.MAX_ITERATIONS=2e7*this.effort,this.GREEDY_MULTIPLIER=5,this.MIN_SUBSTEPS=100}getCombinationDefs(){return[["throughObstacle"],["singleLayerNoDifferentRootIntersections"],["multiHeadPolyLine"],["majorCombinations","orderings6","cellSizeFactor"],["noVias"],["orderings50"],["flipTraceAlignmentDirection","orderings6"],["closedFormSingleTrace"],["highDensityA01"],["highDensityA03"]]}getHyperParameterDefs(){return[{name:"singleLayerNoDifferentRootIntersections",possibleValues:[{SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS:!0}]},{name:"majorCombinations",possibleValues:[{FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR:2,FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR:1,FUTURE_CONNECTION_PROXIMITY_VD:10,MISALIGNED_DIST_PENALTY_FACTOR:5},{FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR:1,FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR:.5,FUTURE_CONNECTION_PROXIMITY_VD:5,MISALIGNED_DIST_PENALTY_FACTOR:2},{FUTURE_CONNECTION_PROX_TRACE_PENALTY_FACTOR:10,FUTURE_CONNECTION_PROX_VIA_PENALTY_FACTOR:1,FUTURE_CONNECTION_PROXIMITY_VD:5,MISALIGNED_DIST_PENALTY_FACTOR:10,VIA_PENALTY_FACTOR_2:1}]},{name:"orderings6",possibleValues:G7e.map(e=>({SHUFFLE_SEED:e}))},{name:"cellSizeFactor",possibleValues:[{CELL_SIZE_FACTOR:.5},{CELL_SIZE_FACTOR:1}]},{name:"flipTraceAlignmentDirection",possibleValues:[{FLIP_TRACE_ALIGNMENT_DIRECTION:!0}]},{name:"noVias",possibleValues:[{CELL_SIZE_FACTOR:2,VIA_PENALTY_FACTOR_2:10}]},{name:"orderings50",possibleValues:Array.from({length:20},(e,n)=>({SHUFFLE_SEED:100+n}))},{name:"throughObstacle",possibleValues:[{THROUGH_OBSTACLE:!0}]},{name:"closedFormSingleTrace",possibleValues:[{CLOSED_FORM_SINGLE_TRANSITION:!0}]},{name:"multiHeadPolyLine",possibleValues:[{MULTI_HEAD_POLYLINE_SOLVER:!0,SEGMENTS_PER_POLYLINE:6,BOUNDARY_PADDING:.05},{MULTI_HEAD_POLYLINE_SOLVER:!0,SEGMENTS_PER_POLYLINE:6,BOUNDARY_PADDING:-.05,ITERATION_PENALTY:1e4,MINIMUM_FINAL_ACCEPTANCE_GAP:.001}]},{name:"highDensityA01",possibleValues:[{HIGH_DENSITY_A01:!0,SHUFFLE_SEED:G7e[0]}]},{name:"highDensityA03",possibleValues:[{HIGH_DENSITY_A03:!0}]}]}initializeCandidateBudget(e){const n=e.setup;typeof n=="function"&&n.call(e)}refreshDynamicIterationLimit(){const e=(this.supervisedSolvers??[]).reduce((n,{solver:o})=>{if(o.solved||o.failed)return n;const i=Math.max(0,o.MAX_ITERATIONS-o.iterations+1);return n+Math.ceil(i/this.MIN_SUBSTEPS)},0);this.MAX_ITERATIONS=Math.max(this.iterations+1,this.iterations+e),this.stats.dynamicSupervisorIterationLimit=this.MAX_ITERATIONS}initializeSolvers(){super.initializeSolvers();for(const{solver:e}of this.supervisedSolvers??[])this.initializeCandidateBudget(e);this.stats.dynamicExpansionWorkBudget=this.getDynamicExpansionWorkBudget(),this.refreshDynamicIterationLimit()}addSupervisedCandidate(e){const n=this.generateSolver(e);this.initializeCandidateBudget(n);const o=this.computeG(n);this.supervisedSolvers.push({hyperParameters:e,solver:n,h:0,g:o,f:o})}expandAdaptiveSearch(){if(!this.adaptiveSearchExpanded){this.adaptiveSearchExpanded=!0;for(const e of G7e.slice(1))this.addSupervisedCandidate({HIGH_DENSITY_A01:!0,SHUFFLE_SEED:e});this.refreshDynamicIterationLimit(),this.stats.adaptiveSearchExpanded=!0,this.stats.adaptiveSearchExpandedAtIteration=this.iterations,this.stats.candidateWorkAtExpansion=this.getTotalCandidateWork(),this.stats.bestProgressAtExpansion=Math.max(0,...(this.supervisedSolvers??[]).map(({solver:e})=>this.getCandidateProgress(e)))}}shouldExpandPortfolio(){if(this.adaptiveSearchExpanded)return!1;const e=this.getDynamicExpansionWorkBudget();return this.stats.dynamicExpansionWorkBudget=e,this.getTotalCandidateWork()>=e}_step(){this.supervisedSolvers||this.initializeSolvers(),this.adaptiveSearchExpanded||this.getSupervisedSolverWithBestFitness()||this.expandAdaptiveSearch(),super._step(),this.solved||this.failed||!this.shouldExpandPortfolio()||this.expandAdaptiveSearch()}computeG(e){return e instanceof S7e||e instanceof w7e?e.iterations/1e6:e?.hyperParameters?.MULTI_HEAD_POLYLINE_SOLVER?1e3+((e.hyperParameters?.ITERATION_PENALTY??0)+e.iterations)/1e4+1e4*(e.hyperParameters.SEGMENTS_PER_POLYLINE-3):e.iterations/1e4}computeH(e){return this.adaptiveSearchExpanded?1-this.getCandidateProgress(e):1-(e.progress||0)}generateSolver(e){if(e.SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS){if(!pft.isApplicable(this.nodeWithPortPoints)){const n=new Wse({nodeWithPortPoints:this.nodeWithPortPoints,connMap:this.connMap,traceWidth:this.constructorParams.traceWidth,viaDiameter:this.constructorParams.viaDiameter,obstacleMargin:this.constructorParams.obstacleMargin});return n.failed=!0,n.error="Single-layer no-different-root-intersection solver not applicable",n}return new pft({nodeWithPortPoints:this.nodeWithPortPoints,traceWidth:this.constructorParams.traceWidth,viaDiameter:this.constructorParams.viaDiameter})}return e.HIGH_DENSITY_A01?new S7e({nodeWithPortPoints:this.nodeWithPortPoints,cellSizeMm:.1,viaDiameter:this.constructorParams.viaDiameter??.3,viaMinDistFromBorder:(this.constructorParams.viaDiameter??.3)/2,traceMargin:.1,traceThickness:this.constructorParams.traceWidth??.15,effort:this.effort,hyperParameters:{shuffleSeed:e.SHUFFLE_SEED??0}}):e.HIGH_DENSITY_A03?new w7e({nodeWithPortPoints:this.nodeWithPortPoints,highResolutionCellSize:.1,highResolutionCellThickness:8,lowResolutionCellSize:.4,viaDiameter:this.constructorParams.viaDiameter??.3,viaMinDistFromBorder:(this.constructorParams.viaDiameter??.3)/2,traceMargin:.1,traceThickness:.1,effort:this.effort,hyperParameters:e}):e.CLOSED_FORM_TWO_TRACE_SAME_LAYER?new $Xn({nodeWithPortPoints:this.nodeWithPortPoints,viaDiameter:this.constructorParams.viaDiameter}):e.CLOSED_FORM_TWO_TRACE_TRANSITION_CROSSING?new WXn({nodeWithPortPoints:this.nodeWithPortPoints,viaDiameter:this.constructorParams.viaDiameter}):e.CLOSED_FORM_SINGLE_TRANSITION?new KXn({nodeWithPortPoints:this.nodeWithPortPoints,viaDiameter:this.constructorParams.viaDiameter}):e.THROUGH_OBSTACLE?new VXn({nodeWithPortPoints:this.nodeWithPortPoints,obstacles:this.constructorParams.obstacles,connMap:this.connMap,layerCount:this.constructorParams.layerCount,viaDiameter:this.constructorParams.viaDiameter,traceThickness:this.constructorParams.traceWidth}):e.MULTI_HEAD_POLYLINE_SOLVER?new FXn({nodeWithPortPoints:this.nodeWithPortPoints,connMap:this.connMap,hyperParameters:e,viaDiameter:this.constructorParams.viaDiameter}):new T7e({...this.constructorParams,hyperParameters:e})}onSolve(e){let n;n=e.solver instanceof S7e||e.solver instanceof w7e?e.solver.getOutput():e.solver.solvedRoutes;const o=n.map(i=>{const r=this.nodeWithPortPoints.portPoints.find(s=>s.connectionName===i.connectionName);return r?.rootConnectionName?{...i,rootConnectionName:r.rootConnectionName}:i});this.solvedRoutes=((i,r)=>{const s=[...i],a=new Map;for(const A of r.portPoints){const c=a.get(A.connectionName)??[];c.push(A),a.set(A.connectionName,c)}for(const[A,c]of a){if(c.length<=1)continue;const l=c[0]?.rootConnectionName??A,u=new Set(c.map(z3));let g=eae(s,A,z3(c[0]));for(const h of c.slice(1)){const d=z3(h);if(g.has(d))continue;const p=s.find(m=>{if((m.rootConnectionName??m.connectionName)!==l||m.connectionName===A)return!1;const[_,f]=qXn(m);if(!_||!f)return!1;const I=z3(_),C=z3(f);return g.has(I)&&C===d||g.has(C)&&I===d||u.has(I)&&u.has(C)&&(I===d||C===d)});p&&(s.push({...p,connectionName:A,rootConnectionName:l,route:p.route.map(m=>({...m,connectionName:A,rootConnectionName:l})),vias:p.vias.map(m=>({...m})),jumpers:p.jumpers?.map(m=>({...m,start:{...m.start},end:{...m.end}}))}),g=eae(s,A,z3(c[0])))}}return s})(o,this.nodeWithPortPoints)}};function Eft(t,e,n,o,i){const r=n-e,s=i-o,a=1e-6;if(Math.abs(t.y-i)<a)return t.x-e;if(Math.abs(t.x-n)<a)return r+(i-t.y);if(Math.abs(t.y-o)<a)return r+s+(n-t.x);if(Math.abs(t.x-e)<a)return 2*r+s+(t.y-o);const A=Math.abs(t.y-i),c=Math.abs(t.x-n),l=Math.abs(t.y-o),u=Math.abs(t.x-e),g=Math.min(A,c,l,u);return g===A?Math.max(0,Math.min(r,t.x-e)):g===c?r+Math.max(0,Math.min(s,i-t.y)):g===l?r+s+Math.max(0,Math.min(r,n-t.x)):2*r+s+Math.max(0,Math.min(s,t.y-o))}function tae(t,e,n=1e-6){return Math.abs(t-e)<n}function Bft(t){if(t.length<2)return 0;const e=t.map(([o,i])=>o<i?[o,i]:[i,o]);let n=0;for(let o=0;o<e.length;o++){const[i,r]=e[o];for(let s=o+1;s<e.length;s++){const[a,A]=e[s];tae(i,a)||tae(i,A)||tae(r,a)||tae(r,A)||(i<a&&a<r&&r<A||a<i&&i<A&&A<r)&&n++}}return n}var Wm=t=>{const e=t.center.x-t.width/2,n=t.center.x+t.width/2,o=t.center.y-t.height/2,i=t.center.y+t.height/2,r=new Map;for(const l of t.portPoints){const u=r.get(l.connectionName)??[];u.some(g=>g.x===l.x&&g.y===l.y&&g.z===l.z)||u.push({x:l.x,y:l.y,z:l.z}),r.set(l.connectionName,u)}const s=new Map,a=[];let A=0;for(const[l,u]of r){if(u.length<2)continue;const g=u[0],h=u[1],d=Eft(g,e,n,o,i),p=Eft(h,e,n,o,i);if(g.z===h.z){const m=g.z,_=s.get(m)??[];_.push([d,p]),s.set(m,_)}else A++,a.push([d,p])}let c=0;for(const[l,u]of s)c+=Bft(u);return{numSameLayerCrossings:c,numEntryExitLayerChanges:A,numTransitionPairCrossings:Bft(a)}},bft=t=>t.availableZ?.length?[...new Set(t.availableZ)].sort((e,n)=>e-n):[...new Set(t.portPoints.map(e=>e.z??0))].sort((e,n)=>e-n),Sft=t=>bft(t).length===1&&Wm(t).numSameLayerCrossings>0,Qft=(t,e,n)=>{const o=new Map,[i]=bft(t);for(const r of t.portPoints)o.set(r.connectionName,[...o.get(r.connectionName)??[],r]);return Array.from(o.entries()).flatMap(([r,s])=>{if(s.length<2)return[];const a=s[0],A=s[s.length-1];return[{connectionName:r,rootConnectionName:a.rootConnectionName,regionId:t.capacityMeshNodeId,traceThickness:e,viaDiameter:n,route:[{x:a.x,y:a.y,z:i??a.z??0},{x:A.x,y:A.y,z:i??A.z??0}],vias:[]}]})},XXn=Qft,zz=(t,e,n)=>({...t,x:e.x+(t.x-e.x)*n,y:e.y+(t.y-e.y)*n}),Y7e=(t,e,n)=>zz(t,e,n),nae=["#dc2626","#2563eb","#16a34a","#ca8a04","#9333ea","#0891b2"],vft=(t,e,n=[])=>[t,e?`rootConnectionName: ${e}`:void 0,...n].filter(Boolean).join(`
`),U7e=class extends yr{getSolverName(){return"GrowShrinkHighDensityIntraNodeSolver"}constructorParams;nodeWithPortPoints;solvedRoutes=[];failedSolvers=[];activeSubSolver=null;winningSolver;scaleFactor=1;growthAttempts=0;maxGrowthAttempts;constructor(e){if(super(),this.constructorParams=e,this.nodeWithPortPoints=e.nodeWithPortPoints,this.maxGrowthAttempts=e.maxGrowthAttempts??3,this.MAX_ITERATIONS=2e7*(e.effort??1)*(this.maxGrowthAttempts+1),Sft(this.nodeWithPortPoints)){if(!e.fallbackToInvalidGeometryOnFailure)return this.failed=!0,this.progress=1,void(this.error="GrowShrinkHighDensityIntraNodeSolver cannot route an impossible single-layer crossing");this.solvedRoutes=XXn(this.nodeWithPortPoints,e.traceWidth??.15,e.viaDiameter??.3),this.solved=!0,this.progress=1,this.stats={invalidGeometryFallback:!0,reason:"single-layer node has same-layer crossings"}}}getConstructorParams(){return this.constructorParams}createActiveSubSolver(){const{growShrinkSolutionValidator:e,...n}=this.constructorParams;var o,i;this.activeSubSolver=new Vz({...n,nodeWithPortPoints:(o=this.nodeWithPortPoints,i=this.scaleFactor,{...o,width:o.width*i,height:o.height*i,portPoints:o.portPoints.map(r=>Y7e(r,o.center,i)),portPointsInPairs:o.portPointsInPairs?.map(([r,s])=>[Y7e(r,o.center,i),Y7e(s,o.center,i)])})}),this.constructorParams.maxInnerIterationsPerGrowthAttempt&&(this.activeSubSolver.MAX_ITERATIONS=this.constructorParams.maxInnerIterationsPerGrowthAttempt)}acceptSolution(e){const n=this.scaleFactor===1?e.solvedRoutes:e.solvedRoutes.map(o=>((i,r,s)=>({...i,route:i.route.map(a=>zz(a,r,s)),vias:i.vias.map(a=>zz(a,r,s)),jumpers:i.jumpers?.map(a=>({...a,start:zz(a.start,r,s),end:zz(a.end,r,s)}))}))(o,this.nodeWithPortPoints.center,1/this.scaleFactor));return this.constructorParams.growShrinkSolutionValidator&&!this.constructorParams.growShrinkSolutionValidator(n)?(e.solved=!1,e.failed=!0,e.error="High-density scale solution rejected by validator",!1):(this.winningSolver=e,this.solvedRoutes=n,this.solved=!0,this.failed=!1,!0)}computeProgress(){return Math.min(.99,(this.growthAttempts+(this.activeSubSolver?.progress??0))/(this.maxGrowthAttempts+1))}_step(){if(this.activeSubSolver||this.createActiveSubSolver(),this.activeSubSolver.step(),this.activeSubSolver.solved&&this.acceptSolution(this.activeSubSolver))this.activeSubSolver=null;else if(this.activeSubSolver.failed){if(this.failedSolvers.push(this.activeSubSolver),this.error=this.activeSubSolver.error,this.activeSubSolver=null,this.growthAttempts>=this.maxGrowthAttempts)return this.constructorParams.fallbackToInvalidGeometryOnFailure?(this.solvedRoutes=Qft(this.nodeWithPortPoints,this.constructorParams.traceWidth??.15,this.constructorParams.viaDiameter??.3),this.solved=!0,this.failed=!1,this.progress=1,this.stats={...this.stats,invalidGeometryFallback:!0,reason:"growth attempts exhausted",lastError:this.error},void(this.error=null)):(this.failed=!0,void(this.error=`GrowShrinkHighDensityIntraNodeSolver failed after resizing to ${this.scaleFactor}x. Last error: ${this.error}`));this.growthAttempts++,this.scaleFactor*=2}}visualize(){const e=this.activeSubSolver?.visualize()??this.winningSolver?.visualize();return e||(this.solvedRoutes.length>0?{title:this.stats.invalidGeometryFallback?"Invalid same-layer crossing geometry":"Grow/shrink high density routes",lines:this.solvedRoutes.flatMap((n,o)=>n.route.slice(0,-1).map((i,r)=>({points:[i,n.route[r+1]],strokeColor:nae[o%nae.length],strokeWidth:n.traceThickness,layer:`z${i.z}`,label:vft(n.connectionName,n.rootConnectionName,[`z${i.z}`,this.stats.invalidGeometryFallback?"invalid fallback route":void 0].filter(Boolean))}))),points:this.nodeWithPortPoints.portPoints.map(n=>({x:n.x,y:n.y,color:nae[Math.max(0,this.solvedRoutes.findIndex(o=>o.connectionName===n.connectionName))%nae.length],label:vft(n.connectionName,n.rootConnectionName,[`z${n.z}`])})),rects:[{center:this.nodeWithPortPoints.center,width:this.nodeWithPortPoints.width,height:this.nodeWithPortPoints.height,fill:this.stats.invalidGeometryFallback?"rgba(245, 158, 11, 0.12)":"rgba(14, 165, 233, 0.08)",stroke:this.stats.invalidGeometryFallback?"rgba(217, 119, 6, 0.8)":"rgba(14, 165, 233, 0.55)",label:[this.nodeWithPortPoints.capacityMeshNodeId,this.stats.reason].filter(Boolean).join(`
`)}],circles:[]}:e??{lines:[],points:[],rects:[],circles:[]})}},wft=(t,e,n=[])=>[t,e?`rootConnectionName: ${e}`:void 0,...n].filter(Boolean).join(`
`),HD=class extends yr{getSolverName(){return"HighDensitySolver"}unsolvedNodePortPoints;routes;colorMap;defaultViaDiameter=.3;defaultTraceThickness=.15;viaDiameter;traceWidth;obstacleMargin;effort;obstacles;layerCount;useGrowShrinkHighDensityIntraNodeSolver;preserveTerminalPcbPortIds;growShrinkMaxInnerIterationsPerGrowthAttempt;growShrinkFallbackToInvalidGeometryOnFailure;growShrinkSolutionValidator;captureSearchDebug;failedSolvers;activeSubSolver=null;connMap;nodePfById;nodeSolveMetadataById;constructor({nodePortPoints:e,colorMap:n,connMap:o,viaDiameter:i,traceWidth:r,obstacleMargin:s,effort:a,nodePfById:A,obstacles:c,layerCount:l,useGrowShrinkHighDensityIntraNodeSolver:u,preserveTerminalPcbPortIds:g,growShrinkMaxInnerIterationsPerGrowthAttempt:h,growShrinkFallbackToInvalidGeometryOnFailure:d,growShrinkSolutionValidator:p,captureSearchDebug:m}){super(),this.unsolvedNodePortPoints=e,this.colorMap=n??{},this.connMap=o,this.routes=[],this.failedSolvers=[],this.effort=a??1,this.viaDiameter=i??this.defaultViaDiameter,this.traceWidth=r??this.defaultTraceThickness,this.obstacleMargin=s??.15,this.obstacles=c??[],this.layerCount=l??2,this.useGrowShrinkHighDensityIntraNodeSolver=u??!1,this.preserveTerminalPcbPortIds=g??!1,this.growShrinkMaxInnerIterationsPerGrowthAttempt=h,this.growShrinkFallbackToInvalidGeometryOnFailure=d??!1,this.growShrinkSolutionValidator=p,this.captureSearchDebug=m??!0,this.MAX_ITERATIONS=1e7*this.effort*(this.useGrowShrinkHighDensityIntraNodeSolver?4:1),this.nodePfById=A instanceof Map?new Map(A):new Map(Object.entries(A??{})),this.nodeSolveMetadataById=new Map,this.stats={solverNodeCount:{},difficultNodePfs:{},highDensityResizeCount:0}}getSolvedNodeSolverType(e){return e instanceof U7e&&e.winningSolver?this.getSolvedNodeSolverType(e.winningSolver):e instanceof Vz&&e.winningSolver?this.getConcreteSolverTypeName(e.winningSolver):this.getConcreteSolverTypeName(e)}recordNodeSolveMetadata(e,n){const o=e.nodeWithPortPoints,i=this.nodePfById.get(o.capacityMeshNodeId)??null;this.nodeSolveMetadataById.set(o.capacityMeshNodeId,{node:o,status:n,solverType:this.getSolvedNodeSolverType(e),iterations:e.iterations,routeCount:e.solvedRoutes.length,nodePf:i,error:e.error??void 0})}createNodeMarkerLabel(e,n){return["hd_node_marker",`node: ${e}`,`status: ${n.status}`,`solver: ${n.solverType}`,`iterations: ${n.iterations}`,`routes: ${n.routeCount}`,`nodePf: ${n.nodePf??"n/a"}`,`portPoints: ${n.node.portPoints.length}`,...n.error?[`error: ${n.error}`]:[]].join(`
`)}getConcreteSolverTypeName(e){if(e instanceof T7e){const n=this.getIntraNodeStrategyName(e.hyperParameters);return e.cacheHit?`${n} [cached]`:n}return e instanceof Wse?this.getIntraNodeStrategyName(e.hyperParameters):e.getSolverName()}getIntraNodeStrategyName(e){return e?.MULTI_HEAD_POLYLINE_SOLVER?"MultiHeadPolyLineIntraNodeSolver3":e?.SINGLE_LAYER_NO_DIFFERENT_ROOT_INTERSECTIONS?"SingleLayerNoDifferentRootIntersectionsIntraNodeSolver":e?.CLOSED_FORM_SINGLE_TRANSITION?"SingleTransitionIntraNodeSolver":e?.CLOSED_FORM_TWO_TRACE_SAME_LAYER?"TwoCrossingRoutesHighDensitySolver":e?.CLOSED_FORM_TWO_TRACE_TRANSITION_CROSSING?"SingleTransitionCrossingRouteSolver":e?.HIGH_DENSITY_A01?"HighDensitySolverA01":e?.HIGH_DENSITY_A03?"HighDensitySolverA03":"SingleHighDensityRouteSolver6_VertHorzLayer_FutureCost"}recordSolvedNodeStats(e,n){const o=this.getSolvedNodeSolverType(e),i=this.stats.solverNodeCount,r=this.stats.difficultNodePfs;i[o]=(i[o]??0)+1;const s=this.nodePfById.get(n.capacityMeshNodeId)??null;s!==null&&s>.05&&(r[o]||(r[o]=[]),r[o].push(s))}recordResizeStats(e){e instanceof U7e&&(this.stats.highDensityResizeCount=(this.stats.highDensityResizeCount??0)+e.growthAttempts)}getSolvedRoutesWithTerminalPcbPortIds(e){const n=e.nodeWithPortPoints.portPoints.filter(i=>i.pcb_port_id!==void 0);if(n.length===0)return e.solvedRoutes;const o=(i,r)=>{const s=n.filter(A=>A.connectionName===i.connectionName&&A.x===r.x&&A.y===r.y&&A.z===r.z);if(s.length>1)throw new Error(`HighDensitySolver found multiple PCB terminals at an endpoint of "${i.connectionName}"`);const a=s[0];if(a?.pcb_port_id)return a.pcb_port_id};return e.solvedRoutes.map(i=>({...i,startPcbPortId:i.route[0]?o(i,i.route[0]):void 0,endPcbPortId:i.route.length>1?o(i,i.route[i.route.length-1]):void 0}))}_step(){if(this.updateCacheStats(),this.activeSubSolver)return this.activeSubSolver.step(),this.activeSubSolver.solved?(this.routes.push(...this.preserveTerminalPcbPortIds?this.getSolvedRoutesWithTerminalPcbPortIds(this.activeSubSolver):this.activeSubSolver.solvedRoutes),this.recordNodeSolveMetadata(this.activeSubSolver,"solved"),this.recordSolvedNodeStats(this.activeSubSolver,this.activeSubSolver.nodeWithPortPoints),this.recordResizeStats(this.activeSubSolver),this.activeSubSolver=null):this.activeSubSolver.failed&&(this.recordNodeSolveMetadata(this.activeSubSolver,"failed"),this.recordResizeStats(this.activeSubSolver),this.failedSolvers.push(this.activeSubSolver),this.activeSubSolver=null),void this.updateCacheStats();if(this.unsolvedNodePortPoints.length===0)return this.failedSolvers.length>0?(this.solved=!1,this.failed=!0,this.error=`Failed to solve ${this.failedSolvers.length} nodes, ${this.failedSolvers.slice(0,5).map(n=>n.nodeWithPortPoints.capacityMeshNodeId)}. err0: ${this.failedSolvers[0].error}.`,void this.updateCacheStats()):(this.solved=!0,void this.updateCacheStats());const e={nodeWithPortPoints:this.unsolvedNodePortPoints.pop(),colorMap:this.colorMap,connMap:this.connMap,viaDiameter:this.viaDiameter,traceWidth:this.traceWidth,obstacleMargin:this.obstacleMargin,effort:this.effort,obstacles:this.obstacles,layerCount:this.layerCount,maxInnerIterationsPerGrowthAttempt:this.growShrinkMaxInnerIterationsPerGrowthAttempt,fallbackToInvalidGeometryOnFailure:this.growShrinkFallbackToInvalidGeometryOnFailure,growShrinkSolutionValidator:this.growShrinkSolutionValidator,captureSearchDebug:this.captureSearchDebug};this.activeSubSolver=this.useGrowShrinkHighDensityIntraNodeSolver?new U7e(e):new Vz(e),this.updateCacheStats()}updateCacheStats(){const e=tB();this.stats.intraNodeCacheHits=e.cacheHits,this.stats.intraNodeCacheMisses=e.cacheMisses}visualize(){let e={lines:[],points:[],rects:[],circles:[]};for(const n of this.routes){const o=Kse(n.route,n.connectionName,this.colorMap[n.connectionName]);for(const i of o)e.lines.push({points:i.points,label:wft(n.connectionName,n.rootConnectionName),strokeColor:i.z===0?i.color:Es(i.color,.5),layer:`z${i.z}`,strokeWidth:n.traceThickness,strokeDash:i.z!==0?[.1,.3]:void 0});for(const i of n.vias)e.circles.push({center:i,layer:"z0,1",radius:n.viaDiameter/2,fill:this.colorMap[n.connectionName],label:wft(n.connectionName,n.rootConnectionName,["via"])})}if(this.solved||this.failed)for(const[n,o]of this.nodeSolveMetadataById){const i=o.node.center.x-o.node.width/2,r=o.node.center.x+o.node.width/2,s=o.node.center.y-o.node.height/2,a=o.node.center.y+o.node.height/2,A=this.createNodeMarkerLabel(n,o),c=o.status==="solved"?"blue":"red";if(e.lines.push({points:[{x:i,y:s},{x:r,y:s}],layer:"hd_node_boundaries",strokeColor:c,strokeDash:"6, 4",strokeWidth:.03,label:A},{points:[{x:r,y:s},{x:r,y:a}],layer:"hd_node_boundaries",strokeColor:c,strokeDash:"6, 4",strokeWidth:.03,label:A},{points:[{x:r,y:a},{x:i,y:a}],layer:"hd_node_boundaries",strokeColor:c,strokeDash:"6, 4",strokeWidth:.03,label:A},{points:[{x:i,y:a},{x:i,y:s}],layer:"hd_node_boundaries",strokeColor:c,strokeDash:"6, 4",strokeWidth:.03,label:A}),o.status==="solved")e.points.push({x:o.node.center.x,y:o.node.center.y,color:c,layer:"hd_node_markers",label:A});else{e.lines.push({points:[{x:0,y:0},{x:o.node.center.x,y:o.node.center.y}],layer:"hd_failed_node_guides",strokeColor:"red",strokeDash:"8, 6",strokeWidth:.05,label:A});const l=Math.max(.1*o.node.width,.12),u=Math.max(.1*o.node.height,.12);e.rects.push({center:o.node.center,layer:"hd_node_markers",width:l,height:u,fill:"red",label:A})}}return this.activeSubSolver&&(e=Il(e,this.activeSubSolver.visualize())),e}};function Pft(t,e){const n=[],o=e.filter(r=>r._containsTarget),i=new Map;for(const r of t.connections){const s=[];for(const a of r.pointsToConnect){let A=e[0],c=Number.MAX_VALUE;for(const l of o){const u=Math.sqrt((l.center.x-a.x)**2+(l.center.y-a.y)**2);u<c&&(c=u,A=l)}s.push(A)}if(s.length<2)throw new Error(`Not enough nodes for connection "${r.name}", only ${s.length} found`);i.set(r.name,s.map(a=>a.capacityMeshNodeId)),n.push({connection:r,nodeIds:[s[0].capacityMeshNodeId,s[s.length-1].capacityMeshNodeId],straightLineDistance:no(s[0].center,s[s.length-1].center)})}return{unshuffledConnectionsWithResults:n,connectionNameToGoalNodeIds:i}}function Mft(t,e){const n=new Map(e.map(u=>[u.capacityMeshNodeId,u])),o=e.map(u=>(u.width+u.height)/2).filter(u=>Number.isFinite(u)&&u>0),i=o.length>0?o.reduce((u,g)=>u+g,0)/o.length:1,r=e.filter(u=>u._offBoardConnectionId),s=new Map,a=new Map,A=new Map;for(const u of e)a.set(u.capacityMeshNodeId,[]),A.set(u.capacityMeshNodeId,[]);for(const u of e)for(const g of u.portPoints){s.set(g.portPointId,g);for(const h of g.connectionNodeIds){const d=a.get(h);d&&!d.some(p=>p.portPointId===g.portPointId)&&d.push(g)}}const{unshuffledConnectionsWithResults:c,connectionNameToGoalNodeIds:l}=Pft(t,e);return{nodeMap:n,avgNodePitch:i,offBoardNodes:r,portPointMap:s,nodePortPointsMap:a,nodeAssignedPortPoints:A,unshuffledConnectionsWithResults:c,connectionNameToGoalNodeIds:l}}var l7=(t,e=1,n={})=>{const o=n.viaDiameter??.3,i="width"in t?t.width:t,r=n.obstacleMargin??.2,s="height"in t&&typeof t.height=="number"?t.height:i;if(!Number.isFinite(i)||!Number.isFinite(s)||i<=0||s<=0)return 0;const a=Math.min(i,s)/(o+r),A=(Math.sqrt(i*s)*Math.min(1.2,Math.max(.85,a**.05))/(o/2+r)/2)**1.1*e;return Number.isFinite(A)?t.availableZ?.length===1&&A>1?1:A:0},$Q=(t,e=.5,n=16)=>{let o=0,i=t;for(;o<n&&!(l7({width:i})<=e);)i/=2,o++;return Math.max(1,o)},wy=(t,e,n,o)=>{if(t?._containsTarget)return 0;if((t.availableZ?.length??2)===1&&(e>0||n>0||o>0))return 1;const i=((.82*e+.41*n+.2*o)/2)**1.1;if(!Number.isFinite(i))return 1;const r=l7(t);if(!Number.isFinite(r)||r<=0)return i>0?1:0;const s=i/r;if(Number.isNaN(s))throw new Error("calculateNodeProbabilityOfFailure returned NaN");return Number.isFinite(s)?s:i>0?1:0};function Dft(t,e,n){let o=0;const i=.99999;for(const r of t){const s=e.get(r.capacityMeshNodeId);if(!s||s._containsTarget)continue;const a=Wm(r),A=Math.min(wy(s,a.numSameLayerCrossings,a.numEntryExitLayerChanges,a.numTransitionPairCrossings),i);o+=Math.log(1-A)}return o}function Nft(t,e){if(e._containsTarget)return 0;const n=Wm(t);return wy(e,n.numSameLayerCrossings,n.numEntryExitLayerChanges,n.numTransitionPairCrossings)}function Rft(t,e,n,o,i){const r=n-e,s=i-o,a=1e-6;if(Math.abs(t.y-i)<a)return t.x-e;if(Math.abs(t.x-n)<a)return r+(i-t.y);if(Math.abs(t.y-o)<a)return r+s+(n-t.x);if(Math.abs(t.x-e)<a)return 2*r+s+(t.y-o);const A=Math.abs(t.y-i),c=Math.abs(t.x-n),l=Math.abs(t.y-o),u=Math.abs(t.x-e),g=Math.min(A,c,l,u);return g===A?Math.max(0,Math.min(r,t.x-e)):g===c?r+Math.max(0,Math.min(s,i-t.y)):g===l?r+s+Math.max(0,Math.min(r,n-t.x)):2*r+s+Math.max(0,Math.min(s,t.y-o))}var ZXn=1.6*3.2,Jz=(t,e)=>{const n=Math.ceil(e/2),o=Math.min(t.width,t.height),i=Math.max(t.width,t.height),r=(Math.floor(o/1.6)+.1)*(Math.floor(i/3.2)+.1)/ZXn;return Math.min(1,n/r)};function K7e(t,e,n,o){const i=e.x-n/2,r=e.x+n/2,s=e.y-o/2,a=e.y+o/2,A=Math.abs(t.y-a),c=Math.abs(t.x-r),l=Math.abs(t.y-s),u=Math.abs(t.x-i),g=Math.min(A,c,l,u);return g>.001?"interior":g===A?"top":g===c?"right":g===l?"bottom":"left"}function Tft(t,e,n,o,i){const r=K7e(t,n,o,i),s=K7e(e,n,o,i);return r!=="interior"&&r===s}function kft(t,e,n,o,i){const r=K7e(t,n,o,i);let s;if(r==="top"||r==="bottom"){const c=o;s=Math.abs(e.x-t.x)/c}else{const c=i;s=Math.abs(e.y-t.y)/c}s=Math.min(1,Math.max(0,s));const a=(t.x+e.x)/2,A=(t.y+e.y)/2;return{x:a+(n.x-a)*s,y:A+(n.y-A)*s}}function oae(t){return"computeNodePf"in t&&typeof t.computeNodePf=="function"}function V7e(t){const e={lines:[],points:[],rects:[],circles:[]};for(const o of t.inputNodes){let i=0,r=0,s={numSameLayerCrossings:0,numEntryExitLayerChanges:0,numTransitionPairCrossings:0},a=0;if(oae(t)){i=t.computeNodePf(o),r=t.nodeMemoryPfMap.get(o.capacityMeshNodeId)??0;const u=t.buildNodeWithPortPointsForCrossing(o);s=Wm(u);const g=new Set,h=t.nodeAssignedPortPoints.get(o.capacityMeshNodeId)??[];for(const d of h)d.connectionName&&g.add(d.connectionName);a=g.size}else{i=t.nodePfMap.get(o.capacityMeshNodeId)??0;const u=t.nodeAssignedPortPoints.get(o.capacityMeshNodeId)??[],g={capacityMeshNodeId:o.capacityMeshNodeId,center:o.center,width:o.width,height:o.height,portPoints:u,availableZ:o.availableZ};s=Wm(g);const h=new Set;for(const d of u)d.connectionName&&h.add(d.connectionName);a=h.size}const A=Math.min(255,Math.floor(512*i)),c=Math.max(0,255-Math.floor(512*i));let l=`rgba(${A}, ${c}, ${c}, ${i<.001?"0.1":"0.3"})`;o._containsObstacle&&(l="rgba(255, 0, 0, 0.3)"),o._offBoardConnectedCapacityMeshNodeIds?.length&&(l="rgba(255, 165, 0, 0.3)"),e.rects.push({center:o.center,width:o.width-.2,height:o.height-.2,layer:`z${o.availableZ.join(",")}`,fill:l,label:`${o.capacityMeshNodeId}
pf: ${i.toFixed(3)}, memPf: ${r.toFixed(3)}
C#: ${a}
xSame: ${s.numSameLayerCrossings}, xLC: ${s.numEntryExitLayerChanges}, xTransition: ${s.numTransitionPairCrossings}
obCmid: ${o._offBoardConnectedCapacityMeshNodeIds?.join(",")}
obs: ${o._containsObstacle?"yes":"no"}`})}if(oae(t))for(const[o,i]of t.portPointMap){const r=t.assignedPortPoints.get(o),s=r?t.colorMap[r.connectionName]??"blue":"rgba(150, 150, 150, 0.5)";e.circles.push({center:{x:i.x,y:i.y},radius:.05,fill:s,layer:`z${i.z}`,label:[o,`conn: ${r?.connectionName}`,`cd: ${i.distToCentermostPortOnZ}`,`connects: ${i.connectionNodeIds.join(",")}`,`rootConn: ${r?.rootConnectionName}`].filter(Boolean).join(`
`)})}const n=oae(t)?t.connectionsWithResults:t.connectionResults;for(const o of n){if(!o.path)continue;const i=o.connection,r=t.colorMap[i.name]??"blue",s=[];for(const a of o.path)s.push({x:a.point.x,y:a.point.y,z:a.z,nodeId:a.currentNodeId});for(let a=0;a<s.length-1;a++){const A=s[a],c=s[a+1],l=A.z===c.z,u=A.z;let g;g=l?u===0?void 0:"10 5":"3 3 10";const h=A.nodeId?t.nodeMap.get(A.nodeId):null;if(h&&Tft(A,c,h.center,h.width,h.height)){const d=kft(A,c,h.center,h.width,h.height);e.lines.push({points:[{x:A.x,y:A.y},{x:d.x,y:d.y}],strokeColor:r,strokeDash:g}),e.lines.push({points:[{x:d.x,y:d.y},{x:c.x,y:c.y}],strokeColor:r,strokeDash:g})}else e.lines.push({points:[{x:A.x,y:A.y},{x:c.x,y:c.y}],strokeColor:r,strokeDash:g})}}if(oae(t)&&!t.solved&&t.candidates&&t.candidates.length>0){const o=t.currentConnection,i=o?t.colorMap[o.connection.name]??"blue":"blue";if(o){const[s,a]=o.nodeIds,A=t.nodeMap.get(s),c=t.nodeMap.get(a),l=o.connection.pointsToConnect[0],u=o.connection.pointsToConnect[o.connection.pointsToConnect.length-1];if(A&&c){const g=l?{x:l.x,y:l.y}:A.center,h=u?{x:u.x,y:u.y}:c.center;e.lines.push({points:[g,h],strokeColor:Es(i,.5),strokeDash:"5 5"}),e.points.push({x:g.x,y:g.y,color:i,label:[`Start: ${o.connection.name}`,`${o.connection.__rootConnectionNames?.[0]}`].join(`
`)}),e.points.push({x:h.x,y:h.y,color:i,label:[`End: ${o.connection.name}`,`${o.connection.__rootConnectionNames?.[0]}`].join(`
`)}),e.circles.push({center:h,radius:.08,stroke:i,label:`Goal: ${o.connection.name}`})}}const r=[...t.candidates].sort((s,a)=>s.f-a.f).slice(0,1);for(const s of r){const a=[];let A=s;for(;A;)a.unshift({x:A.point.x,y:A.point.y,z:A.z,lastMoveWasOffBoard:A.lastMoveWasOffBoard,nodeId:A.currentNodeId}),A=A.prevCandidate;for(let c=0;c<a.length-1;c++){const l=a[c],u=a[c+1],g=l.z===u.z,h=l.z;let d;d=u.lastMoveWasOffBoard?"2 2":g?h===0?void 0:"10 5":"3 3 10";const p=l.nodeId?t.nodeMap.get(l.nodeId):null,m=.02*l.z;if(p&&Tft(l,u,p.center,p.width,p.height)){const _=kft(l,u,p.center,p.width,p.height);e.lines.push({points:[{x:l.x+m,y:l.y+m},{x:_.x+m,y:_.y+m}],strokeColor:Es(i,.25),strokeDash:d}),e.lines.push({points:[{x:_.x+m,y:_.y+m},{x:u.x+m,y:u.y+m}],strokeColor:Es(i,.25),strokeDash:d})}else e.lines.push({points:[{x:l.x+m,y:l.y+m},{x:u.x+m,y:u.y+m}],strokeColor:Es(i,.25),strokeDash:d})}if(a.length>=1){const c=a[a.length-1];let l=0,u=0,g=0,h=0,d=0,p=0;const m=t.nodeMap.get(s.prevCandidate?.currentNodeId);if(m&&s.prevCandidate&&s.portPoint&&o){const S=o.connection.name,Q={x:s.prevCandidate.point.x,y:s.prevCandidate.point.y,z:s.prevCandidate.z,connectionName:S},w={x:s.portPoint.x,y:s.portPoint.y,z:s.portPoint.z,connectionName:S},M=t.buildNodeWithPortPointsForCrossing(m,[Q,w]),k=sft(M);g=k.numSameLayerCrossings,h=k.numTransitionPairCrossings,d=k.numEntryExitLayerChanges;const R=t.capacityMeshNodeMap.get(m.capacityMeshNodeId);R&&(u=t.JUMPER_PF_FN_ENABLED&&m.availableZ.length===1?Jz(R,g):wy(R,g,d,h),l=u**2*t.NODE_PF_FACTOR),p=s.prevCandidate.g>0?s.g-s.prevCandidate.g:s.g}if(!o)continue;const[_,f]=o.nodeIds,I=t.nodeMap.get(f),C=I?Math.sqrt((c.x-I.center.x)**2+(c.y-I.center.y)**2):0,y=t.avgNodePitch>0?C/t.avgNodePitch:0,x=y*t.BASE_CANDIDATE_COST,E=t.nodeMemoryPfMap.get(s.currentNodeId)??0,B=-Math.log(1-E)*t.MEMORY_PF_FACTOR;e.circles.push({center:c,radius:.03,fill:Es(i,.25),layer:`z${s.z}`,label:[`f: ${s.f.toFixed(2)}`,`g: ${s.g.toFixed(2)} (nodeDelta: ${p.toFixed(2)})`,`h: ${s.h.toFixed(2)}`,`  dist: ${C.toFixed(2)}`,`  estHops: ${y.toFixed(1)}`,`  estStepCost: ${x.toFixed(2)}`,`  memRiskCost: ${B.toFixed(2)}`,`z: ${s.z}`,`node: ${s.currentNodeId}`,`Cost(Pf): ${l.toFixed(3)}`,`Pf: ${u.toFixed(3)}`,`xSame: ${g}, xTrans: ${h}, xLC: ${d}`,`routeOffBoard=${t.currentConnectionShouldRouteOffBoard}`,`offBoardTouched=${s.hasTouchedOffBoardNode??!1}`,`lastMoveWasOffBoard=${s.lastMoveWasOffBoard??!1}`].join(`
`)})}}}return e}function Fft(t,e,n){let o=0;const i=.99999;for(const r of t){const s=e.get(r.capacityMeshNodeId);if(!s||s._containsTarget)continue;const a=Wm(r),A=Math.min(Jz(s,a.numSameLayerCrossings),i);o+=Math.log(1-A)}return o}var eZn=class extends yr{constructor(e){super(),this.input=e;const{simpleRouteJson:n,capacityMeshNodes:o,inputNodes:i,colorMap:r,nodeMemoryPfMap:s,hyperParameters:a,precomputedInitialParams:A,fixedRoutes:c}=e;if(this.input=structuredClone(e),this.MAX_ITERATIONS=1e8,this.simpleRouteJson=n,this.inputNodes=i,this.colorMap=r??{},this.capacityMeshNodeMap=new Map(o.map(l=>[l.capacityMeshNodeId,l])),this.nodeMemoryPfMap=s??new Map,this.hyperParameters=a??{},A){this.nodeMap=A.nodeMap,this.avgNodePitch=A.avgNodePitch,this.offBoardNodes=A.offBoardNodes,this.portPointMap=A.portPointMap,this.nodePortPointsMap=A.nodePortPointsMap,this.connectionNameToGoalNodeIds=A.connectionNameToGoalNodeIds;const{nodeAssignedPortPoints:l}=(function(u){const g=new Map;for(const[h,d]of u.nodeAssignedPortPoints)g.set(h,[...d]);return{nodeAssignedPortPoints:g}})(A);this.nodeAssignedPortPoints=l,this.connectionsWithResults=D5(structuredClone(A.unshuffledConnectionsWithResults),this.hyperParameters.SHUFFLE_SEED??0)}else{this.nodeMap=new Map(i.map(h=>[h.capacityMeshNodeId,h]));const l=i.map(h=>(h.width+h.height)/2).filter(h=>Number.isFinite(h)&&h>0);this.avgNodePitch=l.length>0?l.reduce((h,d)=>h+d,0)/l.length:1,this.offBoardNodes=i.filter(h=>h._offBoardConnectionId),this.portPointMap=new Map,this.nodePortPointsMap=new Map;for(const h of i)this.nodePortPointsMap.set(h.capacityMeshNodeId,[]),this.nodeAssignedPortPoints.set(h.capacityMeshNodeId,[]);for(const h of i)for(const d of h.portPoints){this.portPointMap.set(d.portPointId,d);for(const p of d.connectionNodeIds){const m=this.nodePortPointsMap.get(p);m&&!m.some(_=>_.portPointId===d.portPointId)&&m.push(d)}}const{connectionsWithResults:u,connectionNameToGoalNodeIds:g}=this.getConnectionsWithNodes();this.connectionsWithResults=u,this.connectionNameToGoalNodeIds=g}if(c&&c.length>0){for(const l of c)if(this.connectionsWithResults.push(l),l.portPoints)for(const u of l.portPoints)u.portPointId&&this.assignedPortPoints.set(u.portPointId,{connectionName:u.connectionName,rootConnectionName:u.rootConnectionName})}for(const l of this.connectionsWithResults)l.path?this.processedConnectionQueue.push(l):this.unprocessedConnectionQueue.push(l);this.totalConnectionCount=this.connectionsWithResults.length}input;getSolverName(){return"PortPointPathingSolver"}hyperParameters;simpleRouteJson;inputNodes;nodeMap;nodePortPointsMap;portPointMap;connectionsWithResults=[];failedConnection=null;assignedPortPoints=new Map;nodeAssignedPortPoints=new Map;PORT_POINT_REUSE_FACTOR=1e3;BASE_COST_FOR_NOT_GOING_OFF_BOARD=100;get NODE_PF_FACTOR(){return this.hyperParameters.NODE_PF_FACTOR??50}get RANDOM_WALK_DISTANCE(){return this.hyperParameters.RANDOM_WALK_DISTANCE??0}get MEMORY_PF_FACTOR(){return this.hyperParameters.MEMORY_PF_FACTOR??0}get CENTER_OFFSET_FOCUS_SHIFT(){return this.hyperParameters.CENTER_OFFSET_FOCUS_SHIFT??0}get RANDOM_COST_MAGNITUDE(){return this.hyperParameters.RANDOM_COST_MAGNITUDE??0}get BASE_CANDIDATE_COST(){return this.hyperParameters.BASE_CANDIDATE_COST??0}get NODE_PF_MAX_PENALTY(){return this.hyperParameters.NODE_PF_MAX_PENALTY??1e4}get FORCE_CENTER_FIRST(){return this.hyperParameters.FORCE_CENTER_FIRST??!0}get FORCE_OFF_BOARD_FREQUENCY(){return this.offBoardNodes.length===0?0:this.hyperParameters.FORCE_OFF_BOARD_FREQUENCY??0}get FORCE_OFF_BOARD_SEED(){return this.hyperParameters.FORCE_OFF_BOARD_SEED??0}get NODE_MAX_PF(){return Math.min(.99999,1-Math.exp(-this.NODE_PF_MAX_PENALTY))}get CENTER_OFFSET_DIST_PENALTY_FACTOR(){return this.hyperParameters.CENTER_OFFSET_DIST_PENALTY_FACTOR??0}get STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR(){return this.hyperParameters.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR??0}colorMap;get GREEDY_MULTIPLIER(){return this.hyperParameters.GREEDY_MULTIPLIER??1.3}MAX_CANDIDATES_IN_MEMORY=5e3;get MAX_ITERATIONS_PER_PATH(){return this.hyperParameters.MAX_ITERATIONS_PER_PATH??1e4}ITERATIONS_PER_MM_FOR_PATH=30;BASE_ITERATIONS_PER_PATH=1e4;get RIPPING_ENABLED(){return this.hyperParameters.RIPPING_ENABLED??!1}get RIPPING_PF_THRESHOLD(){const e=this.hyperParameters.START_RIPPING_PF_THRESHOLD,n=this.hyperParameters.END_RIPPING_PF_THRESHOLD;if(e!==void 0&&n!==void 0){const o=this.MAX_RIPS;return e+(o>0?this.totalRipCount/o:0)*(n-e)}return this.hyperParameters.RIPPING_PF_THRESHOLD??.3}get MAX_RIPS(){return this.hyperParameters.MAX_RIPS??100}get RANDOM_RIP_FRACTION(){return this.hyperParameters.RANDOM_RIP_FRACTION??0}get JUMPER_PF_FN_ENABLED(){return this.hyperParameters.JUMPER_PF_FN_ENABLED??!1}jumpersPerMmSquared=.1;testedRipConnections=new Map;totalRipCount=0;get MIN_ALLOWED_BOARD_SCORE(){return this.hyperParameters.MIN_ALLOWED_BOARD_SCORE??-1e4}nodeMemoryPfMap;unprocessedConnectionQueue=[];processedConnectionQueue=[];currentConnection=null;totalConnectionCount=0;currentPathIterations=0;candidates;visitedPortPoints;connectionNameToGoalNodeIds;capacityMeshNodeMap;avgNodePitch;currentConnectionShouldRouteOffBoard=!1;activeCandidateStraightLineDistance;offBoardNodes=[];baseNodeCostCache=new Map;getConstructorParams(){return this.input}clearCostCaches(){this.baseNodeCostCache.clear()}clampPf(e){return Number.isFinite(e)?Math.min(Math.max(e,0),.999999):.999999}pfToFailureCost(e){const n=this.clampPf(e);return n>=this.NODE_MAX_PF?this.NODE_PF_MAX_PENALTY:-Math.log(1-n)}getBaseNodeFailureCost(e){const n=this.baseNodeCostCache.get(e);if(n!=null)return n;const o=this.nodeMap.get(e);if(!o)return 0;const i=this.computeNodePf(o),r=this.pfToFailureCost(i);return this.baseNodeCostCache.set(e,r),r}computeBoardScore(){const e=this.getNodesWithPortPoints();return this.JUMPER_PF_FN_ENABLED?Fft(e,this.capacityMeshNodeMap):Dft(e,this.capacityMeshNodeMap)}getMaxIterationsForCurrentPath(){const e=this.activeCandidateStraightLineDistance??0;return Math.min(this.BASE_ITERATIONS_PER_PATH+this.ITERATIONS_PER_MM_FOR_PATH*e,this.MAX_ITERATIONS_PER_PATH)}getNodeDeltaFailureCostForSegment(e,n,o){const i=this.nodeMap.get(e);if(!i)return 0;const r=this.getBaseNodeFailureCost(e),s=this.computeNodePf(i,[n,o]),a=this.pfToFailureCost(s),A=Math.max(0,a-r);return s>=this.NODE_MAX_PF?this.NODE_PF_MAX_PENALTY:A*this.NODE_PF_FACTOR}getConnectionsWithNodes(){const{unshuffledConnectionsWithResults:e,connectionNameToGoalNodeIds:n}=Pft(this.simpleRouteJson,this.inputNodes);return{connectionsWithResults:D5(e,this.hyperParameters.SHUFFLE_SEED??0),connectionNameToGoalNodeIds:n}}buildNodeWithPortPointsForCrossing(e,n){const o=this.nodeAssignedPortPoints.get(e.capacityMeshNodeId)??[],i=n?[...o,...n]:o;return{capacityMeshNodeId:e.capacityMeshNodeId,center:e.center,width:e.width,height:e.height,portPoints:i,availableZ:e.availableZ}}computeNodePf(e,n){if(e._containsTarget)return 0;const o=this.buildNodeWithPortPointsForCrossing(e,n),i=Wm(o);return this.JUMPER_PF_FN_ENABLED&&e.availableZ.length===1?Jz(this.capacityMeshNodeMap.get(e.capacityMeshNodeId),i.numSameLayerCrossings):wy(this.capacityMeshNodeMap.get(e.capacityMeshNodeId),i.numSameLayerCrossings,i.numEntryExitLayerChanges,i.numTransitionPairCrossings)}getPortPointReusePenalty(e,n){const o=this.assignedPortPoints.get(e);return o?n===o.rootConnectionName?0:this.PORT_POINT_REUSE_FACTOR:0}getOtherNodeId(e,n){const[o,i]=e.connectionNodeIds;return o===n?i:i===n?o:null}computeG(e,n,o,i,r){const s=e.currentNodeId,a=e.point,A={x:a.x,y:a.y,z:e.z,connectionName:i,rootConnectionName:r},c={x:n.x,y:n.y,z:n.z,connectionName:i,rootConnectionName:r},l=this.getNodeDeltaFailureCostForSegment(s,A,c);return e.g+l}computeGToEndTarget(e,n,o,i){const r=e.currentNodeId,s={x:e.point.x,y:e.point.y,z:e.z,connectionName:o,rootConnectionName:i},a={x:n.x,y:n.y,z:e.z,connectionName:o,rootConnectionName:i},A=this.getNodeDeltaFailureCostForSegment(r,s,a);return e.g+A}computeDistanceToNearestOffBoardNode(e){if(this.offBoardNodes.length===0)return 1/0;let n=1/0;for(const o of this.offBoardNodes){const i=no(e,o.center);i<n&&(n=i)}return n}computeH(e,n,o,i,r,s){if(this.RANDOM_WALK_DISTANCE>0&&r<this.RANDOM_WALK_DISTANCE)return 0;if(this.currentConnectionShouldRouteOffBoard&&!s)return this.BASE_COST_FOR_NOT_GOING_OFF_BOARD+this.computeDistanceToNearestOffBoardNode(e);const a=this.nodeMap.get(o);if(!a)return 0;const A=no(e,a.center),c=this.avgNodePitch>0?A/this.avgNodePitch:0,l=this.clampPf(this.nodeMemoryPfMap.get(n)??0),u=this.pfToFailureCost(l)*this.MEMORY_PF_FACTOR,g=c*this.BASE_CANDIDATE_COST,h=this.CENTER_OFFSET_DIST_PENALTY_FACTOR*e.distToCentermostPortOnZ**2;let d=0;if(this.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR>0&&this.currentConnection){const p=wc(e,this.currentConnection.connection.pointsToConnect[0],this.currentConnection.connection.pointsToConnect[1]);d=this.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR*p}return A+g+u+h+d}getVisitedPortPointKey(e,n){return this.currentConnectionShouldRouteOffBoard&&n?`${e}:touched_off_board`:e}getAvailableExitPortPoints(e,n){const o=this.currentConnection?.connection.__rootConnectionNames?.[0],i=this.nodePortPointsMap.get(e)??[],r=[];for(const s of i){const a=this.getVisitedPortPointKey(s.portPointId,n);if(this.visitedPortPoints?.has(a))continue;const A=this.assignedPortPoints.get(s.portPointId);A&&A?.rootConnectionName!==o||r.push(s)}return r}getAvailableExitPortPointsWithOmissions(e,n,o){const i=this.nodePortPointsMap.get(e)??[],r=this.currentConnection?.connection.__rootConnectionNames?.[0],s=new Map;for(const A of i){const c=this.getVisitedPortPointKey(A.portPointId,o);if(this.visitedPortPoints?.has(c))continue;const l=this.getOtherNodeId(A,e);if(!l)continue;this.nodeMap.get(l);const u=`${l}|${A.z}`,g=s.get(u)??[];g.push(A),s.set(u,g)}const a=[];for(const[,A]of s){A.sort((p,m)=>p.distToCentermostPortOnZ-m.distToCentermostPortOnZ);const c=A[0];if(!c)continue;const l=this.assignedPortPoints.get(c.portPointId),u=l&&l.rootConnectionName===r;if(!l||u){a.push(c);continue}const g=[...A].sort((p,m)=>p.x!==m.x?p.x-m.x:p.y-m.y),h=[];let d=[];for(const p of g){const m=this.assignedPortPoints.get(p.portPointId);!m||m.rootConnectionName===r?d.push(p):d.length>0&&(h.push(d),d=[])}d.length>0&&h.push(d);for(const p of h){const m=Math.floor(p.length/2);a.push(p[m])}}return a}getAvailableExitPortPointsForOffboardConnection(e,n){const o=this.nodeMap.get(e);if(!o)return[];const i=this.currentConnection?.connection.__rootConnectionNames?.[0],r=[];for(const s of o?._offBoardConnectedCapacityMeshNodeIds??[]){if(s===e||!this.nodeMap.get(s))continue;const a=this.nodePortPointsMap.get(s)??[];for(const A of a){const c=this.getVisitedPortPointKey(A.portPointId,n);if(this.visitedPortPoints?.has(c))continue;const l=this.assignedPortPoints.get(A.portPointId);l&&l.rootConnectionName!==i||r.push({...A,throughNodeId:s})}}return r}canTravelThroughObstacle(e,n,o){return this.connectionNameToGoalNodeIds.get(n)?.includes(e.capacityMeshNodeId)||!!e._offBoardConnectionId}isAtEndGoal(e,n){return e===n}getBacktrackedPath(e){const n=[];let o=e;for(;o;){if(o.lastMoveWasOffBoard&&o.throughNodeId){const i=this.nodeMap.get(o.throughNodeId),r=o.prevCandidate?this.nodeMap.get(o.prevCandidate.currentNodeId):null;n.push(o),i&&n.push({prevCandidate:null,portPoint:null,currentNodeId:o.throughNodeId,point:i.center,z:o.z,f:0,g:0,h:0,distanceTraveled:0}),r&&r._offBoardConnectionId&&n.push({prevCandidate:null,portPoint:null,currentNodeId:o.prevCandidate.currentNodeId,point:r.center,z:o.z,f:0,g:0,h:0,distanceTraveled:0})}else n.push(o);o=o.prevCandidate}return n.reverse()}assignPortPointsForPath(e,n,o){const i=[];for(let A=0;A<e.length;A++){const c=e[A];if(!c.portPoint){const g=A===0,h=A===e.length-1;if(!g&&!h){const d={x:c.point.x,y:c.point.y,z:c.z,connectionName:n,rootConnectionName:o};i.push(d);const p=this.nodeAssignedPortPoints.get(c.currentNodeId)??[];p.push(d),this.nodeAssignedPortPoints.set(c.currentNodeId,p)}continue}const l=c.portPoint;this.assignedPortPoints.set(l.portPointId,{connectionName:n,rootConnectionName:o});const u={portPointId:l.portPointId,x:l.x,y:l.y,z:l.z,connectionName:n,rootConnectionName:o,prevPortPointId:l.prevPortPointId,nextPortPointId:l.nextPortPointId};i.push(u);for(const g of l.connectionNodeIds){const h=this.nodeAssignedPortPoints.get(g)??[];h.push(u),this.nodeAssignedPortPoints.set(g,h)}}const r=i.map(A=>A.portPointId).filter(A=>!!A);let s=0;for(const A of i)A.portPointId&&(A.prevPortPointId=r[s-1],A.nextPortPointId=r[s+1],s+=1);const a=Array.from(new Set(e.map(A=>A.currentNodeId)));for(const A of a){const c=this.nodeMap.get(A);if(c&&c._offBoardConnectionId)for(const l of c?._offBoardConnectedCapacityMeshNodeIds??[]){const u=this.nodePortPointsMap.get(l)??[];for(const g of u)this.assignedPortPoints.set(g.portPointId,{connectionName:n,rootConnectionName:o})}}return i}addTargetPointsToNodes(e,n){const o=e[0],i=e[e.length-1],r=n.pointsToConnect[0],s=n.pointsToConnect[n.pointsToConnect.length-1];if(o&&r){const a=this.nodeAssignedPortPoints.get(o.currentNodeId)??[];a.push({x:r.x,y:r.y,z:o.z,connectionName:n.name,rootConnectionName:n.__rootConnectionNames?.[0]}),this.nodeAssignedPortPoints.set(o.currentNodeId,a)}if(i&&s){const a=this.nodeAssignedPortPoints.get(i.currentNodeId)??[];a.push({x:s.x,y:s.y,z:i.z,connectionName:n.name,rootConnectionName:n.__rootConnectionNames?.[0]}),this.nodeAssignedPortPoints.set(i.currentNodeId,a)}}isPortPointInPathChain(e,n){let o=e;for(;o;){if(o.portPoint?.portPointId===n)return!0;o=o.prevCandidate}return!1}isNodeInPathChain(e,n){let o=e;for(;o;){if(o.currentNodeId===n)return!0;o=o.prevCandidate}return!1}_step(){if(this.currentConnection||(this.currentConnection=this.unprocessedConnectionQueue.shift()??null),!this.currentConnection){const h=this.computeBoardScore();return this.stats={boardScore:h,totalRipCount:this.totalRipCount},h<this.MIN_ALLOWED_BOARD_SCORE?(this.failedConnection=null,this.failed=!0,void(this.error=`Board score ${h.toFixed(2)} is less than MIN_ALLOWED_BOARD_SCORE ${this.MIN_ALLOWED_BOARD_SCORE.toFixed(2)}`)):void(this.solved=!0)}const e=this.currentConnection;this.activeCandidateStraightLineDistance=e.straightLineDistance,this.currentPathIterations++;const n=this.getMaxIterationsForCurrentPath();if(this.currentPathIterations>n)return this.failedConnection=e,this.processedConnectionQueue.push(e),this.currentConnection=null,this.candidates=null,this.visitedPortPoints=null,this.currentPathIterations=0,this.failed=!0,void(this.error=`Exceeded max iterations for path (${n}) on connection ${e.connection.name}`);const[o,i]=e.nodeIds,r=this.nodeMap.get(o),s=this.nodeMap.get(i);if(!r||!s)return this.processedConnectionQueue.push(e),this.currentConnection=null,void(this.currentPathIterations=0);const a=e.connection.name,A=e.connection.__rootConnectionNames?.[0],c=e.connection.pointsToConnect[0];if(!this.candidates){if(this.clearCostCaches(),this.FORCE_OFF_BOARD_FREQUENCY>0){const h=M7e(17*(this.hyperParameters.SHUFFLE_SEED??0)+this.FORCE_OFF_BOARD_SEED+this.processedConnectionQueue.length);this.currentConnectionShouldRouteOffBoard=h()<this.FORCE_OFF_BOARD_FREQUENCY}else this.currentConnectionShouldRouteOffBoard=!1;this.candidates=[],this.visitedPortPoints=new Set;for(const h of r.availableZ){const d=c?{x:c.x,y:c.y}:r.center,p={portPointId:`start:${o}:${h}`,x:d.x,y:d.y,z:h,connectionNodeIds:[o,o],distToCentermostPortOnZ:0},m=this.computeH(p,o,i,h,0,!1),_=0+m*this.GREEDY_MULTIPLIER;this.candidates.push({prevCandidate:null,portPoint:null,currentNodeId:o,point:d,z:h,f:_,g:0,h:m,distanceTraveled:0,hasTouchedOffBoardNode:!1})}}this.candidates.sort((h,d)=>h.f-d.f);let l,u=this.candidates.shift();for(;u?.portPoint&&this.visitedPortPoints;){const h=this.getVisitedPortPointKey(u.portPoint.portPointId,u.hasTouchedOffBoardNode);if(!this.visitedPortPoints.has(h))break;u=this.candidates.shift()}if(this.candidates.length>this.MAX_CANDIDATES_IN_MEMORY&&this.candidates.splice(this.MAX_CANDIDATES_IN_MEMORY,this.candidates.length-this.MAX_CANDIDATES_IN_MEMORY),!u)return this.error=`Ran out of candidates on connection ${a}`,this.failedConnection=e,this.processedConnectionQueue.push(e),this.currentConnection=null,this.candidates=null,this.visitedPortPoints=null,this.currentPathIterations=0,void(this.failed=!0);if(u.portPoint&&this.visitedPortPoints){const h=this.getVisitedPortPointKey(u.portPoint.portPointId,u.hasTouchedOffBoardNode);this.visitedPortPoints.add(h)}if(this.isAtEndGoal(u.currentNodeId,i)){const h=e.connection.pointsToConnect[e.connection.pointsToConnect.length-1],d=h?{x:h.x,y:h.y}:s.center,p=this.computeGToEndTarget(u,d,a,A),m={prevCandidate:u,portPoint:null,currentNodeId:i,point:d,z:u.z,g:p,h:0,f:p,distanceTraveled:u.distanceTraveled+no(u.point,d)},_=this.getBacktrackedPath(m);return e.path=_,e.portPoints=this.assignPortPointsForPath(_,a,A),this.addTargetPointsToNodes(_,e.connection),this.clearCostCaches(),this.RIPPING_ENABLED&&this.processRippingForPath(_,a),this.processedConnectionQueue.push(e),this.currentConnection=null,this.progress=this.processedConnectionQueue.length/this.totalConnectionCount,this.candidates=null,this.visitedPortPoints=null,void(this.currentPathIterations=0)}const g=this.nodeMap.get(u.currentNodeId);l=g?._offBoardConnectionId?this.getAvailableExitPortPointsForOffboardConnection(u.currentNodeId,u.hasTouchedOffBoardNode):this.FORCE_CENTER_FIRST?this.getAvailableExitPortPointsWithOmissions(u.currentNodeId,i,u.hasTouchedOffBoardNode):this.getAvailableExitPortPoints(u.currentNodeId,u.hasTouchedOffBoardNode);for(const h of l){if(this.isPortPointInPathChain(u,h.portPointId)||this.visitedPortPoints?.has(h.portPointId))continue;const d=this.getOtherNodeId(h,h.throughNodeId??u.currentNodeId);if(!d||this.isNodeInPathChain(u,d))continue;const p="throughNodeId"in h?h.throughNodeId:void 0,m=p?this.nodeMap.get(p):null,_=this.nodeMap.get(d);if(!_||_._containsObstacle&&!this.canTravelThroughObstacle(_,a,A))continue;const f=this.computeG(u,h,d,a,A);if(!this.RIPPING_ENABLED&&f>-this.MIN_ALLOWED_BOARD_SCORE)continue;const I=u.distanceTraveled+no(u.point,h),C=u.hasTouchedOffBoardNode||!!_._offBoardConnectionId,y=this.computeH(h,d,i,h.z,I,C),x=f+y*this.GREEDY_MULTIPLIER,E=!!g?._offBoardConnectionId&&!!m?._offBoardConnectionId;this.candidates.push({prevCandidate:u,portPoint:h,currentNodeId:d,point:{x:h.x,y:h.y},z:h.z,f:x,g:f,h:y,distanceTraveled:I,lastMoveWasOffBoard:E,throughNodeId:E?p:void 0,hasTouchedOffBoardNode:C||!!_._offBoardConnectionId||!!g?._offBoardConnectionId})}}getNodesWithPortPoints(){const e=[];for(const n of this.inputNodes){const o=this.nodeAssignedPortPoints.get(n.capacityMeshNodeId)??[];o.length>0&&e.push({capacityMeshNodeId:n.capacityMeshNodeId,center:n.center,width:n.width,height:n.height,portPoints:o,availableZ:n.availableZ})}return e}getConnectionsInNode(e,n){const o=[],i=new Set;for(const r of this.connectionsWithResults)if(r.path&&r.connection.name!==n&&!i.has(r.connection.name)){for(const s of r.path)if(s.currentNodeId===e){o.push(r),i.add(r.connection.name);break}}return o}computeNodePfWithoutConnection(e,n){if(e._containsTarget)return{pf:0,totalCrossings:0};const o=(this.nodeAssignedPortPoints.get(e.capacityMeshNodeId)??[]).filter(a=>a.connectionName!==n),i={capacityMeshNodeId:e.capacityMeshNodeId,center:e.center,width:e.width,height:e.height,portPoints:o,availableZ:e.availableZ},r=Wm(i),s=r.numSameLayerCrossings+r.numEntryExitLayerChanges+r.numTransitionPairCrossings;return{pf:wy(this.capacityMeshNodeMap.get(e.capacityMeshNodeId),r.numSameLayerCrossings,r.numEntryExitLayerChanges,r.numTransitionPairCrossings),totalCrossings:s}}computeNodeCrossings(e){if(e._containsTarget)return 0;const n=this.buildNodeWithPortPointsForCrossing(e),o=Wm(n);return o.numSameLayerCrossings+o.numEntryExitLayerChanges+o.numTransitionPairCrossings}ripConnection(e){const n=e.connection.name;for(const[o,i]of this.assignedPortPoints.entries())i.connectionName===n&&this.assignedPortPoints.delete(o);for(const[o,i]of this.nodeAssignedPortPoints.entries()){const r=i.filter(s=>s.connectionName!==n);this.nodeAssignedPortPoints.set(o,r)}e.path=void 0,e.portPoints=void 0}requeueConnection(e){this.totalRipCount++;const n=this.processedConnectionQueue.indexOf(e);if(n!==-1)return this.processedConnectionQueue.splice(n,1),this.unprocessedConnectionQueue.push(e),!0;const o=this.unprocessedConnectionQueue.indexOf(e);return o!==-1&&(this.unprocessedConnectionQueue.splice(o,1),this.unprocessedConnectionQueue.unshift(e)),!0}processRippingForPath(e,n){const o=Array.from(new Set(e.map(r=>r.currentNodeId)));let i=!1;for(const r of o){if(this.totalRipCount>this.MAX_RIPS)break;const s=this.nodeMap.get(r);if(!s)continue;let a=this.computeNodePf(s);if(a<=this.RIPPING_PF_THRESHOLD)continue;this.testedRipConnections.has(r)||this.testedRipConnections.set(r,new Set);const A=this.testedRipConnections.get(r),c=D5(this.getConnectionsInNode(r,n),(this.hyperParameters.SHUFFLE_SEED??0)+this.processedConnectionQueue.length);for(const l of c){if(a<=this.RIPPING_PF_THRESHOLD)break;const u=l.connection.name;A.add(u);const{pf:g}=this.computeNodePfWithoutConnection(s,u);if(this.ripConnection(l),!this.requeueConnection(l))return;a=g,i=!0,this.clearCostCaches()}}i&&this.RANDOM_RIP_FRACTION>0&&this.processRandomRipping(n)}processRandomRipping(e){const n=this.processedConnectionQueue.filter(r=>r.path!==void 0&&r.connection.name!==e);if(n.length===0)return;const o=Math.max(1,Math.floor(this.RANDOM_RIP_FRACTION*n.length)),i=D5(n,(this.hyperParameters.SHUFFLE_SEED??0)+this.totalRipCount+this.processedConnectionQueue.length);for(let r=0;r<o&&r<i.length&&!(this.totalRipCount>this.MAX_RIPS);r++){const s=i[r];if(this.ripConnection(s),!this.requeueConnection(s))return;this.clearCostCaches()}}visualize(){let e={};if(this.failed){const n=this.failedConnection?.connection.pointsToConnect[0],o=this.failedConnection?.connection.pointsToConnect[1];n&&o&&(e={lines:[{points:[n,o],label:`Failed Connection ${this.failedConnection?.connection.name}`,strokeWidth:1,strokeColor:"red",strokeDash:[2,2]}]})}return MD(V7e(this),e)}},z7e=class extends Zse{getSolverName(){return"HyperPortPointPathingSolver"}params;precomputedInitialParams;constructor(e){super(),this.params=e,this.MAX_ITERATIONS=1e8,this.GREEDY_MULTIPLIER=1.2,this.MIN_SUBSTEPS=50,this.precomputedInitialParams=e.precomputedInitialParams??Mft(e.simpleRouteJson,e.inputNodes)}getHyperParameterDefs(){const e=this.params.numShuffleSeeds??50;return[{name:"SHUFFLE_SEED",possibleValues:Array.from({length:e},(n,o)=>({SHUFFLE_SEED:o+1700*(this.params.hyperParameters?.SHUFFLE_SEED??0)}))}]}getCombinationDefs(){return[["SHUFFLE_SEED"]]}generateSolver(e){return new eZn({simpleRouteJson:this.params.simpleRouteJson,capacityMeshNodes:this.params.capacityMeshNodes,inputNodes:this.params.inputNodes,colorMap:this.params.colorMap,nodeMemoryPfMap:this.params.nodeMemoryPfMap,hyperParameters:{...this.params.hyperParameters,...e,MIN_ALLOWED_BOARD_SCORE:this.params.minAllowedBoardScore??e.MIN_ALLOWED_BOARD_SCORE??this.params.hyperParameters?.MIN_ALLOWED_BOARD_SCORE},precomputedInitialParams:this.precomputedInitialParams,fixedRoutes:this.params.fixedRoutes})}computeG(e){return-e.computeBoardScore()}computeH(e){const n=e.progress||0;return n<.1?0:-(e.computeBoardScore()/n)*(1-n)}getNodesWithPortPoints(){if(this.winningSolver)return this.winningSolver.getNodesWithPortPoints();const e=this.getSupervisedSolverWithBestFitness();return e?e.solver.getNodesWithPortPoints():[]}get connectionsWithResults(){if(this.winningSolver)return this.winningSolver.connectionsWithResults;const e=this.getSupervisedSolverWithBestFitness();return e?e.solver.connectionsWithResults:[]}get inputNodes(){if(this.winningSolver)return this.winningSolver.inputNodes;const e=this.getSupervisedSolverWithBestFitness();return e?e.solver.inputNodes:this.params.inputNodes}get nodeMap(){if(this.winningSolver)return this.winningSolver.nodeMap;const e=this.getSupervisedSolverWithBestFitness();return e?e.solver.nodeMap:new Map(this.params.inputNodes.map(n=>[n.capacityMeshNodeId,n]))}get assignedPortPoints(){if(this.winningSolver)return this.winningSolver.assignedPortPoints;const e=this.getSupervisedSolverWithBestFitness();return e?e.solver.assignedPortPoints:new Map}get nodeAssignedPortPoints(){if(this.winningSolver)return this.winningSolver.nodeAssignedPortPoints;const e=this.getSupervisedSolverWithBestFitness();return e?e.solver.nodeAssignedPortPoints:new Map}computeNodePf(e){if(this.winningSolver)return this.winningSolver.computeNodePf(e);const n=this.getSupervisedSolverWithBestFitness();return n?n.solver.computeNodePf(e):null}computeBoardScore(){if(this.winningSolver)return this.winningSolver.computeBoardScore();const e=this.getSupervisedSolverWithBestFitness();return e?e.solver.computeBoardScore():0}onSolve(e){this.stats={...e.solver.stats,winningHyperParameters:this.winningSolver?.hyperParameters}}visualize(){return this.winningSolver?this.winningSolver.visualize():super.visualize()}};function Lft(t){let e=t;return()=>{e+=1831565813;let n=e;return n=Math.imul(n^n>>>15,1|n),n^=n+Math.imul(n^n>>>7,61|n),((n^n>>>14)>>>0)/4294967296}}var tZn=[{SHUFFLE_SEED:100,NODE_PF_FACTOR:100,NODE_PF_MAX_PENALTY:100,MEMORY_PF_FACTOR:0,EXPANSION_DEGREES:10,FORCE_CENTER_FIRST:!0,FORCE_OFF_BOARD_FREQUENCY:0,CENTER_OFFSET_DIST_PENALTY_FACTOR:0}],nZn=class extends yr{getSolverName(){return"MultiSectionPortPointOptimizer"}simpleRouteJson;inputNodes;capacityMeshNodes;capacityMeshEdges;colorMap;nodeMap;capacityMeshNodeMap;connectionResults;assignedPortPoints;nodeAssignedPortPoints;sections=[];activeSubSolver=null;currentSection=null;sectionScoreBeforeOptimization=0;currentSectionCenterNodeId=null;currentScheduleIndex=0;nodePfMap=new Map;attemptsToFixNode=new Map;sectionAttempts=0;MAX_ATTEMPTS_PER_NODE=100;MAX_SECTION_ATTEMPTS=15;ACCEPTABLE_PF=.05;FRACTION_TO_REPLACE=.2;JUMPER_PF_FN_ENABLED=!1;SHUFFLE_SEEDS_PER_SECTION=null;ALWAYS_RIP_INTERSECTIONS=!0;effort=1;HYPERPARAMETER_SCHEDULE=tZn;constructor(e){super(),this.MAX_ITERATIONS=1e6,this.simpleRouteJson=e.simpleRouteJson,this.inputNodes=e.inputNodes,this.capacityMeshNodes=e.capacityMeshNodes,this.capacityMeshEdges=e.capacityMeshEdges,this.colorMap=e.colorMap??{},this.effort=e.effort??1,e.FRACTION_TO_REPLACE!==void 0&&(this.FRACTION_TO_REPLACE=e.FRACTION_TO_REPLACE),e.ALWAYS_RIP_INTERSECTIONS!==void 0&&(this.ALWAYS_RIP_INTERSECTIONS=e.ALWAYS_RIP_INTERSECTIONS),e.MAX_ATTEMPTS_PER_NODE!==void 0&&(this.MAX_ATTEMPTS_PER_NODE=e.MAX_ATTEMPTS_PER_NODE),e.MAX_SECTION_ATTEMPTS!==void 0&&(this.MAX_SECTION_ATTEMPTS=e.MAX_SECTION_ATTEMPTS),e.HYPERPARAMETER_SCHEDULE!==void 0&&(this.HYPERPARAMETER_SCHEDULE=e.HYPERPARAMETER_SCHEDULE),this.JUMPER_PF_FN_ENABLED=e.JUMPER_PF_FN_ENABLED??this.JUMPER_PF_FN_ENABLED,this.SHUFFLE_SEEDS_PER_SECTION=e.SHUFFLE_SEEDS_PER_SECTION,this.nodeMap=new Map(e.inputNodes.map(o=>[o.capacityMeshNodeId,o])),this.capacityMeshNodeMap=new Map(e.capacityMeshNodes.map(o=>[o.capacityMeshNodeId,o])),this.connectionResults=[...e.initialConnectionResults],this.assignedPortPoints=new Map(e.initialAssignedPortPoints),this.nodeAssignedPortPoints=new Map(e.initialNodeAssignedPortPoints),this.nodePfMap=this.computeInitialPfMap();const n=this.computeBoardScore();this.stats.successfulOptimizations=0,this.stats.failedOptimizations=0,this.stats.nodesExamined=0,this.stats.sectionAttempts=0,this.stats.sectionScores={},this.stats.initialBoardScore=n,this.stats.currentBoardScore=n,this.stats.errors=0}computeInitialPfMap(){const e=new Map;for(const n of this.capacityMeshNodes){const o=this.nodeAssignedPortPoints.get(n.capacityMeshNodeId)??[];if(o.length===0)continue;const i={capacityMeshNodeId:n.capacityMeshNodeId,center:n.center,width:n.width,height:n.height,portPoints:o,availableZ:n.availableZ},r=this.JUMPER_PF_FN_ENABLED&&n.availableZ.length===1?Jz(n,Wm(i).numSameLayerCrossings):Nft(i,n);e.set(n.capacityMeshNodeId,r)}return e}computeBoardScore(){const e=this.getNodesWithPortPoints();return this.computeScoreForNodes(e)}computeScoreForNodes(e){return this.JUMPER_PF_FN_ENABLED?Fft(e,this.capacityMeshNodeMap):Dft(e,this.capacityMeshNodeMap)}recomputePfForNodes(e){for(const n of e){const o=this.capacityMeshNodeMap.get(n);if(!o)continue;const i=this.nodeAssignedPortPoints.get(n)??[];if(i.length===0){this.nodePfMap.set(n,0);continue}const r={center:o.center,width:o.width,height:o.height,portPoints:i,availableZ:o.availableZ},s=this.JUMPER_PF_FN_ENABLED&&o.availableZ.length===1?Jz(o,Wm(r).numSameLayerCrossings):Nft(r,o);this.nodePfMap.set(n,s)}}getCreatePortPointSectionInput(){return{inputNodes:this.inputNodes,capacityMeshNodes:this.capacityMeshNodes,capacityMeshEdges:this.capacityMeshEdges,nodeMap:this.nodeMap,connectionResults:this.connectionResults}}createSection(e){return(function(n,o){const{inputNodes:i,capacityMeshNodes:r,capacityMeshEdges:s,connectionResults:a}=n,{centerOfSectionCapacityNodeId:A,expansionDegrees:c}=o,l=new Map;for(const C of s){const[y,x]=C.nodeIds;l.has(y)||l.set(y,new Set),l.has(x)||l.set(x,new Set),l.get(y).add(x),l.get(x).add(y)}const u=new Set,g=new Set,h=[];for(h.push({nodeId:A,depth:0}),g.add(A);h.length>0;){const{nodeId:C,depth:y}=h.shift();if(u.add(C),y<c){const x=l.get(C)??new Set;for(const E of x)g.has(E)||(g.add(E),h.push({nodeId:E,depth:y+1}))}}const d=i.filter(C=>u.has(C.capacityMeshNodeId)),p=r.filter(C=>u.has(C.capacityMeshNodeId)),m=[],_=[];for(const C of s){const[y,x]=C.nodeIds,E=u.has(y),B=u.has(x);E&&B?m.push(C):(E||B)&&_.push(C)}const f=d.map(C=>{const y=C.portPoints.filter(x=>{const[E,B]=x.connectionNodeIds,S=u.has(E),Q=u.has(B);return S||Q});return{...C,portPoints:y}}),I=(function(C,y){const x=[];for(const E of C){if(!E.path||E.path.length===0)continue;const B=E.connection.name,S=E.connection.__rootConnectionNames?.[0],Q=[];for(let Y=0;Y<E.path.length;Y++){const W=E.path[Y];y.has(W.currentNodeId)&&Q.push(Y)}if(Q.length===0)continue;const w=Q[0],M=Q[Q.length-1];let k=w,R=M;if(w>0){const Y=E.path[0].currentNodeId;(E.nodeIds[0]===Y||E.nodeIds[1]===Y)&&(k=0)}if(M<E.path.length-1){const Y=E.path.length-1,W=E.path[Y].currentNodeId;(E.nodeIds[0]===W||E.nodeIds[1]===W)&&(R=Y)}const F=E.path.slice(k,R+1),O=k>0,U=R<E.path.length-1;x.push({connectionName:B,rootConnectionName:S,points:F.map(Y=>({x:Y.point.x,y:Y.point.y,z:Y.z,nodeId:Y.currentNodeId,portPointId:Y.portPoint?.portPointId})),originalStartIndex:k,originalEndIndex:R,hasEntryFromOutside:O,hasExitToOutside:U})}return x})(a??[],u);return{centerNodeId:A,expansionDegrees:c,nodeIds:u,inputNodes:f,capacityMeshNodes:p,internalEdges:m,boundaryEdges:_,sectionPaths:I}})(this.getCreatePortPointSectionInput(),e)}getSectionNodesWithPortPoints(e){const n=[];for(const o of e.nodeIds){const i=this.nodeMap.get(o),r=this.capacityMeshNodeMap.get(o);if(!i||!r)continue;const s=this.nodeAssignedPortPoints.get(o)??[];s.length>0&&n.push({capacityMeshNodeId:o,center:i.center,width:i.width,height:i.height,portPoints:s,availableZ:i.availableZ})}return n}getNodesWithPortPoints(){const e=[];for(const n of this.inputNodes){const o=this.nodeAssignedPortPoints.get(n.capacityMeshNodeId)??[];o.length>0&&e.push({capacityMeshNodeId:n.capacityMeshNodeId,center:n.center,width:n.width,height:n.height,portPoints:o,availableZ:n.availableZ})}return e}findHighestPfNode(){let e=null,n=0;for(const[o,i]of this.nodePfMap.entries())i*(1-(this.attemptsToFixNode.get(o)??0)/this.MAX_ATTEMPTS_PER_NODE)**2>n&&(n=i,e=o);return!e||n<this.ACCEPTABLE_PF?null:e}currentSectionCutPathInfo=new Map;currentSectionKeptPortPoints=new Map;currentSectionFixedRoutes=[];determineConnectionsToRip(e,n){const o=31337*this.sectionAttempts,i=Lft(o);if(this.FRACTION_TO_REPLACE>=1)return new Set(n);const r=(function(A,c){const l=Lft(c),u=[...A];for(let g=u.length-1;g>0;g--){const h=Math.floor(l()*(g+1));[u[g],u[h]]=[u[h],u[g]]}return u})(n,o),s=Math.max(1,Math.ceil(r.length*this.FRACTION_TO_REPLACE)),a=new Set(r.slice(0,s));if(this.ALWAYS_RIP_INTERSECTIONS){const A=(function(c){const{section:l,nodePfMap:u,capacityMeshNodeMap:g,nodeAssignedPortPoints:h,acceptablePf:d}=c,p=[];for(const m of l.nodeIds){if((u.get(m)??0)<=d)continue;const _=g.get(m);if(!_)continue;const f=h.get(m)??[];if(f.length<2)continue;const I=_.center.x-_.width/2,C=_.center.x+_.width/2,y=_.center.y-_.height/2,x=_.center.y+_.height/2,E=new Map;for(const Q of f){const w=E.get(Q.connectionName)??[];w.some(M=>M.x===Q.x&&M.y===Q.y&&M.z===Q.z)||w.push({x:Q.x,y:Q.y,z:Q.z}),E.set(Q.connectionName,w)}const B=new Map;for(const[Q,w]of E){if(w.length<2)continue;const M=w[0],k=w[1];if(M.z!==k.z)continue;const R=Rft(M,I,C,y,x),F=Rft(k,I,C,y,x),O=M.z,U=B.get(O)??[];U.push({connectionName:Q,t1:R,t2:F}),B.set(O,U)}const S=1e-6;for(const[,Q]of B){const w=Q.map(M=>({connectionName:M.connectionName,a:Math.min(M.t1,M.t2),b:Math.max(M.t1,M.t2)}));for(let M=0;M<w.length;M++){const{connectionName:k,a:R,b:F}=w[M];for(let O=M+1;O<w.length;O++){const{connectionName:U,a:Y,b:W}=w[O];Math.abs(R-Y)<S||Math.abs(R-W)<S||Math.abs(F-Y)<S||Math.abs(F-W)<S||(R<Y&&Y<F&&F<W||Y<R&&R<W&&W<F)&&p.push([k,U])}}}}return p})({section:e,nodePfMap:this.nodePfMap,capacityMeshNodeMap:this.capacityMeshNodeMap,nodeAssignedPortPoints:this.nodeAssignedPortPoints,acceptablePf:this.ACCEPTABLE_PF});for(const[c,l]of A){if(a.has(c)||a.has(l))continue;const u=n.includes(c),g=n.includes(l);if(u&&g){const h=i()<.5;a.add(h?c:l)}else u?a.add(c):g&&a.add(l)}}return this.stats.lastRipCount=a.size,a}createSectionSimpleRouteJson(e){const n=[];this.currentSectionCutPathInfo.clear(),this.currentSectionKeptPortPoints.clear(),this.currentSectionFixedRoutes=[];const o=[],i=[];for(const A of this.connectionResults){if(!A.path||A.path.length===0)continue;const[c,l]=A.nodeIds,u=e.nodeIds.has(c),g=e.nodeIds.has(l);u&&g&&(i.push(A),o.push(A.connection.name))}const r=[];for(const A of e.sectionPaths){if(!A.hasEntryFromOutside&&!A.hasExitToOutside||A.points.length<2)continue;const c=this.connectionResults.find(l=>l.connection.name===A.connectionName);c&&(r.push({sectionPath:A,originalResult:c}),o.includes(A.connectionName)||o.push(A.connectionName))}const s=this.determineConnectionsToRip(e,o);for(const A of i)s.has(A.connection.name)&&n.push(A.connection);for(const{sectionPath:A,originalResult:c}of r){if(!s.has(A.connectionName))continue;const l=`__cut__${A.connectionName}__${A.originalStartIndex}`;this.colorMap[l]=this.colorMap[A.connectionName];const u=A.points[0],g=A.points[A.points.length-1],h={name:l,__rootConnectionNames:[A.rootConnectionName??A.connectionName],pointsToConnect:[{x:u.x,y:u.y,layers:[`layer${u.z+1}`]},{x:g.x,y:g.y,layers:[`layer${g.z+1}`]}]};n.push(h),this.currentSectionCutPathInfo.set(l,{sectionPath:A,originalConnectionResult:c})}const a=new Set(o.filter(A=>!s.has(A)));if(a.size>0){for(const A of e.nodeIds){const c=(this.nodeAssignedPortPoints.get(A)??[]).filter(l=>a.has(l.connectionName));c.length>0&&this.currentSectionKeptPortPoints.set(A,c)}for(const A of i)a.has(A.connection.name)&&this.currentSectionFixedRoutes.push(A);for(const{sectionPath:A,originalResult:c}of r)if(a.has(A.connectionName)){const l={connection:{name:A.connectionName,__rootConnectionNames:A.rootConnectionName?[A.rootConnectionName]:void 0,pointsToConnect:c.connection.pointsToConnect},path:A.points.map(u=>({prevCandidate:null,portPoint:null,currentNodeId:u.nodeId,point:{x:u.x,y:u.y},z:u.z,f:0,g:0,h:0,distanceTraveled:0})),portPoints:A.points.map(u=>({portPointId:u.portPointId,x:u.x,y:u.y,z:u.z,connectionName:A.connectionName,rootConnectionName:A.rootConnectionName})),nodeIds:c.nodeIds,straightLineDistance:c.straightLineDistance};this.currentSectionFixedRoutes.push(l)}}return{...this.simpleRouteJson,connections:n}}prepareSectionInputNodesForCutPaths(e){const n=new Set;for(const[,o]of this.currentSectionCutPathInfo.entries()){const{sectionPath:i}=o;if(i.points.length===0)continue;const r=i.points[0].nodeId;n.add(r);const s=i.points[i.points.length-1].nodeId;n.add(s)}return e.inputNodes.map(o=>n.has(o.capacityMeshNodeId)?{...o,_containsTarget:!0}:o)}getHyperParametersForScheduleIndex(e,n){const o=this.HYPERPARAMETER_SCHEDULE[e];return{...o,SHUFFLE_SEED:(o.SHUFFLE_SEED??0)+17*n}}createSectionSolver(e){const n=this.createSectionSimpleRouteJson(e),o=this.prepareSectionInputNodesForCutPaths(e),i=Mft(n,o);for(const[r,s]of this.currentSectionKeptPortPoints){const a=i.nodeAssignedPortPoints.get(r)??[];i.nodeAssignedPortPoints.set(r,[...a,...s])}return new z7e({simpleRouteJson:n,inputNodes:o,capacityMeshNodes:e.capacityMeshNodes,colorMap:this.colorMap,nodeMemoryPfMap:this.nodePfMap,numShuffleSeeds:this.SHUFFLE_SEEDS_PER_SECTION??2*n.connections.length*this.effort,hyperParameters:{...this.getHyperParametersForScheduleIndex(this.currentScheduleIndex,this.sectionAttempts)},precomputedInitialParams:i,fixedRoutes:this.currentSectionFixedRoutes})}reattachSection(e,n,o,i){const r=[],s=[];for(const A of n)A.connection.name.startsWith("__cut__")?s.push(A):r.push(A);const a=new Set(r.map(A=>A.connection.name));this.connectionResults=this.connectionResults.filter(A=>!a.has(A.connection.name)),this.connectionResults.push(...r);for(const[A,c]of this.nodeAssignedPortPoints.entries()){if(!e.nodeIds.has(A))continue;const l=c.filter(u=>!a.has(u.connectionName));this.nodeAssignedPortPoints.set(A,l)}for(const[A,c]of this.assignedPortPoints.entries())a.has(c.connectionName)&&this.assignedPortPoints.delete(A);for(const A of s){const c=this.currentSectionCutPathInfo.get(A.connection.name);if(!c||!A.path)continue;const{sectionPath:l,originalConnectionResult:u}=c,g=u.path;if(!g)continue;const h=l.connectionName;for(const[f,I]of this.nodeAssignedPortPoints.entries()){const C=I.filter(y=>y.connectionName!==h||!e.nodeIds.has(f));this.nodeAssignedPortPoints.set(f,C)}const d=g.slice(0,l.originalStartIndex),p=g.slice(l.originalEndIndex+1),m=[];let _=d.length>0?d[d.length-1]:null;for(const f of A.path){const I={...f,prevCandidate:_};m.push(I),_=I}if(p.length>0&&m.length>0&&(p[0]={...p[0],prevCandidate:m[m.length-1]}),u.path=[...d,...m,...p],A.portPoints)for(const f of A.portPoints){const I={...f,connectionName:h,rootConnectionName:l.rootConnectionName??h};for(const C of e.inputNodes)for(const y of C.portPoints)if(Math.abs(y.x-f.x)<.001&&Math.abs(y.y-f.y)<.001&&y.z===f.z){for(const x of y.connectionNodeIds){const E=this.nodeAssignedPortPoints.get(x)??[];E.push(I),this.nodeAssignedPortPoints.set(x,E)}break}}}for(const[A,c]of o.entries())c.connectionName.startsWith("__cut__")||this.assignedPortPoints.set(A,c);for(const[A,c]of i.entries()){const l=c.filter(u=>!u.connectionName.startsWith("__cut__"));if(l.length>0){const u=this.nodeAssignedPortPoints.get(A)??[];this.nodeAssignedPortPoints.set(A,[...u,...l])}}}_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved||this.activeSubSolver.failed){if(this.activeSubSolver.failed){if(this.currentScheduleIndex++,this.activeSubSolver.error&&this.stats.errors++,this.currentScheduleIndex<this.HYPERPARAMETER_SCHEDULE.length&&this.currentSectionCenterNodeId){const l=this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];this.currentSection=this.createSection({centerOfSectionCapacityNodeId:this.currentSectionCenterNodeId,expansionDegrees:l.EXPANSION_DEGREES}),this.activeSubSolver=this.createSectionSolver(this.currentSection)}else this.stats.failedOptimizations++,this.activeSubSolver=null,this.currentSection=null,this.currentSectionCenterNodeId=null,this.currentScheduleIndex=0;return}const i=this.activeSubSolver.getNodesWithPortPoints().map(l=>({...l,portPoints:l.portPoints.map(u=>{if(u.connectionName.startsWith("__cut__")){const g=u.connectionName.slice(7),h=g.lastIndexOf("__"),d=h>=0?g.slice(0,h):g;return{...u,connectionName:d}}return u})})),r=new Set;for(const l of i)for(const u of l.portPoints)r.add(u.connectionName);const s=this.getSectionNodesWithPortPoints(this.currentSection).map(l=>({...l,portPoints:l.portPoints.filter(u=>r.has(u.connectionName))})).filter(l=>l.portPoints.length>0),a=this.computeScoreForNodes(s),A=this.computeScoreForNodes(i),c=`attempt${this.sectionAttempts}`;if(this.stats.lastSectionScore=A,A>a){const l=this.stats.currentBoardScore;this.stats.lastBoardScore=l;const u=[...this.connectionResults],g=new Map(this.assignedPortPoints),h=new Map(Array.from(this.nodeAssignedPortPoints.entries()).map(([p,m])=>[p,[...m]]));this.reattachSection(this.currentSection,this.activeSubSolver.connectionsWithResults,this.activeSubSolver.assignedPortPoints,this.activeSubSolver.nodeAssignedPortPoints),this.recomputePfForNodes(this.currentSection.nodeIds);const d=this.computeBoardScore();this.stats.sectionScores[c]=d,d>l?(this.stats.successfulOptimizations++,this.stats.currentBoardScore=d):(this.connectionResults=u,this.assignedPortPoints=g,this.nodeAssignedPortPoints=h,this.recomputePfForNodes(this.currentSection.nodeIds),this.stats.failedOptimizations++),this.activeSubSolver=null,this.currentSection=null,this.currentSectionCenterNodeId=null,this.currentScheduleIndex=0}else if(this.currentScheduleIndex++,this.currentScheduleIndex<this.HYPERPARAMETER_SCHEDULE.length&&this.currentSectionCenterNodeId){const l=this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];this.currentSection=this.createSection({centerOfSectionCapacityNodeId:this.currentSectionCenterNodeId,expansionDegrees:l.EXPANSION_DEGREES}),this.activeSubSolver=this.createSectionSolver(this.currentSection)}else this.stats.failedOptimizations++,this.activeSubSolver=null,this.currentSection=null,this.currentSectionCenterNodeId=null,this.currentScheduleIndex=0}return}if(this.sectionAttempts>=this.MAX_SECTION_ATTEMPTS)return void(this.solved=!0);const e=this.findHighestPfNode();if(!e)return void(this.solved=!0);this.sectionAttempts++,this.stats.sectionAttempts=this.sectionAttempts,this.stats.nodesExamined++,this.attemptsToFixNode.set(e,(this.attemptsToFixNode.get(e)??0)+1),this.currentSectionCenterNodeId=e,this.currentScheduleIndex=0;const n=this.HYPERPARAMETER_SCHEDULE[this.currentScheduleIndex];this.currentSection=this.createSection({centerOfSectionCapacityNodeId:e,expansionDegrees:n.EXPANSION_DEGREES});const o=this.getSectionNodesWithPortPoints(this.currentSection);if(this.sectionScoreBeforeOptimization=this.computeScoreForNodes(o),this.createSectionSimpleRouteJson(this.currentSection).connections.length===0)return this.currentSection=null,void(this.currentSectionCenterNodeId=null);this.activeSubSolver=this.createSectionSolver(this.currentSection)}computeProgress(){return this.sectionAttempts/this.MAX_SECTION_ATTEMPTS}visualize(){return this.solved?V7e(this):this.activeSubSolver?this.activeSubSolver.visualize():this.currentSection?(function(e,n){const o={lines:[],points:[],rects:[],circles:[]};for(const i of e.inputNodes){const r=i.capacityMeshNodeId===e.centerNodeId,s=r?"rgba(0, 200, 0, 0.3)":"rgba(200, 200, 200, 0.3)";o.rects.push({center:i.center,width:.9*i.width,height:.9*i.height,layer:`z${i.availableZ.join(",")}`,fill:s,label:`${i.capacityMeshNodeId}${r?" (CENTER)":""}`})}for(const i of e.inputNodes)for(const r of i.portPoints)o.circles.push({center:{x:r.x,y:r.y},radius:.05,fill:"rgba(150, 150, 150, 0.5)",layer:`z${r.z}`,label:[r.portPointId,`cd: ${r.distToCentermostPortOnZ}`,`connects: ${r.connectionNodeIds.join(",")}`].filter(Boolean).join(`
`)});for(const i of e.sectionPaths){const r=n?.[i.connectionName]??"blue";for(let s=0;s<i.points.length-1;s++){const a=i.points[s],A=i.points[s+1],c=a.z===A.z,l=a.z;let u;u=c?l===0?"5 5":"10 5":"3 3 10",o.lines.push({points:[{x:a.x,y:a.y},{x:A.x,y:A.y}],strokeColor:r,strokeDash:u})}}return o})(this.currentSection,this.colorMap):V7e(this)}},Hft=class{parent={};constructor(e){for(const n of e)this.parent[n]=n}find(e){return this.parent[e]===e?e:this.parent[e]=this.find(this.parent[e])}union(e,n){const o=this.find(e),i=this.find(n);o!==i&&(this.parent[i]=o)}getGroup(e){const n=this.find(e),o=[];for(const i in this.parent)this.find(i)===n&&o.push(i);return o}},oZn=class{point;left=null;right=null;constructor(e){this.point=e}},iZn=class{root=null;constructor(e){e.length>0&&(this.root=this.buildTree(e,0))}buildTree(e,n){const o=n%2==0?"x":"y";e.sort((s,a)=>s[o]-a[o]);const i=Math.floor(e.length/2),r=new oZn(e[i]);return i>0&&(r.left=this.buildTree(e.slice(0,i),n+1)),i<e.length-1&&(r.right=this.buildTree(e.slice(i+1),n+1)),r}findNearestNeighbor(e){if(!this.root)throw new Error("Tree is empty");const n=this.root.point,o=this.distance(e,n);return this.nearestNeighborSearch(this.root,e,0,n,o),n}nearestNeighborSearch(e,n,o,i,r){if(!e)return i;const s=o%2?"x":"y",a=this.distance(n,e.point);a<r&&(i=e.point,r=a);const A=n[s]-e.point[s],c=A<=0?e.left:e.right,l=A<=0?e.right:e.left;return i=this.nearestNeighborSearch(c,n,o+1,i,r),r=this.distance(n,i),Math.abs(A)<r&&(i=this.nearestNeighborSearch(l,n,o+1,i,r)),i}findKNearestNeighbors(e,n){if(!this.root)return[];const o=[];return this.kNearestNeighborSearch(this.root,e,0,o,n),o.sort((i,r)=>i.distance-r.distance).slice(0,n).map(i=>i.point)}kNearestNeighborSearch(e,n,o,i,r){if(!e)return;const s=o%2?"x":"y",a=this.distance(n,e.point);i.push({point:e.point,distance:a});const A=n[s]-e.point[s],c=A<=0?e.left:e.right,l=A<=0?e.right:e.left;this.kNearestNeighborSearch(c,n,o+1,i,r);let u=1/0;i.length>=r&&(i.sort((g,h)=>g.distance-h.distance),u=i[r-1]?.distance||1/0),(Math.abs(A)<u||i.length<r)&&this.kNearestNeighborSearch(l,n,o+1,i,r)}distance(e,n){return Math.sqrt((e.x-n.x)**2+(e.y-n.y)**2)}},rZn=class{parent=new Map;rank=new Map;constructor(e){for(const n of e){const o=this.pointToKey(n);this.parent.set(o,o),this.rank.set(o,0)}}pointToKey(e){return`${e.x},${e.y}`}find(e){const n=this.pointToKey(e);if(!this.parent.has(n))throw new Error(`Point ${n} not found in DisjointSet`);let o=n;for(;o!==this.parent.get(o);)o=this.parent.get(o);let i=n;for(;i!==o;){const r=this.parent.get(i);this.parent.set(i,o),i=r}return o}union(e,n){const o=this.find(e),i=this.find(n);if(o===i)return!1;const r=this.rank.get(o)||0,s=this.rank.get(i)||0;return r<s?this.parent.set(o,i):r>s?this.parent.set(i,o):(this.parent.set(i,o),this.rank.set(o,r+1)),!0}};function Oft(t,e={}){if(t.length<=1)return[];const n=[...t],o=new iZn(n),i=[],r=Math.min(10,t.length-1);for(const A of n){const c=o.findKNearestNeighbors(A,r+1);for(const l of c){if(A.x===l.x&&A.y===l.y)continue;const u=Math.sqrt((A.x-l.x)**2+(A.y-l.y)**2);i.push({from:A,to:l,weight:u})}}e.extraEdges&&i.push(...e.extraEdges),i.sort((A,c)=>A.weight-c.weight);const s=new rZn(n),a=[];for(const A of i)if(s.union(A.from,A.to)&&(a.push(A),a.length===n.length-1))break;return a}var sZn=(t,e)=>{const n=new Map;for(const i of t.pointsToConnect){if(!i.pointId)continue;const r=e.getNetConnectedToId(i.pointId);if(!r)continue;const s=n.get(r)??[];s.push(i),n.set(r,s)}const o=[];for(const i of n.values()){const r=i[0];if(r)for(const s of i.slice(1))o.push({from:r,to:s,weight:0})}return o},Gft=(t,e)=>({zeroWeightEdges:sZn(t,e),arePointsConnected:(n,o)=>!!(n.pointId&&o.pointId&&((i,r,s)=>{const a=i.getNetConnectedToId(r);return!!a&&a===i.getNetConnectedToId(s)})(e,n.pointId,o.pointId))});function iae(t){if(t.pointId)return t.pointId;let e="";return ND(t)?e=t.layer:E7e(t)&&t.layers&&(e=t.layers.sort().join("-")),`${t.x.toFixed(4)},${t.y.toFixed(4)},${e}`}function Yft(t){if(t.length===0)return[];const e=t.map((s,a)=>`conn_${a}`),n=new Hft(e),o=new Map;t.forEach((s,a)=>{const A=`conn_${a}`;s.pointsToConnect.forEach(c=>{const l=iae(c);o.has(l)||o.set(l,[]),o.get(l).push(A)})});for(const s of o.values())if(s.length>1){const a=s[0];for(let A=1;A<s.length;A++)n.union(a,s[A])}const i=new Map;t.forEach((s,a)=>{const A=`conn_${a}`,c=n.find(A);i.has(c)||i.set(c,[]),i.get(c).push(s)});const r=[];for(const s of i.values()){if(s.length===1){r.push(s[0]);continue}const a=new Map,A=new Set;let c=!1;const l=[],u=new Set;let g;s.forEach(d=>{d.pointsToConnect.forEach(m=>a.set(iae(m),m));const p=d.__rootConnectionNames;if(p&&p.length>0)for(const m of p)A.add(m);else A.add(d.name);d.isOffBoard&&(c=!0),d.externallyConnectedPointIds&&l.push(...d.externallyConnectedPointIds),d.__netConnectionName&&u.add(d.__netConnectionName),g===void 0&&d.nominalTraceWidth!==void 0&&(g=d.nominalTraceWidth)});const h={name:s.map(d=>d.name).join("__"),pointsToConnect:Array.from(a.values()),isOffBoard:c,externallyConnectedPointIds:l.length>0?l:void 0,__netConnectionName:u.size>0?Array.from(u).join("__"):void 0,__rootConnectionNames:Array.from(A),nominalTraceWidth:g};r.push(h)}return r}var J7e=class extends yr{constructor(e,n={},o){super(),this.ogSrj=e,this.colorMap=n;const i=new Map;for(const s of e.buses??[])if(s.traceWidth!==void 0)for(const a of s.connectionNames)i.set(a,Math.max(i.get(a)??0,s.traceWidth));const r=e.connections.map(s=>{const a=i.get(s.name);return a===void 0?s:{...s,nominalTraceWidth:Math.max(s.nominalTraceWidth??0,a)}});this.unprocessedConnections=Yft(r),this.newConnections=[],this.initiallyConnectedMap=o}ogSrj;colorMap;getSolverName(){return"NetToPointPairsSolver"}unprocessedConnections;newConnections;initiallyConnectedMap;_step(){if(this.unprocessedConnections.length===0)return void(this.solved=!0);const e=this.unprocessedConnections.pop(),{zeroWeightEdges:n,arePointsConnected:o}=Gft(e,this.initiallyConnectedMap);if(e.pointsToConnect.length===2){const[s,a]=e.pointsToConnect;return s&&a&&o(s,a)?void 0:void this.newConnections.push({...e,__rootConnectionNames:e.__rootConnectionNames??[e.name]})}const i=Oft(e.pointsToConnect,{extraEdges:n});let r=0;for(const s of i)o(s.from,s.to)||this.newConnections.push({...e,pointsToConnect:[s.from,s.to],name:`${e.name}_mst${r++}`,__rootConnectionNames:e.__rootConnectionNames??[e.name],__netConnectionName:e.__netConnectionName})}getNewSimpleRouteJson(){return{...structuredClone(this.ogSrj),connections:structuredClone(this.newConnections)}}visualize(){const e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Net To Point Pairs Visualization"};return this.unprocessedConnections.forEach(n=>{n.pointsToConnect.forEach(s=>{e.points.push({x:s.x,y:s.y,color:"red",label:s.pcb_port_id??s.pointId})});const o=n.pointsToConnect.length**2,i=M7e(0),r=new Set;for(let s=0;s<Math.max(o,2*n.pointsToConnect.length);s++){const a=Math.floor(i()*n.pointsToConnect.length),A=Math.floor(i()*n.pointsToConnect.length);r.has(`${a}-${A}`)||(r.add(`${a}-${A}`),e.lines.push({points:[n.pointsToConnect[a],n.pointsToConnect[A]],strokeColor:"rgba(255,0,0,0.25)",label:n.name}))}}),this.newConnections.forEach(n=>{const o=this.colorMap?.[n.name]||"blue";n.pointsToConnect.forEach(i=>{e.points.push({x:i.x,y:i.y,color:o,label:i.pcb_port_id??i.pointId})});for(let i=0;i<n.pointsToConnect.length-1;i++)for(let r=i+1;r<n.pointsToConnect.length;r++)e.lines.push({points:[n.pointsToConnect[i],n.pointsToConnect[r]],strokeColor:o,label:n.name})}),e}},rL=class extends J7e{constructor(e,n={},o){const i=e.connections.flatMap(c=>c.pointsToConnect),r=new Map;for(const c of i)c.pointId&&r.set(c.pointId,c);const s=i.map(c=>c.pointId).filter(c=>!!c),a=new Hft(s),A=[];for(const c of e.connections)c.isOffBoard?c.pointsToConnect.length>=2&&c.pointsToConnect[0].pointId&&c.pointsToConnect[1].pointId&&a.union(c.pointsToConnect[0].pointId,c.pointsToConnect[1].pointId):A.push(c);super({...e,connections:A},n,o),this.ogSrj=e,this.colorMap=n,this.connectionPointDsu=a,this.connectionPointMap=r,this.ogSrj=e}ogSrj;colorMap;getSolverName(){return"NetToPointPairsSolver2_OffBoardConnection"}connectionPointDsu;connectionPointMap;_findBestConnectionPointsFromDisjointSets(e,n){if(!e.pointId||!n.pointId)return{pointsToConnect:[e,n]};const o=this.connectionPointDsu.getGroup(e.pointId).map(A=>this.connectionPointMap.get(A)),i=this.connectionPointDsu.getGroup(n.pointId).map(A=>this.connectionPointMap.get(A));let r=e,s=n,a=1/0;for(const A of o)for(const c of i){const l=Math.sqrt(Math.pow(A.x-c.x,2)+Math.pow(A.y-c.y,2));l<a&&(a=l,r=A,s=c)}return{pointsToConnect:[r,s]}}_step(){if(this.unprocessedConnections.length===0)return void(this.solved=!0);const e=this.unprocessedConnections.pop(),{zeroWeightEdges:n,arePointsConnected:o}=Gft(e,this.initiallyConnectedMap);if(e.pointsToConnect.length===2){const[s,a]=e.pointsToConnect;if(s&&a&&o(s,a))return;const A=this._findBestConnectionPointsFromDisjointSets(e.pointsToConnect[0],e.pointsToConnect[1]);return void this.newConnections.push({...e,pointsToConnect:A.pointsToConnect,__rootConnectionNames:e.__rootConnectionNames??[e.name]})}const i=Oft(e.pointsToConnect,{extraEdges:n});let r=0;for(const s of i){if(o(s.from,s.to))continue;const a=this._findBestConnectionPointsFromDisjointSets(s.from,s.to);this.newConnections.push({...e,pointsToConnect:a.pointsToConnect,name:`${e.name}_mst${r++}`,__rootConnectionNames:e.__rootConnectionNames??[e.name],__netConnectionName:e.__netConnectionName})}}},W7e=class{netMap;idToNetMap;constructor(e){this.netMap=e,this.idToNetMap={};for(const[n,o]of Object.entries(e))for(const i of o)this.idToNetMap[i]=n}addConnections(e){for(const n of e){const o=new Set;for(const r of n){const s=this.idToNetMap[r];s&&o.add(s)}let i;if(o.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(o.size===1)i=o.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=o.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(const r of o)if(r!==i){const s=this.netMap[i],a=this.netMap[r];if(s&&a){s.push(...a),this.netMap[r]=s;for(const A of s)this.idToNetMap[A]=i}}}for(const r of n){const s=this.netMap[i];s&&!s.includes(r)&&s.push(r),this.idToNetMap[r]=i}}}getIdsConnectedToNet(e){return this.netMap[e]||[]}getNetConnectedToId(e){return this.idToNetMap[e]}areIdsConnected(e,n){if(e===n)return!0;const o=this.getNetConnectedToId(e);if(!o)return!1;const i=this.getNetConnectedToId(n);return!!i&&(o===i||i===e||i===e)}areAllIdsConnected(e){if(e.length===0)return!0;const n=this.getNetConnectedToId(e[0]);if(!n)return!1;for(const o of e){const i=this.getNetConnectedToId(o);if(i===void 0||i!==n)return!1}return!0}};function aZn(t,e={}){const n=[],o=[],i=e.color??"gray",r=e.label,s=W8[t.footprint]??W8["0603"],a=t.end.x-t.start.x,A=t.end.y-t.start.y,c=Math.abs(a)>Math.abs(A),l=c?s.padLength:s.padWidth,u=c?s.padWidth:s.padLength;return n.push({center:t.start,width:l,height:u,fill:Es(i,.5),stroke:"rgba(0, 0, 0, 0.5)",layer:"jumper",label:r?`${r} (start)`:void 0}),n.push({center:t.end,width:l,height:u,fill:Es(i,.5),stroke:"rgba(0, 0, 0, 0.5)",layer:"jumper",label:r?`${r} (end)`:void 0}),o.push({points:[t.start,t.end],strokeColor:"rgba(100, 100, 100, 0.8)",strokeWidth:.3*s.padWidth,layer:"jumper-body"}),{rects:n,lines:o}}function _x(t,e={}){const n={rects:[],lines:[]};for(const o of t){const{rects:i,lines:r}=aZn(o,e);n.rects.push(...i),n.lines.push(...r)}return n}var rae=1e5,Wz=.001,Uft=class extends yr{getSolverName(){return"SingleHighDensityRouteStitchSolver"}mergedHdRoute;remainingHdRoutes;start;end;colorMap;constructor(e){if(super(),this.remainingHdRoutes=[...e.hdRoutes],this.colorMap=e.colorMap??{},e.hdRoutes.length===0){this.start=e.start,this.end=e.end;const A=[{x:e.start.x,y:e.start.y,z:e.start.z}],c=[];return e.start.z!==e.end.z&&(A.push({x:e.start.x,y:e.start.y,z:e.end.z}),c.push({x:e.start.x,y:e.start.y})),A.push({x:e.end.x,y:e.end.y,z:e.end.z}),this.mergedHdRoute={connectionName:e.connectionName,rootConnectionName:e.hdRoutes[0]?.rootConnectionName,route:A,vias:c,jumpers:[],viaDiameter:e.defaultViaDiameter??.3,traceThickness:e.defaultTraceThickness??.15},void(this.solved=!0)}let n=1/0,o=e.hdRoutes[0],i="start-to-end";for(const A of e.hdRoutes){const c=A.route[0],l=A.route[A.route.length-1],u=no(e.start,c),g=no(e.start,l),h=no(e.end,c),d=no(e.end,l),p=Math.min(u,g,h,d);p<n&&(n=p,o=A,i=Math.min(h,d)<Math.min(u,g)?"end-to-start":"start-to-end")}i==="start-to-end"?(this.start=e.start,this.end=e.end):(this.start=e.end,this.end=e.start);const r=o.route[0],s=o.route[o.route.length-1],a=no(this.start,r)<=no(this.start,s)?r:s;this.mergedHdRoute={connectionName:e.connectionName,rootConnectionName:o.rootConnectionName,route:[{x:this.start.x,y:this.start.y,z:a.z}],vias:[],jumpers:[],viaDiameter:o.viaDiameter,traceThickness:o.traceThickness}}getDisjointedRoute(){for(const e of this.remainingHdRoutes)if([e.route[0],e.route[e.route.length-1]].some(n=>!this.remainingHdRoutes.some(o=>o===e?!1:[o.route[0],o.route[o.route.length-1]].some(i=>i.z===n.z&&no(n,i)<.001))))return{firstRoute:e};return{firstRoute:this.remainingHdRoutes[0]}}_step(){if(this.remainingHdRoutes.length===0){const a=this.mergedHdRoute.route[this.mergedHdRoute.route.length-1];return this.mergedHdRoute.route.push({x:this.end.x,y:this.end.y,z:a.z}),void(this.solved=!0)}const e=this.mergedHdRoute.route[this.mergedHdRoute.route.length-1];let n=-1,o="first",i=1/0;for(let a=0;a<this.remainingHdRoutes.length;a++){const A=this.remainingHdRoutes[a],c=A.route[0],l=A.route[A.route.length-1],u=no(e,c),g=no(e,l);let h=1/0;h=e.z===c.z?u<Wz?u:rae+u:u<Wz?1e3+u:rae+u,h<i&&(i=h,n=a,o="first");let d=1/0;d=e.z===l.z?g<Wz?g:rae+g:g<Wz?1e3+g:rae+g,d<i&&(i=d,n=a,o="last")}if(n===-1)return void(this.remainingHdRoutes=[]);const r=this.remainingHdRoutes[n];let s;this.remainingHdRoutes.splice(n,1),s=o==="first"?r.route:[...r.route].reverse(),no(e,s[0])<Wz&&e.z===s[0].z?this.mergedHdRoute.route.push(...s.slice(1)):this.mergedHdRoute.route.push(...s),this.mergedHdRoute.vias.push(...r.vias),r.jumpers&&this.mergedHdRoute.jumpers.push(...r.jumpers)}visualize(){const e={points:[],lines:[],circles:[],rects:[],title:"Single High Density Route Stitch Solver"};if(e.points?.push({x:this.start.x,y:this.start.y,color:"green",label:"Start"},{x:this.end.x,y:this.end.y,color:"red",label:"End"}),this.mergedHdRoute&&this.mergedHdRoute.route.length>1){e.lines?.push({points:this.mergedHdRoute.route.map(n=>({x:n.x,y:n.y})),strokeColor:"green"});for(const n of this.mergedHdRoute.route)e.points?.push({x:n.x,y:n.y,color:"green"});for(const n of this.mergedHdRoute.vias)e.circles?.push({center:{x:n.x,y:n.y},radius:this.mergedHdRoute.viaDiameter/2,fill:"green"});if(this.mergedHdRoute.jumpers&&this.mergedHdRoute.jumpers.length>0){const n=_x(this.mergedHdRoute.jumpers,{color:"green",label:this.mergedHdRoute.connectionName});e.rects.push(...n.rects??[]),e.lines.push(...n.lines??[])}}for(const[n,o]of this.remainingHdRoutes.entries()){const i=this.colorMap[o.connectionName]??"gray";e.lines?.push({points:o.route.map(r=>({x:r.x,y:r.y})),strokeColor:i});for(let r=0;r<o.route.length;r++){const s=o.route[r];e.points?.push({x:s.x+(n%2-.5)/500+(r%8-4)/1e3,y:s.y+(n%2-.5)/500+(r%8-4)/1e3,color:i,label:`Route ${o.connectionName} ${s===o.route[0]?"First":s===o.route[o.route.length-1]?"Last":""}`})}for(const r of o.vias)e.circles?.push({center:{x:r.x,y:r.y},radius:o.viaDiameter/2,fill:i});if(o.jumpers&&o.jumpers.length>0){const r=_x(o.jumpers,{color:i,label:o.connectionName});e.rects.push(...r.rects??[]),e.lines.push(...r.lines??[])}}return e}},sL=t=>`${Math.round(100*t.x)},${Math.round(100*t.y)},${Math.round(100*t.z)}`,AZn=t=>({startHash:sL(t.route[0]),endHash:sL(t.route[t.route.length-1])}),j7e=class extends yr{getSolverName(){return"MultipleHighDensityRouteStitchSolver"}unsolvedRoutes;activeSolver=null;mergedHdRoutes=[];colorMap={};defaultTraceThickness;defaultViaDiameter;getClosestEndpointHash(e,n){let o=null,i=1/0;for(const r of e){const s=[r.route[0],r.route[r.route.length-1]];for(const a of s){const A=no(n,a);A<i&&(i=A,o=sL(a))}}return o}selectRoutesAlongEndpointPath(e,n,o){if(e.length<=2)return e;const i=this.getClosestEndpointHash(e,n),r=this.getClosestEndpointHash(e,o);if(!i||!r||i===r)return e;const s=new Map;for(let g=0;g<e.length;g++){const{startHash:h,endHash:d}=AZn(e[g]),p=s.get(h)??[];p.push({nextHash:d,routeIndex:g}),s.set(h,p);const m=s.get(d)??[];m.push({nextHash:h,routeIndex:g}),s.set(d,m)}const a=[i],A=new Set([i]),c=new Map;for(;a.length>0;){const g=a.shift();if(g===r)break;for(const h of s.get(g)??[])A.has(h.nextHash)||(A.add(h.nextHash),c.set(h.nextHash,{prevHash:g,routeIndex:h.routeIndex}),a.push(h.nextHash))}if(!A.has(r))return e;const l=new Set;let u=r;for(;u!==i;){const g=c.get(u);if(!g)return e;l.add(g.routeIndex),u=g.prevHash}return l.size===0?e:e.filter((g,h)=>l.has(h))}constructor(e){super(),this.colorMap=e.colorMap??{};const n=e.hdRoutes[0];this.defaultTraceThickness=n?.traceThickness??.15,this.defaultViaDiameter=n?.viaDiameter??e.defaultViaDiameter??.3;const o=new W7e({}),i=[],r=new Map;for(let A=0;A<e.hdRoutes.length;A++){const c=e.hdRoutes[A],l=c.route[0],u=c.route[c.route.length-1];i.push([`route_island_${A}`,`${c.connectionName}:${sL(l)}`,`${c.connectionName}:${sL(u)}`])}o.addConnections(i);for(const A of i)for(const c of A.slice(1))r.set(c,(r.get(c)??0)+1);this.unsolvedRoutes=[];const s=Array.from(new Set(Object.values(o.idToNetMap)));for(const A of s){const c=o.getIdsConnectedToNet(A),l=e.hdRoutes.filter((_,f)=>c.includes(`route_island_${f}`));if(l.length===0)continue;const u=e.connections.find(_=>_.name===l[0].connectionName),g=l.flatMap(_=>[_.route[0],_.route[_.route.length-1]]),h=[];for(const _ of g){const f=`${l[0].connectionName}:${sL(_)}`;r.get(f)===1&&h.push(_)}if(h.length===0){console.log("no possible endpoints, can't stitch");continue}let d,p;h.length!==2?(d={...u.pointsToConnect[0],z:Kr(tI(u.pointsToConnect[0]),e.layerCount)},p={...u.pointsToConnect[1],z:Kr(tI(u.pointsToConnect[1]),e.layerCount)}):(d=h[0],p=h[1],no(d,u.pointsToConnect[1])<no(p,u.pointsToConnect[0])&&([d,p]=[p,d]));const m=this.selectRoutesAlongEndpointPath(l,d,p);this.unsolvedRoutes.push({connectionName:l[0].connectionName,hdRoutes:m,start:d,end:p})}const a=new Map;for(const A of this.unsolvedRoutes){const c=a.get(A.connectionName);c?c.push(A):a.set(A.connectionName,[A])}this.unsolvedRoutes=Array.from(a.entries()).flatMap(([A,c])=>{if(!c.some(d=>d.hdRoutes.some(p=>p.route.length<2)))return c;const l=e.connections.find(d=>d.name===A);if(!l)return c;const u={...l.pointsToConnect[0],z:Kr(tI(l.pointsToConnect[0]),e.layerCount)},g={...l.pointsToConnect[1],z:Kr(tI(l.pointsToConnect[1]),e.layerCount)},h=c.flatMap(d=>d.hdRoutes);return[{connectionName:A,hdRoutes:this.selectRoutesAlongEndpointPath(h,u,g),start:u,end:g}]}),this.MAX_ITERATIONS=1e5}_step(){if(this.activeSolver)return this.activeSolver.step(),void(this.activeSolver.solved?(this.activeSolver instanceof Uft&&this.mergedHdRoutes.push(this.activeSolver.mergedHdRoute),this.activeSolver=null):this.activeSolver.failed&&(this.failed=!0,this.error=this.activeSolver.error));const e=this.unsolvedRoutes.pop();e?this.activeSolver=new Uft({connectionName:e.connectionName,hdRoutes:e.hdRoutes,start:e.start,end:e.end,colorMap:this.colorMap,defaultTraceThickness:this.defaultTraceThickness,defaultViaDiameter:this.defaultViaDiameter}):this.solved=!0}visualize(){const e={points:[],lines:[],circles:[],rects:[],title:"Multiple High Density Route Stitch Solver"};if(this.activeSolver){const n=this.activeSolver.visualize();n.points?.length&&e.points?.push(...n.points),n.lines?.length&&e.lines?.push(...n.lines),n.circles?.length&&e.circles?.push(...n.circles),n.rects?.length&&(e.rects||(e.rects=[]),e.rects.push(...n.rects))}for(const[n,o]of this.mergedHdRoutes.entries()){const i=this.colorMap[o.connectionName]??`hsl(120, 100%, ${40+10*n%40}%)`;for(let r=0;r<o.route.length-1;r++){const s=o.route[r],a=o.route[r+1],A=s.z!==0?Es(i,.5):i;e.lines?.push({points:[{x:s.x,y:s.y},{x:a.x,y:a.y}],strokeColor:A,strokeWidth:o.traceThickness})}for(const r of o.route){const s=r.z!==0?Es(i,.5):i;e.points?.push({x:r.x,y:r.y,color:s})}for(const r of o.vias)e.circles?.push({center:{x:r.x,y:r.y},radius:o.viaDiameter/2,fill:i});if(o.jumpers&&o.jumpers.length>0){const r=_x(o.jumpers,{color:i,label:o.connectionName});e.rects.push(...r.rects??[]),e.lines.push(...r.lines??[])}}for(const n of this.unsolvedRoutes){const o=this.colorMap[n.connectionName]??"gray";e.points?.push({x:n.start.x,y:n.start.y,color:o,label:`${n.connectionName} Start (z=${n.start.z})`},{x:n.end.x,y:n.end.y,color:o,label:`${n.connectionName} End (z=${n.end.z})`}),e.lines?.push({points:[{x:n.start.x,y:n.start.y},{x:n.end.x,y:n.end.y}],strokeColor:o,strokeDash:"2 2"});for(const i of n.hdRoutes){i.route.length>1&&e.lines?.push({points:i.route.map(r=>({x:r.x,y:r.y})),strokeColor:Es(o,.5),strokeDash:"10 5"});for(const r of i.vias)e.circles?.push({center:{x:r.x,y:r.y},radius:i.viaDiameter/2,fill:o});if(i.jumpers&&i.jumpers.length>0){const r=_x(i.jumpers,{color:o,label:i.connectionName});e.rects.push(...r.rects??[]),e.lines.push(...r.lines??[])}}}return e}},jz=class{tree;constructor(e=9){this.tree=new vz(e)}insert(e,n,o,i,r){this.tree.insert({minX:n,minY:o,maxX:i,maxY:r,data:e})}bulkLoad(e){const n=e.map(({item:o,minX:i,minY:r,maxX:s,maxY:a})=>({minX:i,minY:r,maxX:s,maxY:a,data:o}));this.tree.load(n)}search(e,n,o,i){return this.tree.search({minX:e,minY:n,maxX:o,maxY:i}).map(r=>r.data)}clear(){this.tree.clear()}},Kft=class{index;items=[];currentIndex=0;capacity;constructor(e){this.capacity=Math.max(1,e),this.index=new X4(this.capacity)}insert(e,n,o,i,r){if(this.currentIndex>=this.index.numItems)throw new Error("Exceeded initial capacity");this.items[this.currentIndex]=e,this.index.add(n,o,i,r),this.currentIndex++}finish(){this.index.finish()}search(e,n,o,i){return this.index.search(e,n,o,i).map(r=>this.items[r]||null).filter(Boolean)}clear(){this.items=[],this.currentIndex=0,this.index=new X4(this.capacity)}},OD=class{idx;storage=[];constructor(e="native",n=[]){e==="flatbush"?n.length===0?(this.idx=new jz,e="rbush"):this.idx=new Kft(n.length):this.idx=e==="rbush"?new jz:new class{shi=new cZn(n);insert(o){}search(o,i,r,s){const a=(o+r)/2,A=(i+s)/2,c=r-o,l=s-i;return this.shi.getNodesInArea(a,A,c,l)}clear(){}},n.forEach(o=>this.insert(o)),e==="flatbush"&&n.length>0&&this.idx.finish?.()}insert(e){this.storage.push(e),this.idx.insert(e,e.center.x-e.width/2,e.center.y-e.height/2,e.center.x+e.width/2,e.center.y+e.height/2)}search(e){return this.idx.search(e.minX,e.minY,e.maxX,e.maxY)}searchArea(e,n,o,i){return this.search({minX:e-o/2,minY:n-i/2,maxX:e+o/2,maxY:n+i/2})}},cZn=class{constructor(e){this.obstacles=e,this.buckets=new Map;for(let n=0;n<e.length;n++){const o=e[n],i=o.center.x-o.width/2,r=o.center.y-o.height/2,s=o.center.x+o.width/2,a=o.center.y+o.height/2;for(let A=i;A<=s;A+=this.CELL_SIZE)for(let c=r;c<=a;c+=this.CELL_SIZE){const l=this.getBucketKey(A,c),u=this.buckets.get(l);u?u.push([o,n]):this.buckets.set(l,[[o,n]])}}}obstacles;buckets;CELL_SIZE=.4;getBucketKey(e,n){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(n/this.CELL_SIZE)}`}getNodesInArea(e,n,o,i){const r=[],s=new Set,a=n-i/2,A=e+o/2,c=n+i/2;for(let l=e-o/2;l<=A;l+=this.CELL_SIZE)for(let u=a;u<=c;u+=this.CELL_SIZE){const g=this.getBucketKey(l,u),h=this.buckets.get(g)||[];for(const d of h)s.has(d[1])||(s.add(d[1]),r.push(d[0]))}return r}},Vft=(t,e)=>{const n=[],o=Math.abs(e.x-t.x),i=Math.abs(e.y-t.y),r=e.x>t.x?1:-1,s=e.y>t.y?1:-1,a={x:e.x-r*Math.abs(e.y-t.y),y:t.y};(a.x-t.x)*r>=0&&(a.x-e.x)*r<=0&&n.push([t,a,e]);const A={x:t.x,y:e.y-s*Math.abs(e.x-t.x)};(A.y-t.y)*s>=0&&(A.y-e.y)*s<=0&&n.push([t,A,e]);const c=Math.min(o,i),l={x:t.x+r*c,y:t.y+s*c};return(l.x-t.x)*r>=0&&(l.x-e.x)*r<=0&&(l.y-t.y)*s>=0&&(l.y-e.y)*s<=0&&n.push([t,l,e]),n};function qQ(t,e,n,o){if(Uh(t,e,n,o))return 0;const i=sae(t,n,o),r=sae(e,n,o),s=sae(n,t,e),a=sae(o,t,e);return Math.min(i,r,s,a)}function sae(t,e,n){const o={x:n.x-e.x,y:n.y-e.y},i=zft({x:t.x-e.x,y:t.y-e.y},o);if(i<=0)return $7e(t,e);const r=zft(o,o);if(r<=i)return $7e(t,n);const s=i/r;return $7e(t,{x:e.x+s*o.x,y:e.y+s*o.y})}function zft(t,e){return t.x*e.x+t.y*e.y}function $7e(t,e){const n=e.x-t.x,o=e.y-t.y;return Math.sqrt(n*n+o*o)}var aae=1e-6,q7e=(t,e,n)=>wc(t,e,n)<=aae,Aae=(t,e)=>Math.abs(t.x-e.x)<=aae&&Math.abs(t.y-e.y)<=aae,X7e=(t,e)=>{if(!e||e.length<3)return!1;for(let o=0;o<e.length;o++){const i=e[o],r=e[(o+1)%e.length];if(q7e(t,i,r))return!0}let n=!1;for(let o=0,i=e.length-1;o<e.length;i=o++){const r=e[o],s=e[i];r.y>t.y!=s.y>t.y&&t.x<(s.x-r.x)*(t.y-r.y)/(s.y-r.y)+r.x&&(n=!n)}return n},$z=({start:t,end:e,polygon:n,margin:o=.2})=>{if(!n||n.length<3)return!1;const i=X7e(t,n),r=X7e(e,n);if(!i||!r)return!0;for(let s=0;s<n.length;s++){const a=n[s],A=n[(s+1)%n.length],c=q7e(t,a,A),l=q7e(e,a,A);if(c&&l)continue;if(!Uh(t,e,a,A)){if(!c&&!l&&qQ(t,e,a,A)<o-aae)return!0;continue}const u=DD(t,e,a,A);if((!u||!(c&&Aae(u,t)||l&&Aae(u,e)))&&(!u||!Aae(u,t)&&!Aae(u,e)))return!0}return!1},qz=t=>{const e=[],n=t.route;if(n.length===0)return[];let o={startIndex:0,endIndex:-1,z:n[0].z,points:[n[0]]};for(let i=1;i<n.length;i++)n[i].z===o.z?o.points.push(n[i]):(o.endIndex=i-1,e.push(o),o={startIndex:i,endIndex:-1,z:n[i].z,points:[n[i]]});return o.endIndex=n.length-1,e.push(o),e},Jft=({endpointX:t,endpointY:e,targetZ:n,endpointPcbPortId:o,terminalLayerIndicesByPcbPortId:i,obstacleSHI:r,route:s,connMap:a})=>{const A=o?i?.get(o):void 0;if(A&&!A.has(n))return!1;const c=[s.connectionName,s.rootConnectionName].filter(u=>u!==void 0),l=r.searchArea(t,e,2,2).filter(u=>{if(!c.some(m=>u.connectedTo.some(_=>_===m||a.areIdsConnected(m,_))))return!1;const g=u.width/2+.05,h=u.height/2+.05,d=Math.abs(t-u.center.x)<=g,p=Math.abs(e-u.center.y)<=h;return d&&p});return l.length>0&&l.some(u=>u.__zLayers?.includes(n))},GD=({currentSection:t,targetZ:e,route:n,hdRouteSHI:o,obstacleSHI:i,connMap:r,defaultTraceThickness:s,obstacleMargin:a,traceMargin:A,shouldCheckStaticGeometryForSegment:c})=>{const l=n.traceThickness??s,u=A??0,g=[n.connectionName,n.rootConnectionName].filter(h=>h!==void 0);for(let h=0;h<t.points.length-1;h++){const d={...t.points[h],z:e},p={...t.points[h+1],z:e},m=o.getConflictingRoutesForSegment(d,p,l/2+u);for(const{conflictingRoute:C,distance:y}of m){const x=[C.connectionName,C.rootConnectionName].filter(B=>B!==void 0);if(g.some(B=>x.some(S=>S===B||r.areIdsConnected(S,B))))continue;const E=C.traceThickness??s;if(y<l/2+(u>0?Math.max(E/2,C.viaDiameter/2):E/2)+u)return!1}if(c?.(d,p)===!1)continue;const _={centerX:(d.x+p.x)/2,centerY:(d.y+p.y)/2,width:Math.abs(d.x-p.x),height:Math.abs(d.y-p.y)},f=l/2+a,I=i.searchArea(_.centerX,_.centerY,_.width+2*f,_.height+2*f);for(const C of I)if(!g.some(y=>C.connectedTo.some(x=>x===y||r.areIdsConnected(x,y)))&&!(C.__zLayers?.includes(e)&&(Math.abs(d.x-C.center.x)<.01&&Math.abs(d.y-C.center.y)<.01||Math.abs(p.x-C.center.x)<.01&&Math.abs(p.y-C.center.y)<.01))&&K8(d,p,C)<f)return!1}return!0},lZn=class extends yr{getSolverName(){return"SingleRouteUselessViaRemovalSolver"}obstacleSHI;hdRouteSHI;unsimplifiedRoute;connMap;outline;terminalLayerIndicesByPcbPortId;routeSections;currentSectionIndex;TRACE_THICKNESS=.15;OBSTACLE_MARGIN=.1;GEOMETRY_SHORTCUT_TRACE_MARGIN=.1;GEOMETRY_SHORTCUT_OBSTACLE_MARGIN=.15;MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH=4;ENABLE_GEOMETRY_SHORTCUTS=!0;ENABLE_OBSTACLE_DETOUR_SHORTCUTS=!1;PRESERVE_ROUTE_ENDPOINTS=!1;geometryShortcutsApplied=0;multilayerSectionsCollapsed=0;obstacleDetourCandidatesValidated=0;constructor(e){super(),this.currentSectionIndex=0,this.obstacleSHI=e.obstacleSHI,this.hdRouteSHI=e.hdRouteSHI,this.unsimplifiedRoute=e.unsimplifiedRoute,this.connMap=e.connMap,this.outline=e.outline,this.terminalLayerIndicesByPcbPortId=e.terminalLayerIndicesByPcbPortId,this.GEOMETRY_SHORTCUT_TRACE_MARGIN=e.geometryShortcutTraceMargin??this.GEOMETRY_SHORTCUT_TRACE_MARGIN,this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN=e.geometryShortcutObstacleMargin??this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN,this.ENABLE_GEOMETRY_SHORTCUTS=e.enableGeometryShortcuts??!0,this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS=e.enableObstacleDetourShortcuts??!1,this.PRESERVE_ROUTE_ENDPOINTS=e.preserveRouteEndpoints??!1,this.routeSections=qz(this.unsimplifiedRoute)}getPathLength(e){let n=0;for(let o=1;o<e.length;o++)n+=Math.hypot(e[o].x-e[o-1].x,e[o].y-e[o-1].y);return n}normalizeShortcutPath(e,n,o){const i=e.filter((r,s)=>{const a=e[s-1];return!a||r.x!==a.x||r.y!==a.y});return i.map((r,s)=>s===0?{...n}:s===i.length-1?{...o}:{x:r.x,y:r.y,z:n.z})}shortcutCrossesOutline(e){if(!this.outline||this.outline.length<3)return!1;for(let n=1;n<e.length;n++)if($z({start:e[n-1],end:e[n],polygon:this.outline}))return!0;return!1}getObstacleDetourPaths(e,n,o,i){const r=(this.unsimplifiedRoute.traceThickness??this.TRACE_THICKNESS)/2+this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN+1e-6,s=this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH/2+r,a=Math.min(e.x,n.x)-s,A=Math.max(e.x,n.x)+s,c=Math.min(e.y,n.y)-s,l=Math.max(e.y,n.y)+s,u=this.obstacleSHI.search({minX:a,minY:c,maxX:A,maxY:l}).filter(_=>_.__zLayers?.includes(o));if(u.length===0)return[];const g=new Set,h=new Set;for(const _ of u)g.add(_.center.x-_.width/2-r),g.add(_.center.x+_.width/2+r),h.add(_.center.y-_.height/2-r),h.add(_.center.y+_.height/2+r);const d=[],p=new Set,m=_=>{let f=0;for(let E=1;E<_.length;E++)f+=Math.hypot(_[E].x-_[E-1].x,_[E].y-_[E-1].y);if(f>i)return;const I=this.normalizeShortcutPath(_,e,n);let C=0,y=-1;for(let E=0;E<I.length-1;E++){const B=I[E+1].x-I[E].x,S=I[E+1].y-I[E].y,Q=B*B+S*S;Q>y&&(C=E,y=Q)}const x=I.map(E=>`${E.x}:${E.y}`).join("|");p.has(x)||(p.add(x),d.push({path:I,length:f,longestSegmentIndex:C}))};for(const _ of h)m([e,{x:e.x,y:_},{x:n.x,y:_},n]);for(const _ of g)m([e,{x:_,y:e.y},{x:_,y:n.y},n]);return d}getDirectGeometryShortcut(e,n,o){let i=null;for(let r=0;r<e.points.length;r++){const s=e.points[r];for(let a=0;a<o.points.length;a++){const A=o.points[a],c=[...e.points.slice(r),...n.points,...o.points.slice(0,a+1)];if(!c.some(l=>l.insideJumperPad||l.toNextSegmentType))for(const l of Vft(s,A)){const u=this.normalizeShortcutPath(l,s,A),g=this.getPathLength(c)-this.getPathLength(u);if(g<-1e-6||this.shortcutCrossesOutline(u))continue;const h={startIndex:e.startIndex+r,endIndex:o.startIndex+a,z:e.z,points:u};GD({currentSection:h,targetZ:e.z,route:this.unsimplifiedRoute,hdRouteSHI:this.hdRouteSHI,obstacleSHI:this.obstacleSHI,connMap:this.connMap,defaultTraceThickness:this.TRACE_THICKNESS,obstacleMargin:this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN,traceMargin:this.GEOMETRY_SHORTCUT_TRACE_MARGIN})&&(!i||g>i.savedLength)&&(i={path:u,previousPointIndex:r,nextPointIndex:a,savedLength:g})}}}return i}getObstacleDetourShortcut(e,n,o){const i=e.points.length-1,r=[];for(let l=0;l<=i;l++)r.push([l,0]);for(let l=1;l<o.points.length;l++)r.push([i,l]);const s=[];for(const[l,u]of r){const g=e.points[l],h=o.points[u],d=[...e.points.slice(l),...n.points,...o.points.slice(0,u+1)];if(d.some(m=>m.insideJumperPad||m.toNextSegmentType))continue;const p=this.getPathLength(d);for(const{path:m,length:_,longestSegmentIndex:f}of this.getObstacleDetourPaths(g,h,e.z,p+this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH+1e-6)){const I=p-_;I<-this.MAX_GEOMETRY_SHORTCUT_ADDED_LENGTH-1e-6||s.push({path:m,previousPointIndex:l,nextPointIndex:u,savedLength:I,validationFirstSegmentIndex:f})}}s.sort((l,u)=>u.savedLength-l.savedLength);let a=0;const A=s.length>=256,c=(({targetZ:l,route:u,hdRouteSHI:g,obstacleSHI:h,connMap:d,defaultTraceThickness:p,obstacleMargin:m,traceMargin:_,useNumericSegmentKeys:f})=>{const I=u.traceThickness??p,C=I/2+_,y=I/2+m,x=u.connectionName,E=u.rootConnectionName,B=new Map,S=new WeakMap,Q=new WeakMap,w=f?new Map:void 0;let M=0;const k=O=>{let U=w.get(O.x);U||(U=new Map,w.set(O.x,U));let Y=U.get(O.y);return Y===void 0&&(Y=M++,U.set(O.y,Y)),Y},R=(O,U)=>{if(f){const Y=k(O),W=k(U),te=Math.max(Y,W);return te*(te+1)/2+Math.min(Y,W)}return O.x<U.x||O.x===U.x&&O.y<=U.y?`${O.x}:${O.y}|${U.x}:${U.y}`:`${U.x}:${U.y}|${O.x}:${O.y}`},F=O=>O===x||d.areIdsConnected(O,x)||E!==void 0&&(O===E||d.areIdsConnected(O,E));return(O,U)=>{const Y=O.length-1;for(let W=0;W<Y;W++){const te=W-1,j=U===0?W:W===0?U:te>=U?te+1:te,J=O[j],oe=O[j+1],ie=R(J,oe),ne=B.get(ie);if(ne!==void 0){if(!ne)return!1;continue}const le=J.z===l?J:{...J,z:l},ge=oe.z===l?oe:{...oe,z:l},_e={centerX:(le.x+ge.x)/2,centerY:(le.y+ge.y)/2,width:Math.abs(le.x-ge.x),height:Math.abs(le.y-ge.y)},ue=h.searchArea(_e.centerX,_e.centerY,_e.width+2*y,_e.height+2*y);for(const pe of ue){let ye=S.get(pe);if(ye===void 0&&(ye=pe.connectedTo.some(F),S.set(pe,ye)),!ye&&(!pe.__zLayers?.includes(l)||!(Math.abs(le.x-pe.center.x)<.01&&Math.abs(le.y-pe.center.y)<.01||Math.abs(ge.x-pe.center.x)<.01&&Math.abs(ge.y-pe.center.y)<.01))&&K8(le,ge,pe)<y)return B.set(ie,!1),!1}const fe=g.getConflictingRoutesForSegment(le,ge,C);for(const{conflictingRoute:pe,distance:ye}of fe){let Me=Q.get(pe);if(Me===void 0&&(Me=F(pe.connectionName)||pe.rootConnectionName!==void 0&&F(pe.rootConnectionName),Q.set(pe,Me)),Me)continue;const ve=pe.traceThickness??p,he=Math.max(ve/2,pe.viaDiameter/2);if(ye<I/2+he+_)return B.set(ie,!1),!1}B.set(ie,!0)}return!0}})({targetZ:e.z,route:this.unsimplifiedRoute,hdRouteSHI:this.hdRouteSHI,obstacleSHI:this.obstacleSHI,connMap:this.connMap,defaultTraceThickness:this.TRACE_THICKNESS,obstacleMargin:this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN,traceMargin:this.GEOMETRY_SHORTCUT_TRACE_MARGIN,useNumericSegmentKeys:A});for(const l of s){a++;const{path:u}=l;if(c(u,l.validationFirstSegmentIndex??0)&&!this.shortcutCrossesOutline(u))return this.obstacleDetourCandidatesValidated+=a,this.stats.obstacleDetourCandidatesValidated=this.obstacleDetourCandidatesValidated,l}return this.obstacleDetourCandidatesValidated+=a,this.stats.obstacleDetourCandidatesValidated=this.obstacleDetourCandidatesValidated,null}findGeometryShortcut(e,n,o){if(this.unsimplifiedRoute.jumpers?.length)return null;if(this.ENABLE_GEOMETRY_SHORTCUTS){const i=this.getDirectGeometryShortcut(e,n,o);if(i)return i}return this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS?this.getObstacleDetourShortcut(e,n,o):null}applyGeometryShortcut(e){const n=this.routeSections[this.currentSectionIndex-1],o=this.routeSections[this.currentSectionIndex+1],i=[...n.points.slice(0,e.previousPointIndex),...e.path,...o.points.slice(e.nextPointIndex+1)].filter((r,s,a)=>{const A=a[s-1];return!A||r.x!==A.x||r.y!==A.y||r.z!==A.z});this.routeSections.splice(this.currentSectionIndex-1,3,{startIndex:n.startIndex,endIndex:o.endIndex,z:n.z,points:i}),this.geometryShortcutsApplied++,this.stats.geometryShortcutsApplied=this.geometryShortcutsApplied,this.stats.viasRemovedByGeometryShortcuts=2*this.geometryShortcutsApplied,this.currentSectionIndex=Math.max(0,this.currentSectionIndex-1)}findMultilayerSectionCollapse(e,n,o){if(e.z===o.z||this.unsimplifiedRoute.jumpers?.length)return null;const i=e.points[e.points.length-1];if(i?.insideJumperPad||i?.toNextSegmentType||n.points.some(s=>s.insideJumperPad||s.toNextSegmentType))return null;const r=[{targetZ:e.z,mergeWith:"previous"},{targetZ:o.z,mergeWith:"next"}];for(const s of r)if(s.targetZ!==n.z&&GD({currentSection:n,targetZ:s.targetZ,route:this.unsimplifiedRoute,hdRouteSHI:this.hdRouteSHI,obstacleSHI:this.obstacleSHI,connMap:this.connMap,defaultTraceThickness:this.TRACE_THICKNESS,obstacleMargin:this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN,traceMargin:this.GEOMETRY_SHORTCUT_TRACE_MARGIN}))return s;return null}applyMultilayerSectionCollapse(e){const n=this.routeSections[this.currentSectionIndex-1],o=this.routeSections[this.currentSectionIndex],i=this.routeSections[this.currentSectionIndex+1],r=o.points.map(a=>({...a,z:e.targetZ})),s=a=>a.filter((A,c)=>{const l=a[c-1];return!l||A.x!==l.x||A.y!==l.y||A.z!==l.z});e.mergeWith==="previous"?this.routeSections.splice(this.currentSectionIndex-1,2,{startIndex:n.startIndex,endIndex:o.endIndex,z:e.targetZ,points:s([...n.points,...r])}):this.routeSections.splice(this.currentSectionIndex,2,{startIndex:o.startIndex,endIndex:i.endIndex,z:e.targetZ,points:s([...r,...i.points])}),this.multilayerSectionsCollapsed++,this.stats.multilayerSectionsCollapsed=this.multilayerSectionsCollapsed,this.stats.viasRemovedByMultilayerSectionCollapses=this.multilayerSectionsCollapsed,this.currentSectionIndex=Math.max(0,this.currentSectionIndex-1)}_step(){if(this.currentSectionIndex>=this.routeSections.length)return void(this.solved=!0);if(this.currentSectionIndex===0&&this.routeSections.length>1){const s=this.routeSections[0],a=this.routeSections[1];if(!this.PRESERVE_ROUTE_ENDPOINTS&&s.z!==a.z){const A=a.z,c=s.points[0];if(Jft({endpointX:c.x,endpointY:c.y,targetZ:A,endpointPcbPortId:this.unsimplifiedRoute.startPcbPortId,terminalLayerIndicesByPcbPortId:this.terminalLayerIndicesByPcbPortId,obstacleSHI:this.obstacleSHI,route:this.unsimplifiedRoute,connMap:this.connMap})&&GD({currentSection:s,targetZ:A,route:this.unsimplifiedRoute,hdRouteSHI:this.hdRouteSHI,obstacleSHI:this.obstacleSHI,connMap:this.connMap,defaultTraceThickness:this.TRACE_THICKNESS,obstacleMargin:this.OBSTACLE_MARGIN}))return s.z=A,s.points=s.points.map(l=>({...l,z:A})),void(this.currentSectionIndex=2)}return void this.currentSectionIndex++}if(this.currentSectionIndex===this.routeSections.length-1){if(!this.PRESERVE_ROUTE_ENDPOINTS&&this.routeSections.length>=2){const s=this.routeSections[this.routeSections.length-1],a=this.routeSections[this.routeSections.length-2];if(s.z!==a.z){const A=a.z,c=s.points[s.points.length-1];Jft({endpointX:c.x,endpointY:c.y,targetZ:A,endpointPcbPortId:this.unsimplifiedRoute.endPcbPortId,terminalLayerIndicesByPcbPortId:this.terminalLayerIndicesByPcbPortId,obstacleSHI:this.obstacleSHI,route:this.unsimplifiedRoute,connMap:this.connMap})&&GD({currentSection:s,targetZ:A,route:this.unsimplifiedRoute,hdRouteSHI:this.hdRouteSHI,obstacleSHI:this.obstacleSHI,connMap:this.connMap,defaultTraceThickness:this.TRACE_THICKNESS,obstacleMargin:this.OBSTACLE_MARGIN})&&(s.z=A,s.points=s.points.map(l=>({...l,z:A})))}}return void(this.solved=!0)}const e=this.routeSections[this.currentSectionIndex-1],n=this.routeSections[this.currentSectionIndex],o=this.routeSections[this.currentSectionIndex+1];if(e.z!==o.z){const s=this.findMultilayerSectionCollapse(e,n,o);return s?void this.applyMultilayerSectionCollapse(s):void this.currentSectionIndex++}const i=e.z;if(GD({currentSection:n,targetZ:i,route:this.unsimplifiedRoute,hdRouteSHI:this.hdRouteSHI,obstacleSHI:this.obstacleSHI,connMap:this.connMap,defaultTraceThickness:this.TRACE_THICKNESS,obstacleMargin:this.OBSTACLE_MARGIN}))return n.z=i,n.points=n.points.map(s=>({...s,z:i})),void(this.currentSectionIndex+=2);const r=this.findGeometryShortcut(e,n,o);r?this.applyGeometryShortcut(r):this.currentSectionIndex++}getConstructorParams(){return{obstacleSHI:this.obstacleSHI,hdRouteSHI:this.hdRouteSHI,unsimplifiedRoute:this.unsimplifiedRoute,connMap:this.connMap,outline:this.outline,geometryShortcutTraceMargin:this.GEOMETRY_SHORTCUT_TRACE_MARGIN,geometryShortcutObstacleMargin:this.GEOMETRY_SHORTCUT_OBSTACLE_MARGIN,enableGeometryShortcuts:this.ENABLE_GEOMETRY_SHORTCUTS,enableObstacleDetourShortcuts:this.ENABLE_OBSTACLE_DETOUR_SHORTCUTS,preserveRouteEndpoints:this.PRESERVE_ROUTE_ENDPOINTS,terminalLayerIndicesByPcbPortId:this.terminalLayerIndicesByPcbPortId}}getOptimizedHdRoute(){const e=this.routeSections.flatMap(o=>o.points),n=[];for(let o=0;o<e.length-1;o++)e[o].z!==e[o+1].z&&n.push({x:e[o].x,y:e[o].y});return{connectionName:this.unsimplifiedRoute.connectionName,rootConnectionName:this.unsimplifiedRoute.rootConnectionName,startPcbPortId:this.unsimplifiedRoute.startPcbPortId,endPcbPortId:this.unsimplifiedRoute.endPcbPortId,route:e,traceThickness:this.unsimplifiedRoute.traceThickness,vias:n,viaDiameter:this.unsimplifiedRoute.viaDiameter,jumpers:this.unsimplifiedRoute.jumpers}}visualize(){const e={circles:[],lines:[],points:[],rects:[],coordinateSystem:"cartesian",title:"Single Route Useless Via Removal Solver"};for(let n=0;n<this.routeSections.length;n++){const o=this.routeSections[n];e.lines.push({points:o.points,strokeWidth:this.TRACE_THICKNESS,strokeColor:n===this.currentSectionIndex?"orange":o.z===0?"red":"blue"})}return e}},uZn=class extends yr{constructor(e){super(),this.input=e,this.input={...e,obstacles:c7(e.obstacles,e.layerCount)},this.MAX_ITERATIONS=1e6,this.unsimplifiedHdRoutes=e.unsimplifiedHdRoutes,this.optimizedHdRoutes=[],this.unprocessedRoutes=[...e.unsimplifiedHdRoutes],this.obstacleSHI=new OD("flatbush",this.input.obstacles),this.hdRouteSHI=new oB([...this.unsimplifiedHdRoutes,...e.otherHdRoutes??[]])}input;getSolverName(){return"UselessViaRemovalSolver"}unsimplifiedHdRoutes;optimizedHdRoutes;unprocessedRoutes;activeSubSolver=null;obstacleSHI=null;hdRouteSHI=null;_step(){if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){const n=this.activeSubSolver.getOptimizedHdRoute();this.hdRouteSHI.removeRoute(n.connectionName),this.hdRouteSHI.addRoute(n),this.optimizedHdRoutes.push(n),this.activeSubSolver=null}else(this.activeSubSolver.failed||this.activeSubSolver.error)&&(this.error=this.activeSubSolver.error,this.failed=!0);return}const e=this.unprocessedRoutes.shift();e?this.activeSubSolver=new lZn({hdRouteSHI:this.hdRouteSHI,obstacleSHI:this.obstacleSHI,unsimplifiedRoute:e,connMap:this.input.connMap,outline:this.input.outline,geometryShortcutTraceMargin:this.input.geometryShortcutTraceMargin,geometryShortcutObstacleMargin:this.input.geometryShortcutObstacleMargin,enableGeometryShortcuts:this.input.enableGeometryShortcuts,enableObstacleDetourShortcuts:this.input.enableObstacleDetourShortcuts,preserveRouteEndpoints:this.input.preserveRouteEndpoints,terminalLayerIndicesByPcbPortId:this.input.terminalLayerIndicesByPcbPortId}):this.solved=!0}getOptimizedHdRoutes(){return this.optimizedHdRoutes}visualize(){const e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Useless Via Removal Solver"};for(const n of this.input.obstacles){let o="rgba(128, 128, 128, 0.2)";const i=n.__zLayers?.includes(0),r=n.__zLayers?.includes(1);i&&r?o="rgba(128, 0, 128, 0.2)":i?o="rgba(255, 0, 0, 0.2)":r&&(o="rgba(0, 0, 255, 0.2)"),e.rects.push({center:n.center,width:n.width,height:n.height,fill:o,label:`Obstacle (Z: ${n.__zLayers?.join(", ")})`})}for(const n of this.optimizedHdRoutes){if(n.route.length===0)continue;const o=this.input.colorMap[n.connectionName]||"#888888";for(let i=0;i<n.route.length-1;i++){const r=n.route[i],s=n.route[i+1];r.z===s.z&&e.lines.push({points:[{x:r.x,y:r.y},{x:s.x,y:s.y}],strokeColor:r.z===0?"red":"blue",strokeWidth:n.traceThickness,label:`${n.connectionName} (z=${r.z})`})}for(const i of n.vias)e.circles.push({center:{x:i.x,y:i.y},radius:n.viaDiameter/2,fill:"rgba(255, 0, 255, 0.5)",label:`${n.connectionName} via`});if(n.jumpers&&n.jumpers.length>0){const i=_x(n.jumpers,{color:o,label:n.connectionName});e.rects.push(...i.rects??[]),e.lines.push(...i.lines??[])}}return this.activeSubSolver&&e.lines.push(...this.activeSubSolver.visualize().lines??[]),e}},gZn=class extends yr{getSolverName(){return"SingleSimplifiedPathSolver"}newRoute;newVias;headIndex=0;tailIndex=0;inputRoute;otherHdRoutes;obstacles;connMap;colorMap;outline;minBoardEdgeClearance;constructor(e){super(),this.inputRoute=e.inputRoute,this.otherHdRoutes=e.otherHdRoutes,this.obstacles=e.obstacles,this.connMap=e.connMap,this.colorMap=e.colorMap,this.outline=e.outline,this.minBoardEdgeClearance=e.minBoardEdgeClearance??.2,this.newRoute=[this.inputRoute.route[0]],this.newVias=[]}getConstructorParams(){return{inputRoute:this.inputRoute,otherHdRoutes:this.otherHdRoutes,obstacles:this.obstacles,connMap:this.connMap.netMap,colorMap:this.colorMap,outline:this.outline,minBoardEdgeClearance:this.minBoardEdgeClearance}}get simplifiedRoute(){return{connectionName:this.inputRoute.connectionName,rootConnectionName:this.inputRoute.rootConnectionName,startPcbPortId:this.inputRoute.startPcbPortId,endPcbPortId:this.inputRoute.endPcbPortId,traceThickness:this.inputRoute.traceThickness,viaDiameter:this.inputRoute.viaDiameter,route:this.newRoute,vias:this.newVias,jumpers:this.inputRoute.jumpers}}isValidPath(e){throw new Error("Not implemented")}_step(){throw new Error("Not implemented")}getVisualsForNewRouteAndObstacles(){const e={lines:[],points:[],circles:[],rects:[],coordinateSystem:"cartesian",title:"Simplified Path Solver"};for(let n=0;n<this.inputRoute.route.length-1;n++)e.lines.push({points:[{x:this.inputRoute.route[n].x,y:this.inputRoute.route[n].y},{x:this.inputRoute.route[n+1].x,y:this.inputRoute.route[n+1].y}],strokeColor:"rgba(255, 0, 0, 0.8)",strokeDash:this.inputRoute.route[n].z===1?"5, 5":void 0,layer:`z${this.inputRoute.route[n].z.toString()}`});for(let n=0;n<this.newRoute.length;n++)n<this.newRoute.length-1&&e.lines.push({points:[{x:this.newRoute[n].x,y:this.newRoute[n].y},{x:this.newRoute[n+1].x,y:this.newRoute[n+1].y}],strokeWidth:.15,strokeColor:"rgba(0, 255, 0, 0.8)",strokeDash:this.newRoute[n].z===1?[.4,.4]:void 0,layer:`z${this.newRoute[n].z.toString()}`}),e.points.push({x:this.newRoute[n].x,y:this.newRoute[n].y,color:"rgba(0, 255, 0, 0.8)",label:`z: ${this.newRoute[n].z}`,layer:`z${this.newRoute[n].z.toString()}`});for(const n of this.newVias)e.circles.push({center:n,radius:this.inputRoute.viaDiameter/2,fill:"rgba(0, 0, 255, 0.5)"});for(const n of this.obstacles)e.rects.push({center:n.center,width:n.width,height:n.height,fill:n.layers?.includes("top")?"rgba(255, 0, 0, 0.3)":n.layers?.includes("bottom")?"rgba(0, 0, 255, 0.3)":"rgba(128, 128, 128, 0.3)"});for(const n of this.otherHdRoutes)for(let o=0;o<n.route.length-1;o++)e.lines.push({points:[{x:n.route[o].x,y:n.route[o].y},{x:n.route[o+1].x,y:n.route[o+1].y}],strokeWidth:.15,strokeColor:n.route[o].z===0?"rgba(255, 0, 255, 0.5)":n.route[o].z===1?"rgba(128, 0, 128, 0.5)":"rgba(0, 0, 255, 0.5)",layer:`z${n.route[o].z.toString()}`});if("filteredObstaclePathSegments"in this){const n=this.filteredObstaclePathSegments;for(const[o,i]of n)e.lines.push({points:[o,i]})}return e}},dZn=t=>({minX:Math.min(t[0].x,t[1].x),maxX:Math.max(t[0].x,t[1].x),minY:Math.min(t[0].y,t[1].y),maxY:Math.max(t[0].y,t[1].y)}),Wft=class{constructor(e,n=.4){this.segments=e,this.buckets=new Map,this.SEGMENT_MARGIN=n;const o=new Map;for(const i of e){const r=this.getSegmentKey(i);if(o.has(r))continue;o.set(r,i);const s=dZn(i),a=Math.floor(s.minX/this.CELL_SIZE),A=Math.floor(s.maxX/this.CELL_SIZE),c=Math.floor(s.minY/this.CELL_SIZE),l=Math.floor(s.maxY/this.CELL_SIZE);for(let u=a;u<=A;u++)for(let g=c;g<=l;g++){const h=`${u}x${g}`,d=this.buckets.get(h),p=[i[0],i[1],r];d?d.push(p):this.buckets.set(h,[p])}}}segments;buckets;CELL_SIZE=.4;SEGMENT_MARGIN;getBucketKey(e,n){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(n/this.CELL_SIZE)}`}getSegmentKey(e){return`${e[0].x}-${e[0].y}-${e[0].z}-${e[1].x}-${e[1].y}-${e[1].z}`}getSegmentsThatCouldIntersect(e,n){const o=[],i=new Set,r=Math.min(e.x,n.x)-this.SEGMENT_MARGIN,s=Math.min(e.y,n.y)-this.SEGMENT_MARGIN,a=Math.max(e.x,n.x)+this.SEGMENT_MARGIN,A=Math.max(e.y,n.y)+this.SEGMENT_MARGIN,c=Math.floor(r/this.CELL_SIZE),l=Math.floor(a/this.CELL_SIZE),u=Math.floor(s/this.CELL_SIZE),g=Math.floor(A/this.CELL_SIZE);for(let h=c;h<=l;h++)for(let d=u;d<=g;d++){const p=`${h}x${d}`,m=this.buckets.get(p);if(m)for(const _ of m){const f=_[2];i.has(f)||(i.add(f),o.push(_))}}return o}},hZn=class extends gZn{pathSegments=[];totalPathLength=0;headDistanceAlongPath=0;tailDistanceAlongPath=0;minStepSize=.25;lastValidPath=null;lastValidPathHeadDistance=0;STEP_SIZE_REDUCTION_FACTOR=.25;maxStepSize=4;currentStepSize=this.maxStepSize;lastHeadMoveDistance=0;cachedValidPathSegments;filteredObstacles=[];filteredObstaclePathSegments=[];traceThicknessByObstacleSegmentId=new Map;filteredVias=[];filteredJumperPads=[];jumperPadPointIndices=new Set;segmentTree;OBSTACLE_MARGIN=.1;TRACE_THICKNESS=.15;useTraceWidthAwareClearance=!1;clearanceTraceThickness=this.TRACE_THICKNESS;TAIL_JUMP_RATIO=.8;isSameNetRoute(e){const n=[this.inputRoute.connectionName,this.inputRoute.rootConnectionName].filter(i=>i!==void 0),o=[e.connectionName,e.rootConnectionName].filter(i=>i!==void 0);return n.some(i=>o.some(r=>i===r||this.connMap.areIdsConnected(i,r)))}constructor(e){if(super(e),this.cachedValidPathSegments=new Set,this.useTraceWidthAwareClearance=e.useTraceWidthAwareClearance??!1,this.clearanceTraceThickness=this.useTraceWidthAwareClearance?this.inputRoute.traceThickness:this.TRACE_THICKNESS,this.inputRoute.route.length<=1)return this.newRoute=[...this.inputRoute.route],void(this.solved=!0);const n=this.inputRoute.route.reduce((a,A)=>(a.minX=Math.min(a.minX,A.x),a.maxX=Math.max(a.maxX,A.x),a.minY=Math.min(a.minY,A.y),a.maxY=Math.max(a.maxY,A.y),a),{minX:1/0,maxX:-1/0,minY:1/0,maxY:-1/0}),o=this.useTraceWidthAwareClearance?Math.max(0,...this.otherHdRoutes.flatMap(a=>[a.traceThickness,...a.route.map(A=>A.traceThickness??a.traceThickness)])):this.TRACE_THICKNESS,i=this.useTraceWidthAwareClearance?this.OBSTACLE_MARGIN+this.clearanceTraceThickness/2+o/2:this.OBSTACLE_MARGIN+this.TRACE_THICKNESS,r={center:{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2},width:n.maxX-n.minX,height:n.maxY-n.minY};this.filteredObstacles=this.obstacles.filter(a=>!a.connectedTo.some(A=>this.connMap.areIdsConnected(this.inputRoute.connectionName,A))).filter(a=>a.connectedTo.some(A=>this.connMap.areIdsConnected(this.inputRoute.connectionName,A))?!1:(function(A,c){const l=Is(A),u=Is(c),g=Math.max(l.minX-u.maxX,u.minX-l.maxX,0),h=Math.max(l.minY-u.maxY,u.minY-l.maxY,0);return Math.hypot(g,h)})(r,a)<this.OBSTACLE_MARGIN+this.clearanceTraceThickness/2),this.filteredObstaclePathSegments=this.otherHdRoutes.flatMap(a=>{if(this.isSameNetRoute(a))return[];const A=a.route,c=[];for(let l=0;l<A.length-1;l++){const u=A[l],g=A[l+1];if(Dz(u,g,n)<=i){c.push([u,g]);const h=`${u.x}-${u.y}-${u.z}-${g.x}-${g.y}-${g.z}`;if(this.useTraceWidthAwareClearance){const d=Math.max(u.traceThickness??a.traceThickness,g.traceThickness??a.traceThickness);this.traceThicknessByObstacleSegmentId.set(h,Math.max(this.traceThicknessByObstacleSegmentId.get(h)??0,d))}}}return c}),this.segmentTree=this.useTraceWidthAwareClearance?new Wft(this.filteredObstaclePathSegments,i):new Wft(this.filteredObstaclePathSegments),this.filteredVias=this.otherHdRoutes.flatMap(a=>{if(this.isSameNetRoute(a))return[];const A=a.vias,c=[];for(const l of A){const u=this.OBSTACLE_MARGIN+this.clearanceTraceThickness/2+a.viaDiameter/2,g=l.x-u,h=l.x+u,d=l.y-u,p=l.y+u;g<=n.maxX&&h>=n.minX&&d<=n.maxY&&p>=n.minY&&c.push({...l,diameter:a.viaDiameter})}return c});const s=(a,A)=>{const c=[];for(const l of a){const u=W8[l.footprint]??W8["0603"],g=l.end.x-l.start.x,h=l.end.y-l.start.y,d=Math.abs(g)>Math.abs(h),p=d?u.padLength:u.padWidth,m=d?u.padWidth:u.padLength,_=this.OBSTACLE_MARGIN+this.clearanceTraceThickness/2;l.start.x-p/2-_<=n.maxX&&l.start.x+p/2+_>=n.minX&&l.start.y-m/2-_<=n.maxY&&l.start.y+m/2+_>=n.minY&&c.push({center:l.start,width:p,height:m,connectionName:A}),l.end.x-p/2-_<=n.maxX&&l.end.x+p/2+_>=n.minX&&l.end.y-m/2-_<=n.maxY&&l.end.y+m/2+_>=n.minY&&c.push({center:l.end,width:p,height:m,connectionName:A})}return c};if(this.filteredJumperPads=this.otherHdRoutes.flatMap(a=>this.isSameNetRoute(a)?[]:s(a.jumpers??[],a.connectionName)),this.inputRoute.jumpers&&this.inputRoute.jumpers.length>0){this.filteredJumperPads.push(...s(this.inputRoute.jumpers,this.inputRoute.connectionName));for(const a of this.inputRoute.jumpers)for(let A=0;A<this.inputRoute.route.length;A++){const c=this.inputRoute.route[A];(Math.abs(c.x-a.start.x)<.01&&Math.abs(c.y-a.start.y)<.01||Math.abs(c.x-a.end.x)<.01&&Math.abs(c.y-a.end.y)<.01)&&this.jumperPadPointIndices.add(A)}}this.computePathSegments()}computePathSegments(){let e=0;for(let n=0;n<this.inputRoute.route.length-1;n++){const o=this.inputRoute.route[n],i=this.inputRoute.route[n+1],r=Math.sqrt((i.x-o.x)**2+(i.y-o.y)**2)+n/1e4;this.pathSegments.push({start:o,end:i,length:r,startDistance:e,endDistance:e+r}),e+=r}this.totalPathLength=e}arePointsEqual(e,n){return e.x===n.x&&e.y===n.y&&e.z===n.z}getPointAtDistance(e){e=Math.max(0,Math.min(e,this.totalPathLength));const n=this.pathSegments.find(i=>e>=i.startDistance&&e<=i.endDistance);if(!n)return this.inputRoute.route[this.inputRoute.route.length-1];const o=(e-n.startDistance)/n.length;return{x:n.start.x+o*(n.end.x-n.start.x),y:n.start.y+o*(n.end.y-n.start.y),z:o<.5?n.start.z:n.end.z}}getNearestIndexForDistance(e){if(e<=0)return 0;if(e>=this.totalPathLength)return this.inputRoute.route.length-1;const n=this.pathSegments.findIndex(r=>e>=r.startDistance&&e<=r.endDistance);if(n===-1)return 0;const o=this.pathSegments[n],i=(o.startDistance+o.endDistance)/2;return e>i?n+1:n}isValidPathSegment(e,n){for(const i of this.filteredObstacles)if(i.__zLayers?.includes(e.z)&&K8(e,n,i)<this.OBSTACLE_MARGIN+this.clearanceTraceThickness/2)return!1;const o=this.segmentTree.getSegmentsThatCouldIntersect(e,n);for(const[i,r,s]of o)if(i.z===e.z&&r.z===e.z){const a=qQ({x:e.x,y:e.y},{x:n.x,y:n.y},{x:i.x,y:i.y},{x:r.x,y:r.y});if(!this.useTraceWidthAwareClearance){if(a<this.OBSTACLE_MARGIN+this.TRACE_THICKNESS)return!1;continue}const A=this.traceThicknessByObstacleSegmentId.get(s);if(A===void 0)throw new Error(`Missing trace thickness for segment "${s}"`);if(a<this.OBSTACLE_MARGIN+this.clearanceTraceThickness/2+A/2)return!1}for(const i of this.filteredVias)if(wc(i,e,n)<this.OBSTACLE_MARGIN+i.diameter/2+this.clearanceTraceThickness/2)return!1;for(const i of this.filteredJumperPads)if(K8(e,n,i)<this.OBSTACLE_MARGIN+this.clearanceTraceThickness/2)return!1;return!(this.outline&&this.outline.length>=3&&$z({start:{x:e.x,y:e.y},end:{x:n.x,y:n.y},polygon:this.outline,margin:this.minBoardEdgeClearance+this.inputRoute.traceThickness/2}))}isValidPath(e){if(e.length<2)return!0;for(let n=0;n<e.length-1;n++)if(e[n].z!==e[n+1].z)return!1;for(let n=0;n<e.length-1;n++)if(!this.isValidPathSegment(e[n],e[n+1]))return!1;return!0}find45DegreePath(e,n){if(this.arePointsEqual(e,n))return[e];if(e.z!==n.z)return null;const o=Vft({x:e.x,y:e.y},{x:n.x,y:n.y});for(const i of o){const r=i.map(s=>({x:s.x,y:s.y,z:e.z}));if(this.isValidPath(r))return r}return null}addPathToResult(e){if(e.length!==0){for(let n=0;n<e.length;n++)n===0&&this.newRoute.length>0&&this.arePointsEqual(this.newRoute[this.newRoute.length-1],e[n])||this.newRoute.push(e[n]);this.currentStepSize=this.maxStepSize}}appendOriginalRouteSlice(e,n){const o=this.pathSegments.findIndex(i=>e>=i.startDistance&&e<=i.endDistance);if(o===-1)throw new Error(`Could not find path segment containing distance ${e}`);for(let i=o+1;i<=n&&i<this.inputRoute.route.length;i++){const r=this.inputRoute.route[i],s=this.newRoute[this.newRoute.length-1];s&&this.arePointsEqual(s,r)||this.newRoute.push({...r})}}moveHead(e){this.lastHeadMoveDistance=e,this.headDistanceAlongPath=Math.min(this.headDistanceAlongPath+e,this.totalPathLength)}stepBackAndReduceStepSize(){this.headDistanceAlongPath=Math.max(this.tailDistanceAlongPath,this.headDistanceAlongPath-this.lastHeadMoveDistance),this.currentStepSize=Math.max(this.minStepSize,this.currentStepSize*this.STEP_SIZE_REDUCTION_FACTOR)}_step(){const e=this.tailDistanceAlongPath>=this.totalPathLength,n=this.headDistanceAlongPath>=this.totalPathLength;if(e){const h=this.inputRoute.route[this.inputRoute.route.length-1];return this.newRoute.length!==0&&this.arePointsEqual(this.newRoute[this.newRoute.length-1],h)||this.newRoute.push(h),void(this.solved=!0)}if(n){const h=this.getPointAtDistance(this.tailDistanceAlongPath),d=this.inputRoute.route[this.inputRoute.route.length-1],p=this.find45DegreePath(h,d);if(p)return this.addPathToResult(p),void(this.solved=!0);const m=this.lastValidPath?this.lastValidPathHeadDistance:this.tailDistanceAlongPath;return this.lastValidPath&&(this.addPathToResult(this.lastValidPath),this.lastValidPath=null),this.getNearestIndexForDistance(m),this.appendOriginalRouteSlice(m,this.inputRoute.route.length-1),this.tailDistanceAlongPath=this.totalPathLength,this.headDistanceAlongPath=this.totalPathLength,void(this.solved=!0)}this.moveHead(this.currentStepSize);const o=this.getPointAtDistance(this.tailDistanceAlongPath),i=this.getPointAtDistance(this.headDistanceAlongPath),r=this.getNearestIndexForDistance(this.tailDistanceAlongPath),s=this.getNearestIndexForDistance(this.headDistanceAlongPath);let a=!1,A=-1;for(let h=r;h<s;h++)if(h+1<this.inputRoute.route.length&&this.inputRoute.route[h].z!==this.inputRoute.route[h+1].z){a=!0;const d=h;A=this.pathSegments[d].startDistance;break}if(a&&this.lastHeadMoveDistance>this.minStepSize)return void this.stepBackAndReduceStepSize();let c=!1,l=-1,u=-1;for(let h=r+1;h<=s;h++)if(this.jumperPadPointIndices.has(h)){c=!0,l=h,u=h>0&&h-1<this.pathSegments.length?this.pathSegments[h-1].endDistance:this.pathSegments[0]?.startDistance??0;break}if(c&&this.lastHeadMoveDistance>this.minStepSize)return void this.stepBackAndReduceStepSize();if(c&&l>=0){const h=this.inputRoute.route[l];this.lastValidPath&&(this.addPathToResult(this.lastValidPath),this.lastValidPath=null);const d=this.newRoute[this.newRoute.length-1];return d&&d.x===h.x&&d.y===h.y||this.newRoute.push({x:h.x,y:h.y,z:h.z}),this.currentStepSize=this.maxStepSize,this.tailDistanceAlongPath=u,this.headDistanceAlongPath=this.tailDistanceAlongPath,this.lastValidPath=null,void(this.lastValidPathHeadDistance=this.tailDistanceAlongPath)}if(a&&A>0){const h=this.lastValidPath?this.lastValidPathHeadDistance:this.tailDistanceAlongPath,d=this.getNearestIndexForDistance(A)+1,p=this.inputRoute.route[d],m={x:p.x,y:p.y};this.lastValidPath&&(this.addPathToResult(this.lastValidPath),this.lastValidPath=null);const _=this.newRoute[this.newRoute.length-1],f={x:m.x,y:m.y,z:_.z};if(!this.arePointsEqual(_,f)){const C=this.find45DegreePath(_,f);C?this.addPathToResult(C):this.appendOriginalRouteSlice(h,d-1)}this.newVias.push(m),this.newRoute.push({x:m.x,y:m.y,z:p.z}),this.currentStepSize=this.maxStepSize;const I=this.pathSegments.findIndex(C=>C.start===p);if(I!==-1)this.tailDistanceAlongPath=this.pathSegments[I].startDistance,this.headDistanceAlongPath=this.tailDistanceAlongPath,this.lastValidPath=null,this.lastValidPathHeadDistance=this.tailDistanceAlongPath;else if(d<this.inputRoute.route.length){if(d===this.inputRoute.route.length-1)return void(this.solved=!0);console.warn("Fallback used for tailDistanceAlongPath after layer change");const C=this.pathSegments.find(y=>y.start===this.inputRoute.route[d]);C?(this.tailDistanceAlongPath=C.startDistance,this.headDistanceAlongPath=this.tailDistanceAlongPath,this.lastValidPath=null,this.lastValidPathHeadDistance=this.tailDistanceAlongPath):(console.error(`[${this.inputRoute.connectionName}] Could not find segment start after layer change. Path might be incomplete.
            Index sought: ${d}, Point: (${this.inputRoute.route[d].x.toFixed(3)}, ${this.inputRoute.route[d].y.toFixed(3)}, z=${this.inputRoute.route[d].z})
            Route Length: ${this.inputRoute.route.length}, Path Segments: ${this.pathSegments.length}`),this.solved=!0)}else console.warn("Layer change occurred at the end of the path."),this.solved=!0;return}const g=this.find45DegreePath(o,i);if(!g&&this.lastHeadMoveDistance>this.minStepSize)this.stepBackAndReduceStepSize();else{if(!g&&!this.lastValidPath){const h=this.getPointAtDistance(this.tailDistanceAlongPath);this.tailDistanceAlongPath+=this.minStepSize,this.moveHead(this.minStepSize);const d=this.getNearestIndexForDistance(this.tailDistanceAlongPath),p=this.inputRoute.route[d],m=this.inputRoute.route[this.inputRoute.route.length-1];return void(this.arePointsEqual(h,p)||this.arePointsEqual(p,m)||this.newRoute.push(p))}if(g)return this.lastValidPath=g,void(this.lastValidPathHeadDistance=this.headDistanceAlongPath);this.lastValidPath&&(this.addPathToResult(this.lastValidPath),this.lastValidPath=null,this.tailDistanceAlongPath=this.lastValidPathHeadDistance,this.moveHead(this.minStepSize))}}visualize(){const e=this.getVisualsForNewRouteAndObstacles(),n=this.getPointAtDistance(this.tailDistanceAlongPath),o=this.getPointAtDistance(this.headDistanceAlongPath);e.points.push({x:n.x,y:n.y,color:"yellow",label:["Tail",`z: ${n.z}`].join(`
`)}),e.points.push({x:o.x,y:o.y,color:"orange",label:["Head",`z: ${o.z}`].join(`
`)});const i=this.getPointAtDistance(this.headDistanceAlongPath+this.currentStepSize);e.points.push({x:i.x,y:i.y,color:"red",label:["Tentative Head",`z: ${i.z}`].join(`
`)});let r=0;for(;r<this.totalPathLength;){const s=this.getPointAtDistance(r);e.circles.push({center:{x:s.x,y:s.y},radius:.05,fill:"rgba(100, 100, 100, 0.5)"}),r+=this.totalPathLength/20}if(this.lastValidPath&&this.lastValidPath.length>1)for(let s=0;s<this.lastValidPath.length-1;s++)e.lines.push({points:[{x:this.lastValidPath[s].x,y:this.lastValidPath[s].y},{x:this.lastValidPath[s+1].x,y:this.lastValidPath[s+1].y}],strokeColor:"rgba(0, 255, 255, 0.9)",strokeDash:"3, 3"});return e}},pZn=class extends yr{getSolverName(){return"MultiSimplifiedPathSolver"}simplifiedHdRoutes;currentUnsimplifiedHdRouteIndex=0;activeSubSolver=null;unsimplifiedHdRoutes;otherHdRoutes;obstacles;connMap;colorMap;outline;minBoardEdgeClearance;defaultViaDiameter;useTraceWidthAwareClearance;constructor(e){super(),this.MAX_ITERATIONS=1e8,this.unsimplifiedHdRoutes=e.unsimplifiedHdRoutes,this.otherHdRoutes=e.otherHdRoutes??[];const n=Math.max(2,...[...e.unsimplifiedHdRoutes,...this.otherHdRoutes].flatMap(o=>o.route.map(i=>i.z+1)))||2;this.obstacles=c7(e.obstacles,n),this.connMap=e.connMap||new TD({}),this.colorMap=e.colorMap||{},this.outline=e.outline,this.minBoardEdgeClearance=e.minBoardEdgeClearance??.2,this.defaultViaDiameter=e.defaultViaDiameter??.3,this.useTraceWidthAwareClearance=e.useTraceWidthAwareClearance??!1,this.simplifiedHdRoutes=[]}_step(){const e=this.unsimplifiedHdRoutes[this.currentUnsimplifiedHdRouteIndex];if(!this.activeSubSolver)return e?(this.activeSubSolver=new hZn({inputRoute:e,otherHdRoutes:this.otherHdRoutes.concat(this.unsimplifiedHdRoutes.slice(this.currentUnsimplifiedHdRouteIndex+1).concat(this.simplifiedHdRoutes)),obstacles:this.obstacles,connMap:this.connMap,colorMap:this.colorMap,outline:this.outline,minBoardEdgeClearance:this.minBoardEdgeClearance,useTraceWidthAwareClearance:this.useTraceWidthAwareClearance}),void this.currentUnsimplifiedHdRouteIndex++):void(this.solved=!0);this.activeSubSolver.step(),this.activeSubSolver.solved&&(this.simplifiedHdRoutes.push(this.activeSubSolver.simplifiedRoute),this.activeSubSolver=null)}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const e={lines:[],points:[],circles:[],rects:[],coordinateSystem:"cartesian",title:"Multi Simplified Path Solver"};for(const n of this.unsimplifiedHdRoutes)if(!this.simplifiedHdRoutes.some(o=>o.connectionName===n.connectionName)){for(let o=0;o<n.route.length-1;o++)e.lines.push({points:[{x:n.route[o].x,y:n.route[o].y},{x:n.route[o+1].x,y:n.route[o+1].y}],strokeColor:n.route[o].z===1?"rgba(0, 0, 255, 0.4)":"rgba(255, 0, 0, 0.4)",strokeWidth:.15,strokeDash:n.route[o].z===1?[.5,.5]:void 0});for(const o of n.vias||[])e.circles.push({center:o,radius:(n.viaDiameter??this.defaultViaDiameter)/2,fill:"rgba(0, 0, 255, 0.4)"})}for(const n of this.simplifiedHdRoutes){const o=this.colorMap?.[n.connectionName]||"rgba(128, 128, 128, 0.8)";for(let i=0;i<n.route.length-1;i++)e.lines.push({points:[{x:n.route[i].x,y:n.route[i].y},{x:n.route[i+1].x,y:n.route[i+1].y}],strokeWidth:.15,strokeColor:o,strokeDash:n.route[i].z===1?[.5,.5]:void 0,step:1});for(const i of n.vias||[])e.circles.push({center:i,radius:n.viaDiameter/2,fill:"rgba(0, 0, 255, 0.5)",step:1})}for(const n of this.unsimplifiedHdRoutes){for(let o=0;o<n.route.length-1;o++)e.lines.push({points:[{x:n.route[o].x,y:n.route[o].y},{x:n.route[o+1].x,y:n.route[o+1].y}],strokeWidth:.15,strokeColor:"rgba(255, 0, 0, 0.2)",strokeDash:[.5,.5],step:0,layer:`z${n.route[o].z.toString()}`});for(const o of n.vias)e.circles.push({center:{x:o.x,y:o.y},radius:n.viaDiameter/2,fill:"rgba(255, 0, 0, 0.2)",step:0})}for(const n of this.obstacles)e.rects.push({center:n.center,width:n.width,height:n.height,fill:n.layers?.includes("top")?"rgba(255, 0, 0, 0.3)":n.layers?.includes("bottom")?"rgba(0, 0, 255, 0.3)":"rgba(128, 128, 128, 0.3)"});if(this.currentUnsimplifiedHdRouteIndex<this.unsimplifiedHdRoutes.length){const n=this.unsimplifiedHdRoutes[this.currentUnsimplifiedHdRouteIndex];n.route.length>0&&e.circles.push({center:{x:n.route[0].x,y:n.route[0].y},radius:.2,fill:"yellow",label:"Current"})}return e}},mZn=(t,e)=>{for(let n=0;n<t.route.length-1;n++){const o=t.route[n],i=t.route[n+1];if(o.z===i.z||o.x!==e.x||o.y!==e.y||i.x!==e.x||i.y!==e.y)continue;let r=n;for(;r>0&&t.route[r-1].x===e.x&&t.route[r-1].y===e.y;)r--;let s=n+1;for(;s<t.route.length-1&&t.route[s+1].x===e.x&&t.route[s+1].y===e.y;)s++;if(r===0||s===t.route.length-1)return!0}return!1},Z7e=(t,e,n)=>n?.get(e.connectionName)??t.idToNetMap[e.connectionName]??(e.rootConnectionName?t.idToNetMap[e.rootConnectionName]:void 0),_Zn=(t,e,n)=>{for(const o of e.connectedTo)if(o===n.net||t.idToNetMap[o]===n.net||t.areIdsConnected(o,n.net))return!0;return!1},fZn=(t,e,n)=>{const o=n.mergedViaHdRoutes[t.routeIndex];if(!o)throw new Error(`SameNetViaMergerSolver could not find route for via at index ${t.routeIndex}`);const i=new Set;for(let r=1;r<o.route.length;r++){const s=o.route[r-1],a=o.route[r];s.z!==a.z&&s.x===t.x&&s.y===t.y&&a.x===t.x&&a.y===t.y&&(i.add(s.z),i.add(a.z))}if(i.size===0)throw new Error(`SameNetViaMergerSolver could not find transition layers for via at (${t.x}, ${t.y})`);for(const r of i){const s=o.traceThickness,a={x:t.x,y:t.y,z:r},A={x:e.x,y:e.y,z:r};if(a.x===A.x&&a.y===A.y)continue;const c=n.hdRouteSHI.getConflictingRoutesForSegment(a,A,s/2);for(const{conflictingRoute:h,distance:d}of c)if(h.connectionName!==o.connectionName&&Z7e(n.connMap,h,n.netByConnectionName)!==t.net&&d<s/2+h.traceThickness/2)return!1;const l={centerX:(a.x+A.x)/2,centerY:(a.y+A.y)/2,width:Math.abs(a.x-A.x),height:Math.abs(a.y-A.y)},u=s/2+.1,g=n.obstacleSHI.searchArea(l.centerX,l.centerY,l.width+2*u,l.height+2*u);for(const h of g){if(!h.__zLayers)throw new Error(`SameNetViaMergerSolver found obstacle without zLayers near via at (${t.x}, ${t.y})`);if(h.__zLayers.includes(r)&&!_Zn(n.connMap,h,t)&&K8(a,A,h)<u)return!1}}return!0},jft=class extends yr{constructor(e){if(super(),this.input=e,!e.connMap)throw new Error("SameNetViaMergerSolver requires connMap");this.input={...e,obstacles:c7(e.obstacles,e.layerCount)},this.MAX_ITERATIONS=1e6,this.inputHdRoutes=this.input.inputHdRoutes,this.mergedViaHdRoutes=structuredClone(this.inputHdRoutes),this.unprocessedRoutes=[...this.input.inputHdRoutes],this.colorMap=this.input.colorMap,this.outline=this.input.outline,this.obstacles=this.input.obstacles,this.obstacleSHI=new OD("flatbush",this.input.obstacles),this.hdRouteSHI=this.createHdRouteSpatialIndex(),this.vias=[],this.offendingVias=[],this.connMap=e.connMap,this.netByConnectionName=e.netByConnectionName,this.viasByNet=new Map,this.rebuildVias()}input;getSolverName(){return"SameNetViaMergerSolver"}inputHdRoutes;mergedViaHdRoutes;unprocessedRoutes;vias;offendingVias;currentViaRoutes=[];connMap;colorMap;outline;obstacles;viasByNet;netByConnectionName;obstacleSHI;hdRouteSHI;createHdRouteSpatialIndex(){return new oB([...this.mergedViaHdRoutes,...this.input.otherHdRoutes??[]])}rebuildVias(){this.vias=[],this.viasByNet=new Map;const e=(n,o,i)=>{if(n.vias.length===0)return;const r=i?((s,a,A)=>{const c=Z7e(s,a,A);if(!c)throw new Error(`SameNetViaMergerSolver could not find net for route "${a.connectionName}"`);return c})(this.connMap,n,this.netByConnectionName):Z7e(this.connMap,n,this.netByConnectionName);if(r)for(let s=0;s<n.vias.length;s++){const a=n.vias[s],A=[...new Set(n.route.map(u=>u.z))];if(A.length===0)throw new Error(`SameNetViaMergerSolver found via on route "${n.connectionName}" with no route points`);const c={x:a.x,y:a.y,diameter:n.viaDiameter,net:r,layers:A,routeIndex:o,mutable:i&&!(this.input.preserveRouteEndpoints&&mZn(n,a))};this.vias.push(c);const l=this.viasByNet.get(c.net);l?l.push(c):this.viasByNet.set(c.net,[c])}};for(let n=0;n<this.mergedViaHdRoutes.length;n++)e(this.mergedViaHdRoutes[n],n,!0);for(let n=0;n<(this.input.otherHdRoutes?.length??0);n++)e(this.input.otherHdRoutes[n],this.mergedViaHdRoutes.length+n,!1)}getViaKey(e){return[e.mutable?"mutable":"immutable",e.routeIndex,e.x,e.y,e.layers.join(","),e.net].join(":")}dedupeRouteVias(e){const n=new Set;e.vias=e.vias.filter(o=>{const i=`${o.x}:${o.y}`;return!n.has(i)&&(n.add(i),!0)})}getOffendingViaGroupsBatch(){const e=[],n=new Set,o=[];for(const i of this.viasByNet.values()){if(i.length<2)continue;const r=Math.max(1e-6,...i.map(a=>a.diameter)),s=new Map;for(let a=0;a<i.length;a++){const A=i[a],c=`${Math.floor(A.x/r)}:${Math.floor(A.y/r)}`,l=s.get(c);l?l.push(a):s.set(c,[a])}for(let a=0;a<i.length;a++){const A=i[a],c=Math.floor(A.x/r),l=Math.floor(A.y/r),u=Math.ceil(2.5),g=[];for(let h=-u;h<=u;h++)for(let d=-u;d<=u;d++){const p=s.get(`${c+h}:${l+d}`);if(p)for(const m of p){if(m===a)continue;const _=i[m];if(!_.mutable)continue;const f=A.x-_.x,I=A.y-_.y,C=f*f+I*I,y=A.diameter/2+_.diameter/2,x=2.5*y;C!==0?(C<=y*y||C<=x*x&&fZn(_,A,{connMap:this.connMap,mergedViaHdRoutes:this.mergedViaHdRoutes,hdRouteSHI:this.hdRouteSHI,obstacleSHI:this.obstacleSHI,netByConnectionName:this.netByConnectionName}))&&g.push(_):A.mutable||g.push(_)}}g.length>0&&o.push({keep:A,remove:g})}}o.sort((i,r)=>r.remove.length!==i.remove.length?r.remove.length-i.remove.length:i.keep.mutable!==r.keep.mutable?i.keep.mutable?1:-1:r.keep.layers.length!==i.keep.layers.length?r.keep.layers.length-i.keep.layers.length:i.keep.routeIndex-r.keep.routeIndex);for(const i of o){const r=this.getViaKey(i.keep);if(n.has(r))continue;const s=i.remove.filter(a=>!n.has(this.getViaKey(a)));if(s.length!==0){e.push({keep:i.keep,remove:s}),n.add(r);for(const a of s)n.add(this.getViaKey(a))}}return e}moveViaTo(e,n,o=!0){if(!e.mutable)throw new Error("SameNetViaMergerSolver cannot mutate an immutable via anchor");const i=this.mergedViaHdRoutes[e.routeIndex];if(!i)throw new Error(`SameNetViaMergerSolver could not find route for via at index ${e.routeIndex}`);const r=i.route,s=new Set;let a=!1;for(let A=r.length-1;A>=1;A--){const c=r[A-1],l=r[A];if(c.z===l.z||c.x!==e.x||c.y!==e.y||l.x!==e.x||l.y!==e.y)continue;let u=A-1;for(;u>0&&r[u-1].x===e.x&&r[u-1].y===e.y;)u--;let g=A;for(;g<r.length-1&&r[g+1].x===e.x&&r[g+1].y===e.y;)g++;for(let h=u;h<=g;h++)s.add(h)}if(s.size===0)throw new Error(`SameNetViaMergerSolver could not find route transition for via at (${e.x}, ${e.y}) on route "${i.connectionName}"`);for(const A of s){const c=r[A];r[A]={...c,x:n.x,y:n.y}}if(i.vias=i.vias.flatMap(A=>A.x!==e.x||A.y!==e.y?A:(a=!0,n.mutable?[{x:n.x,y:n.y}]:[])),!a)throw new Error(`SameNetViaMergerSolver could not find via at (${e.x}, ${e.y}) on route "${i.connectionName}"`);this.dedupeRouteVias(i),o&&this.rebuildVias()}_step(){const e=this.getOffendingViaGroupsBatch();if(e.length===0)return void(this.solved=!0);let n=0;for(const o of e)for(const i of o.remove)this.moveViaTo(i,o.keep,!1),n++;this.rebuildVias(),this.hdRouteSHI=this.createHdRouteSpatialIndex(),this.stats.mergedViaGroups=e.length,this.stats.mergedViaCount=n}getMergedViaHdRoutes(){return this.mergedViaHdRoutes}visualize(){const e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Same Net Via Merger Solver"};for(const n of this.input.obstacles){if(!n.__zLayers)throw new Error("SameNetViaMergerSolver found obstacle without zLayers while visualizing");let o="rgba(128, 128, 128, 0.2)";const i=n.__zLayers.includes(0),r=n.__zLayers.includes(1);i&&r?o="rgba(128, 0, 128, 0.2)":i?o="rgba(255, 0, 0, 0.2)":r&&(o="rgba(0, 0, 255, 0.2)"),e.rects.push({center:n.center,width:n.width,height:n.height,fill:o,label:`Obstacle (Z: ${n.__zLayers?.join(", ")})`})}for(const n of this.mergedViaHdRoutes){if(n.route.length===0)continue;const o=this.input.colorMap[n.connectionName];if(!o)throw new Error(`SameNetViaMergerSolver could not find color for route "${n.connectionName}"`);for(let i=0;i<n.route.length-1;i++){const r=n.route[i],s=n.route[i+1];r.z===s.z&&e.lines.push({points:[{x:r.x,y:r.y},{x:s.x,y:s.y}],strokeColor:r.z===0?"rgba(255, 0, 0, 0.5)":"rgba(0, 0, 255, 0.5)",strokeWidth:n.traceThickness,label:`${n.connectionName} (z=${r.z})`})}for(const i of n.vias)e.circles.push({center:{x:i.x,y:i.y},radius:n.viaDiameter/2,fill:"rgba(255, 0, 255, 0.5)",label:`${n.connectionName} via`});if(n.jumpers&&n.jumpers.length>0){const i=_x(n.jumpers,{color:o,label:n.connectionName});if(!i.rects||!i.lines)throw new Error(`SameNetViaMergerSolver expected jumper graphics for route "${n.connectionName}"`);e.rects.push(...i.rects),e.lines.push(...i.lines)}}return e}},IZn={getConflictingRoutesForSegment:()=>[],getConflictingRoutesNearPoint:()=>[]},Py=1e-6,Xz=(t,e)=>{const n=`${t.x}:${t.y}:${t.z}`,o=`${e.x}:${e.y}:${e.z}`;return n<o?`${n}|${o}`:`${o}|${n}`},$ft=t=>{const e=new Set;for(let n=1;n<t.route.length;n++){const o=t.route[n-1],i=t.route[n];o.z===i.z&&e.add(Xz(o,i))}return e},e6e=t=>t.filter((e,n)=>{const o=t[n-1];return!o||e.x!==o.x||e.y!==o.y||e.z!==o.z}),t6e=t=>{const e=[],n=new Set;for(let o=1;o<t.length;o++){const i=t[o-1],r=t[o];if(i.z===r.z||i.toNextSegmentType==="through_obstacle")continue;if(i.x!==r.x||i.y!==r.y)throw new Error(`CrossingViaReductionSolver found a layer transition without a via at route point ${o}`);const s=`${r.x}:${r.y}`;n.has(s)||(n.add(s),e.push({x:r.x,y:r.y}))}return e},n6e=t=>{const e=[t.connectionName];return t.rootConnectionName&&e.push(t.rootConnectionName),e},o6e=(t,e,n)=>{const o=n6e(t),i=n6e(e);return o.some(r=>i.some(s=>r===s||n.areIdsConnected(r,s)))},CZn=(t,e,n)=>{const o=n6e(e);return t.connectedTo.some(i=>o.some(r=>i===r||n.areIdsConnected(i,r)))},qft=t=>{let e=0;for(let n=1;n<t.length;n++)e+=Math.hypot(t[n].x-t[n-1].x,t[n].y-t[n-1].y);return e},Xft=(t,e)=>{const n=qft(t);if(e<=Py||e>=n-Py)return null;let o=0;for(let i=1;i<t.length;i++){const r=t[i-1],s=t[i],a=Math.hypot(s.x-r.x,s.y-r.y);if(o+a<e-Py){o+=a;continue}const A=e-o;if(A<=Py)return{prefix:t.slice(0,i).map(u=>({...u})),suffix:t.slice(i-1).map(u=>({...u})),point:{...r}};if(a-A<=Py)return{prefix:t.slice(0,i+1).map(u=>({...u})),suffix:t.slice(i).map(u=>({...u})),point:{...s}};const c=A/a,l={x:r.x+(s.x-r.x)*c,y:r.y+(s.y-r.y)*c,z:r.z};return{prefix:[...t.slice(0,i),l].map(u=>({...u})),suffix:[l,...t.slice(i)].map(u=>({...u})),point:l}}return null},yZn=(t,e,n,o)=>{const i=DD(t,e,n,o);if(!i)return null;const r=Math.hypot(i.x-t.x,i.y-t.y),s=Math.hypot(i.x-e.x,i.y-e.y),a=Math.hypot(i.x-n.x,i.y-n.y),A=Math.hypot(i.x-o.x,i.y-o.y);return Math.min(r,s,a,A)<=Py?null:r},Zft=t=>t.points.some(e=>e.insideJumperPad||e.toNextSegmentType),e1t=({sections:t,sectionIndex:e,side:n})=>{const o=t[e],i=n==="start"?t[e-1]:t[e+1];if(!i)return null;const r=n==="start"?o.points[0]:o.points.at(-1),s=n==="start"?i.points.at(-1):i.points[0];return r.x!==s.x||r.y!==s.y?null:i.z},t1t=({sections:t,sectionIndex:e,targetZ:n,side:o})=>e1t({sections:t,sectionIndex:e,side:o})===n,n1t=({baseIndexes:t,otherCandidateRoutes:e,ignoredConnectionNames:n,originalRouteSegmentKeys:o})=>{const i=new oB([...e]);return{getConflictingRoutesForSegment:(r,s,a)=>{const A=o.has(Xz(r,s));return[...A?[]:t.mutableRoutes.getConflictingRoutesForSegment(r,s,a).filter(({conflictingRoute:c})=>!n.has(c.connectionName)),...A?[]:t.immutableRoutes?.getConflictingRoutesForSegment(r,s,a)??[],...i.getConflictingRoutesForSegment(r,s,a)]},getConflictingRoutesNearPoint:(r,s)=>[...t.mutableRoutes.getConflictingRoutesNearPoint(r,s).filter(({conflictingRoute:a})=>!n.has(a.connectionName)),...t.immutableRoutes?.getConflictingRoutesNearPoint(r,s)??[],...i.getConflictingRoutesNearPoint(r,s)]}},xZn=class extends yr{input;obstacleSHI;traceMargin;obstacleMargin;reducedHdRoutes;getSolverName(){return"CrossingViaReductionSolver"}constructor(e){super(),this.input={...e,obstacles:c7(e.obstacles,e.layerCount)},this.traceMargin=e.traceMargin??.1,this.obstacleMargin=e.obstacleMargin??.15,this.reducedHdRoutes=structuredClone([...e.inputHdRoutes]),this.obstacleSHI=new OD("flatbush",[...this.input.obstacles]),this.MAX_ITERATIONS=1e6}collapseDetourSection({route:e,section:n,targetZ:o}){const i=n.points.map(s=>({...s,z:o})),r=e6e([...e.route.slice(0,n.startIndex).map(s=>({...s})),...i,...e.route.slice(n.endIndex+1).map(s=>({...s}))]);return{...e,route:r,vias:t6e(r)}}relocateTransitionVia({route:e,section:n,targetZ:o,side:i,newViaDistance:r}){const s=Xft(n.points,r);if(!s)return null;const a=i==="start"?o:n.z,A=i==="start"?n.z:o,c=[...s.prefix.map(u=>({...u,z:a})),...s.suffix.map(u=>({...u,z:A}))],l=e6e([...e.route.slice(0,n.startIndex).map(u=>({...u})),...c,...e.route.slice(n.endIndex+1).map(u=>({...u}))]);return{route:{...e,route:l,vias:t6e(l)},relocatedVia:{x:s.point.x,y:s.point.y}}}relocateTransitionVias({route:e,sections:n,crossingGroups:o,detourZ:i,detourTraceThickness:r}){const s=new Map;for(const u of o){const g=s.get(u.transitionSectionIndex)??[];g.push(u),s.set(u.transitionSectionIndex,g)}const a=[],A=[],c=e.viaDiameter/2+r/2+this.traceMargin+Py;for(const[u,g]of s){if(g.length!==1)return null;const h=n[u],d=g[0];if(!t1t({sections:n,sectionIndex:u,targetZ:i,side:d.side}))return null;const p=d.side==="start"?Math.max(...d.crossingDistances)+c:Math.min(...d.crossingDistances)-c,m=Xft(h.points,p);if(!m)return null;const _=d.side==="start"?i:h.z,f=d.side==="start"?h.z:i;a.push({section:h,points:[...m.prefix.map(I=>({...I,z:_})),...m.suffix.map(I=>({...I,z:f}))]}),A.push({x:m.point.x,y:m.point.y})}let l=e.route.map(u=>({...u}));for(const u of a.sort((g,h)=>h.section.startIndex-g.section.startIndex))l=[...l.slice(0,u.section.startIndex),...u.points,...l.slice(u.section.endIndex+1)];return l=e6e(l),{route:{...e,route:l,vias:t6e(l)},relocatedVias:A}}routeIsClear(e,n,o){for(const i of qz(e)){for(let r=1;r<i.points.length;r++){const s=i.points[r-1],a=i.points[r];if(!o.has(Xz(s,a))&&this.input.outline&&$z({start:s,end:a,polygon:[...this.input.outline],margin:e.traceThickness/2}))return!1}if(!GD({currentSection:i,targetZ:i.z,route:e,hdRouteSHI:n,obstacleSHI:this.obstacleSHI,connMap:this.input.connMap,defaultTraceThickness:e.traceThickness,obstacleMargin:this.obstacleMargin,traceMargin:this.traceMargin,shouldCheckStaticGeometryForSegment:(r,s)=>!o.has(Xz(r,s))}))return!1}return!0}relocatedViaIsClear(e,n,o){const i=e.viaDiameter/2;for(let a=0;a<this.input.layerCount;a++)if(o.getConflictingRoutesNearPoint({...n,z:a},i+this.traceMargin).some(({conflictingRoute:A})=>!o6e(e,A,this.input.connMap)))return!1;const r=i+this.obstacleMargin,s=this.obstacleSHI.searchArea(n.x,n.y,2*r,2*r);for(const a of s)if(!CZn(a,e,this.input.connMap)&&K8(n,n,a)<r)return!1;if(this.input.outline){for(let a=0;a<this.input.outline.length;a++)if(wc(n,this.input.outline[a],this.input.outline[(a+1)%this.input.outline.length])<i+this.traceMargin)return!1}return!0}changedSectionsAreStaticallyClear(e,n){for(const o of qz(e))if(o.points.some((i,r)=>{const s=o.points[r-1];return s!==void 0&&!n.has(Xz(s,i))})){if(this.input.outline){for(let i=1;i<o.points.length;i++)if($z({start:o.points[i-1],end:o.points[i],polygon:[...this.input.outline],margin:e.traceThickness/2}))return!1}if(!GD({currentSection:o,targetZ:o.z,route:e,hdRouteSHI:IZn,obstacleSHI:this.obstacleSHI,connMap:this.input.connMap,defaultTraceThickness:e.traceThickness,obstacleMargin:Math.min(this.obstacleMargin,.1),traceMargin:this.traceMargin}))return!1}return!0}candidateIsClear(e,n){const o=[{routeIndex:e.detourRouteIndex,route:e.detourRoute},...e.transitionUpdates],i=new Set(o.map(({routeIndex:a})=>this.reducedHdRoutes[a].connectionName)),r=$ft(this.reducedHdRoutes[e.detourRouteIndex]),s=n1t({baseIndexes:n,otherCandidateRoutes:e.transitionUpdates.map(({route:a})=>a),ignoredConnectionNames:i,originalRouteSegmentKeys:r});if(this.stats.candidateClearanceChecks=(this.stats.candidateClearanceChecks??0)+1,!this.routeIsClear(e.detourRoute,s,r))return!1;for(const a of e.transitionUpdates){const A=$ft(this.reducedHdRoutes[a.routeIndex]),c=n1t({baseIndexes:n,otherCandidateRoutes:o.filter(({routeIndex:l})=>l!==a.routeIndex).map(({route:l})=>l),ignoredConnectionNames:i,originalRouteSegmentKeys:A});if(!this.routeIsClear(a.route,c,A)||a.relocatedVias.some(l=>!this.relocatedViaIsClear(a.route,l,c)))return!1}return this.changedSectionsAreStaticallyClear(e.detourRoute,r)}candidateRoutesHaveNoExternalCopperConflicts(e,n){const o=[e.detourRoute,...e.transitionUpdates.map(({route:s})=>s)],i=new Set(o.map(({connectionName:s})=>s)),r=[n.mutableRoutes,...n.immutableRoutes?[n.immutableRoutes]:[]];for(const s of o)for(const a of qz(s))for(let A=1;A<a.points.length;A++){const c=a.points[A-1],l=a.points[A];for(const u of r)if(u.getConflictingRoutesForSegment(c,l,s.traceThickness/2+this.traceMargin).some(({conflictingRoute:g})=>!i.has(g.connectionName)&&!o6e(s,g,this.input.connMap)))return!1}return!0}buildTransitionSegmentIndex(e,n){const o=[];for(let r=0;r<this.reducedHdRoutes.length;r++){if(this.reducedHdRoutes[r].jumpers?.length)continue;const s=e[r];for(let a=0;a<s.length;a++){const A=s[a];if(!Zft(A))for(const c of["start","end"]){const l=e1t({sections:s,sectionIndex:a,side:c});if(l===null||l===A.z||!n.has(`${A.z}:${l}`))continue;let u=0;for(let g=1;g<A.points.length;g++){const h=A.points[g-1],d=A.points[g],p=Math.hypot(d.x-h.x,d.y-h.y);p>Py&&o.push({routeIndex:r,sectionIndex:a,side:c,adjacentZ:l,start:h,end:d,distanceFromSectionStart:u}),u+=p}}}}if(this.stats.transitionSegmentsIndexed=(this.stats.transitionSegmentsIndexed??0)+o.length,o.length===0)return null;const i=new Kft(o.length);for(const r of o)i.insert(r,Math.min(r.start.x,r.end.x),Math.min(r.start.y,r.end.y),Math.max(r.start.x,r.end.x),Math.max(r.start.y,r.end.y));return i.finish(),i}getIndexedCrossingGroups({detourRouteIndex:e,detourSection:n,targetZ:o,transitionSegmentIndex:i}){const r=new Map;for(let s=1;s<n.points.length;s++){const a=n.points[s-1],A=n.points[s];if(Math.hypot(A.x-a.x,A.y-a.y)<=Py)continue;this.stats.indexedDetourSegmentQueries=(this.stats.indexedDetourSegmentQueries??0)+1;const c=i.search(Math.min(a.x,A.x)-Py,Math.min(a.y,A.y)-Py,Math.max(a.x,A.x)+Py,Math.max(a.y,A.y)+Py);for(const l of c){if(l.routeIndex===e||l.start.z!==o||l.adjacentZ!==n.z)continue;this.stats.exactSegmentIntersectionChecks=(this.stats.exactSegmentIntersectionChecks??0)+1;const u=yZn(l.start,l.end,a,A);if(u===null)continue;const g=`${l.routeIndex}:${l.sectionIndex}:${l.side}`;let h=r.get(g);h||(h={transitionRouteIndex:l.routeIndex,transitionSectionIndex:l.sectionIndex,side:l.side,crossingDistances:[]},r.set(g,h)),h.crossingDistances.push(l.distanceFromSectionStart+u)}}return[...r.values()].sort((s,a)=>s.transitionRouteIndex!==a.transitionRouteIndex?s.transitionRouteIndex-a.transitionRouteIndex:s.transitionSectionIndex!==a.transitionSectionIndex?s.transitionSectionIndex-a.transitionSectionIndex:s.side===a.side?0:s.side==="start"?-1:1)}tryCreateCandidate({detourRouteIndex:e,detourSection:n,targetZ:o,transitionRouteIndex:i,transitionSection:r,transitionSections:s,transitionSectionIndex:a,side:A,crossingDistances:c,baseClearanceIndexes:l}){if(!t1t({sections:s,sectionIndex:a,targetZ:n.z,side:A}))return null;const u=this.reducedHdRoutes[e],g=this.reducedHdRoutes[i];if(c.length===0)return null;const h=g.viaDiameter/2+u.traceThickness/2+this.traceMargin+Py,d=A==="start"?Math.max(...c)+h:Math.min(...c)-h,p=this.relocateTransitionVia({route:g,section:r,targetZ:n.z,side:A,newViaDistance:d});if(!p)return null;const m=this.collapseDetourSection({route:u,section:n,targetZ:o});if(u.vias.length+g.vias.length-m.vias.length-p.route.vias.length!==2)return null;const _={detourRouteIndex:e,detourRoute:m,transitionUpdates:[{routeIndex:i,route:p.route,relocatedVias:[p.relocatedVia]}]};return this.candidateIsClear(_,l)?_:null}tryCreateMultiCrossingCandidate({detourRouteIndex:e,detourSection:n,targetZ:o,crossingGroups:i,sectionsByRoute:r,baseClearanceIndexes:s}){if(i.length<2)return null;const a=this.reducedHdRoutes[e],A=[],c=new Map;for(const g of i){const h=c.get(g.transitionRouteIndex)??[];h.push(g),c.set(g.transitionRouteIndex,h)}for(const[g,h]of c){const d=this.reducedHdRoutes[g],p=this.relocateTransitionVias({route:d,sections:r[g],crossingGroups:h,detourZ:n.z,detourTraceThickness:a.traceThickness});if(!p)return null;A.push({routeIndex:g,route:p.route,relocatedVias:p.relocatedVias})}const l=this.collapseDetourSection({route:a,section:n,targetZ:o});if(a.vias.length+[...c.keys()].reduce((g,h)=>g+this.reducedHdRoutes[h].vias.length,0)-(l.vias.length+A.reduce((g,{route:h})=>g+h.vias.length,0))!==2)return null;this.stats.multiCrossingCandidates=(this.stats.multiCrossingCandidates??0)+1;const u={detourRouteIndex:e,detourRoute:l,transitionUpdates:A};return this.candidateIsClear(u,s)?this.candidateRoutesHaveNoExternalCopperConflicts(u,s)?(this.stats.multiCrossingReductions=(this.stats.multiCrossingReductions??0)+1,this.stats.transitionRoutesMovedByMultiCrossingReductions=(this.stats.transitionRoutesMovedByMultiCrossingReductions??0)+A.length,u):(this.stats.multiCrossingPreexistingConflictRejections=(this.stats.multiCrossingPreexistingConflictRejections??0)+1,null):null}findCrossingReduction(){const e=this.reducedHdRoutes.map(s=>qz(s)),n=[],o=new Set;for(let s=0;s<this.reducedHdRoutes.length;s++){if(this.reducedHdRoutes[s].jumpers?.length)continue;const a=e[s];for(let A=1;A<a.length-1;A++){const c=a[A-1],l=a[A],u=a[A+1];c.z!==u.z||c.z===l.z||Zft(l)||(n.push({routeIndex:s,section:l,targetZ:c.z}),o.add(`${c.z}:${l.z}`))}}if(n.length===0)return null;const i=this.buildTransitionSegmentIndex(e,o);if(!i)return null;let r=null;for(const s of n){const a=s.routeIndex,A=s.section,c=this.reducedHdRoutes[a],l=this.getIndexedCrossingGroups({detourRouteIndex:a,detourSection:A,targetZ:s.targetZ,transitionSegmentIndex:i}).filter(({transitionRouteIndex:h})=>{const d=this.reducedHdRoutes[h];return!d.jumpers?.length&&!o6e(c,d,this.input.connMap)}),u=new Map;for(const h of l){const d=`${h.transitionRouteIndex}:${h.transitionSectionIndex}`,p=u.get(d)??[];p.push(h),u.set(d,p)}if(u.size>1){r??={mutableRoutes:new oB(this.reducedHdRoutes),immutableRoutes:this.input.otherHdRoutes?.length?new oB([...this.input.otherHdRoutes]):null};let h=[{groups:[],movement:0}];const d=p=>{const m=this.reducedHdRoutes[p.transitionRouteIndex],_=e[p.transitionRouteIndex][p.transitionSectionIndex],f=m.viaDiameter/2+c.traceThickness/2+this.traceMargin+Py,I=p.side==="start"?Math.max(...p.crossingDistances)+f:Math.min(...p.crossingDistances)-f;return p.side==="start"?I:qft(_.points)-I};for(const p of u.values()){const m=p.map(_=>({group:_,movement:d(_)})).sort((_,f)=>_.movement-f.movement);h=h.flatMap(_=>m.map(f=>({groups:[..._.groups,f.group],movement:_.movement+f.movement}))).sort((_,f)=>_.movement-f.movement).slice(0,4)}for(const p of h){const m=this.tryCreateMultiCrossingCandidate({detourRouteIndex:a,detourSection:A,targetZ:s.targetZ,crossingGroups:p.groups,sectionsByRoute:e,baseClearanceIndexes:r});if(m)return m}continue}const g=u.values().next().value??[];for(const h of g){const d=h.transitionRouteIndex,p=e[d],m=p[h.transitionSectionIndex];r??={mutableRoutes:new oB(this.reducedHdRoutes),immutableRoutes:this.input.otherHdRoutes?.length?new oB([...this.input.otherHdRoutes]):null};const _=this.tryCreateCandidate({detourRouteIndex:a,detourSection:A,targetZ:s.targetZ,transitionRouteIndex:d,transitionSection:m,transitionSections:p,transitionSectionIndex:h.transitionSectionIndex,side:h.side,crossingDistances:h.crossingDistances,baseClearanceIndexes:r});if(_)return _}}return null}_step(){const e=this.findCrossingReduction();if(e){this.reducedHdRoutes[e.detourRouteIndex]=e.detourRoute;for(const n of e.transitionUpdates)this.reducedHdRoutes[n.routeIndex]=n.route;this.stats.crossingViaReductions=(this.stats.crossingViaReductions??0)+1,this.stats.viasRemovedByCrossingReductions=(this.stats.viasRemovedByCrossingReductions??0)+2}else this.solved=!0}getReducedHdRoutes(){return this.reducedHdRoutes}visualize(){const e={lines:[],circles:[],rects:[],coordinateSystem:"cartesian",title:"Crossing Via Reduction Solver"};for(const n of this.input.obstacles)e.rects.push({center:n.center,width:n.width,height:n.height,fill:"rgba(128, 128, 128, 0.2)"});for(const n of this.reducedHdRoutes){for(let o=1;o<n.route.length;o++){const i=n.route[o-1],r=n.route[o];i.z===r.z&&e.lines.push({points:[i,r],strokeColor:i.z===0?"#d32f2f":"#3367a8",strokeWidth:n.traceThickness,label:`${n.connectionName} (z=${i.z})`})}for(const o of n.vias)e.circles.push({center:o,radius:n.viaDiameter/2,fill:"#ff20d6",label:`${n.connectionName} via`})}return e}},cae=1e-6,i6e=(t,e)=>Math.abs(t.x-e.center.x)<=e.width/2+cae&&Math.abs(t.y-e.center.y)<=e.height/2+cae,o1t=t=>(t.__zLayers?.length??t.layers?.length??0)>1,j8=class extends yr{constructor(e){if(super(),this.simplificationConfig=e,this.simplificationConfig={...e,obstacles:c7(e.obstacles,e.layerCount)},this.hdRoutes=this.markThroughObstacleSegments(e.hdRoutes),e.preserveRouteEndpoints){const n=new Map;for(const o of e.hdRoutes){const i=o.route[0],r=o.route.at(-1);if(!i||!r)throw new Error(`TraceSimplificationSolver cannot preserve endpoints for empty route "${o.connectionName}"`);if(n.has(o.connectionName))throw new Error(`TraceSimplificationSolver cannot preserve endpoints for duplicate route "${o.connectionName}"`);n.set(o.connectionName,{start:{...i},end:{...r}})}this.preservedRouteEndpoints=n}this.MAX_ITERATIONS=1e8}simplificationConfig;getSolverName(){return"TraceSimplificationSolver"}hdRoutes=[];preservedRouteEndpoints;simplificationPipelineLoops=0;MAX_SIMPLIFICATION_PIPELINE_LOOPS=2;PHASE_ORDER=["via_removal","crossing_via_reduction","via_merging","path_simplification"];currentPhase="via_removal";extractResult=null;get simplifiedHdRoutes(){return this.hdRoutes}validatePreservedRouteEndpoints(e){if(!this.preservedRouteEndpoints)return;if(e.length!==this.preservedRouteEndpoints.size)throw new Error(`TraceSimplificationSolver changed the preserved route set (expected ${this.preservedRouteEndpoints.size}, got ${e.length})`);const n=new Set,o=(i,r)=>Math.abs(i.x-r.x)<=cae&&Math.abs(i.y-r.y)<=cae&&i.z===r.z;for(const i of e){if(n.has(i.connectionName))throw new Error(`TraceSimplificationSolver produced duplicate preserved route "${i.connectionName}"`);n.add(i.connectionName);const r=this.preservedRouteEndpoints.get(i.connectionName),s=i.route[0],a=i.route.at(-1);if(!(r&&s&&a&&o(s,r.start)&&o(a,r.end)))throw new Error(`TraceSimplificationSolver changed a preserved endpoint for route "${i.connectionName}"`)}}isSameNetObstacle(e,n){return n.connectedTo.some(o=>o===e.connectionName||o===e.rootConnectionName||this.simplificationConfig.connMap.areIdsConnected(e.connectionName,o)||e.rootConnectionName!==void 0&&this.simplificationConfig.connMap.areIdsConnected(e.rootConnectionName,o))}getSameNetObstacleForSegment(e,n,o){return this.simplificationConfig.obstacles.find(i=>o1t(i)&&this.isSameNetObstacle(e,i)&&i6e(n,i)&&i6e(o,i))}isViaInsideSameNetObstacle(e,n){return this.simplificationConfig.obstacles.some(o=>o1t(o)&&this.isSameNetObstacle(e,o)&&i6e(n,o))}markThroughObstacleSegments(e){return e.map(n=>({...n,route:n.route.map((o,i,r)=>{const s=r[i+1],a=s&&o.z!==s.z&&this.getSameNetObstacleForSegment(n,o,s);if(a)return{...o,toNextSegmentType:"through_obstacle",...a.circuitJsonMetadata?{toNextSegmentCircuitJsonMetadata:a.circuitJsonMetadata}:{}};const A={...o};return delete A.toNextSegmentType,delete A.toNextSegmentCircuitJsonMetadata,A}),vias:n.vias.filter(o=>!this.isViaInsideSameNetObstacle(n,o))}))}_step(){if(this.simplificationPipelineLoops>=this.MAX_SIMPLIFICATION_PIPELINE_LOOPS)this.solved=!0;else{if(this.activeSubSolver){if(this.activeSubSolver.step(),!this.activeSubSolver.failed&&!this.activeSubSolver.solved)return;if(this.activeSubSolver.solved){if(this.extractResult){const e=this.extractResult(this.activeSubSolver);this.validatePreservedRouteEndpoints(e),this.hdRoutes=this.markThroughObstacleSegments(e)}if(this.activeSubSolver=null,this.extractResult=null,this.currentPhase==="via_removal"?this.currentPhase=this.simplificationConfig.enableCrossingViaReduction?"crossing_via_reduction":"via_merging":this.currentPhase==="crossing_via_reduction"?this.currentPhase="via_merging":this.currentPhase==="via_merging"?this.currentPhase="path_simplification":(this.currentPhase="via_removal",this.simplificationPipelineLoops++),this.simplificationPipelineLoops>=this.MAX_SIMPLIFICATION_PIPELINE_LOOPS)return void(this.solved=!0)}else if(this.activeSubSolver.failed)return this.failed=!0,void(this.error=this.activeSubSolver.error??"Sub-solver failed without error message")}if(!this.activeSubSolver&&!this.solved)switch(this.currentPhase){case"via_removal":this.activeSubSolver=new uZn({unsimplifiedHdRoutes:this.hdRoutes,otherHdRoutes:[...this.simplificationConfig.otherHdRoutes??[]],obstacles:[...this.simplificationConfig.obstacles],colorMap:{...this.simplificationConfig.colorMap},layerCount:this.simplificationConfig.layerCount,connMap:this.simplificationConfig.connMap,outline:this.simplificationConfig.outline?[...this.simplificationConfig.outline]:void 0,geometryShortcutTraceMargin:.1,geometryShortcutObstacleMargin:this.simplificationConfig.minTraceToPadEdgeClearance??.15,enableGeometryShortcuts:this.simplificationPipelineLoops>0,enableObstacleDetourShortcuts:this.simplificationConfig.enableCrossingViaReduction===!0&&this.simplificationPipelineLoops>0,preserveRouteEndpoints:this.simplificationConfig.preserveRouteEndpoints,terminalLayerIndicesByPcbPortId:this.simplificationConfig.terminalLayerIndicesByPcbPortId}),this.extractResult=e=>e.getOptimizedHdRoutes()??[];break;case"crossing_via_reduction":this.activeSubSolver=new xZn({inputHdRoutes:this.hdRoutes,otherHdRoutes:[...this.simplificationConfig.otherHdRoutes??[]],obstacles:[...this.simplificationConfig.obstacles],connMap:this.simplificationConfig.connMap,layerCount:this.simplificationConfig.layerCount,outline:this.simplificationConfig.outline?[...this.simplificationConfig.outline]:void 0,traceMargin:.1,obstacleMargin:this.simplificationConfig.minTraceToPadEdgeClearance??.15}),this.extractResult=e=>e.getReducedHdRoutes();break;case"via_merging":this.activeSubSolver=new jft({inputHdRoutes:this.hdRoutes,otherHdRoutes:[...this.simplificationConfig.otherHdRoutes??[]],netByConnectionName:this.simplificationConfig.netByConnectionName,obstacles:[...this.simplificationConfig.obstacles],colorMap:{...this.simplificationConfig.colorMap},layerCount:this.simplificationConfig.layerCount,connMap:this.simplificationConfig.connMap,outline:this.simplificationConfig.outline?[...this.simplificationConfig.outline]:void 0,preserveRouteEndpoints:this.simplificationConfig.preserveRouteEndpoints}),this.extractResult=e=>e.getMergedViaHdRoutes()??[];break;case"path_simplification":this.activeSubSolver=new pZn({unsimplifiedHdRoutes:this.hdRoutes,otherHdRoutes:[...this.simplificationConfig.otherHdRoutes??[]],obstacles:[...this.simplificationConfig.obstacles],connMap:this.simplificationConfig.connMap,colorMap:{...this.simplificationConfig.colorMap},outline:this.simplificationConfig.outline?[...this.simplificationConfig.outline]:void 0,minBoardEdgeClearance:this.simplificationConfig.minBoardEdgeClearance,defaultViaDiameter:this.simplificationConfig.defaultViaDiameter,useTraceWidthAwareClearance:this.simplificationConfig.useTraceWidthAwareClearance}),this.extractResult=e=>e.simplifiedHdRoutes;break;default:this.failed=!0,this.error=`Unknown phase: ${this.currentPhase}`}}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Trace Simplification Solver"};for(const n of this.simplificationConfig.obstacles){let o="rgba(128, 128, 128, 0.2)";const i=n.__zLayers?.includes(0),r=n.__zLayers?.includes(1);i&&r?o="rgba(128, 0, 128, 0.2)":i?o="rgba(255, 0, 0, 0.2)":r&&(o="rgba(0, 0, 255, 0.2)"),e.rects.push({center:n.center,width:n.width,height:n.height,fill:o,label:`Obstacle (Z: ${n.__zLayers?.join(", ")})`})}for(const n of this.simplificationConfig.otherHdRoutes??[]){for(let o=0;o<n.route.length-1;o++){const i=n.route[o],r=n.route[o+1];i.z===r.z&&e.lines.push({points:[{x:i.x,y:i.y},{x:r.x,y:r.y}],strokeColor:i.z===0?"rgba(160, 32, 32, 0.55)":"rgba(32, 32, 160, 0.55)",strokeWidth:n.traceThickness,strokeDash:[.08,.08],label:`${n.connectionName} immutable (z=${i.z})`})}for(const o of n.vias)e.circles.push({center:{x:o.x,y:o.y},radius:n.viaDiameter/2,fill:"rgba(96, 96, 96, 0.45)",label:`${n.connectionName} immutable via`})}for(const n of this.hdRoutes)if(n.route.length!==0){for(let o=0;o<n.route.length-1;o++){const i=n.route[o],r=n.route[o+1];i.z===r.z&&e.lines.push({points:[{x:i.x,y:i.y},{x:r.x,y:r.y}],strokeColor:i.z===0?"red":"blue",strokeWidth:n.traceThickness,label:`${n.connectionName} (z=${i.z})`})}for(const o of n.vias)e.circles.push({center:{x:o.x,y:o.y},radius:n.viaDiameter/2,fill:"rgba(255, 0, 255, 0.5)",label:`${n.connectionName} via`});if(n.jumpers&&n.jumpers.length>0){const o=_x(n.jumpers,{color:"orange",label:n.connectionName});e.rects.push(...o.rects??[]),e.lines.push(...o.lines??[])}}return e}},J3=1e-9,aL=class extends yr{getSolverName(){return"TraceWidthSolver"}hdRoutes;hdRoutesWithWidths=[];nominalTraceWidth;minTraceWidth;obstacleMargin;TRACE_WIDTH_SCHEDULE;connectionNominalTraceWidthMap;unprocessedRoutes=[];processedRoutes=[];currentTrace=null;cursorPosition=null;currentTraceSegmentIndex=0;currentTraceSegmentT=0;currentScheduleIndex=0;currentTargetWidth=0;hasInsufficientClearance=!1;lastCollidingObstacles=[];lastCollidingRoutes=[];lastClearance=1/0;obstacles=[];obstacleSHI;hdRouteSHI;connMap;colorMap;constructor(e){super(),this.MAX_ITERATIONS=1e6,this.hdRoutes=[...e.hdRoutes],this.minTraceWidth=e.minTraceWidth,this.obstacleMargin=e.obstacleMargin??.15,this.nominalTraceWidth=0,this.TRACE_WIDTH_SCHEDULE=[],this.unprocessedRoutes=[...this.hdRoutes],this.connMap=e.connMap,this.colorMap=e.colorMap;const n=e.layerCount;this.obstacles=c7(e.obstacles??[],n),this.connectionNominalTraceWidthMap=new Map;for(const o of e.connection)o.nominalTraceWidth!==void 0&&this.connectionNominalTraceWidthMap.set(o.name,o.nominalTraceWidth);this.obstacles.length>0&&(this.obstacleSHI=new OD("flatbush",this.obstacles)),this.hdRouteSHI=new oB(this.hdRoutes)}getNominalTraceWidthForRoute(e){const n=this.connectionNominalTraceWidthMap.get(e.connectionName);return n!==void 0?n:e.rootConnectionName?this.connectionNominalTraceWidthMap.get(e.rootConnectionName):void 0}_step(){if(!this.currentTrace){const e=this.unprocessedRoutes.shift();if(!e)return this.hdRoutesWithWidths=this.processedRoutes,void(this.solved=!0);const n=this.getNominalTraceWidthForRoute(e);if(n===void 0){const i=e.traceThickness??this.minTraceWidth;return this.processedRoutes.push(this.createRouteWithWidth(e,i)),void(this.currentTrace=null)}this.currentTrace=e,this.nominalTraceWidth=n;const o=(this.nominalTraceWidth+this.minTraceWidth)/2;return this.TRACE_WIDTH_SCHEDULE=[this.nominalTraceWidth,o],this.currentTrace.route.length<2?(this.processedRoutes.push(this.createRouteWithWidth(this.currentTrace,this.minTraceWidth)),void(this.currentTrace=null)):(this.currentScheduleIndex=0,this.currentTargetWidth=this.TRACE_WIDTH_SCHEDULE[0],void this.initializeCursor())}if(!this.stepCursorForward())return void this.finalizeCurrentTrace(this.currentTargetWidth);this.getClearanceAtPosition(this.cursorPosition)<this.currentTargetWidth/2+this.obstacleMargin&&(this.hasInsufficientClearance=!0,this.currentScheduleIndex++,this.currentScheduleIndex<this.TRACE_WIDTH_SCHEDULE.length?(this.currentTargetWidth=this.TRACE_WIDTH_SCHEDULE[this.currentScheduleIndex],this.initializeCursor()):this.finalizeCurrentTrace(this.minTraceWidth))}initializeCursor(){if(!this.currentTrace)return;const e=this.currentTrace.route[0];this.cursorPosition={...e},this.currentTraceSegmentIndex=0,this.currentTraceSegmentT=0,this.hasInsufficientClearance=!1}stepCursorForward(){if(!this.currentTrace||!this.cursorPosition)return!1;const e=this.currentTrace.route;let n=.1;for(;n>0;){if(this.currentTraceSegmentIndex>=e.length-1)return!1;const o=e[this.currentTraceSegmentIndex],i=e[this.currentTraceSegmentIndex+1];if(o.insideJumperPad&&i.insideJumperPad){this.currentTraceSegmentIndex++,this.currentTraceSegmentT=0;continue}const r=i.x-o.x,s=i.y-o.y,a=Math.sqrt(r*r+s*s);if(a===0){this.currentTraceSegmentIndex++,this.currentTraceSegmentT=0;continue}const A=this.currentTraceSegmentT*a,c=a-A;if(n<=c){const l=A+n;return this.currentTraceSegmentT=l/a,this.cursorPosition={x:o.x+r*this.currentTraceSegmentT,y:o.y+s*this.currentTraceSegmentT,z:o.z},!0}if(n-=c,this.currentTraceSegmentIndex++,this.currentTraceSegmentT=0,this.currentTraceSegmentIndex>=e.length-1){const l=e[e.length-1];return this.cursorPosition={...l},!1}}return!0}isObstacleOwnJumperPad(e){if(!this.currentTrace?.jumpers)return!1;for(const n of this.currentTrace.jumpers){const o=Math.sqrt((e.center.x-n.start.x)**2+(e.center.y-n.start.y)**2),i=Math.sqrt((e.center.x-n.end.x)**2+(e.center.y-n.end.y)**2),r=Math.max(e.width,e.height)/2+.01;if(o<r||i<r)return!0}return!1}getClearanceAtPosition(e){if(!this.currentTrace)return 1/0;const n=this.currentTrace.rootConnectionName??this.currentTrace.connectionName,o=2*this.nominalTraceWidth;let i=1/0;if(this.lastCollidingObstacles=[],this.lastCollidingRoutes=[],this.obstacleSHI){const s=this.obstacleSHI.searchArea(e.x,e.y,o,o);for(const a of s){if(a.__zLayers&&!a.__zLayers.includes(e.z)||a.connectedTo.includes(n)||a.obstacleId&&this.connMap?.areIdsConnected(n,a.obstacleId))continue;let A=!1;if(this.connMap){for(const m of a.connectedTo)if(this.connMap.areIdsConnected(n,m)){A=!0;break}}if(A||this.isObstacleOwnJumperPad(a))continue;const c=a.center.x-a.width/2,l=a.center.x+a.width/2,u=a.center.y-a.height/2,g=a.center.y+a.height/2,h=Math.max(c-e.x,0,e.x-l),d=Math.max(u-e.y,0,e.y-g),p=Math.sqrt(h*h+d*d);p<this.currentTargetWidth/2+this.obstacleMargin&&this.lastCollidingObstacles.push(a),p<i&&(i=p)}}const r=this.hdRouteSHI.getConflictingRoutesNearPoint({x:e.x,y:e.y,z:e.z},o);for(const{conflictingRoute:s,distance:a}of r){const A=s.rootConnectionName??s.connectionName;if(A===n||this.connMap?.areIdsConnected(n,A))continue;const c=a-(s.traceThickness??.15)/2;c<this.currentTargetWidth/2+this.obstacleMargin&&this.lastCollidingRoutes.push(s),c<i&&(i=c)}return this.lastClearance=i,i}isObstacleOnPointLayer(e,n){return!e.__zLayers||e.__zLayers.includes(n.z)}getAdjacentNonCoincidentRoutePoint(e,n){const o=e.route[n];if(!o)return;const i=n===0?1:-1;for(let r=n+i;r>=0&&r<e.route.length;r+=i){const s=e.route[r];if(no(s,o)>J3)return s}}getObstacleWidthAlongVector(e,n){const o=(e.ccwRotationDegrees??0)*Math.PI/180,i=Math.cos(o),r=Math.sin(o),s=i,a=r,A=-r,c=i;return Math.abs(n.x*s+n.y*a)*e.width+Math.abs(n.x*A+n.y*c)*e.height}getTerminalPadWidthLimit(e,n,o){const i=e.route[n];if(!i)return;const r=this.getAdjacentNonCoincidentRoutePoint(e,n);if(!r)return;const s=n===0?u7e(i,r):u7e(r,i);if(no(s,{x:0,y:0})<=J3)return;const a={x:-s.y,y:s.x};let A;for(const c of this.obstacles){if(!this.isObstacleOnPointLayer(c,i)||!Hse(c,e,this.connMap)||o7(i,c)>J3)continue;const l=this.getObstacleWidthAlongVector(c,a);if(l<=J3)continue;const u=this.getObstacleWidthAlongVector(c,s)/2;(!A||l<A.width||Math.abs(l-A.width)<=J3&&u>A.neckDistance)&&(A={width:l,neckDistance:u})}return!A||A.width>=o-J3?void 0:A}getRouteDistanceInfo(e){const n=[0];let o=0;for(let i=1;i<e.length;i++){const r=e[i-1];o+=no(e[i],r),n.push(o)}return{distances:n,totalDistance:o}}interpolateRoutePointAtDistance(e,n,o){for(let i=1;i<e.length;i++){const r=n[i-1],s=n[i],a=s-r;if(o>s+J3)continue;const A=e[i-1],c=e[i];if(a<=J3)return{...c};const l=Math.max(0,Math.min(1,(o-r)/a));return{x:A.x+(c.x-A.x)*l,y:A.y+(c.y-A.y)*l,z:A.z}}return{...e[e.length-1]}}getTaperWidthAtDistance({distanceFromStart:e,totalDistance:n,startLimit:o,endLimit:i,taperDistance:r,traceWidth:s}){let a=s;if(o!==void 0&&e<=r){const A=Math.min(o.neckDistance,r);if(e<=A)a=Math.min(a,o.width);else{const c=(e-A)/Math.max(r-A,J3);a=Math.min(a,o.width+(s-o.width)*c)}}if(i!==void 0){const A=n-e;if(A<=r){const c=Math.min(i.neckDistance,r);if(A<=c)a=Math.min(a,i.width);else{const l=(A-c)/Math.max(r-c,J3);a=Math.min(a,i.width+(s-i.width)*l)}}}return a}createTerminalTaperedRoute(e,n){if(e.route.length<2)return e.route.map(l=>({...l,traceThickness:l.traceThickness??n}));const o=this.getTerminalPadWidthLimit(e,0,n),i=this.getTerminalPadWidthLimit(e,e.route.length-1,n),{distances:r,totalDistance:s}=this.getRouteDistanceInfo(e.route);if(s<=J3){const l=Math.min(o?.width??n,i?.width??n);return e.route.map(u=>({...u,traceThickness:l}))}const a=Math.min(Math.max(2*n,.75),s/2),A=r.map((l,u)=>({distanceFromStart:l,originalPointIndex:u})),c=[];if(o!==void 0){c.push(o.neckDistance);for(let l=0;l<=8;l++)c.push(a*l/8)}if(i!==void 0){c.push(s-i.neckDistance);for(let l=0;l<=8;l++)c.push(s-a+a*l/8)}for(const l of c){const u=Math.max(0,Math.min(s,l));A.some(g=>Math.abs(g.distanceFromStart-u)<=J3)||A.push({distanceFromStart:u})}return A.sort((l,u)=>{const g=l.distanceFromStart-u.distanceFromStart;return Math.abs(g)>J3?g:(l.originalPointIndex??1/0)-(u.originalPointIndex??1/0)}),A.map(l=>{const{distanceFromStart:u}=l,g=l.originalPointIndex!==void 0?{...e.route[l.originalPointIndex]}:this.interpolateRoutePointAtDistance(e.route,r,u);return g.traceThickness=this.getTaperWidthAtDistance({distanceFromStart:u,totalDistance:s,startLimit:o,endLimit:i,taperDistance:a,traceWidth:n}),g})}createRouteWithWidth(e,n){return{connectionName:e.connectionName,rootConnectionName:e.rootConnectionName,traceThickness:n,viaDiameter:e.viaDiameter,route:this.createTerminalTaperedRoute(e,n),vias:[...e.vias],jumpers:e.jumpers}}finalizeCurrentTrace(e){if(!this.currentTrace)return;const n=this.createRouteWithWidth(this.currentTrace,e);this.processedRoutes.push(n),this.currentTrace=null,this.cursorPosition=null,this.hasInsufficientClearance=!1}visualize(){const e={lines:[],points:[],circles:[],rects:[],coordinateSystem:"cartesian",title:`Trace Width Solver (schedule: [${this.TRACE_WIDTH_SCHEDULE.map(i=>i.toFixed(2)).join(", ")}]mm, fallback: ${this.minTraceWidth.toFixed(2)}mm, margin: ${this.obstacleMargin.toFixed(2)}mm)`},n=new Set(this.lastCollidingObstacles.map(i=>i.obstacleId)),o=new Set(this.lastCollidingRoutes.map(i=>i.connectionName));for(const i of this.obstacles){const r=n.has(i.obstacleId),s=i.__zLayers?.includes(0),a=i.__zLayers?.includes(1);let A;A=r?"rgba(255, 0, 0, 0.6)":s&&a?"rgba(128, 0, 128, 0.15)":s?"rgba(255, 0, 0, 0.15)":a?"rgba(0, 0, 255, 0.15)":"rgba(128, 128, 128, 0.15)",e.rects.push({center:i.center,width:i.width,height:i.height,fill:A,stroke:r?"red":void 0,label:r?`COLLIDING: ${i.obstacleId??"obstacle"}`:`${i.obstacleId??"obstacle"} (Z: ${i.__zLayers?.join(", ")})`})}for(const i of this.processedRoutes){if(i.route.length===0)continue;const r=i.traceThickness===this.nominalTraceWidth,s=i.traceThickness===this.TRACE_WIDTH_SCHEDULE[1],a=r?"green":s?"yellow":"orange";for(let A=0;A<i.route.length-1;A++){const c=i.route[A],l=i.route[A+1];c.insideJumperPad&&l.insideJumperPad||c.z===l.z&&e.lines.push({points:[{x:c.x,y:c.y},{x:l.x,y:l.y}],strokeColor:a,strokeWidth:c.traceThickness??i.traceThickness,label:`${i.connectionName} (w=${(c.traceThickness??i.traceThickness).toFixed(2)})`})}for(const A of i.vias)e.circles.push({center:{x:A.x,y:A.y},radius:i.viaDiameter/2,fill:"rgba(255, 0, 255, 0.5)",label:`${i.connectionName} via`});if(i.jumpers&&i.jumpers.length>0){const A=_x(i.jumpers,{color:a,label:i.connectionName});e.rects.push(...A.rects??[]),e.lines.push(...A.lines??[])}}if(this.currentTrace){for(let i=0;i<this.currentTrace.route.length-1;i++){const r=this.currentTrace.route[i],s=this.currentTrace.route[i+1];r.insideJumperPad&&s.insideJumperPad||r.z===s.z&&e.lines.push({points:[{x:r.x,y:r.y},{x:s.x,y:s.y}],strokeColor:"cyan",strokeWidth:this.currentTrace.traceThickness??this.minTraceWidth,label:`Processing: ${this.currentTrace.connectionName}`})}this.cursorPosition&&(e.circles.push({center:{x:this.cursorPosition.x,y:this.cursorPosition.y},radius:this.currentTargetWidth/2,stroke:this.hasInsufficientClearance?"red":"green",fill:"none",label:`Testing width: ${this.currentTargetWidth.toFixed(2)}mm (clearance: ${this.lastClearance.toFixed(2)}mm)`}),e.points.push({x:this.cursorPosition.x,y:this.cursorPosition.y,color:"orange",label:"Cursor"}))}for(const i of this.unprocessedRoutes){if(i.route.length===0)continue;const r=o.has(i.connectionName);for(let s=0;s<i.route.length-1;s++){const a=i.route[s],A=i.route[s+1];a.z===A.z&&e.lines.push({points:[{x:a.x,y:a.y},{x:A.x,y:A.y}],strokeColor:r?"rgba(255, 0, 0, 0.8)":"rgba(128, 128, 128, 0.3)",strokeWidth:i.traceThickness??this.minTraceWidth,label:r?`COLLIDING: ${i.connectionName}`:i.connectionName})}}return e}getHdRoutesWithWidths(){return this.hdRoutesWithWidths}},EZn=class extends yr{getSolverName(){return"CapacityEdgeToPortSegmentSolver"}nodes;edges;capacityPaths;nodeMap;nodeEdgeMap;unprocessedNodeIds;nodePortSegments;colorMap;constructor({nodes:t,edges:e,capacityPaths:n,colorMap:o}){super(),this.nodes=t,this.edges=e,this.nodeMap=new Map(t.map(i=>[i.capacityMeshNodeId,i])),this.nodeEdgeMap=tL(e),this.capacityPaths=n,this.colorMap=o??{},this.unprocessedNodeIds=[...new Set(n.flatMap(i=>i.nodeIds))],this.nodePortSegments=new Map}step(){const t=this.unprocessedNodeIds.pop();if(!t)return void(this.solved=!0);const e=[];for(const r of this.capacityPaths){const s=r.nodeIds.indexOf(t);s!==-1&&e.push({path:r,indexOfNodeInPath:s})}const n=this.nodeMap.get(t),o=[];for(const{path:r,indexOfNodeInPath:s}of e){const a=r.nodeIds[s-1],A=r.nodeIds[s+1];for(const c of[a,A]){const l=this.nodeMap.get(c);if(!l)continue;const u=BZn(n,l),g=l.availableZ.filter(d=>n.availableZ.includes(d));if(g.length===0)continue;const h={capacityMeshNodeId:t,start:u.start,end:u.end,connectionNames:[r.connectionName],rootConnectionNames:r.rootConnectionName?[r.rootConnectionName]:void 0,availableZ:g};o.push(h)}}const i=(function(r){const s=[],a=r.map(A=>({...A,connectionNames:[...A.connectionNames],rootConnectionNames:A.rootConnectionNames?[...A.rootConnectionNames]:[],availableZ:[...A.availableZ].sort((c,l)=>c-l)}));for(;a.length>0;){const A=a.pop();let c=!1;for(let l=0;l<s.length;l++){const u=s[l],g=lae(u.start,A.start)&&lae(u.end,A.end)||lae(u.start,A.end)&&lae(u.end,A.start),h=bZn(u.availableZ,A.availableZ);if(g&&h){const d=new Set(u.connectionNames);A.connectionNames.forEach(m=>d.add(m)),u.connectionNames=Array.from(d);const p=new Set(u.rootConnectionNames||[]);A.rootConnectionNames?.forEach(m=>p.add(m)),u.rootConnectionNames=Array.from(p),c=!0;break}}c||s.push(A)}return s})(o);this.nodePortSegments.set(t,i)}visualize(){const t={lines:[],points:[],rects:[],circles:[]};return this.nodePortSegments.forEach((e,n)=>{this.nodeMap.get(n),e.forEach(o=>{o.start.x,o.end.x;for(let i=0;i<o.connectionNames.length;i++){const r={x:.05*Math.max(...o.availableZ),y:.05*Math.max(...o.availableZ)},s={x:(o.start.x+o.end.x)/2,y:(o.start.y+o.end.y)/2},a={x:s.x+r.x,y:s.y+r.y};r.x>0&&t.lines.push({points:[s,a],strokeColor:"rgba(0, 0, 0, 0.25)",strokeDash:"5 5"}),t.points.push({x:a.x,y:a.y,label:`${n}: ${o.connectionNames.join(", ")}
availableZ: ${o.availableZ.join(",")}
nodePortSegmentId: ${o.nodePortSegmentId}`}),t.lines.push({points:[o.start,o.end],strokeColor:Es(this.colorMap[o.connectionNames[i]],.6)})}})}),t}};function BZn(t,e){const n={start:Math.max(t.center.x-t.width/2,e.center.x-e.width/2),end:Math.min(t.center.x+t.width/2,e.center.x+e.width/2)},o={start:Math.max(t.center.y-t.height/2,e.center.y-e.height/2),end:Math.min(t.center.y+t.height/2,e.center.y+e.height/2)};if(n.end-n.start<o.end-o.start){const i=(n.start+n.end)/2;return{start:{x:i,y:o.start},end:{x:i,y:o.end}}}{const i=(o.start+o.end)/2;return{start:{x:n.start,y:i},end:{x:n.end,y:i}}}}var i1t=1e-9;function lae(t,e){return Math.abs(t.x-e.x)<i1t&&Math.abs(t.y-e.y)<i1t}function bZn(t,e){if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}var SZn=class{constructor(e){this.targets=e,this.buckets=new Map;for(let n=0;n<e.length;n++){const o=e[n],i=Math.floor(o.bounds.minX/this.CELL_SIZE)*this.CELL_SIZE,r=Math.floor(o.bounds.minY/this.CELL_SIZE)*this.CELL_SIZE,s=o.bounds.maxX,a=o.bounds.maxY;for(let A=i;A<=s;A+=this.CELL_SIZE)for(let c=r;c<=a;c+=this.CELL_SIZE){const l=this.getBucketKey(A,c),u=this.buckets.get(l);u?u.push([o,n]):this.buckets.set(l,[[o,n]])}}}targets;buckets;CELL_SIZE=5;getBucketKey(e,n){return`${Math.floor(e/this.CELL_SIZE)}x${Math.floor(n/this.CELL_SIZE)}`}getTargetsInArea(e,n,o,i){const r=[],s=new Set,a=Math.floor((e-o/2)/this.CELL_SIZE)*this.CELL_SIZE,A=Math.floor((n-i/2)/this.CELL_SIZE)*this.CELL_SIZE,c=e+o/2,l=n+i/2;for(let u=a;u<=c;u+=this.CELL_SIZE)for(let g=A;g<=l;g+=this.CELL_SIZE){const h=this.getBucketKey(u,g),d=this.buckets.get(h)||[];for(const p of d)s.has(p[1])||(s.add(p[1]),r.push(p[0]))}return r}},QZn=class extends yr{constructor(e,n={}){super(),this.srj=e,this.opts=n,this.MAX_DEPTH=n?.capacityDepth??this.MAX_DEPTH,this.MAX_ITERATIONS=1e5,this.layerCount=e.layerCount??2,this.outlinePolygon=e.outline&&e.outline.length>=3?e.outline:void 0;const o={x:(e.bounds.minX+e.bounds.maxX)/2,y:(e.bounds.minY+e.bounds.maxY)/2},i={width:e.bounds.maxX-e.bounds.minX,height:e.bounds.maxY-e.bounds.minY},r=Math.max(i.width,i.height);this.unfinishedNodes=[{capacityMeshNodeId:this.getNextNodeId(),center:o,width:r,height:r,layer:"top",availableZ:Array.from({length:this.layerCount},(a,A)=>A),_depth:0,_containsTarget:!0,_containsObstacle:!0,_completelyInsideObstacle:!1}],this.finishedNodes=[],this.nodeToXYOverlappingObstaclesMap=new Map,this.obstacleZLayersByObstacle=new WeakMap;const s=c7(this.srj.obstacles,this.layerCount);for(const[a,A]of this.srj.obstacles.entries())this.obstacleZLayersByObstacle.set(A,s[a].__zLayers);this.obstacleTree=new OD("flatbush",this.srj.obstacles),this.targets=this.computeTargets(),this.targetTree=new SZn(this.targets)}srj;opts;getSolverName(){return"CapacityMeshNodeSolver"}unfinishedNodes;finishedNodes;nodeToXYOverlappingObstaclesMap;layerCount;outlinePolygon;MAX_DEPTH=4;targets;targetTree;obstacleTree;obstacleZLayersByObstacle;computeTargets(){const e=[];for(const n of this.srj.connections)for(const o of n.pointsToConnect){const i=RD(o),r=this.obstacleTree.searchArea(o.x,o.y,.01,.01).filter(A=>{const c=this.getObstacleZLayers(A);return!(!c||c.length===0)&&c.some(l=>i.some(u=>l===Kr(u,this.layerCount)))});let s={minX:o.x-.005,minY:o.y-.005,maxX:o.x+.005,maxY:o.y+.005};r.length>0&&(s={minX:Math.min(...r.map(A=>A.center.x-A.width/2)),minY:Math.min(...r.map(A=>A.center.y-A.height/2)),maxX:Math.max(...r.map(A=>A.center.x+A.width/2)),maxY:Math.max(...r.map(A=>A.center.y+A.height/2))});const a={...o,connectionName:n.name,availableZ:i.map(A=>Kr(A,this.layerCount)),bounds:s};e.push(a)}return e}getNodeBounds(e){const n=e.width/2,o=e.height/2;return{minX:e.center.x-n,maxX:e.center.x+n,minY:e.center.y-o,maxY:e.center.y+o}}getNodeRect(e){return{center:{x:e.center.x,y:e.center.y},width:e.width,height:e.height}}_nextNodeCounter=0;getNextNodeId(){return"cn"+this._nextNodeCounter++}getCapacityFromDepth(e){return(this.MAX_DEPTH-e+1)**2}getTargetIfNodeContainsTarget(e){const n=e.width>4*this.targetTree.CELL_SIZE?this.targets:this.targetTree.getTargetsInArea(e.center.x,e.center.y,e.width,e.height);for(const o of n)if(o.bounds.minX<=e.center.x+e.width/2&&o.bounds.maxX>=e.center.x-e.width/2&&o.bounds.minY<=e.center.y+e.height/2&&o.bounds.maxY>=e.center.y-e.height/2&&o.availableZ.some(i=>e.availableZ.includes(i)))return o;return null}getXYOverlappingObstacles(e){const n=this.nodeToXYOverlappingObstaclesMap.get(e.capacityMeshNodeId);if(n)return n;const o=[],i=this.getNodeBounds(e),r=i.minX,s=i.maxX,a=i.minY,A=i.maxY,c=e._parent?this.getXYOverlappingObstacles(e._parent):this.srj.obstacles;for(const l of c){const u=l.center.x-l.width/2,g=l.center.x+l.width/2,h=l.center.y-l.height/2,d=l.center.y+l.height/2;(s>=u&&r<=g&&A>=h&&a<=d||r>=u&&s<=g&&a>=h&&A<=d||u>=r&&g<=s&&h>=a&&d<=A)&&o.push(l)}return this.nodeToXYOverlappingObstaclesMap.set(e.capacityMeshNodeId,o),o}getXYZOverlappingObstacles(e){const n=this.getXYOverlappingObstacles(e),o=[];for(const i of n)e.availableZ.some(r=>this.getObstacleZLayers(i).includes(r))&&o.push(i);return o}doesNodeOverlapObstacle(e){if(this.getXYZOverlappingObstacles(e).length>0)return!0;const n=this.getNodeBounds(e);if(this.outlinePolygon){const o=this.getNodeRect(e);if(!E_t(o,this.outlinePolygon))return!0}return n.minX<this.srj.bounds.minX||n.maxX>this.srj.bounds.maxX||n.minY<this.srj.bounds.minY||n.maxY>this.srj.bounds.maxY}isNodeCompletelyInsideObstacle(e){const n=this.getXYZOverlappingObstacles(e),o=this.getNodeBounds(e);if(this.outlinePolygon){const i=this.getNodeRect(e);if(!Nse(i,this.outlinePolygon))return!0}for(const i of n){const r=i.center.x-i.width/2,s=i.center.x+i.width/2,a=i.center.y-i.height/2,A=i.center.y+i.height/2;if(o.minX>=r&&o.maxX<=s&&o.minY>=a&&o.maxY<=A)return!0}return!1}getChildNodes(e){if(e._depth===this.MAX_DEPTH)return[];const n=[],o={width:e.width/2,height:e.height/2},i=[{x:e.center.x-o.width/2,y:e.center.y-o.height/2},{x:e.center.x+o.width/2,y:e.center.y-o.height/2},{x:e.center.x-o.width/2,y:e.center.y+o.height/2},{x:e.center.x+o.width/2,y:e.center.y+o.height/2}];for(const r of i){const s={capacityMeshNodeId:this.getNextNodeId(),center:r,width:o.width,height:o.height,layer:e.layer,availableZ:e.availableZ,_depth:(e._depth??0)+1,_parent:e};s._containsObstacle=this.doesNodeOverlapObstacle(s);const a=this.getTargetIfNodeContainsTarget(s);a&&(s._targetConnectionName=a.connectionName,s.availableZ=a.availableZ,s._containsTarget=!0),s._containsObstacle&&(s._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(s)),s._completelyInsideObstacle&&!s._containsTarget||n.push(s)}return n}shouldNodeBeXYSubdivided(e){return!(e._depth>=this.MAX_DEPTH)&&(!!e._containsTarget||!(!e._containsObstacle||e._completelyInsideObstacle))}_step(){const e=this.unfinishedNodes.pop();if(!e)return void(this.solved=!0);const n=this.getChildNodes(e),o=[],i=[];for(const r of n){const s=this.shouldNodeBeXYSubdivided(r);s?i.push(r):s||r._containsObstacle?!s&&r._containsTarget&&o.push(r):o.push(r)}this.unfinishedNodes.push(...i),this.finishedNodes.push(...o)}visualize(){const e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Mesh Visualization"};if(this.outlinePolygon&&this.outlinePolygon.length>=2){const o=this.outlinePolygon.map(i=>({x:i.x,y:i.y}));o.push({...o[0]}),e.lines.push({points:o,strokeColor:"rgba(0, 136, 255, 0.95)",label:"outline"});for(const i of this.outlinePolygon)e.points.push({x:i.x,y:i.y,color:"rgba(0, 136, 255, 0.95)"})}for(const o of this.srj.obstacles){if(o.isCopperPour)continue;const i=this.getObstacleZLayers(o);e.rects.push({center:o.center,width:o.width,height:o.height,fill:i.length===1&&i.includes(1)?"rgba(0,0,255,0.3)":"rgba(255,0,0,0.3)",stroke:"red",label:["obstacle",`z: ${i.join(",")}`].join(`
`)})}const n=[...this.finishedNodes,...this.unfinishedNodes];for(const o of n){const i=Math.min(...o.availableZ),r=this.unfinishedNodes.length>0&&o===this.unfinishedNodes[this.unfinishedNodes.length-1];e.rects.push({center:{x:o.center.x+i*o.width*.05,y:o.center.y-i*o.width*.05},width:Math.max(o.width-2,.8*o.width),height:Math.max(o.height-2,.8*o.height),fill:o._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[o.availableZ.join(",")]??"rgba(0,200,200,0.1)",stroke:r?"rgba(255,165,0,0.5)":void 0,label:[o.capacityMeshNodeId,`availableZ: ${o.availableZ.join(",")}`,`target? ${o._containsTarget??!1}`,`obs? ${o._containsObstacle??!1}`,`${o.width.toFixed(2)}x${o.height.toFixed(2)}`,`capacity: ${l7(o).toFixed(2)}`].join(`
`)})}return e.rects.sort((o,i)=>o.center.y-i.center.y),this.srj.connections.forEach((o,i)=>{const r=Y_t[i%Y_t.length];for(const s of o.pointsToConnect){const a=RD(s);e.points.push({x:s.x,y:s.y,label:`conn-${i} (${a.join(",")})`,color:r})}}),e}getObstacleZLayers(e){return this.obstacleZLayersByObstacle.get(e)??[]}},vZn=class extends QZn{constructor(e,n={}){super(e,n),this.srj=e,this.opts=n,this.VIA_DIAMETER=om(e).padDiameter}srj;opts;getSolverName(){return"CapacityMeshNodeSolver2_NodeUnderObstacle"}VIA_DIAMETER=.6;OBSTACLE_MARGIN=.1;OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES=.2;isNodeCompletelyOutsideBounds(e){if(this.outlinePolygon){const n=this.getNodeRect(e);if(!Nse(n,this.outlinePolygon))return!0}return e.center.x+e.width/2<this.srj.bounds.minX||e.center.x-e.width/2>this.srj.bounds.maxX||e.center.y+e.height/2<this.srj.bounds.minY||e.center.y-e.height/2>this.srj.bounds.maxY}isNodePartiallyOutsideBounds(e){if(this.outlinePolygon){const n=this.getNodeRect(e);return!!Nse(n,this.outlinePolygon)&&!E_t(n,this.outlinePolygon)}return e.center.x-e.width/2<this.srj.bounds.minX||e.center.x+e.width/2>this.srj.bounds.maxX||e.center.y-e.height/2<this.srj.bounds.minY||e.center.y+e.height/2>this.srj.bounds.maxY}getObstacleCoveragePercentage(e){const n=this.getXYZOverlappingObstacles(e);if(n.length===0)return 0;const o=e.center.x-e.width/2,i=e.center.x+e.width/2,r=e.center.y-e.height/2,s=e.center.y+e.height/2,a=e.width*e.height;let A=0;for(const c of n){const l=Math.max(o,c.center.x-c.width/2),u=Math.min(i,c.center.x+c.width/2),g=Math.max(r,c.center.y-c.height/2),h=Math.min(s,c.center.y+c.height/2);l<u&&g<h&&(A+=(u-l)*(h-g))}return A/a}shouldFilterSingleLayerNodeForObstacle(e){return e.availableZ.length!==1||!e._containsObstacle?!1:this.getObstacleCoveragePercentage(e)>this.OVERLAP_THRESHOLD_FOR_SINGLE_LAYER_NODES}shouldFilterNodeForObstacle(e){return!!e._containsObstacle&&(e.availableZ.length!==1||this.shouldFilterSingleLayerNodeForObstacle(e))}createChildNodeAtPosition(e,n){const o={capacityMeshNodeId:this.getNextNodeId(),center:n.center,width:n.width,height:n.height,layer:e.layer,availableZ:n.availableZ,_depth:n._depth??(e._depth??0)+1,_parent:e},i=this.getXYZOverlappingObstacles(o);o._containsObstacle=i.length>0||this.isNodePartiallyOutsideBounds(o);const r=this.getTargetIfNodeContainsTarget(o);return r&&(o._targetConnectionName=r.connectionName,o._containsTarget=!0),o._containsObstacle&&(o._completelyInsideObstacle=this.isNodeCompletelyInsideObstacle(o)),o}getZSubdivisionChildNodes(e){if(e.availableZ.length===1)return[];const n=[],o=e.availableZ.map(i=>[i]);for(const i of o){const r=this.createChildNodeAtPosition(e,{center:{...e.center},width:e.width,height:e.height,availableZ:i,_depth:e._depth});this.isNodeCompletelyOutsideBounds(r)||n.push(r)}return n}getChildNodes(e){if(e._depth>=this.MAX_DEPTH)return[];const n=[],o={width:e.width/2,height:e.height/2},i=[{x:e.center.x-o.width/2,y:e.center.y-o.height/2},{x:e.center.x+o.width/2,y:e.center.y-o.height/2},{x:e.center.x-o.width/2,y:e.center.y+o.height/2},{x:e.center.x+o.width/2,y:e.center.y+o.height/2}];for(const r of i){const s=this.createChildNodeAtPosition(e,{center:r,width:o.width,height:o.height,availableZ:e.availableZ});this.isNodeCompletelyOutsideBounds(s)||n.push(s)}return n}shouldNodeBeXYSubdivided(e){return!(e._depth>=this.MAX_DEPTH)&&(!!e._containsTarget||e.availableZ.length===1&&e._depth<=this.MAX_DEPTH||!(!e._containsObstacle||e._completelyInsideObstacle))}_step(){const e=this.unfinishedNodes.pop();if(!e)return void(this.solved=!0);const n=this.getChildNodes(e),o=[],i=[];for(const r of n){const s=this.shouldNodeBeXYSubdivided(r),a=r.availableZ.length>1&&!s&&(r._containsObstacle||r.width<this.VIA_DIAMETER+this.OBSTACLE_MARGIN);if(s)i.push(r);else if(s||this.shouldFilterNodeForObstacle(r)||a)if(!s&&r._containsTarget)if(a){const A=this.getZSubdivisionChildNodes(r);o.push(...A.filter(c=>c._containsTarget||!this.shouldFilterNodeForObstacle(c)))}else o.push(r);else a&&o.push(...this.getZSubdivisionChildNodes(r).filter(A=>!this.shouldFilterNodeForObstacle(A)));else o.push(r)}this.unfinishedNodes.push(...i),this.finishedNodes.push(...o)}},wZn=class extends yr{getSolverName(){return"CapacitySegmentToPointSolver"}unsolvedSegments;solvedSegments;nodeMap;colorMap;constructor({segments:e,colorMap:n,nodes:o}){super(),this.MAX_ITERATIONS=1e5,this.unsolvedSegments=e,this.solvedSegments=[],this.colorMap=n??{},this.nodeMap=Object.fromEntries(o.map(i=>[i.capacityMeshNodeId,i]))}_step(){let e=!1;const n=[...this.unsolvedSegments];for(const o of n){const i=o.connectionNames.length;if((!("assignedPoints"in o)||o.assignedPoints?.length!==i)&&i===1){const r={x:(o.start.x+o.end.x)/2,y:(o.start.y+o.end.y)/2,z:o.availableZ[0]};o.assignedPoints=[{connectionName:o.connectionNames[0],rootConnectionName:o.rootConnectionNames?.[0],point:r}],this.unsolvedSegments.splice(this.unsolvedSegments.indexOf(o),1),this.solvedSegments.push(o),e=!0}}if(!e&&n.length>0){let o=n[0];for(const c of n)c.connectionNames.length<o.connectionNames.length&&(o=c);const i=[...o.connectionNames].sort(),r=o.end.x-o.start.x,s=o.end.y-o.start.y,a=i.length,A=[];for(let c=1;c<=a;c++){const l=c/(a+1);A.push({x:o.start.x+r*l,y:o.start.y+s*l,z:o.availableZ[0]})}o.assignedPoints=i.map((c,l)=>({connectionName:c,rootConnectionName:o.rootConnectionNames?.[o.connectionNames.indexOf(c)],point:A[l]})),this.unsolvedSegments.splice(this.unsolvedSegments.indexOf(o),1),this.solvedSegments.push(o),e=!0}this.unsolvedSegments.length===0&&(this.solved=!0)}getNodesWithPortPoints(){if(!this.solved)throw new Error("CapacitySegmentToPointSolver not solved, can't give port points yet");const e=new Map;for(const n of this.solvedSegments){const o=n.capacityMeshNodeId,i=this.nodeMap[o];e.has(o)||e.set(o,{capacityMeshNodeId:o,portPoints:[],center:i.center,width:i.width,height:i.height}),e.get(o).portPoints.push(...n.assignedPoints.map(r=>({...r.point,connectionName:r.connectionName})))}return Array.from(e.values())}visualize(){const e={points:[],lines:this.solvedSegments.map(i=>({points:[i.start,i.end],step:4})),rects:[],circles:[],coordinateSystem:"cartesian",title:"Capacity Segment to Point Solver"};for(let i=0;i<this.solvedSegments.length;i++){const r=this.solvedSegments[i];for(let s=0;s<r.assignedPoints.length;s++){const a=r.assignedPoints[s],A={x:a.point.x,y:a.point.y},c={x:a.point.x+.05*a.point.z,y:a.point.y+.05*a.point.z};a.point.z!==0&&e.lines.push({points:[A,c],strokeColor:"rgba(0, 0, 0, 0.25)",strokeDash:"5 5",step:4}),e.points.push({x:c.x,y:c.y,label:[`${r.capacityMeshNodeId}-${a.connectionName}`,`z: ${r.availableZ.join(",")}`,`nodePortSegmentId: ${r.nodePortSegmentId}`].join(`
`),color:this.colorMap[a.connectionName],step:4})}}const n=[],o={};for(const i of this.solvedSegments){const r=i.capacityMeshNodeId;o[r]||(o[r]={});for(const s of i.assignedPoints)o[r][s.connectionName]||(o[r][s.connectionName]=[]),o[r][s.connectionName].push({x:s.point.x,y:s.point.y})}for(const i in o)for(const r in o[i]){const s=o[i][r];s.length>1&&n.push({points:s,step:4,strokeDash:"5 5",strokeColor:this.colorMap[r]||"#000"})}return e.lines.push(...n),e}},Wf=(t,e={})=>{const n=Math.min(...t.availableZ);return{center:!e.rectMargin||e.zOffset?{x:t.center.x+n*t.width*(e.zOffset??.05),y:t.center.y-n*t.width*(e.zOffset??.05)}:t.center,width:e.rectMargin?t.width-2*e.rectMargin:Math.max(t.width-.5,.8*t.width),height:e.rectMargin?t.height-2*e.rectMargin:Math.max(t.height-.5,.8*t.height),fill:t._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[t.availableZ.join(",")]??"rgba(0,200,200,0.1)",layer:`z${t.availableZ.join(",")}`,label:[t.capacityMeshNodeId,`availableZ: ${t.availableZ.join(",")}`,t._containsTarget?"containsTarget":"",t._containsObstacle?"containsObstacle":""].filter(Boolean).join(`
`)}},PZn=class extends yr{getSolverName(){return"CapacityPathingSolver"}connectionsWithNodes;usedNodeCapacityMap;simpleRouteJson;nodes;edges;GREEDY_MULTIPLIER=1.1;MAX_CANDIDATES_IN_MEMORY=1e5;nodeMap;nodeEdgeMap;connectionNameToGoalNodeIds;colorMap;maxDepthOfNodes;activeCandidateStraightLineDistance;debug_lastNodeCostMap;hyperParameters;constructor({simpleRouteJson:e,nodes:n,edges:o,colorMap:i,MAX_ITERATIONS:r=1e6,hyperParameters:s={}}){super(),this.MAX_ITERATIONS=r,this.simpleRouteJson=e,this.nodes=n,this.edges=o,this.colorMap=i??{};const{connectionsWithNodes:a,connectionNameToGoalNodeIds:A}=this.getConnectionsWithNodes();this.connectionsWithNodes=a,this.connectionNameToGoalNodeIds=A,this.hyperParameters=s,this.usedNodeCapacityMap=new Map(this.nodes.map(c=>[c.capacityMeshNodeId,0])),this.nodeMap=new Map(this.nodes.map(c=>[c.capacityMeshNodeId,c])),this.nodeEdgeMap=tL(this.edges),this.maxDepthOfNodes=Math.max(...this.nodes.map(c=>c._depth??0)),this.debug_lastNodeCostMap=new Map}getTotalCapacity(e){const n=e._depth??0;return(this.maxDepthOfNodes-n+1)**2}getConnectionsWithNodes(){const e=[],n=this.nodes.filter(i=>i._containsTarget),o=new Map;for(const i of this.simpleRouteJson.connections){const r=[];for(const s of i.pointsToConnect){let a=this.nodes[0],A=Number.MAX_VALUE;for(const c of n){const l=Math.sqrt((c.center.x-s.x)**2+(c.center.y-s.y)**2);l<A&&(A=l,a=c)}r.push(a)}if(r.length<2)throw new Error(`Not enough nodes for connection "${i.name}", only ${r.length} found`);o.set(i.name,r.map(s=>s.capacityMeshNodeId)),e.push({connection:i,nodes:r,pathFound:!1,straightLineDistance:no(r[0].center,r[r.length-1].center)})}return e.sort((i,r)=>i.straightLineDistance-r.straightLineDistance),{connectionsWithNodes:e,connectionNameToGoalNodeIds:o}}currentConnectionIndex=0;candidates;visitedNodes;computeG(e,n,o){return e.g+this.getDistanceBetweenNodes(e.node,n)}computeH(e,n,o){return this.getDistanceBetweenNodes(n,o)}getBacktrackedPath(e){const n=[];let o=e;for(;o;)n.push(o.node),o=o.prevCandidate;return n}getNeighboringNodes(e){return this.nodeEdgeMap.get(e.capacityMeshNodeId).flatMap(n=>n.nodeIds.filter(o=>o!==e.capacityMeshNodeId)).map(n=>this.nodeMap.get(n))}getCapacityPaths(){const e=[];for(const n of this.connectionsWithNodes){const o=n.path;o&&e.push({capacityPathId:n.connection.name,connectionName:n.connection.name,rootConnectionName:n.connection.__rootConnectionNames?.[0],nodeIds:o.map(i=>i.capacityMeshNodeId)})}return e}doesNodeHaveCapacityForTrace(e,n){const o=this.usedNodeCapacityMap.get(e.capacityMeshNodeId)??0,i=this.getTotalCapacity(e);if(e.availableZ.length===1&&!e._containsTarget&&o>0)return!1;let r=0;return e.availableZ.length>1&&n.availableZ.length===1&&(r+=.5),o+r<i}canTravelThroughObstacle(e,n){return this.connectionNameToGoalNodeIds.get(n)?.includes(e.capacityMeshNodeId)??!1}getDistanceBetweenNodes(e,n){return Math.sqrt((e.center.x-n.center.x)**2+(e.center.y-n.center.y)**2)}reduceCapacityAlongPath(e){for(const n of e.path??[])this.usedNodeCapacityMap.set(n.capacityMeshNodeId,this.usedNodeCapacityMap.get(n.capacityMeshNodeId)+1)}isConnectedToEndGoal(e,n){return this.nodeEdgeMap.get(e.capacityMeshNodeId).some(o=>o.nodeIds.includes(n.capacityMeshNodeId))}_step(){const e=this.connectionsWithNodes[this.currentConnectionIndex];if(!e)return void(this.solved=!0);const[n,o]=e.nodes;this.candidates||(this.candidates=[{prevCandidate:null,node:n,f:0,g:0,h:0}],this.debug_lastNodeCostMap=new Map,this.visitedNodes=new Set([n.capacityMeshNodeId]),this.activeCandidateStraightLineDistance=no(n.center,o.center)),this.candidates.sort((s,a)=>s.f-a.f);const i=this.candidates.shift();if(this.candidates.length>this.MAX_CANDIDATES_IN_MEMORY&&this.candidates.splice(this.MAX_CANDIDATES_IN_MEMORY,this.candidates.length-this.MAX_CANDIDATES_IN_MEMORY),!i)return console.error(`Ran out of candidates on connection ${e.connection.name}`),this.currentConnectionIndex++,this.candidates=null,this.visitedNodes=null,void(this.failed=!0);if(this.isConnectedToEndGoal(i.node,o))return e.path=this.getBacktrackedPath({prevCandidate:i,node:o,f:0,g:0,h:0}),this.reduceCapacityAlongPath(e),this.currentConnectionIndex++,this.candidates=null,void(this.visitedNodes=null);const r=this.getNeighboringNodes(i.node);for(const s of r){if(this.visitedNodes?.has(s.capacityMeshNodeId)||!this.doesNodeHaveCapacityForTrace(s,i.node))continue;const a=this.connectionsWithNodes[this.currentConnectionIndex].connection.name;if(s._containsObstacle&&!this.canTravelThroughObstacle(s,a))continue;const A=this.computeG(i,s,o),c=this.computeH(i,s,o),l=A+c*this.GREEDY_MULTIPLIER;this.debug_lastNodeCostMap.set(s.capacityMeshNodeId,{f:l,g:A,h:c});const u={prevCandidate:i,node:s,f:l,g:A,h:c};this.candidates.push(u)}this.visitedNodes.add(i.node.capacityMeshNodeId)}visualize(){const e={lines:[],points:[],rects:[],circles:[]};if(this.connectionsWithNodes)for(let o=0;o<this.connectionsWithNodes.length;o++){const i=this.connectionsWithNodes[o];if(i.path&&i.path.length>0){const r=i.path.map(({center:{x:s,y:a},width:A,availableZ:c})=>({x:s+.005*A*(o%10+o%19),y:a+.005*A*(o%10+o%19),availableZ:c}));e.lines.push({points:r,strokeColor:this.colorMap[i.connection.name]});for(let s=0;s<r.length;s++){const a=r[s];e.points.push({x:a.x,y:a.y,label:[`conn: ${i.connection.name}`,`node: ${i.path[s].capacityMeshNodeId}`,`z: ${a.availableZ.join(",")}`].join(`
`)})}}}for(const o of this.nodes){const i=this.usedNodeCapacityMap.get(o.capacityMeshNodeId)??0,r=this.getTotalCapacity(o),s=this.debug_lastNodeCostMap.get(o.capacityMeshNodeId);e.rects.push({...Wf(o,{rectMargin:.025,zOffset:.01}),label:[`${o.capacityMeshNodeId}`,`${i}/${r}`,`${o.width.toFixed(2)}x${o.height.toFixed(2)}`,`g: ${s?.g!==void 0?s.g.toFixed(2):"?"}`,`h: ${s?.h!==void 0?s.h.toFixed(2):"?"}`,`f: ${s?.f!==void 0?s.f.toFixed(2):"?"}`,`z: ${o.availableZ.join(", ")}`].join(`
`),stroke:i>r+.5?"red":void 0})}if(this.connectionsWithNodes){for(const o of this.connectionsWithNodes)if(o.connection?.pointsToConnect)for(const i of o.connection.pointsToConnect)e.points.push({x:i.x,y:i.y,label:[`pointsToConnect ${o.connection.name}`].join(`
`)})}let n=this.connectionsWithNodes[this.currentConnectionIndex];if(!this.candidates&&this.currentConnectionIndex>0&&!this.connectionsWithNodes[this.currentConnectionIndex-1].path&&(n=this.connectionsWithNodes[this.currentConnectionIndex-1]),n){const[o,i]=n.connection.pointsToConnect;e.lines.push({points:[{x:o.x,y:o.y},{x:i.x,y:i.y}],strokeColor:"red",strokeDash:"10 5"})}if(this.candidates){const o=this.candidates.slice(0,5),i=this.connectionsWithNodes[this.currentConnectionIndex].connection.name;o.forEach((r,s)=>{const a=.5*(1-s/5),A=this.getBacktrackedPath(r);e.lines.push({points:A.map(({center:{x:c,y:l}})=>({x:c,y:l})),strokeColor:Es(this.colorMap[i]??"red",1-a)})})}return e}},MZn=class extends PZn{getSolverName(){return"CapacityPathingSolver5"}NEGATIVE_CAPACITY_PENALTY_FACTOR=1;REDUCED_CAPACITY_PENALTY_FACTOR=1;constructor(...t){super(...t),this.GREEDY_MULTIPLIER=2.5}get maxCapacityFactor(){return this.hyperParameters.MAX_CAPACITY_FACTOR??1}getTotalCapacity(t){return l7(t,this.maxCapacityFactor)}getNodeCapacityPenalty(t){const e=t.width+t.height,n=.05,o=this.getTotalCapacity(t)-(this.usedNodeCapacityMap.get(t.capacityMeshNodeId)??0);return o>2?n:(e-n)*Math.max(1,(2-o)/(e-n))+n}getDistanceBetweenNodes(t,e){const n=t.center.x-e.center.x,o=t.center.y-e.center.y;return Math.sqrt(n**2+o**2)}computeG(t,e,n){return t.g+this.getDistanceBetweenNodes(t.node,e)+this.getNodeCapacityPenalty(e)}computeH(t,e,n){return this.getDistanceBetweenNodes(e,n)+this.getNodeCapacityPenalty(e)}},r1t=class extends MZn{getSolverName(){return"CapacityPathingGreedySolver"}doesNodeHaveCapacityForTrace(e,n){return!0}getNodeCapacityPenalty(e){const n=this.getTotalCapacity(e)-(this.usedNodeCapacityMap.get(e.capacityMeshNodeId)??0)-1;if(n>0)return 0;let o=1;return e.availableZ.length===1&&(o=10),(.05+2*Math.abs(n))*o}};function s1t(t,e,n){const o=e.x-t.x,i=e.y-t.y;if(Math.abs(o)<1e-9&&Math.abs(i)<1e-9)return t;const r=n.width/2,s=n.height/2,a=n.center.x-r,A=n.center.x+r,c=n.center.y-s,l=n.center.y+s;let u=0,g=1/0;if(Math.abs(o)>1e-9){const h=(a-t.x)/o,d=(A-t.x)/o;u=Math.max(u,Math.min(h,d)),g=Math.min(g,Math.max(h,d))}else if(t.x<a||t.x>A)return t;if(Math.abs(i)>1e-9){const h=(c-t.y)/i,d=(l-t.y)/i;u=Math.max(u,Math.min(h,d)),g=Math.min(g,Math.max(h,d))}else if(t.y<c||t.y>l)return t;return g<u||u===1/0||u<-1e9?t:{x:t.x+o*u,y:t.y+i*u}}function DZn(t,e){const n=t.center,o=e.center,i=s1t(n,o,t),r=s1t(o,n,e),s=o.x-n.x,a=o.y-n.y,A=Math.sqrt(s*s+a*a);let c=i,l=r;if(A>1e-9){const u={x:s/A,y:a/A},g=.3*t.width,h=.3*e.width;g+h<Math.sqrt((r.x-i.x)**2+(r.y-i.y)**2)?(c={x:i.x+u.x*g,y:i.y+u.y*g},l={x:r.x-u.x*h,y:r.y-u.y*h}):(c=i,l=r)}return{lineStart:c,lineEnd:l}}var uae=t=>{const{usedCapacity:e,totalCapacity:n,layerCount:o}=t;if(e<n||n<1&&e<=1)return 0;if(o===1&&e>1)return 1-.01**e;const i=e/n-1;return 1-Math.exp(-2*i)},r6e=(t,e,n)=>{if(n._containsTarget||t<=e)return 0;const o=1-uae({usedCapacity:t,totalCapacity:e,layerCount:n.availableZ.length});return o<=0?-1e9:Math.log(o)},Zz=({totalNodeCapacityMap:t,usedNodeCapacityMap:e,nodeMap:n,sectionNodeIds:o})=>{let i=0;const r=o??new Set(e.keys());for(const s of r){if(!t.has(s))continue;const a=n.get(s);if(!a)continue;const A=t.get(s),c=e.get(s)??0;i+=r6e(c,A,a)}return i};function s6e({sectionNodes:t,sectionEdges:e,sectionConnectionTerminals:n,completedPaths:o,nodeMap:i,colorMap:r,centerNodeId:s,title:a,nodeOpacity:A=.1,usedNodeCapacityMap:c,totalCapacityMap:l}){const u={points:[],lines:[],rects:[],circles:[],title:a},g=new Set(t.map(h=>h.capacityMeshNodeId));for(const h of t){let d=`rgba(128, 128, 128, ${A})`,p=`rgba(128, 128, 128, ${A})`;const m=h.availableZ??[],_=m.includes(0),f=m.includes(1);_&&f?(d=`rgba(128, 0, 128, ${A})`,p=`rgba(128, 0, 128, ${A})`):_?(d=`rgba(0, 0, 255, ${A})`,p=`rgba(0, 0, 255, ${A})`):f&&(d=`rgba(255, 0, 0, ${A})`,p=`rgba(255, 0, 0, ${A})`),s&&h.capacityMeshNodeId===s&&(d=`rgba(0, 255, 0, ${A})`,p=`rgba(0, 128, 0, ${A})`),u.rects.push({...Wf(h),fill:d,stroke:p,label:`${h.capacityMeshNodeId}
(Section Node)
Z: ${m.join(",")}`});const I=u.rects.length-1;if(c&&l){const C=c.get(h.capacityMeshNodeId)??0,y=l.get(h.capacityMeshNodeId)??0,x=y>0?(C/y*100).toFixed(1):"N/A",E=uae({usedCapacity:C,totalCapacity:y,layerCount:h.availableZ.length});u.rects[I].label+=`
${C.toFixed(1)} / ${y.toFixed(1)}
${x}% (Pf: ${(100*E).toFixed(1)}%)`,E>.2&&(u.rects[I].stroke=Es("red",.7*(.8+A)))}}for(const h of e){const[d,p]=h.nodeIds,m=i.get(d),_=i.get(p);if(m&&_){const{lineStart:f,lineEnd:I}=DZn(m,_);u.lines.push({points:[f,I],strokeColor:`rgba(0, 0, 0, ${.2*Math.min(1,A/.1)})`})}}return n.forEach((h,d)=>{const p=i.get(h.startNodeId),m=i.get(h.endNodeId),_=r[h.connectionName]??"black",f=p&&g.has(p.capacityMeshNodeId),I=m&&g.has(m.capacityMeshNodeId),C=(d+d/50)%5;let y=0,x=0,E=0,B=0;if(f&&p){const S=.02*Math.min(p.width,p.height);y=S*C,x=S*C,u.points.push({x:p.center.x+y,y:p.center.y+x,color:_,label:`Start: ${h.connectionName}
(${h.startNodeId})`}),u.lines.push({points:[{x:p.center.x,y:p.center.y},{x:p.center.x+y,y:p.center.y+x}],strokeColor:"gray",strokeDash:"2 2"})}if(I&&m){const S=.02*Math.min(m.width,m.height);E=S*C,B=S*C,u.points.push({x:m.center.x+E,y:m.center.y+B,color:_,label:`End: ${h.connectionName}
(${h.endNodeId})`}),u.lines.push({points:[{x:m.center.x,y:m.center.y},{x:m.center.x+E,y:m.center.y+B}],strokeColor:"gray",strokeDash:"2 2"})}f&&I&&p&&m&&u.lines.push({points:[{x:p.center.x+y,y:p.center.y+x},{x:m.center.x+E,y:m.center.y+B}],strokeColor:_,strokeDash:"5 5"})}),o&&o.forEach((h,d)=>{if(h.path&&h.path.length>0){const p=r[h.connectionName]??"gray",m={x:(d+d/50)%5*.03,y:(d+d/50)%5*.03};u.lines.push({points:h.path.map(({center:{x:_,y:f}})=>({x:_+m.x,y:f+m.y})),strokeColor:Es(p,.2)})}}),u}var NZn=class extends yr{getSolverName(){return"CapacityPathingSingleSectionSolver"}GREEDY_MULTIPLIER=1.5;sectionNodes;sectionEdges;sectionConnectionTerminals;nodeMap;nodeEdgeMap;colorMap;usedNodeCapacityMap;totalNodeCapacityMap;centerNodeId;currentSectionScore=0;MAX_CANDIDATES_IN_MEMORY=1e4;currentConnectionIndex=0;candidates=null;visitedNodes=null;queuedNodes=null;activeCandidateStraightLineDistance;debug_lastNodeCostMap=new Map;maxCapacityFactor=1;constructor(e){super(),this.MAX_ITERATIONS=1e4,this.centerNodeId=e.centerNodeId,this.sectionNodes=e.sectionNodes,this.sectionEdges=e.sectionEdges,this.sectionConnectionTerminals=e.sectionConnectionTerminals.map(o=>({...o,path:void 0})),this.nodeMap=e.nodeMap??new Map(this.sectionNodes.map(o=>[o.capacityMeshNodeId,o])),this.nodeEdgeMap=e.nodeEdgeMap??tL(this.sectionEdges),this.colorMap=e.colorMap??{},this.usedNodeCapacityMap=new Map(this.sectionNodes.map(o=>[o.capacityMeshNodeId,0])),this.totalNodeCapacityMap=new Map(this.sectionNodes.map(o=>[o.capacityMeshNodeId,this.getTotalCapacity(o)]));const n=new Set(this.sectionNodes.map(o=>o.capacityMeshNodeId));this.currentSectionScore=Zz({totalNodeCapacityMap:this.totalNodeCapacityMap,usedNodeCapacityMap:this.usedNodeCapacityMap,nodeMap:this.nodeMap,sectionNodeIds:n}),e.hyperParameters?.SHUFFLE_SEED&&(this.sectionConnectionTerminals=D5(this.sectionConnectionTerminals,e.hyperParameters?.SHUFFLE_SEED))}getTotalCapacity(e){return l7(e,this.maxCapacityFactor)}getNodeCapacityPenalty(e){if(!this.nodeMap.has(e.capacityMeshNodeId))return 1/0;const n=this.getTotalCapacity(e)-(this.usedNodeCapacityMap.get(e.capacityMeshNodeId)??0)-1;if(n>0)return 0;let o=1;return e.availableZ.length===1&&(o=10),(.05+n**2*4)*o}getDistanceBetweenNodes(e,n){const o=e.center.x-n.center.x,i=e.center.y-n.center.y;return Math.sqrt(o**2+i**2)}computeG(e,n,o){return e.g+this.getDistanceBetweenNodes(e.node,n)+this.getNodeCapacityPenalty(n)}computeH(e,n,o){return this.getDistanceBetweenNodes(n,o)+this.getNodeCapacityPenalty(n)}getBacktrackedPath(e){const n=[];let o=e;for(;o;){if(n.push(o.node),!this.nodeMap.has(o.node.capacityMeshNodeId)){console.warn("Backtracked path went outside section bounds");break}o=o.prevCandidate}return n.reverse()}getNeighboringNodes(e){return this.nodeMap.has(e.capacityMeshNodeId)?this.nodeEdgeMap.get(e.capacityMeshNodeId)?.flatMap(n=>n.nodeIds.filter(o=>o!==e.capacityMeshNodeId)).map(n=>this.nodeMap.get(n)).filter(Boolean)??[]:[]}isConnectedToEndGoal(e,n){return!(!this.nodeMap.has(e.capacityMeshNodeId)||!this.nodeMap.has(n.capacityMeshNodeId))&&(this.nodeEdgeMap.get(e.capacityMeshNodeId)??[]).some(o=>o.nodeIds.includes(n.capacityMeshNodeId))}doesNodeHaveCapacityForTrace(e,n){return!0}reduceCapacityAlongPath(e){for(const n of e)if(this.usedNodeCapacityMap.has(n.capacityMeshNodeId)){const o=n.capacityMeshNodeId,i=this.nodeMap.get(o);if(!i){console.warn(`Node ${o} from path not found in section's nodeMap during score update.`);continue}const r=this.totalNodeCapacityMap.get(o),s=this.usedNodeCapacityMap.get(o)??0,a=r6e(s,r,i);this.currentSectionScore-=a;const A=s+1;this.usedNodeCapacityMap.set(o,A);const c=r6e(A,r,i);this.currentSectionScore+=c}}getSolvedSectionScore(){return this.currentSectionScore}_step(){const e=this.sectionConnectionTerminals[this.currentConnectionIndex];if(!e)return void(this.solved=!0);const n=this.nodeMap.get(e.startNodeId),o=this.nodeMap.get(e.endNodeId);if(!n||!o)return console.error(`Start or end node not found in section for connection ${e.connectionName}`),this.currentConnectionIndex++,this.candidates=null,void(this.visitedNodes=null);this.candidates||this._setupAStar(n,o);const i=this.candidates;if(i.length===0)return void this._handleCandidatesExhausted(e);i.sort((a,A)=>a.f-A.f);const r=i.shift();if(i.length>this.MAX_CANDIDATES_IN_MEMORY&&i.splice(this.MAX_CANDIDATES_IN_MEMORY,i.length-this.MAX_CANDIDATES_IN_MEMORY),this.visitedNodes.add(r.node.capacityMeshNodeId),r.node.capacityMeshNodeId===o.capacityMeshNodeId)return void this._handleGoalReached(r,e,o);const s=this.getNeighboringNodes(r.node);for(const a of s){if(this.queuedNodes?.has(a.capacityMeshNodeId)||!this.doesNodeHaveCapacityForTrace(a,r.node))continue;if(a._containsObstacle){const g=a.capacityMeshNodeId===e.startNodeId,h=a.capacityMeshNodeId===e.endNodeId;if(!g&&!h)continue}const A=this.computeG(r,a,o),c=this.computeH(r,a,o),l=A+c*this.GREEDY_MULTIPLIER;this.debug_lastNodeCostMap.set(a.capacityMeshNodeId,{f:l,g:A,h:c});const u={prevCandidate:r,node:a,f:l,g:A,h:c};this.queuedNodes?.add(a.capacityMeshNodeId),i.push(u)}}computeProgress(){const e=this.sectionConnectionTerminals.length;if(e===0)return 1;let n=this.currentConnectionIndex/e;if(this.currentConnectionIndex<e&&this.candidates&&this.candidates.length>0&&this.activeCandidateStraightLineDistance&&this.activeCandidateStraightLineDistance>0){const o=this.candidates.reduce((i,r)=>r.f<i.f?r:i);n+=Math.max(0,Math.min(1,1-o.h/this.activeCandidateStraightLineDistance))/e}else this.solved&&(n=1);return Math.min(1,n)}_setupAStar(e,n){this.candidates=[{prevCandidate:null,node:e,f:0,g:0,h:0}],this.visitedNodes=new Set([e.capacityMeshNodeId]),this.debug_lastNodeCostMap=new Map,this.activeCandidateStraightLineDistance=no(e.center,n.center);const o=this.computeH(null,e,n);this.candidates[0].h=o,this.candidates[0].f=o*this.GREEDY_MULTIPLIER,this.debug_lastNodeCostMap.set(e.capacityMeshNodeId,{f:this.candidates[0].f,g:0,h:o}),this.queuedNodes=new Set([e.capacityMeshNodeId])}_handleCandidatesExhausted(e){console.error(`Ran out of candidates for section connection ${e.connectionName}`),this.currentConnectionIndex++,this.candidates=null,this.visitedNodes=null,this.queuedNodes=null}_handleGoalReached(e,n,o){const i=this.getBacktrackedPath(e);n.path=i,this.reduceCapacityAlongPath(i),this.currentConnectionIndex++,this.candidates=null,this.visitedNodes=null,this.queuedNodes=null}visualize(){const e=this.sectionConnectionTerminals.filter(o=>o.path&&o.path.length>0).map(o=>({connectionName:o.connectionName,path:o.path})),n=s6e({sectionNodes:this.sectionNodes,sectionEdges:this.sectionEdges,sectionConnectionTerminals:this.sectionConnectionTerminals,completedPaths:e,nodeMap:this.nodeMap,colorMap:this.colorMap,centerNodeId:null,title:`Section Pathing: Conn ${this.currentConnectionIndex+1}/${this.sectionConnectionTerminals.length} (${this.sectionNodes.length} nodes)`,nodeOpacity:.1});for(const o of this.sectionNodes){const i=n.rects.findIndex(r=>r.label?.includes(o.capacityMeshNodeId));if(i!==-1){const r=this.debug_lastNodeCostMap.get(o.capacityMeshNodeId),s=this.usedNodeCapacityMap.get(o.capacityMeshNodeId)??0,a=this.getTotalCapacity(o),A=`${s.toFixed(1)}/${a.toFixed(1)}`,c=r?`f:${r.f.toFixed(1)} g:${r.g.toFixed(1)} h:${r.h.toFixed(1)}`:"cost:?";n.rects[i].label=[o.capacityMeshNodeId,`Cap: ${A}`,c,`Z: ${o.availableZ.join(",")}`].join(`
`),s>a&&(n.rects[i].stroke=Es("red",.7))}}if(this.candidates&&this.candidates.length>0){const o=this.candidates.slice().sort((a,A)=>a.f-A.f).slice(0,5),i=this.sectionConnectionTerminals[this.currentConnectionIndex],r=i?.connectionName??"unknown",s=this.colorMap[r]??"purple";o.forEach((a,A)=>{const c=.8*(1-A/5),l=this.getBacktrackedPath(a);l.length>0&&n.lines.push({points:l.map(({center:{x:u,y:g}})=>({x:u,y:g})),strokeColor:Es(s,1-c),strokeWidth:.05})})}return n}},gae=t=>Array.from({length:t},(e,n)=>n),RZn=class extends Zse{getSolverName(){return"HyperCapacityPathingSingleSectionSolver"}constructorParams;constructor(e){super(),this.MAX_ITERATIONS=1e5,this.constructorParams=e}computeG(e){return-e.getSolvedSectionScore()}computeH(e){return 0}getCombinationDefs(){const e=this.constructorParams.sectionConnectionTerminals.length;return e===2?[["orderings2_for2"]]:e===3?[["orderings6_for3"]]:e===4?[["orderings24_for4"]]:[["orderings30"]]}getFailureMessage(){return`All CapacityPathingSingleSection solvers failed for "${this.centerNodeId}"`}getHyperParameterDefs(){return[{name:"orderings2_for2",possibleValues:gae(2).map(e=>({SHUFFLE_SEED:e}))},{name:"orderings6_for3",possibleValues:gae(6).map(e=>({SHUFFLE_SEED:e}))},{name:"orderings24_for4",possibleValues:gae(24).map(e=>({SHUFFLE_SEED:e}))},{name:"orderings30",possibleValues:gae(30).map(e=>({SHUFFLE_SEED:e}))}]}generateSolver(e){return new NZn({...this.constructorParams,hyperParameters:{...this.constructorParams.hyperParameters,...e}})}onSolve({solver:e}){this.winningSolver=e}get centerNodeId(){return this.constructorParams.centerNodeId}get sectionNodes(){return this.constructorParams.sectionNodes}get sectionConnectionTerminals(){return this.winningSolver?.sectionConnectionTerminals}},TZn=t=>Math.floor(10*t)/10,kZn=class extends RZn{cacheHit=!1;cacheProvider;hasAttemptedToUseCache=!1;sectionNodeIdSet;cachedSectionConnectionTerminals=null;sectionScore=0;constructor(e){e.nodeMap=e.nodeMap??new Map(e.sectionNodes.map(n=>[n.capacityMeshNodeId,n])),super(e),this.sectionNodeIdSet=new Set(e.sectionNodes.map(n=>n.capacityMeshNodeId)),this.cacheProvider=e.cacheProvider===void 0?tB():e.cacheProvider}_step(){!this.hasAttemptedToUseCache&&this.cacheProvider&&this.attemptToUseCacheSync()||(super._step(),(this.solved||this.failed)&&this.cacheProvider&&this.saveToCacheSync())}_computeBfsOrderingOfNodesInSection(){const e=new Set(this.constructorParams.centerNodeId),n=[],o=[{ancestorCapacitySum:0,capacity:0,g:0,capacityMeshNodeId:this.constructorParams.centerNodeId}];for(;o.length>0;){o.sort((s,a)=>a.g-s.g);const i=o.pop();if(!i)break;n.push(i.capacityMeshNodeId);const r=this.constructorParams.nodeEdgeMap.get(i.capacityMeshNodeId).flatMap(s=>s.nodeIds).filter(s=>!e.has(s)).filter(s=>this.sectionNodeIdSet.has(s));for(const s of r){e.add(s);const a=this.constructorParams.nodeMap.get(s),A=l7(a);o.push({ancestorCapacitySum:i.g,capacity:A,g:i.g+A,capacityMeshNodeId:s})}}return n}computeCacheKeyAndTransform(){const e=this._computeBfsOrderingOfNodesInSection(),n=new Map,o=new Map;e.forEach((g,h)=>{const d=`node${h}`;n.set(g,d),o.set(d,g)});const i={};for(const g of e){const h=n.get(g),d=this.constructorParams.nodeMap.get(g),p=l7(d);i[h]=TZn(p).toFixed(1)}const r=new Set,s=[];for(const g of e){const h=n.get(g),d=this.constructorParams.nodeEdgeMap.get(g)??[];for(const p of d){const m=p.nodeIds.find(_=>_!==g);if(this.sectionNodeIdSet.has(m)){const _=[h,n.get(m)].sort(),f=`${_[0]}-${_[1]}`;r.has(f)||(s.push(_),r.add(f))}}}s.sort((g,h)=>g[0]!==h[0]?g[0].localeCompare(h[0]):g[1].localeCompare(h[1]));const a={},A=new Map,c=new Map;for(const g of this.constructorParams.sectionConnectionTerminals){const h=n.get(g.startNodeId),d=n.get(g.endNodeId),[p,m]=[h,d].sort(),_=`${p}->${m}`,f=c.get(_)??0;c.set(_,f+1);const I=`${p}->${m}::${f}`;a[I]={start:p,end:m},A.set(I,g.connectionName)}const l=`capacitypathing:${$9e({node_capacity_map:i,node_edge_map:s,terminals:a})}`,u={cacheSpaceToRealConnectionId:A,cacheSpaceToRealNodeId:o};return this.cacheKey=l,this.cacheToSolveSpaceTransform=u,{cacheKey:l,cacheToSolveSpaceTransform:u}}applyCachedSolution(e){if(!this.cacheToSolveSpaceTransform)return console.error("Cache transform not available, cannot apply cached solution."),void(this.failed=!0);if(!e.success)return this.failed=!0,void(this.cacheHit=!0);this.cachedSectionConnectionTerminals=[];const{cacheSpaceToRealNodeId:n,cacheSpaceToRealConnectionId:o}=this.cacheToSolveSpaceTransform;for(const[i,r]of Object.entries(e.solutionPaths)){const s=o.get(i);if(!s){console.warn(`Could not find real connection name for ${i}`);continue}const a=this.constructorParams.sectionConnectionTerminals.find(c=>c.connectionName===s);if(!a){console.warn(`Could not find original terminal for connection name ${s}`);continue}const A=r.map(c=>{const l=n.get(c);if(!l)throw new Error(`Could not map cache node ID ${c} to real node ID for connection ${s}`);const u=this.constructorParams.nodeMap.get(l);if(!u)throw new Error(`Could not find node with ID ${l} in nodeMap for connection ${s}`);return u});this.cachedSectionConnectionTerminals.push({...a,path:A})}this.sectionScore=e.sectionScore,this.solved=!0,this.cacheHit=!0}attemptToUseCacheSync(){if(this.hasAttemptedToUseCache=!0,!this.cacheProvider?.isSyncCache)return console.log("Cache provider is not synchronous, skipping sync cache check."),!1;if(this.cacheKey||this.computeCacheKeyAndTransform(),!this.cacheKey)return console.error("Failed to compute cache key."),!1;try{const e=this.cacheProvider.getCachedSolutionSync(this.cacheKey);if(e)return this.applyCachedSolution(e),!0}catch(e){console.error("Error attempting to use cache:",e)}return!1}saveToCacheSync(){if(!this.cacheKey)return void console.error("Cannot save to cache without cache key.");if(!this.cacheToSolveSpaceTransform)return void console.error("Cache transform not available, cannot save solution to cache.");let e;if(this.failed)e={success:!1};else{if(!this.solved)return;{const n={},{cacheSpaceToRealNodeId:o,cacheSpaceToRealConnectionId:i}=this.cacheToSolveSpaceTransform,r=new Map;for(const[A,c]of o)r.set(c,A);const s=new Map;for(const[A,c]of i)s.set(c,A);const a=[];if(super.sectionConnectionTerminals){for(const A of super.sectionConnectionTerminals)if(A.path&&A.path.length>0){const c=A.path.map(l=>l.capacityMeshNodeId);a.push([A.connectionName,c])}}for(const[A,c]of a){const l=s.get(A);if(!l){console.warn(`Could not find cache space connection ID for ${A} when saving to cache.`);continue}const u=c.map(g=>{const h=r.get(g);if(!h)throw new Error(`Could not map real node ID ${g} to cache node ID for connection ${A} when saving to cache.`);return h});n[l]=u}e={success:!0,sectionScore:this.sectionScore,solutionPaths:n}}}try{this.cacheProvider?.setCachedSolutionSync(this.cacheKey,e)}catch(n){console.error("Error saving solution to cache:",n)}}get sectionConnectionTerminals(){return this.cacheHit&&this.solved&&this.cachedSectionConnectionTerminals?(console.log("returning the cached section connection terminals"),this.cachedSectionConnectionTerminals):super.sectionConnectionTerminals}visualize(){return this.cacheHit?s6e({sectionNodes:this.constructorParams.sectionNodes,sectionEdges:this.constructorParams.sectionEdges,sectionConnectionTerminals:this.cachedSectionConnectionTerminals,completedPaths:this.cachedSectionConnectionTerminals.map(e=>({connectionName:e.connectionName,path:e.path})),nodeMap:this.constructorParams.nodeMap,colorMap:this.constructorParams.colorMap,title:"CachedHyperCapacityPathingSingleSectionSolver"}):super.visualize()}},FZn=class extends yr{getSolverName(){return"CapacityPathingMultiSectionSolver"}simpleRouteJson;nodes;edges;nodeEdgeMap;connectionsWithNodes=[];colorMap;initialSolver;cacheProvider;stage="initialization";nodeMap=new Map;allNodeIdsSet;usedNodeCapacityMap=new Map;totalNodeCapacityMap=new Map;nodeCapacityPercentMap=new Map;nodeOptimizationAttemptCountMap=new Map;currentSection=null;sectionSolver=null;currentScheduleIndex=0;stats;OPTIMIZATION_SCHEDULE=[{MAX_ATTEMPTS_PER_NODE:1,MAX_EXPANSION_DEGREES:3,MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE:.05},{MAX_ATTEMPTS_PER_NODE:2,MAX_EXPANSION_DEGREES:5,MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE:.2},{MAX_ATTEMPTS_PER_NODE:3,MAX_EXPANSION_DEGREES:7,MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE:.9}];get currentSchedule(){return this.OPTIMIZATION_SCHEDULE[this.currentScheduleIndex]??null}constructor(e){super(),this.stats={successfulOptimizations:0,failedOptimizations:0,failedSectionSolvers:0,startingScore:0,scheduleScores:this.OPTIMIZATION_SCHEDULE.map(({MAX_EXPANSION_DEGREES:n})=>({maxExpansionDegrees:n,endingScore:0,endingHighestNodePf:0,sectionAttempts:0})),cacheHits:0,cacheMisses:0},this.MAX_ITERATIONS=e.MAX_ITERATIONS??1e7,this.cacheProvider=e.cacheProvider,this.simpleRouteJson=e.simpleRouteJson,this.nodes=e.nodes,this.edges=e.edges,this.nodeEdgeMap=tL(this.edges),this.colorMap=e.colorMap??{},this.nodeMap=new Map(this.nodes.map(n=>[n.capacityMeshNodeId,n])),this.nodeEdgeMap=tL(this.edges),this.initialSolver=e.initialPathingSolver||new r1t({simpleRouteJson:this.simpleRouteJson,nodes:this.nodes,edges:this.edges,colorMap:this.colorMap}),this.activeSubSolver=this.initialSolver;for(const n of this.nodes){const o=this.initialSolver.getTotalCapacity(n);this.totalNodeCapacityMap.set(n.capacityMeshNodeId,o)}this.allNodeIdsSet=new Set(this.nodes.map(n=>n.capacityMeshNodeId))}_stepInitialization(){if(this.initialSolver?.step(),this.initialSolver?.failed)return this.failed=!0,void(this.error=this.initialSolver.error);if(this.initialSolver?.solved){this.usedNodeCapacityMap=new Map(this.initialSolver.usedNodeCapacityMap);for(const e of this.nodes){const n=this.totalNodeCapacityMap.get(e.capacityMeshNodeId)??0,o=this.usedNodeCapacityMap.get(e.capacityMeshNodeId)??0,i=n>0?o/n:0;this.nodeCapacityPercentMap.set(e.capacityMeshNodeId,i),this.nodeOptimizationAttemptCountMap.set(e.capacityMeshNodeId,0)}this.connectionsWithNodes=this.initialSolver.connectionsWithNodes,this.stats.startingScore=Zz({totalNodeCapacityMap:this.totalNodeCapacityMap,usedNodeCapacityMap:this.usedNodeCapacityMap,nodeMap:this.nodeMap,sectionNodeIds:this.allNodeIdsSet}),this.stage="section-optimization"}}_getNextNodeToOptimize(){let e=0,n=null;for(const o of this.nodes){if(o._containsTarget)continue;const i=this.nodeOptimizationAttemptCountMap.get(o.capacityMeshNodeId),r=this.totalNodeCapacityMap.get(o.capacityMeshNodeId),s=uae({usedCapacity:this.usedNodeCapacityMap.get(o.capacityMeshNodeId)??0,totalCapacity:r,layerCount:o.availableZ.length}),a=s/(i+1);i<this.currentSchedule.MAX_ATTEMPTS_PER_NODE&&a>e&&s>this.currentSchedule.MINIMUM_PROBABILITY_OF_FAILURE_TO_OPTIMIZE&&(e=a,n=o.capacityMeshNodeId)}return n}getOverallScore(){let e=0;for(const n of this.nodes){if(n._containsTarget)continue;const o=this.totalNodeCapacityMap.get(n.capacityMeshNodeId),i=uae({usedCapacity:this.usedNodeCapacityMap.get(n.capacityMeshNodeId)??0,totalCapacity:o,layerCount:n.availableZ.length});i>e&&(e=i)}return{highestNodePf:e,score:Zz({totalNodeCapacityMap:this.totalNodeCapacityMap,usedNodeCapacityMap:this.usedNodeCapacityMap,nodeMap:this.nodeMap,sectionNodeIds:this.allNodeIdsSet})}}_stepSectionOptimization(){if(!this.sectionSolver){const e=this._getNextNodeToOptimize();if(!e){const{highestNodePf:o,score:i}=this.getOverallScore();return this.stats.scheduleScores[this.currentScheduleIndex].endingHighestNodePf=o,this.stats.scheduleScores[this.currentScheduleIndex].endingScore=i,this.currentScheduleIndex++,void(this.currentSchedule||(this.solved=!0))}const n=(o=>{const{centerNodeId:i,connectionsWithNodes:r,nodeMap:s,edges:a,nodeEdgeMap:A,expansionDegrees:c}=o,l=new Set,u=[{nodeId:i,depth:0}];l.add(i);let g=0;for(;g<u.length;){const{nodeId:m,depth:_}=u[g++];if(_>=c)continue;const f=A.get(m)?.flatMap(I=>I.nodeIds.filter(C=>C!==m))??[];for(const I of f)l.has(I)||(l.add(I),u.push({nodeId:I,depth:_+1}))}const h=Array.from(l).map(m=>s.get(m)),d=a.filter(m=>{const[_,f]=m.nodeIds;return l.has(_)&&l.has(f)}),p=[];for(const m of r){if(!m.path)continue;let _=null,f=null;for(const I of m.path)if(l.has(I.capacityMeshNodeId)){_=I.capacityMeshNodeId;break}for(let I=m.path.length-1;I>=0;I--){const C=m.path[I];if(l.has(C.capacityMeshNodeId)){f=C.capacityMeshNodeId;break}}_&&f&&p.push({connectionName:m.connection.name,startNodeId:_,endNodeId:f})}return{sectionConnectionTerminals:p,sectionNodes:h,sectionEdges:d,centerNodeId:i}})({centerNodeId:e,connectionsWithNodes:this.connectionsWithNodes,nodeMap:this.nodeMap,edges:this.edges,expansionDegrees:this.currentSchedule.MAX_EXPANSION_DEGREES,nodeEdgeMap:this.nodeEdgeMap});this.stats.scheduleScores[this.currentScheduleIndex].sectionAttempts++,this.currentSection=n,this.sectionSolver=new kZn({sectionNodes:this.currentSection.sectionNodes,sectionEdges:this.currentSection.sectionEdges,sectionConnectionTerminals:this.currentSection.sectionConnectionTerminals,colorMap:this.colorMap,centerNodeId:this.currentSection.centerNodeId,nodeEdgeMap:this.nodeEdgeMap,hyperParameters:{EXPANSION_DEGREES:this.currentSchedule.MAX_EXPANSION_DEGREES},cacheProvider:this.cacheProvider}),this.activeSubSolver=this.sectionSolver,this.nodeOptimizationAttemptCountMap.set(e,(this.nodeOptimizationAttemptCountMap.get(e)??0)+1)}if(this.sectionSolver.step(),(this.sectionSolver.failed||this.sectionSolver.solved)&&(this.sectionSolver.cacheHit?this.stats.cacheHits++:this.stats.cacheMisses++),this.sectionSolver.failed)return console.warn(`Section solver failed for node ${this.currentSection.centerNodeId}. Error: ${this.sectionSolver.error}`),this.stats.failedSectionSolvers++,this.stats.failedOptimizations++,this.sectionSolver=null,void(this.activeSubSolver=null);if(this.sectionSolver.solved){const e=this.sectionSolver.sectionConnectionTerminals,n=this.sectionSolver.sectionNodes,o=this.sectionSolver.centerNodeId;if(this.sectionSolver=null,this.activeSubSolver=null,!e)return void console.warn(`Pathing sub-solver for section ${this.currentSection.centerNodeId} did not complete successfully. Discarding results.`);const i=new Set(n.map(A=>A.capacityMeshNodeId)),r=Zz({totalNodeCapacityMap:this.totalNodeCapacityMap,usedNodeCapacityMap:this.usedNodeCapacityMap,nodeMap:this.nodeMap,sectionNodeIds:i}),s=new Map(this.usedNodeCapacityMap),a=e;for(const A of a){const c=this.connectionsWithNodes.find(l=>l.connection.name===A.connectionName);if(c?.path){for(const l of c.path)if(i.has(l.capacityMeshNodeId)){const u=s.get(l.capacityMeshNodeId)??0;s.set(l.capacityMeshNodeId,Math.max(0,u-1))}}}for(const A of a)if(A.path)for(const c of A.path)i.has(c.capacityMeshNodeId)&&s.set(c.capacityMeshNodeId,(s.get(c.capacityMeshNodeId)??0)+1);Zz({totalNodeCapacityMap:this.totalNodeCapacityMap,usedNodeCapacityMap:s,nodeMap:this.nodeMap,sectionNodeIds:i})>r?(this.stats.successfulOptimizations++,this._mergeSolvedSectionPaths({centerNodeId:o,sectionConnectionTerminals:e}),this._recalculateNodeCapacityUsage()):this.stats.failedOptimizations++}}_mergeSolvedSectionPaths({centerNodeId:e,sectionConnectionTerminals:n}){for(const o of n){if(!o.path){console.warn(`No path found for connection ${o.connectionName} in section ${e}`);continue}const i=this.connectionsWithNodes.find(d=>d.connection.name===o.connectionName);if(!i||!i.path){console.warn(`Original connection or path not found for ${o.connectionName} while merging section ${e}`);continue}const r=i.path,s=o.path,a=r.findIndex(d=>d.capacityMeshNodeId===o.startNodeId),A=r.findIndex(d=>d.capacityMeshNodeId===o.endNodeId);if(a===-1||A===-1){console.warn(`Could not find start/end nodes (${o.startNodeId}/${o.endNodeId}) in original path for ${o.connectionName}`);continue}const[c,l]=a<=A?[a,A]:[A,a],u=r.slice(0,c),g=r.slice(l+1);let h=s;if(s.length>0&&r[c]&&s[0].capacityMeshNodeId!==r[c].capacityMeshNodeId){if(s[s.length-1].capacityMeshNodeId!==r[c].capacityMeshNodeId){console.warn(`New section path for ${o.connectionName} doesn't align with original path boundaries. Skipping merge for this connection.`);continue}h=[...s].reverse()}i.path=[...u,...h,...g]}}_recalculateNodeCapacityUsage(){this.usedNodeCapacityMap.clear();for(const e of this.connectionsWithNodes)if(e.path)for(const n of e.path)this.usedNodeCapacityMap.set(n.capacityMeshNodeId,(this.usedNodeCapacityMap.get(n.capacityMeshNodeId)??0)+1);for(const e of this.nodes){const n=this.totalNodeCapacityMap.get(e.capacityMeshNodeId)??0,o=this.usedNodeCapacityMap.get(e.capacityMeshNodeId)??0,i=n>0?o/n:0;this.nodeCapacityPercentMap.set(e.capacityMeshNodeId,i)}}getCapacityPaths(){const e=[];for(const n of this.connectionsWithNodes){const o=n.path;o&&e.push({capacityPathId:n.connection.name,connectionName:n.connection.name,nodeIds:o.map(i=>i.capacityMeshNodeId)})}return e}_step(){this.iterations>=this.MAX_ITERATIONS-1?this.solved=!0:this.stage==="initialization"?this._stepInitialization():this.stage==="section-optimization"&&this._stepSectionOptimization()}visualize(){const e=this.connectionsWithNodes.filter(n=>n.path&&n.path.length>0).map(n=>({connectionName:n.connection.name,path:n.path}));return s6e({nodeMap:this.nodeMap,sectionConnectionTerminals:this.connectionsWithNodes.map(n=>({connectionName:n.connection.name,startNodeId:n.path?.[0]?.capacityMeshNodeId,endNodeId:n.path?.[n.path.length-1]?.capacityMeshNodeId})),completedPaths:e,sectionNodes:this.nodes,sectionEdges:this.edges,colorMap:this.colorMap,totalCapacityMap:this.totalNodeCapacityMap,usedNodeCapacityMap:this.usedNodeCapacityMap,nodeOpacity:.05,title:"Capacity Pathing Multi-Section Solver (Solved)"})}},LZn=class extends yr{getSolverName(){return"DeadEndSolver"}removedNodeIds;targetNodeIds;leaves;leavesIndex;adjacencyList;nodeMap;nodes;edges;constructor({nodes:e,edges:n}){super(),this.MAX_ITERATIONS=e.length,this.nodes=e,this.edges=n,this.removedNodeIds=new Set,this.targetNodeIds=new Set(e.filter(o=>o._containsTarget).map(o=>o.capacityMeshNodeId)),this.adjacencyList=new Map(e.map(({capacityMeshNodeId:o})=>[o,new Set]));for(const{nodeIds:[o,i]}of n)this.adjacencyList.get(o).add(i),this.adjacencyList.get(i).add(o);this.leavesIndex=0,this.leaves=[...this.adjacencyList.entries()].filter(([o,i])=>i.size===1).filter(([o,i])=>!this.targetNodeIds.has(o)).map(([o,i])=>o)}_step(){if(this.leavesIndex===this.leaves.length)return void(this.solved=!0);const e=this.leaves[this.leavesIndex],n=this.adjacencyList.get(e);if(!n||n.size===0)return this.removedNodeIds.add(e),this.adjacencyList.delete(e),this.leavesIndex+=1,void(this.leavesIndex===this.leaves.length&&(this.solved=!0));const[o]=n,i=o?this.adjacencyList.get(o):void 0;if(!o||!i)return this.removedNodeIds.add(e),this.adjacencyList.delete(e),this.leavesIndex+=1,void(this.leavesIndex===this.leaves.length&&(this.solved=!0));i.delete(e),this.removedNodeIds.add(e),this.adjacencyList.delete(e),i.size!==1||this.targetNodeIds.has(o)||this.leaves.push(o),this.leavesIndex+=1,this.leavesIndex===this.leaves.length&&(this.solved=!0)}visualize(){if(!this.nodeMap){this.nodeMap=new Map;for(const o of this.nodes)this.nodeMap.set(o.capacityMeshNodeId,o)}const e=new Map;for(const o of this.edges)for(const i of o.nodeIds)e.set(i,1+(e.get(i)??0));const n={lines:[],points:[],rects:this.nodes.map(o=>{const i=Math.min(...o.availableZ);return{width:Math.max(o.width-2,.8*o.width),height:Math.max(o.height-2,.8*o.height),center:{x:o.center.x+i*o.width*.05,y:o.center.y-i*o.width*.05},fill:o._containsObstacle?"rgba(255,0,0,0.1)":{"0,1":"rgba(0,0,0,0.1)",0:"rgba(0,200,200, 0.1)",1:"rgba(0,0,200, 0.1)"}[o.availableZ.join(",")]??"rgba(0,200,200,0.1)",label:[o.capacityMeshNodeId,`availableZ: ${o.availableZ.join(",")}`,`target? ${o._containsTarget??!1}`,`obs? ${o._containsObstacle??!1}`,`conn: ${e.get(o.capacityMeshNodeId)??0}`].join(`
`),layer:`z${o.availableZ.join(",")}`}}),circles:[]};for(const o of this.edges){const i=this.nodeMap.get(o.nodeIds[0]),r=this.nodeMap.get(o.nodeIds[1]);if(i?.center&&r?.center){const s=Math.min(...i.availableZ),a=Math.min(...r.availableZ),A={x:i.center.x+s*i.width*.05,y:i.center.y-s*i.width*.05},c={x:r.center.x+a*r.width*.05,y:r.center.y-a*r.width*.05},l=Array.from(new Set([...i.availableZ,...r.availableZ])).sort();n.lines.push({layer:`z${l.join(",")}`,points:[A,c],strokeDash:i.availableZ.join(",")===r.availableZ.join(",")?void 0:"10 5",strokeColor:o.nodeIds.some(u=>this.removedNodeIds.has(u))?Es("black",.9):void 0})}}return n}},HZn=class extends j7e{getSolverName(){return"NoOffBoardMultipleHighDensityRouteStitchSolver"}constructor(e){super(e),this.unsolvedRoutes=[];const n=new Map;for(const o of e.hdRoutes){const i=n.get(o.connectionName)||[];i.push(o),n.set(o.connectionName,i)}for(const[o,i]of n.entries()){const r=e.connections.find(A=>A.name===o);if(!r)continue;const s={...r.pointsToConnect[0],z:Kr(tI(r.pointsToConnect[0]),e.layerCount)},a={...r.pointsToConnect[1],z:Kr(tI(r.pointsToConnect[1]),e.layerCount)};this.unsolvedRoutes.push({connectionName:o,hdRoutes:i,start:s,end:a})}for(const o of e.connections)n.has(o.name)||this.unsolvedRoutes.push({connectionName:o.name,hdRoutes:[],start:{...o.pointsToConnect[0],z:Kr(tI(o.pointsToConnect[0]),e.layerCount)},end:{...o.pointsToConnect[1],z:Kr(tI(o.pointsToConnect[1]),e.layerCount)}})}},dae=.005,OZn=class extends yr{getSolverName(){return"SingleLayerNodeMergerSolver"}nodeMap;currentBatchNodeIds;absorbedNodeIds;nextBatchNodeIds;batchHadModifications;hasComputedAdjacentNodeIds=!1;newNodes;constructor(e){super(),this.nodeMap=new Map,this.MAX_ITERATIONS=1e5;for(const o of e)this.nodeMap.set(o.capacityMeshNodeId,o);this.newNodes=[],this.absorbedNodeIds=new Set;const n=[];for(const o of e)o.availableZ.length>1?(this.newNodes.push(o),this.absorbedNodeIds.add(o.capacityMeshNodeId)):n.push([o,o.width*o.height]);n.sort((o,i)=>o[1]-i[1]);for(const[o,i]of n){const r={...o,center:{...o.center}};this.nodeMap.set(o.capacityMeshNodeId,r)}this.currentBatchNodeIds=n.map(([o])=>o.capacityMeshNodeId),this.nextBatchNodeIds=[],this.batchHadModifications=!1}computeAdjacentNodeIdsForFirstBatch(e){const n=Math.max(...e.map(i=>Math.max(...i.availableZ))),o=[];for(let i=0;i<=n;i++)o.push(new B7e(e.filter(r=>r.availableZ[0]===i)));for(const i of e){const r=[],s=o[i.availableZ[0]].getNodesInArea(i.center.x,i.center.y,4*i.width,4*i.height);for(const a of s)a._containsTarget&&a._targetConnectionName!==i._targetConnectionName||i._containsTarget&&(!a._containsTarget||a._targetConnectionName!==i._targetConnectionName)||a.capacityMeshNodeId!==i.capacityMeshNodeId&&Use(i,a)&&r.push(a);i._adjacentNodeIds=r.map(a=>a.capacityMeshNodeId)}}getAdjacentSameLayerUnprocessedNodes(e){return this.getAdjacentSameLayerUnprocessedNodes2(e)}getAdjacentSameLayerUnprocessedNodes2(e){const n=[],o=Array.from(new Set((e._adjacentNodeIds??[]).map(i=>this.nodeMap.get(i)))).filter(i=>i&&i.capacityMeshNodeId!==e.capacityMeshNodeId);o.sort((i,r)=>i.width*i.height-r.width*r.height);for(const i of o)this.absorbedNodeIds.has(i.capacityMeshNodeId)||n.push(i);return n}_step(){this.hasComputedAdjacentNodeIds||(this.computeAdjacentNodeIdsForFirstBatch(this.currentBatchNodeIds.map(l=>this.nodeMap.get(l))),this.hasComputedAdjacentNodeIds=!0);let e=this.currentBatchNodeIds.pop();for(;e&&this.absorbedNodeIds.has(e);)e=this.currentBatchNodeIds.pop();if(!e)return this.batchHadModifications?(this.currentBatchNodeIds=this.nextBatchNodeIds.sort((l,u)=>{const g=this.nodeMap.get(l),h=this.nodeMap.get(u);return g.width*g.height-h.width*h.height}),this.nextBatchNodeIds=[],void(this.batchHadModifications=!1)):(this.solved=!0,void this.newNodes.push(...this.nextBatchNodeIds.map(l=>this.nodeMap.get(l))));const n=this.nodeMap.get(e);let o=!1;const i=this.getAdjacentSameLayerUnprocessedNodes(n);if(i.length===0)return void this.nextBatchNodeIds.push(e);const r=l=>{for(const u of l)this.absorbedNodeIds.add(u.capacityMeshNodeId);n._adjacentNodeIds=Array.from(new Set([...n._adjacentNodeIds??[],...l.flatMap(u=>u._adjacentNodeIds??[])].filter(u=>u!==n.capacityMeshNodeId&&!this.absorbedNodeIds.has(u))))},s=i.filter(l=>l.center.x<n.center.x&&Math.abs(l.center.y-n.center.y)<n.height/2);if(s.length>0){const{width:l,height:u}=s[0],g=s.every(h=>h.width===l&&h.height===u);Math.abs(s.reduce((h,d)=>h+d.height,0)-n.height)<dae&&g&&(n.width+=l,n.center.x=n.center.x-l/2,r(s),o=!0)}const a=i.filter(l=>l.center.x>n.center.x&&Math.abs(l.center.y-n.center.y)<n.height/2);if(a.length>0&&!o){const{width:l,height:u}=a[0],g=a.every(h=>h.width===l&&h.height===u);Math.abs(a.reduce((h,d)=>h+d.height,0)-n.height)<dae&&g&&(n.width+=l,n.center.x=n.center.x+l/2,r(a),o=!0)}const A=i.filter(l=>l.center.y>n.center.y&&Math.abs(l.center.x-n.center.x)<n.width/2);if(A.length>0&&!o){const{width:l,height:u}=A[0],g=A.every(h=>h.width===l&&h.height===u);Math.abs(A.reduce((h,d)=>h+d.width,0)-n.width)<dae&&g&&(n.height+=u,n.center.y=n.center.y+u/2,r(A),o=!0)}const c=i.filter(l=>l.center.y<n.center.y&&Math.abs(l.center.x-n.center.x)<n.width/2);if(c.length>0&&!o){const{width:l,height:u}=c[0],g=c.every(h=>h.width===l&&h.height===u);Math.abs(c.reduce((h,d)=>h+d.width,0)-n.width)<dae&&g&&(n.height+=u,n.center.y=n.center.y-u/2,r(c),o=!0)}o?(this.batchHadModifications=!0,this.currentBatchNodeIds.push(e)):this.nextBatchNodeIds.unshift(e)}visualize(){const e={circles:[],lines:[],points:[],rects:[],coordinateSystem:"cartesian",title:"Same Layer Node Merger"};for(const i of this.newNodes)e.rects.push(Wf(i));const n=this.currentBatchNodeIds[this.currentBatchNodeIds.length-1];let o;n&&(o=this.getAdjacentSameLayerUnprocessedNodes(this.nodeMap.get(n)));for(const i of this.currentBatchNodeIds){const r=this.nodeMap.get(i);if(!this.absorbedNodeIds.has(i)&&r){const s=Wf(r,{rectMargin:.01});i===n?s.stroke="rgba(0, 255, 0, 0.8)":o?.some(a=>a.capacityMeshNodeId===i)?s.stroke="rgba(128, 0, 128, 0.8)":s.stroke="rgba(255, 165, 0, 0.8)",s.layer=`z${r.availableZ.join(",")}`,s.label=`${s.label}
(unprocessed)`,e.rects.push(s)}}for(const i of this.nextBatchNodeIds){const r=this.nodeMap.get(i);if(!this.absorbedNodeIds.has(i)&&r){const s=Wf(r,{rectMargin:.01});s.layer=`z${r.availableZ.join(",")}`,s.stroke="rgba(0, 217, 255, 0.8)",s.label=`${s.label}
x: ${r.center.x}, y: ${r.center.y}
${r.width}x${r.height}
(next batch)`,e.rects.push(s)}}return e}},GZn=class extends yr{getSolverName(){return"StrawSolver"}multiLayerNodes;strawNodes;skippedNodes;unprocessedNodes;strawSize;nodeIdCounter;constructor(e){super(),this.MAX_ITERATIONS=1e5,this.strawSize=e.strawSize??.5,this.multiLayerNodes=[],this.strawNodes=[],this.skippedNodes=[],this.nodeIdCounter=0,this.unprocessedNodes=[];for(const n of e.nodes)n.availableZ.length===1?this.unprocessedNodes.push(n):this.multiLayerNodes.push(n)}getCapacityOfMultiLayerNodesWithinBounds(e){let n=0;for(const o of this.multiLayerNodes){const i=o.center.x-o.width/2,r=o.center.x+o.width/2,s=o.center.y-o.height/2,a=o.center.y+o.height/2,A=Math.max(e.minX,i),c=Math.min(e.maxX,r),l=Math.max(e.minY,s),u=Math.min(e.maxY,a);if(A<c&&l<u){const g=(c-A)*(u-l)/(o.width*o.height);n+=l7(o)*g}}return n}getSurroundingCapacities(e){const n=Math.min(e.width,e.height);return{leftSurroundingCapacity:this.getCapacityOfMultiLayerNodesWithinBounds({minX:e.center.x-e.width/2-n,maxX:e.center.x-e.width/2,minY:e.center.y-e.height/2,maxY:e.center.y+e.height/2}),rightSurroundingCapacity:this.getCapacityOfMultiLayerNodesWithinBounds({minX:e.center.x+e.width/2,maxX:e.center.x+e.width/2+n,minY:e.center.y-e.height/2,maxY:e.center.y+e.height/2}),topSurroundingCapacity:this.getCapacityOfMultiLayerNodesWithinBounds({minX:e.center.x-e.width/2,maxX:e.center.x+e.width/2,minY:e.center.y-e.height/2-n,maxY:e.center.y-e.height/2}),bottomSurroundingCapacity:this.getCapacityOfMultiLayerNodesWithinBounds({minX:e.center.x-e.width/2,maxX:e.center.x+e.width/2,minY:e.center.y+e.height/2,maxY:e.center.y+e.height/2+n})}}createStrawsForNode(e){const n=[],{leftSurroundingCapacity:o,rightSurroundingCapacity:i,topSurroundingCapacity:r,bottomSurroundingCapacity:s}=this.getSurroundingCapacities(e);if(1*(o+i)>r+s){const a=Math.floor(e.height/this.strawSize),A=e.height/a;for(let c=0;c<a;c++){const l=e.center.y-e.height/2+c*A+A/2;n.push({capacityMeshNodeId:`${e.capacityMeshNodeId}_straw${c}`,center:{x:e.center.x,y:l},width:e.width,height:A,layer:e.layer,availableZ:[...e.availableZ],_depth:e._depth,_strawNode:!0,_strawParentCapacityMeshNodeId:e.capacityMeshNodeId})}}else{const a=Math.floor(e.width/this.strawSize),A=e.width/a;for(let c=0;c<a;c++){const l=e.center.x-e.width/2+c*A+A/2;n.push({capacityMeshNodeId:`${e.capacityMeshNodeId}_straw${c}`,center:{x:l,y:e.center.y},width:A,height:e.height,layer:e.layer,availableZ:[...e.availableZ],_depth:e._depth,_strawNode:!0,_strawParentCapacityMeshNodeId:e.capacityMeshNodeId})}}return n}getResultNodes(){return[...this.multiLayerNodes,...this.strawNodes,...this.skippedNodes]}_step(){const e=this.unprocessedNodes.pop();if(!e)return void(this.solved=!0);if(e.width<this.strawSize&&e.height<this.strawSize)return void this.skippedNodes.push(e);if(e._containsTarget)return void this.skippedNodes.push(e);const n=this.createStrawsForNode(e);this.strawNodes.push(...n),n.length===0&&this.strawNodes.push(e)}visualize(){const e={rects:[],lines:[],points:[],circles:[],title:"Straw Solver"};for(const n of this.unprocessedNodes)e.rects.push({center:n.center,width:n.width,height:n.height,fill:"rgba(200, 200, 200, 0.5)",stroke:"rgba(0, 0, 0, 0.5)",label:`${n.capacityMeshNodeId}
Unprocessed
${n.width}x${n.height}`});for(const n of this.strawNodes){const o=n.availableZ[0]===0?"rgba(0, 150, 255, 0.5)":"rgba(255, 100, 0, 0.5)";e.rects.push({center:n.center,width:n.width,height:n.height,fill:o,stroke:"rgba(0, 0, 0, 0.5)",label:`${n.capacityMeshNodeId}
Layer: ${n.availableZ[0]}
${n.width}x${n.height}`,layer:`z${n.availableZ.join(",")}`})}for(const n of this.multiLayerNodes)e.rects.push({center:n.center,width:.9*n.width,height:.9*n.height,fill:"rgba(100, 255, 100, 0.5)",stroke:"rgba(0, 0, 0, 0.5)",layer:`z${n.availableZ.join(",")}`,label:`${n.capacityMeshNodeId}
Layers: ${n.availableZ.join(",")}
${n.width}x${n.height}`});return e}};function a1t(t){const{nodeId:e,nodeIdToSegmentIds:n,segmentIdToNodeIds:o,hops:i}=t;if(i===0)return[e];const r=new Set([e]),s=[{nodeId:e,remainingHops:i}];for(;s.length>0;){const{nodeId:a,remainingHops:A}=s.shift();if(A===0)continue;const c=n.get(a)||[];for(const l of c){const u=o.get(l)||[];for(const g of u)r.has(g)||(r.add(g),s.push({nodeId:g,remainingHops:A-1}))}}return Array.from(r)}var a6e=t=>Array.from(t.entries()).map(([e,{x:n,y:o,z:i}])=>`${e}(${n?.toFixed(3)??""},${o?.toFixed(3)??""},${i??""})`).sort().join("&"),YZn=(t,e,n,o)=>{const i=Math.min(t,e),r=Math.max(t,e),s=Math.min(n,o);return i<=Math.max(n,o)&&r>=s},hae=(t,e,n,o)=>{const i=[],r=new Map(t.originalPointMap);for(const[s,a]of n.entries()){const A=r.get(s);r.set(s,{x:a.x??A.x,y:a.y??A.y,z:a.z??A.z})}for(const s of t.allNodeIds){if(!e.get(s))continue;const a=t.segmentPairsInNode.get(s);for(const A of a){const c=r.get(A[0]),l=r.get(A[1]);c.z!==l.z&&i.push({type:"transition_via",segmentPoints:A,capacityMeshNodeId:s,probabilityOfFailure:0})}for(let A=0;A<a.length;A++)for(let c=A+1;c<a.length;c++){const l=a[A],u=a[c],g=r.get(l[0]),h=r.get(l[1]),d=r.get(u[0]),p=r.get(u[1]);if(!YZn(g.z,h.z,d.z,p.z))continue;const m=Uh(g,h,d,p),_=g.z===h.z&&d.z===p.z&&g.z===d.z;m&&(_?i.push({type:"same_layer_crossing",segmentPoints:[l,u],capacityMeshNodeId:s,crossingLine1:l,crossingLine2:u,probabilityOfFailure:0}):g.z===h.z&&d.z!==p.z?i.push({type:"single_transition_crossing",segmentPoints:[l,u],capacityMeshNodeId:s,sameLayerCrossingLine:l,transitionCrossingLine:u,probabilityOfFailure:0}):g.z!==h.z&&d.z===p.z?i.push({type:"single_transition_crossing",segmentPoints:[l,u],capacityMeshNodeId:s,sameLayerCrossingLine:u,transitionCrossingLine:l,probabilityOfFailure:0}):g.z!==h.z&&d.z!==p.z&&i.push({type:"double_transition_crossing",segmentPoints:[l,u],capacityMeshNodeId:s,crossingLine1:l,crossingLine2:u,probabilityOfFailure:0}))}}return i},A1t=(t,e,n)=>{if(e.type==="change_layer")for(const o of e.segmentPointIds){const i=t.get(o)||{};t.set(o,{...i,z:e.newZ})}else if(e.type==="swap_position_on_segment"){const[o,i]=e.segmentPointIds,r=n(o),s=n(i),a=t.get(o)||{},A=t.get(i)||{};t.set(o,{...a,x:s.x,y:s.y}),t.set(i,{...A,x:r.x,y:r.y})}else if(e.type==="combined")for(const o of e.operations)A1t(t,o,n)},c1t=(t,e)=>{const n=new Map,o=new Map,i=new Map;let r=0;for(const s of t)for(const a of s.assignedPoints){const A={segmentPointId:"SP"+r++,segmentId:s.nodePortSegmentId,capacityMeshNodeIds:e.get(s.nodePortSegmentId),connectionName:a.connectionName,rootConnectionName:a.rootConnectionName,x:a.point.x,y:a.point.y,z:a.point.z,directlyConnectedSegmentPointIds:[]};n.set(A.segmentPointId,A);for(const c of A.capacityMeshNodeIds)o.set(c,[...o.get(c)??[],A.segmentPointId]);i.set(s.nodePortSegmentId,[...i.get(s.nodePortSegmentId)??[],A.segmentPointId])}return{segmentPointMap:n,nodeToSegmentPointMap:o,segmentToSegmentPointMap:i}},UZn=class extends yr{getSolverName(){return"UnravelSectionSolver"}nodeMap;dedupedSegments;dedupedSegmentMap;MUTABLE_HOPS=1;unravelSection;candidates=[];lastProcessedCandidate=null;bestCandidate=null;originalCandidate;rootNodeId;nodeIdToSegmentIds;segmentIdToNodeIds;colorMap;tunedNodeCapacityMap;MAX_CANDIDATES=500;iterationsSinceImprovement=0;hyperParameters;selectedCandidateIndex=null;queuedOrExploredCandidatePointModificationHashes=new Set;constructorParams;constructor(e){if(super(),this.constructorParams=e,this.MUTABLE_HOPS=e.MUTABLE_HOPS??this.MUTABLE_HOPS,this.MAX_ITERATIONS=5e4,this.hyperParameters={...e.hyperParameters,MAX_ITERATIONS_WITHOUT_IMPROVEMENT:200},this.nodeMap=e.nodeMap,this.dedupedSegments=e.dedupedSegments,e.dedupedSegmentMap)this.dedupedSegmentMap=e.dedupedSegmentMap;else{this.dedupedSegmentMap=new Map;for(const n of this.dedupedSegments)this.dedupedSegmentMap.set(n.nodePortSegmentId,n)}this.nodeIdToSegmentIds=e.nodeIdToSegmentIds,this.segmentIdToNodeIds=e.segmentIdToNodeIds,this.rootNodeId=e.rootNodeId,this.colorMap=e.colorMap??{},this.unravelSection=this.createUnravelSection({segmentPointMap:e.segmentPointMap,nodeToSegmentPointMap:e.nodeToSegmentPointMap,segmentToSegmentPointMap:e.segmentToSegmentPointMap}),this.tunedNodeCapacityMap=new Map;for(const n of this.unravelSection.allNodeIds)this.tunedNodeCapacityMap.set(n,l7(this.nodeMap.get(n)));this.originalCandidate=this.createInitialCandidate(),this.candidates=[this.originalCandidate]}getConstructorParams(){return{...this.constructorParams,segmentPointMap:this.unravelSection.segmentPointMap,nodeToSegmentPointMap:this.unravelSection.segmentPointsInNode,segmentToSegmentPointMap:this.unravelSection.segmentPointsInSegment}}createUnravelSection(e){const n=a1t({nodeId:this.rootNodeId,nodeIdToSegmentIds:this.nodeIdToSegmentIds,segmentIdToNodeIds:this.segmentIdToNodeIds,hops:this.MUTABLE_HOPS}),o=a1t({nodeId:this.rootNodeId,nodeIdToSegmentIds:this.nodeIdToSegmentIds,segmentIdToNodeIds:this.segmentIdToNodeIds,hops:this.MUTABLE_HOPS+1}),i=Array.from(new Set(o).difference(new Set(n)));e?.segmentPointMap||(e=c1t(this.dedupedSegments,this.segmentIdToNodeIds));const r=new Map;for(const h of o)r.set(h,e.nodeToSegmentPointMap.get(h));const s=new Map;for(const h of o)for(const d of r.get(h)){const p=e.segmentPointMap.get(d);s.set(d,p)}const a=Array.from(s.values()),A=new Map;for(const h of a)A.set(h.segmentId,[...A.get(h.segmentId)??[],h.segmentPointId]);for(const[h,d]of r.entries())for(let p=0;p<d.length;p++){const m=e.segmentPointMap.get(d[p]);for(let _=p+1;_<d.length;_++){const f=e.segmentPointMap.get(d[_]);f.segmentPointId!==m.segmentPointId&&f.segmentId!==m.segmentId&&f.connectionName===m.connectionName&&(f.directlyConnectedSegmentPointIds.includes(m.segmentPointId)||(m.directlyConnectedSegmentPointIds.push(f.segmentPointId),f.directlyConnectedSegmentPointIds.push(m.segmentPointId)))}}const c=new Map;for(const h of o)c.set(h,[]);for(const h of a)for(const d of h.capacityMeshNodeIds){const p=c.get(d);if(p)for(const m of h.directlyConnectedSegmentPointIds){const _=e.segmentPointMap.get(m);_.segmentPointId!==h.segmentPointId&&_.capacityMeshNodeIds.some(f=>f===d)&&(p.some(([f,I])=>f===h.segmentPointId&&I===_.segmentPointId||f===_.segmentPointId&&I===h.segmentPointId)||p.push([h.segmentPointId,_.segmentPointId]))}}const l=new Set;for(const h of n)for(const d of this.nodeIdToSegmentIds.get(h))this.segmentIdToNodeIds.get(d).every(p=>!this.nodeMap.get(p)._containsTarget)&&l.add(d);const u=new Set;for(const h of a){const d=h.capacityMeshNodeIds.some(_=>n.includes(_)),p=this.dedupedSegmentMap.get(h.segmentId),m=p&&p.availableZ.length>1;(d||m)&&u.add(h.segmentPointId)}const g=new Set;for(const h of a)if(h.capacityMeshNodeIds.some(d=>this.nodeMap.get(d)?._containsTarget)){const d=this.dedupedSegmentMap.get(h.segmentId);d&&d.availableZ.length===1&&g.add(h.segmentPointId)}return{allNodeIds:o,mutableNodeIds:n,immutableNodeIds:i,mutableSegmentIds:l,segmentPairsInNode:c,segmentPointMap:s,segmentPointsInNode:r,segmentPointsInSegment:A,originalPointMap:s,mutableSegmentPointIds:u,zLockedSegmentPointIds:g}}createInitialCandidate(){const e=new Map,n=hae(this.unravelSection,this.nodeMap,e),o=this.computeG({issues:n,originalCandidate:{},operationsPerformed:0,operation:{}});return{pointModifications:e,g:o,h:0,f:o,operationsPerformed:0,candidateHash:a6e(e),issues:hae(this.unravelSection,this.nodeMap,e)}}get nextCandidate(){return this.candidates[0]??null}getPointInCandidate(e,n){const o=this.unravelSection.segmentPointMap.get(n),i=e.pointModifications.get(n);return{x:i?.x??o.x,y:i?.y??o.y,z:i?.z??o.z,segmentId:o.segmentId}}getConnectionSegmentPointIds(e){const n=[];for(const[o,i]of this.unravelSection.segmentPointMap.entries())i.connectionName===e&&n.push(o);return n}canConnectionUseLayer(e,n){for(const o of e){const i=this.unravelSection.segmentPointMap.get(o),r=this.dedupedSegmentMap.get(i.segmentId);if(!r||!r.availableZ.includes(n))return!1}return!0}getOperationsForIssue(e,n){const o=[];if(n.type==="transition_via"){const[i,r]=n.segmentPoints,s=this.getPointInCandidate(e,i),a=this.getPointInCandidate(e,r),A=this.unravelSection.segmentPointMap.get(i),c=(this.unravelSection.segmentPointMap.get(r),this.dedupedSegmentMap.get(s.segmentId).availableZ),l=this.dedupedSegmentMap.get(a.segmentId).availableZ,u=this.unravelSection.zLockedSegmentPointIds.has(i),g=this.unravelSection.zLockedSegmentPointIds.has(r),h=this.getConnectionSegmentPointIds(A.connectionName);if(this.canConnectionUseLayer(h,a.z)){const d=h.filter(p=>this.unravelSection.mutableSegmentPointIds.has(p)&&!this.unravelSection.zLockedSegmentPointIds.has(p));d.length>0&&o.push({type:"change_layer",newZ:a.z,segmentPointIds:d})}if(this.canConnectionUseLayer(h,s.z)){const d=h.filter(p=>this.unravelSection.mutableSegmentPointIds.has(p)&&!this.unravelSection.zLockedSegmentPointIds.has(p));d.length>0&&o.push({type:"change_layer",newZ:s.z,segmentPointIds:d})}this.unravelSection.mutableSegmentPointIds.has(i)&&!u&&c.includes(a.z)&&o.push({type:"change_layer",newZ:a.z,segmentPointIds:[i]}),this.unravelSection.mutableSegmentPointIds.has(r)&&!g&&l.includes(s.z)&&o.push({type:"change_layer",newZ:s.z,segmentPointIds:[r]})}if(n.type==="same_layer_crossing"){const[i,r]=n.crossingLine1,[s,a]=n.crossingLine2,A=[],c=this.unravelSection.segmentPointMap.get(i),l=this.unravelSection.segmentPointMap.get(r),u=this.unravelSection.segmentPointMap.get(s),g=this.unravelSection.segmentPointMap.get(a),h=this.unravelSection.mutableSegmentPointIds.has(i),d=this.unravelSection.mutableSegmentPointIds.has(r),p=this.unravelSection.mutableSegmentPointIds.has(s),m=this.unravelSection.mutableSegmentPointIds.has(a),_=this.unravelSection.zLockedSegmentPointIds.has(i),f=this.unravelSection.zLockedSegmentPointIds.has(r),I=this.unravelSection.zLockedSegmentPointIds.has(s),C=this.unravelSection.zLockedSegmentPointIds.has(a);h&&p&&c.segmentId===u.segmentId&&A.push([i,s]),h&&m&&c.segmentId===g.segmentId&&A.push([i,a]),d&&p&&l.segmentId===u.segmentId&&A.push([r,s]),d&&m&&l.segmentId===g.segmentId&&A.push([r,a]);for(const[k,R]of A)o.push({type:"swap_position_on_segment",segmentPointIds:[k,R]});const y=this.getConnectionSegmentPointIds(c.connectionName),x=this.getConnectionSegmentPointIds(u.connectionName),E=new Set;for(const k of this.unravelSection.segmentPointMap.values()){const R=this.dedupedSegmentMap.get(k.segmentId);if(R)for(const F of R.availableZ)E.add(F)}for(const k of E)if(k!==c.z&&this.canConnectionUseLayer(y,k)){const R=y.filter(F=>this.unravelSection.mutableSegmentPointIds.has(F)&&!this.unravelSection.zLockedSegmentPointIds.has(F));R.length>0&&o.push({type:"change_layer",newZ:k,segmentPointIds:R})}for(const k of E)if(k!==u.z&&this.canConnectionUseLayer(x,k)){const R=x.filter(F=>this.unravelSection.mutableSegmentPointIds.has(F)&&!this.unravelSection.zLockedSegmentPointIds.has(F));R.length>0&&o.push({type:"change_layer",newZ:k,segmentPointIds:R})}const B=this.dedupedSegmentMap.get(c.segmentId),S=this.dedupedSegmentMap.get(l.segmentId),Q=this.dedupedSegmentMap.get(u.segmentId),w=this.dedupedSegmentMap.get(g.segmentId),M=(k,R)=>k.every(F=>F.availableZ.includes(R));if(h&&d&&!_&&!f){const k=c.z===0?1:0;M([B,S],k)&&o.push({type:"change_layer",newZ:k,segmentPointIds:[i,r]})}if(p&&m&&!I&&!C){const k=u.z===0?1:0;M([Q,w],k)&&o.push({type:"change_layer",newZ:k,segmentPointIds:[s,a]})}if(h&&!_){const k=c.z===0?1:0;B.availableZ.includes(k)&&o.push({type:"change_layer",newZ:k,segmentPointIds:[i]})}if(d&&!f){const k=l.z===0?1:0;S.availableZ.includes(k)&&o.push({type:"change_layer",newZ:k,segmentPointIds:[r]})}if(p&&!I){const k=u.z===0?1:0;Q.availableZ.includes(k)&&o.push({type:"change_layer",newZ:k,segmentPointIds:[s]})}if(m&&!C){const k=g.z===0?1:0;w.availableZ.includes(k)&&o.push({type:"change_layer",newZ:k,segmentPointIds:[a]})}}return o}computeG(e){const{issues:n,originalCandidate:o,operationsPerformed:i,operation:r}=e,s=new Map;for(const c of n){s.has(c.capacityMeshNodeId)||s.set(c.capacityMeshNodeId,{numTransitionCrossings:0,numSameLayerCrossings:0,numEntryExitLayerChanges:0});const l=s.get(c.capacityMeshNodeId);c.type==="transition_via"?l.numTransitionCrossings++:c.type==="same_layer_crossing"?l.numSameLayerCrossings++:c.type==="double_transition_crossing"||c.type==="single_transition_crossing"?l.numEntryExitLayerChanges++:c.type}let a=0;for(const[c,{numEntryExitLayerChanges:l,numSameLayerCrossings:u,numTransitionCrossings:g}]of s){const h=this.nodeMap.get(c),d=Math.min(wy(h,u,l,g),.999999);a+=Math.log(1-d)}var A;return(A=a)<-Math.LN2?Math.log(1-Math.exp(A)):Math.log(-Math.expm1(A))}getUnexploredNeighborByApplyingOperation(e,n){const o=new Map(e.pointModifications);A1t(o,n,A=>this.getPointInCandidate(e,A));const i=a6e(o);if(this.queuedOrExploredCandidatePointModificationHashes.has(i))return null;const r=hae(this.unravelSection,this.nodeMap,o),s=e.operationsPerformed+1,a=this.computeG({issues:r,originalCandidate:e,operationsPerformed:s,operation:n});return{issues:r,g:a,h:0,f:a,pointModifications:o,candidateHash:i,operationsPerformed:s}}getNeighborOperationsForCandidate(e){return e.issues.flatMap(n=>this.getOperationsForIssue(e,n))}getNeighbors(e){const n=[],o=this.getNeighborOperationsForCandidate(e);for(const i of o){const r=this.getUnexploredNeighborByApplyingOperation(e,i);r&&n.push(r)}return n}_step(){const e=this.candidates.shift();this.iterationsSinceImprovement++,this.iterationsSinceImprovement>this.hyperParameters.MAX_ITERATIONS_WITHOUT_IMPROVEMENT?this.solved=!0:e?(this.lastProcessedCandidate=e,e.f<(this.bestCandidate?.f??1/0)&&(this.bestCandidate=e,this.iterationsSinceImprovement=0),this.getNeighbors(e).forEach(n=>{this.queuedOrExploredCandidatePointModificationHashes.has(n.candidateHash)||(this.queuedOrExploredCandidatePointModificationHashes.add(n.candidateHash),this.candidates.push(n))}),this.candidates.sort((n,o)=>n.f-o.f),this.candidates.length=Math.min(this.candidates.length,this.MAX_CANDIDATES)):this.solved=!0}visualize(){const e={points:[],lines:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Unravel Section Solver"};let n=null;if(n=this.selectedCandidateIndex!==null?this.selectedCandidateIndex==="best"?this.bestCandidate:this.selectedCandidateIndex==="original"?this.originalCandidate:this.candidates[this.selectedCandidateIndex]:this.solved?this.bestCandidate:this.lastProcessedCandidate||this.candidates[0],!n)return e;const o=new Map;for(const[r,s]of this.unravelSection.segmentPointMap){const a={...s},A=n.pointModifications.get(r);A&&(A.x!==void 0&&(a.x=A.x),A.y!==void 0&&(a.y=A.y),A.z!==void 0&&(a.z=A.z)),o.set(r,a)}for(const[r,s]of o)e.points.push({x:s.x,y:s.y,label:`${r}
Segment: ${s.segmentId} ${this.unravelSection.mutableSegmentIds.has(s.segmentId)?"MUTABLE":"IMMUTABLE"}
Layer: ${s.z}`,color:this.colorMap[s.connectionName]||"#000"});const i=new Map;for(const r of this.unravelSection.allNodeIds)i.set(r,{numTransitionCrossings:0,numSameLayerCrossings:0,numEntryExitLayerChanges:0,estPf:0});for(const r of n.issues){const s=i.get(r.capacityMeshNodeId);r.type==="transition_via"?s.numTransitionCrossings++:r.type==="same_layer_crossing"?s.numSameLayerCrossings++:r.type!=="double_transition_crossing"&&r.type!=="single_transition_crossing"||s.numEntryExitLayerChanges++}for(const[r,s]of i.entries()){const a=this.nodeMap.get(r);s.estPf=wy(a,s.numSameLayerCrossings,s.numEntryExitLayerChanges,s.numTransitionCrossings)}for(const r of this.unravelSection.allNodeIds){const s=this.nodeMap.get(r),a=this.unravelSection.mutableNodeIds.includes(r),A=i.get(r),c=[`${r} (${a?"MUT":"IMM"})`,`${s.width.toFixed(2)}x${s.height.toFixed(2)}`,`Pf: ${A.estPf.toFixed(3)}`,`TC: ${A.numTransitionCrossings}`,`SLC: ${A.numSameLayerCrossings}`,`EELC: ${A.numEntryExitLayerChanges}`].join(`
`);e.rects.push({center:s.center,label:c,color:a?"green":"red",width:s.width/8,height:s.height/8})}for(const[r,s]of this.unravelSection.segmentPointsInSegment){if(s.length<=1)continue;const a=s.map(A=>o.get(A));for(let A=0;A<a.length-1;A++)e.lines.push({points:[{x:a[A].x,y:a[A].y},{x:a[A+1].x,y:a[A+1].y}],strokeColor:this.colorMap[r]||"#000"})}for(const[r,s]of o)for(const a of s.directlyConnectedSegmentPointIds)if(r<a){const A=o.get(a);if(!A)continue;const c=s.z===A.z,l=s.z;let u;u=c?l===0?void 0:"10 5":"3 3 10",e.lines.push({points:[{x:s.x,y:s.y},{x:A.x,y:A.y}],strokeDash:u,strokeColor:this.colorMap[s.connectionName]||"#000"})}for(const r of n.issues){const s=this.nodeMap.get(r.capacityMeshNodeId);if(r.type==="transition_via")for(const a of r.segmentPoints){const A=o.get(a);e.circles.push({center:{x:A.x,y:A.y},radius:s.width/16,stroke:"#ff0000",fill:"rgba(255, 0, 0, 0.2)",label:`Via Issue
${a}
Layer: ${A.z}`})}else if(r.type==="same_layer_crossing")for(const[a,A]of[r.crossingLine1,r.crossingLine2]){const c=o.get(a),l=o.get(A);e.lines.push({points:[{x:c.x,y:c.y},{x:l.x,y:l.y}],strokeColor:"rgba(255,0,0,0.2)",strokeWidth:s.width/32})}}for(const[r,s]of n.pointModifications){const a=o.get(r),A=this.unravelSection.segmentPointMap.get(r);e.circles.push({center:{x:a.x,y:a.y},radius:.05,stroke:"#0000ff",fill:"rgba(0, 0, 255, 0.2)",label:`${r}
Original: (${A.x.toFixed(2)}, ${A.y.toFixed(2)}, ${A.z})
New: (${a.x.toFixed(2)}, ${a.y.toFixed(2)}, ${a.z})`})}return e}},pae=t=>(Math.round(20*t)/20).toFixed(2),l1t=t=>(Math.round(1e3*t)/1e3).toFixed(3);Lse();var KZn=class extends UZn{cacheHit=!1;cacheProvider;hasAttemptedToUseCache=!1;constructor(e){super(e),this.cacheProvider=e.cacheProvider===void 0?eXn():e.cacheProvider}_step(){!this.hasAttemptedToUseCache&&this.cacheProvider&&this.attemptToUseCacheSync()||(super._step(),(this.solved||this.failed)&&this.cacheProvider&&this.saveToCacheSync())}computeCacheKeyAndTransform(){const e=this.nodeMap.get(this.rootNodeId),n=r_t(-e.center.x,-e.center.y),o=new Map,i=new Map,r=new Map,s=new Map,a=new Map,A=new Map;let c=0,l=0,u=0;const g=[...this.unravelSection.allNodeIds].sort((I,C)=>{const y=this.nodeMap.get(I),x=this.nodeMap.get(C);return y.center.x!==x.center.x?y.center.x-x.center.x:y.center.y-x.center.y});for(const I of g){const C="node_"+c++;o.set(I,C),i.set(C,I)}const h=[...Array.from(this.unravelSection.segmentPointMap.entries()).sort(([,I],[,C])=>I.x!==C.x?I.x-C.x:I.y-C.y).map(([I])=>I)].sort();for(const I of h){const C="sp_"+u++;a.set(I,C),A.set(C,I);const y=this.unravelSection.segmentPointMap.get(I).segmentId;if(!r.has(y)){const x="seg_"+l++;r.set(y,x),s.set(x,y)}}const d={};for(const[I,C]of o.entries()){const y=this.nodeMap.get(I),x=i_t(n,y.center);d[C]={width:y.width,height:y.height,availableZ:y.availableZ,center:{x:pae(x.x),y:pae(x.y)}}}const p={};for(const[I,C]of a.entries()){const y=this.unravelSection.segmentPointMap.get(I),x=i_t(n,{x:y.x,y:y.y});p[C]={x:pae(x.x),y:pae(x.y),z:y.z}}const m={hyperParameters:this.hyperParameters,normalizedNodes:d,normalizedSegmentPoints:p,mutableHops:this.MUTABLE_HOPS},_=`unravelsec:${$9e(m)}`,f={realToCacheTransform:n,nodeIdMap:o,segmentIdMap:r,segmentPointIdMap:a,reverseNodeIdMap:i,reverseSegmentIdMap:s,reverseSegmentPointIdMap:A};return this.cacheKey=_,this.cacheToSolveSpaceTransform=f,{cacheKey:_,cacheToSolveSpaceTransform:f}}applyCachedSolution(e){if(e.success===!1)return void(this.failed=!0);if(!this.cacheToSolveSpaceTransform)return void console.error("Cache transform not available to apply cached solution.");const{reverseSegmentPointIdMap:n,reverseNodeIdMap:o}=this.cacheToSolveSpaceTransform,i=new Map;for(const[s,a]of e.bestCandidatePointModificationsDelta){const A=n.get(s);if(!A){console.warn(`Could not find original ID for normalized SP ID: ${s} when applying cache.`);continue}const c=this.unravelSection.segmentPointMap.get(A);if(!c){console.warn(`Could not find original segment point for ID: ${A} when applying cache.`);continue}const l={};if(a.dx!==void 0){const u=parseFloat(a.dx);Number.isNaN(u)?console.warn(`Failed to parse cached dx coordinate: ${a.dx}`):l.x=c.x+u}if(a.dy!==void 0){const u=parseFloat(a.dy);Number.isNaN(u)?console.warn(`Failed to parse cached dy coordinate: ${a.dy}`):l.y=c.y+u}a.dz!==void 0&&(l.z=c.z+a.dz),Object.keys(l).length>0&&i.set(A,l)}const r=hae(this.unravelSection,this.nodeMap,i);this.bestCandidate={pointModifications:i,issues:r,f:e.bestCandidateF,g:e.bestCandidateF,h:0,operationsPerformed:-1,candidateHash:a6e(i)},this.cacheHit=!0,this.solved=!0}attemptToUseCacheSync(){if(this.hasAttemptedToUseCache=!0,!this.cacheProvider?.isSyncCache)return console.log("Cache provider is not synchronous, skipping sync cache check."),!1;if(this.cacheKey||this.computeCacheKeyAndTransform(),!this.cacheKey)return console.error("Failed to compute cache key."),!1;try{const e=this.cacheProvider.getCachedSolutionSync(this.cacheKey);if(e)return this.applyCachedSolution(e),!0}catch(e){console.error("Error attempting to use cache:",e)}return!1}saveToCacheSync(){if(this.failed)return void this.cacheProvider?.setCachedSolutionSync(this.cacheKey,{success:!1});if(!this.bestCandidate)return;const{segmentPointIdMap:e}=this.cacheToSolveSpaceTransform,n=[];for(const[i,r]of this.bestCandidate.pointModifications.entries()){const s=e.get(i);if(!s){console.warn(`Could not find normalized ID for original SP ID: ${i} when saving to cache.`);continue}const a=this.unravelSection.segmentPointMap.get(i);if(!a){console.warn(`Could not find original segment point for ID: ${i} when saving cache.`);continue}const A={};let c=!1;if(r.x!==void 0){const l=r.x-a.x,u=l1t(l);parseFloat(u)!==0&&(A.dx=u,c=!0)}if(r.y!==void 0){const l=r.y-a.y,u=l1t(l);parseFloat(u)!==0&&(A.dy=u,c=!0)}if(r.z!==void 0){const l=r.z-a.z;l!==0&&(A.dz=l,c=!0)}c&&n.push([s,A])}const o={success:!0,bestCandidatePointModificationsDelta:n,bestCandidateF:this.bestCandidate.f};this.cacheProvider?.setCachedSolutionSync(this.cacheKey,o)}},VZn=class extends yr{getSolverName(){return"UnravelMultiSectionSolver"}nodeMap;dedupedSegmentMap;dedupedSegments;nodeIdToSegmentIds;segmentIdToNodeIds;nodeToSegmentPointMap;segmentToSegmentPointMap;colorMap;tunedNodeCapacityMap;MAX_NODE_ATTEMPTS=2;MUTABLE_HOPS=1;ACCEPTABLE_PF=.05;MAX_ITERATIONS_WITHOUT_IMPROVEMENT=200;nodePfMap;attemptsToFixNode;activeSubSolver=null;segmentPointMap;cacheProvider=null;constructor({assignedSegments:e,colorMap:n,nodes:o,cacheProvider:i}){super(),this.stats.successfulOptimizations=0,this.stats.failedOptimizations=0,this.stats.cacheHits=0,this.stats.cacheMisses=0,this.cacheProvider=i??null,this.MAX_ITERATIONS=1e6,this.dedupedSegments=(A=>{const c=[],l=new Map;let u=-1;for(const g of A){const h=`${g.start.x}-${g.start.y}-${g.end.x}-${g.end.y}-${g.availableZ.join(",")}`,d=l.get(h);d?g.nodePortSegmentId=d.nodePortSegmentId:(u++,g.nodePortSegmentId=`SEG${u}`,l.set(h,g),c.push(g))}return c})(e),this.dedupedSegmentMap=new Map;for(const A of this.dedupedSegments)this.dedupedSegmentMap.set(A.nodePortSegmentId,A);this.nodeMap=new Map;for(const A of o)this.nodeMap.set(A.capacityMeshNodeId,A);this.nodeIdToSegmentIds=new Map,this.segmentIdToNodeIds=new Map,this.attemptsToFixNode=new Map;for(const A of e)this.segmentIdToNodeIds.set(A.nodePortSegmentId,[...this.segmentIdToNodeIds.get(A.nodePortSegmentId)??[],A.capacityMeshNodeId]),this.nodeIdToSegmentIds.set(A.capacityMeshNodeId,[...this.nodeIdToSegmentIds.get(A.capacityMeshNodeId)??[],A.nodePortSegmentId]);this.colorMap=n??{},this.tunedNodeCapacityMap=new Map;for(const[A,c]of this.nodeMap)this.tunedNodeCapacityMap.set(A,l7(c));const{segmentPointMap:r,nodeToSegmentPointMap:s,segmentToSegmentPointMap:a}=c1t(this.dedupedSegments,this.segmentIdToNodeIds);this.segmentPointMap=r,this.nodeToSegmentPointMap=s,this.segmentToSegmentPointMap=a,this.nodePfMap=this.computeInitialPfMap()}computeInitialPfMap(){const e=new Map;for(const[n,o]of this.nodeMap.entries())e.set(n,this.computeNodePf(o));return e}computeNodePf(e){const{numSameLayerCrossings:n,numEntryExitLayerChanges:o,numTransitionCrossings:i}=(r=>{let s=0,a=0,A=0;const c=new Map;for(const g of r)c.has(g.connectionName)||c.set(g.connectionName,[]),c.get(g.connectionName).push(g);const l=[],u=[];for(const[g,h]of c.entries()){if(h.length<2)continue;const d=h[0];for(let p=1;p<h.length;p++){const m=h[p],_={connectionName:g,z:d.z,points:[d,m]};d.z!==m.z?(a++,u.push({connectionName:g,points:[d,m]})):l.push(_)}}for(let g=0;g<l.length;g++)for(let h=g+1;h<l.length;h++){const d=l[g],p=l[h];d.z===p.z&&Uh(d.points[0],d.points[1],p.points[0],p.points[1])&&s++}for(let g=0;g<u.length;g++)for(let h=g+1;h<u.length;h++){const d=u[g],p=u[h];Uh(d.points[0],d.points[1],p.points[0],p.points[1])&&A++}for(let g=0;g<u.length;g++)for(let h=0;h<l.length;h++){const d=u[g],p=l[h];Uh(d.points[0],d.points[1],p.points[0],p.points[1])&&A++}return{numSameLayerCrossings:s,numEntryExitLayerChanges:a,numTransitionCrossings:A}})((this.nodeToSegmentPointMap.get(e.capacityMeshNodeId)??[]).map(r=>this.segmentPointMap.get(r)));return wy(e,n,o,i)}_step(){if(this.iterations>=this.MAX_ITERATIONS-1)return void(this.solved=!0);if(!this.activeSubSolver){let i=null,r=0;for(const[s,a]of this.nodePfMap.entries())a*(1-(this.attemptsToFixNode.get(s)??0)/this.MAX_NODE_ATTEMPTS)>r&&(r=a,i=s);if(!i||r<this.ACCEPTABLE_PF)return void(this.solved=!0);this.attemptsToFixNode.set(i,(this.attemptsToFixNode.get(i)??0)+1),this.activeSubSolver=new KZn({dedupedSegments:this.dedupedSegments,dedupedSegmentMap:this.dedupedSegmentMap,nodeMap:this.nodeMap,nodeIdToSegmentIds:this.nodeIdToSegmentIds,segmentIdToNodeIds:this.segmentIdToNodeIds,colorMap:this.colorMap,rootNodeId:i,MUTABLE_HOPS:this.MUTABLE_HOPS,segmentPointMap:this.segmentPointMap,nodeToSegmentPointMap:this.nodeToSegmentPointMap,segmentToSegmentPointMap:this.segmentToSegmentPointMap,cacheProvider:this.cacheProvider})}this.activeSubSolver.step();const{bestCandidate:e,originalCandidate:n,lastProcessedCandidate:o}=this.activeSubSolver;if(this.activeSubSolver.failed)return this.stats.failedOptimizations+=1,void(this.activeSubSolver=null);if(this.activeSubSolver.solved){if(this.activeSubSolver.cacheHit?this.stats.cacheHits+=1:this.stats.cacheMisses+=1,e&&e.g<n.g){this.stats.successfulOptimizations+=1;for(const[i,r]of e.pointModifications.entries()){const s=this.segmentPointMap.get(i);s.x=r.x??s.x,s.y=r.y??s.y,s.z=r.z??s.z}for(const i of this.activeSubSolver.unravelSection.allNodeIds)this.nodePfMap.set(i,this.computeNodePf(this.nodeMap.get(i)))}else this.stats.failedOptimizations+=1;this.activeSubSolver=null}}visualize(){if(this.activeSubSolver)return this.activeSubSolver.visualize();const e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:"Unravel Multi Section Solver"};for(const[r,s]of this.nodeMap.entries()){const a=this.nodePfMap.get(r)||0,A=Math.min(a,1),c=`rgb(${Math.floor(255*A)}, ${Math.floor(255*(1-A))}, 0)`;(this.attemptsToFixNode.get(r)??0)===0&&A===0||e.rects.push({center:s.center,label:[r,`${s.width.toFixed(2)}x${s.height.toFixed(2)}`,`Pf: ${a.toFixed(3)}`].join(`
`),color:c,width:s.width/8,height:s.height/8})}for(const r of this.segmentPointMap.values()){const s=this.dedupedSegmentMap.get(r.segmentId);e.points.push({x:r.x,y:r.y,label:[r.segmentPointId,r.segmentId,`z: ${r.z}`,`segment.availableZ: ${s?.availableZ.join(",")}`].join(`
`),color:this.colorMap[r.connectionName]||"#000"})}const n=new Map;for(const r of this.segmentPointMap.values())n.has(r.segmentId)||n.set(r.segmentId,[]),n.get(r.segmentId).push(r);for(const[r,s]of n.entries()){if(s.length<2)continue;const a=[...s].sort((A,c)=>A.x!==c.x?A.x-c.x:A.y-c.y);for(let A=0;A<a.length-1;A++)e.lines.push({points:[{x:a[A].x,y:a[A].y},{x:a[A+1].x,y:a[A+1].y}],strokeColor:this.colorMap[r]||"#000"})}const o=new Set,i=Array.from(this.segmentPointMap.values());for(let r=0;r<i.length;r++){const s=i[r];for(let a=r+1;a<i.length;a++){const A=i[a];if(!(s.connectionName!==A.connectionName||s.segmentId===A.segmentId)&&s.capacityMeshNodeIds.some(c=>A.capacityMeshNodeIds.includes(c))){const c=`${s.segmentPointId}-${A.segmentPointId}`;if(o.has(c))continue;o.add(c);const l=s.z===A.z,u=s.z;let g;g=l?u===0?void 0:"10 5":"3 3 10",e.lines.push({points:[{x:s.x,y:s.y},{x:A.x,y:A.y}],strokeDash:g,strokeColor:this.colorMap[s.connectionName]||"#666"})}}}return e}getNodesWithPortPoints(){if(!this.solved)throw new Error("CapacitySegmentToPointSolver not solved, can't give port points yet");const e=new Map;for(const n of this.dedupedSegments){const o=n.nodePortSegmentId;for(const i of this.segmentIdToNodeIds.get(o)){const r=this.nodeMap.get(i);e.has(i)||e.set(i,{capacityMeshNodeId:i,portPoints:[],center:r.center,width:r.width,height:r.height})}}for(const n of this.segmentPointMap.values())for(const o of n.capacityMeshNodeIds){const i=e.get(o);i&&i.portPoints.push({x:n.x,y:n.y,z:n.z,connectionName:n.connectionName,rootConnectionName:n.rootConnectionName})}return Array.from(e.values())}};function fx(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved}}var zZn=class extends yr{constructor(e,n={}){super(),this.srj=e,this.opts=n,this.srj=e,this.opts={...n},this.MAX_ITERATIONS=1e8,this.viaDiameter=om(e).padDiameter,this.minTraceWidth=e.minTraceWidth;const o=this.opts;if(o.capacityDepth===void 0){const i=e.bounds.maxX-e.bounds.minX,r=e.bounds.maxY-e.bounds.minY,s=Math.max(i,r),a=o.targetMinCapacity??.5;o.capacityDepth=$Q(s,a)}this.connMap=Jm(e),this.colorMap=Jf(e,this.connMap),this.cacheProvider=o.cacheProvider===void 0?tB():o.cacheProvider===null?null:o.cacheProvider,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={}}srj;opts;getSolverName(){return"AutoroutingPipeline1_OriginalUnravel"}netToPointPairsSolver;nodeSolver;nodeTargetMerger;edgeSolver;initialPathingSolver;pathingOptimizer;edgeToPortSegmentSolver;colorMap;segmentToPointSolver;unravelMultiSectionSolver;segmentToPointOptimizer;highDensityRouteSolver;highDensityStitchSolver;singleLayerNodeMerger;strawSolver;deadEndSolver;traceSimplificationSolver;viaDiameter;minTraceWidth;startTimeOfPhase;endTimeOfPhase;timeSpentOnPhase;activeSubSolver=null;connMap;srjWithPointPairs;capacityNodes=null;capacityEdges=null;cacheProvider=null;pipelineDef=[fx("netToPointPairsSolver",rL,e=>[e.srj,e.colorMap,JQ(e.srj)],{onSolved:e=>{e.srjWithPointPairs=e.netToPointPairsSolver?.getNewSimpleRouteJson(),e.colorMap=Jf(e.srjWithPointPairs,this.connMap),e.connMap=Jm(e.srjWithPointPairs)}}),fx("nodeSolver",vZn,e=>[e.netToPointPairsSolver?.getNewSimpleRouteJson()||e.srj,e.opts],{onSolved:e=>{e.capacityNodes=e.nodeSolver?.finishedNodes}}),fx("singleLayerNodeMerger",OZn,e=>[e.nodeSolver?.finishedNodes],{onSolved:e=>{e.capacityNodes=e.singleLayerNodeMerger?.newNodes}}),fx("strawSolver",GZn,e=>[{nodes:e.singleLayerNodeMerger?.newNodes}],{onSolved:e=>{e.capacityNodes=e.strawSolver?.getResultNodes()}}),fx("edgeSolver",WQ,e=>[e.capacityNodes],{onSolved:e=>{e.capacityEdges=e.edgeSolver?.edges}}),fx("deadEndSolver",LZn,e=>[{nodes:e.capacityNodes,edges:e.capacityEdges}],{onSolved:e=>{const n=e.deadEndSolver?.removedNodeIds;e.capacityNodes=e.capacityNodes.filter(o=>!n.has(o.capacityMeshNodeId)),e.capacityEdges=e.capacityEdges.filter(o=>o.nodeIds.every(i=>!n.has(i)))}}),fx("initialPathingSolver",r1t,e=>[{simpleRouteJson:e.srjWithPointPairs,nodes:e.capacityNodes,edges:e.capacityEdges||[],colorMap:e.colorMap,hyperParameters:{MAX_CAPACITY_FACTOR:1}}]),fx("pathingOptimizer",FZn,e=>[{initialPathingSolver:e.initialPathingSolver,simpleRouteJson:e.srjWithPointPairs,nodes:e.capacityNodes,edges:e.capacityEdges||[],colorMap:e.colorMap,cacheProvider:e.cacheProvider,hyperParameters:{MAX_CAPACITY_FACTOR:1}}]),fx("edgeToPortSegmentSolver",EZn,e=>[{nodes:e.capacityNodes,edges:e.capacityEdges||[],capacityPaths:e.pathingOptimizer?.getCapacityPaths()||[],colorMap:e.colorMap}]),fx("segmentToPointSolver",wZn,e=>{const n=[];return e.edgeToPortSegmentSolver?.nodePortSegments&&e.edgeToPortSegmentSolver.nodePortSegments.forEach(o=>{n.push(...o)}),[{segments:n,colorMap:e.colorMap,nodes:e.capacityNodes}]}),fx("unravelMultiSectionSolver",VZn,e=>[{assignedSegments:e.segmentToPointSolver?.solvedSegments||[],colorMap:e.colorMap,nodes:e.capacityNodes,cacheProvider:this.cacheProvider}]),fx("highDensityRouteSolver",HD,e=>[{nodePortPoints:e.unravelMultiSectionSolver?.getNodesWithPortPoints()??e.segmentToPointOptimizer?.getNodesWithPortPoints()??[],colorMap:e.colorMap,connMap:e.connMap,viaDiameter:e.viaDiameter,traceWidth:e.minTraceWidth}]),fx("highDensityStitchSolver",HZn,e=>[{connections:e.srjWithPointPairs.connections,hdRoutes:e.highDensityRouteSolver.routes,colorMap:e.colorMap,layerCount:e.srj.layerCount,defaultViaDiameter:e.viaDiameter}]),fx("traceSimplificationSolver",j8,e=>[{hdRoutes:e.highDensityStitchSolver.mergedHdRoutes,obstacles:e.srj.obstacles,connMap:e.connMap,colorMap:e.colorMap,outline:e.srj.outline,defaultViaDiameter:e.viaDiameter,layerCount:e.srj.layerCount}])];getConstructorParams(){return[this.srj,this.opts]}currentPipelineStepIndex=0;_step(){const e=this.pipelineDef[this.currentPipelineStepIndex];if(!e)return void(this.solved=!0);if(this.activeSubSolver)return this.activeSubSolver.step(),void(this.activeSubSolver.solved?(this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null));const n=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...n),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now()}solveUntilPhase(e){for(;this.getCurrentPhase()!==e;)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();const e=this.netToPointPairsSolver?.visualize(),n=this.nodeSolver?.visualize(),o=this.nodeTargetMerger?.visualize(),i=this.singleLayerNodeMerger?.visualize(),r=this.strawSolver?.visualize(),s=this.edgeSolver?.visualize(),a=this.deadEndSolver?.visualize(),A=this.initialPathingSolver?.visualize(),c=this.pathingOptimizer?.visualize(),l=this.edgeToPortSegmentSolver?.visualize(),u=this.segmentToPointSolver?.visualize(),g=this.unravelMultiSectionSolver?.visualize()??this.segmentToPointOptimizer?.visualize(),h=this.highDensityRouteSolver?.visualize(),d=this.highDensityStitchSolver?.visualize(),p=this.traceSimplificationSolver?.visualize(),m=this.srj.outline,_=[];if(_.push({points:[{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.minY??-50},{x:this.srj.bounds?.maxX??50,y:this.srj.bounds?.minY??-50},{x:this.srj.bounds?.maxX??50,y:this.srj.bounds?.maxY??50},{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.maxY??50},{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.minY??-50}],strokeColor:"rgba(255,0,0,0.25)"}),m&&m.length>=2){const y=m.map(x=>({x:x.x,y:x.y}));y.push({...y[0]}),_.push({points:y,strokeColor:"rgba(0, 136, 255, 0.95)"})}const f=z8(this.srj),I={points:[...this.srj.connections.flatMap(y=>y.pointsToConnect.map(x=>({...x,layer:J8(x,this.srj.layerCount),label:`${y.name} ${x.pcb_port_id??""}`})))],rects:[...(this.srj.obstacles??[]).filter(y=>!y.isCopperPour).map(y=>({...y,fill:y.layers?.includes("top")?"rgba(255,0,0,0.25)":y.layers?.includes("bottom")?"rgba(0,0,255,0.25)":"rgba(255,0,0,0.25)",layer:r7(y,this.srj.layerCount),label:f(y)}))],lines:_},C=[I,e,n,o,i,r,s,a,A,c,l,u,g,h?Il(I,h):null,d,p,this.solved?Il({lines:_},mx(this.getOutputSimpleRouteJson())):null].filter(Boolean);return Il(...C)}preview(){if(this.highDensityRouteSolver){const e=[];for(let n=this.highDensityRouteSolver.routes.length-1;n>=0;n--){const o=this.highDensityRouteSolver.routes[n];if(e.push({points:o.route.map(i=>({x:i.x,y:i.y})),strokeColor:this.colorMap[o.connectionName]}),e.length>200)break}return{lines:e}}if(this.pathingOptimizer){const e=[];for(const n of this.pathingOptimizer.connectionsWithNodes)n.path&&e.push({points:n.path.map(o=>({x:o.center.x,y:o.center.y})),strokeColor:this.colorMap[n.connection.name]});return{lines:e}}return this.netToPointPairsSolver?this.netToPointPairsSolver?.visualize():{}}_getOutputHdRoutes(){return this.traceSimplificationSolver?.simplifiedHdRoutes??this.highDensityStitchSolver.mergedHdRoutes}getOutputSimplifiedPcbTraces(){if(!this.solved||!this.highDensityRouteSolver)throw new Error("Cannot get output before solving is complete");const e=[],n=this._getOutputHdRoutes();for(const o of this.netToPointPairsSolver?.newConnections??[]){const i=o.__netConnectionName??this.srj.connections.find(s=>s.name===o.name)?.__netConnectionName,r=n.filter(s=>s.connectionName===o.name);for(let s=0;s<r.length;s++){const a=r[s],A={type:"pcb_trace",pcb_trace_id:`${o.name}_${s}`,connection_name:i??o.__rootConnectionNames?.[0]??o.name,route:nB(a,this.srj.layerCount)};e.push(A)}}return e}getOutputSimpleRouteJson(){return{...this.srj,traces:this.getOutputSimplifiedPcbTraces()}}};function mae(t){const{pos:e,segments:n,dir:o,keepoutRadius:i}=t;let r=1/0;const s=i/4,a={x:e.x-o.x*s,y:e.y-o.y*s},A={x:e.x+o.x*s,y:e.y+o.y*s};for(const c of n){const l=M5(a,A,c.start,c.end);r=Math.min(r,l)}return r}function JZn(t,e,n,o){const i=_ae(n,o,t),r=_ae(n,o,e),s=_ae(t,e,n),a=_ae(t,e,o);if((i>0&&r<0||i<0&&r>0)&&(s>0&&a<0||s<0&&a>0))return!0;const A=1e-4;return!!(Math.abs(i)<A&&fae(n,o,t))||!!(Math.abs(r)<A&&fae(n,o,e))||!!(Math.abs(s)<A&&fae(t,e,n))||!!(Math.abs(a)<A&&fae(t,e,o))}function _ae(t,e,n){return(n.x-t.x)*(e.y-t.y)-(e.x-t.x)*(n.y-t.y)}function fae(t,e,n){return n.x>=Math.min(t.x,e.x)-1e-4&&n.x<=Math.max(t.x,e.x)+1e-4&&n.y>=Math.min(t.y,e.y)-1e-4&&n.y<=Math.max(t.y,e.y)+1e-4}function A6e(t,e,n){for(const o of n)if(JZn(t,e,o.start,o.end))return!1;return!0}var XQ=1e-4;function c6e(t){const e=t.width/2,n=t.height/2,o=t.center.x,i=t.center.y,r={x:o-e,y:i+n},s={x:o+e,y:i+n},a={x:o-e,y:i-n},A={x:o+e,y:i-n};return[{start:r,end:s},{start:s,end:A},{start:A,end:a},{start:a,end:r}]}function WZn(t,e,n=.1){const o=e.x-t.x,i=e.y-t.y,r=Math.sqrt(o*o+i*i);if(r===0)return[];const s=-(i/r),a=o/r,A=n/2;return[{start:{x:t.x+s*A,y:t.y+a*A},end:{x:e.x+s*A,y:e.y+a*A}},{start:{x:t.x-s*A,y:t.y-a*A},end:{x:e.x-s*A,y:e.y-a*A}}]}function jZn(t,e,n){const o=Math.hypot(t.start.x-e.x,t.start.y-e.y),i=Math.hypot(t.end.x-e.x,t.end.y-e.y);if(o<=n||i<=n)return!0;const r=t.end.x-t.start.x,s=t.end.y-t.start.y,a=r*r+s*s;if(a===0)return!1;const A=Math.max(0,Math.min(1,((e.x-t.start.x)*r+(e.y-t.start.y)*s)/a)),c=t.start.x+A*r,l=t.start.y+A*s;return Math.hypot(c-e.x,l-e.y)<=n}function $Zn(t,e,n){if(!n||n.length===0)return!1;for(const o of n){const i=Math.abs(t.x-o.start.x)<XQ&&Math.abs(t.y-o.start.y)<XQ&&Math.abs(e.x-o.end.x)<XQ&&Math.abs(e.y-o.end.y)<XQ,r=Math.abs(t.x-o.end.x)<XQ&&Math.abs(t.y-o.end.y)<XQ&&Math.abs(e.x-o.start.x)<XQ&&Math.abs(e.y-o.start.y)<XQ;if(i||r)return!0}return!1}function qZn(t,e,n,o,i){const r=[];for(let s=0;s<t.length-1;s++){const a=t[s],A=t[s+1];$Zn(a,A,i)||jZn({start:a,end:A},n,o+e)&&r.push(...WZn(a,A,e))}return r}var Iae=1e-4;function XZn(t,e,n,o){const i=e.x-t.x,r=e.y-t.y,s=o.x-n.x,a=o.y-n.y,A=i*a-r*s;if(Math.abs(A)<1e-10)return null;const c=n.x-t.x,l=n.y-t.y,u=(c*a-l*s)/A,g=(c*r-l*i)/A,h=1e-6;return u>h&&u<.999999&&g>h&&g<.999999?{x:t.x+u*i,y:t.y+u*r}:null}function ZZn(t,e){if(!e||e.length===0)return!1;for(const n of e)if(Math.abs(t.x-n.start.x)<Iae&&Math.abs(t.y-n.start.y)<Iae||Math.abs(t.x-n.end.x)<Iae&&Math.abs(t.y-n.end.y)<Iae)return!0;return!1}function eeo(t,e,n,o){if(!o||o.length===0)return!1;for(let i=e;i<=n;i++)if(i>=0&&i<t.length&&ZZn(t[i],o))return!0;return!1}var W3=1e-4,u1t=class extends yr{constructor(e){super(),this.input=e;const n=e.srj?.layerCount??2;this.input={...e,obstacles:c7(e.obstacles,n)},this.MAX_ITERATIONS=1e6,this.originalHdRoutes=[...this.input.hdRoutes],this.hdRoutes=this.input.hdRoutes,this.KEEPOUT_RADIUS_SCHEDULE=e.keepoutRadiusSchedule??[.3,.5,.5],this.currentKeepoutRadius=this.KEEPOUT_RADIUS_SCHEDULE[0]??.15,this.unprocessedRoutes=[...this.hdRoutes],this.smoothedCursorRoutes=[...this.unprocessedRoutes];const o=[...this.input.obstacles,...this.getJumperPadObstacles()];this.obstacleSHI=new OD("flatbush",o),this.boardOutlineRoutes=this.createBoardOutlineRoutes(),this.hdRouteSHI=new oB([...this.hdRoutes,...this.boardOutlineRoutes]);for(const[i,r,s]of this.hdRoutes.flatMap(a=>[[a.route[0],a.connectionName,a.rootConnectionName],[a.route[a.route.length-1],a.connectionName,a.rootConnectionName]])){const a=this.obstacleSHI.searchArea(i.x,i.y,.01,.01).filter(c=>c.__zLayers?.includes(i.z));if(a.length===0)continue;const A=a[0];this.input.connMap.addConnections([[r,s,...A.offBoardConnectsTo??[],A.obstacleId,...A.connectedTo].filter(Boolean)])}}input;getSolverName(){return"TraceKeepoutSolver"}originalHdRoutes;hdRoutes;redrawnHdRoutes=[];KEEPOUT_RADIUS_SCHEDULE;currentScheduleIndex=0;currentKeepoutRadius;unprocessedRoutes=[];smoothedCursorRoutes=[];processedRoutes=[];currentTrace=null;cursorPosition=null;lastCursorPosition=null;drawPosition=null;currentTraceSegmentIndex=0;currentTraceSegmentT=0;recordedDrawPositions=[];lastCollidingSegments=[];currentTraceJumperSegments=new Map;obstacleSHI;hdRouteSHI;boardOutlineRoutes=[];getSmoothDistance(){return this.currentKeepoutRadius}getJumperPadObstacles(){const e=[];if(!this.input.jumpers)return e;for(const n of this.input.jumpers)for(const o of n.pads)e.push({...o,__zLayers:[0]});return e}buildJumperSegmentMap(e){const n=new Map;if(!e.jumpers||e.jumpers.length===0)return n;const o=e.route;for(const i of e.jumpers){let r=-1,s=1/0;for(let a=0;a<o.length-1;a++){const A=o[a],c=o[a+1],l=Math.sqrt((A.x-i.start.x)**2+(A.y-i.start.y)**2),u=Math.sqrt((c.x-i.end.x)**2+(c.y-i.end.y)**2),g=l+u,h=Math.sqrt((A.x-i.end.x)**2+(A.y-i.end.y)**2),d=Math.sqrt((c.x-i.start.x)**2+(c.y-i.start.y)**2),p=h+d,m=Math.min(g,p);(g<=p?l:h)<1&&(g<=p?u:d)<1&&m<s&&(s=m,r=a)}r>=0&&n.set(r,i)}return n}_step(){if(!this.currentTrace){const r=this.unprocessedRoutes.shift();if(!r)return this.currentScheduleIndex++,this.currentScheduleIndex<this.KEEPOUT_RADIUS_SCHEDULE.length?(this.currentKeepoutRadius=this.KEEPOUT_RADIUS_SCHEDULE[this.currentScheduleIndex],this.unprocessedRoutes=D5([...this.processedRoutes],this.currentScheduleIndex),this.smoothedCursorRoutes=[...this.unprocessedRoutes],this.processedRoutes=[],void(this.hdRouteSHI=new oB([...this.unprocessedRoutes,...this.boardOutlineRoutes]))):(this.redrawnHdRoutes=this.processedRoutes,void(this.solved=!0));if(this.currentTrace=r,this.currentTrace.route.length<2)return this.processedRoutes.push(this.currentTrace),void(this.currentTrace=null);this.currentTraceJumperSegments=this.buildJumperSegmentMap(this.currentTrace);const s=this.currentTrace.route[0];return this.cursorPosition={...s},this.lastCursorPosition={...s},this.drawPosition={x:s.x,y:s.y},this.currentTraceSegmentIndex=0,this.currentTraceSegmentT=0,void(this.recordedDrawPositions=[{...s}])}this.lastCursorPosition={...this.cursorPosition};const e=this.stepCursorForward();if(e==="end")return void this.finalizeCurrentTrace();if(e==="jumper")return void(this.drawPosition={x:this.cursorPosition.x,y:this.cursorPosition.y});const n=this.getCollidingSegments(this.cursorPosition);this.lastCollidingSegments=n;const o=(function(r){const{cursorPosition:s,lastCursorPosition:a,collidingSegments:A,keepoutRadius:c}=r;if(A.length===0)return null;const l=1e-4,u=s.x-a.x,g=s.y-a.y,h=Math.sqrt(u*u+g*g),d=h>l?{x:u/h,y:g/h}:{x:1,y:0},p=-d.y,m=d.x,_=mae({pos:s,segments:A,dir:d,keepoutRadius:c});if(_>=c)return null;for(let F=1;F<=20;F++){const O=F/20*c,U={x:s.x+p*O,y:s.y+m*O},Y=mae({pos:U,segments:A,dir:d,keepoutRadius:c}),W={x:s.x-p*O,y:s.y-m*O},te=mae({pos:W,segments:A,dir:d,keepoutRadius:c}),j=Y>=c&&A6e(s,U,A),J=te>=c&&A6e(s,W,A);if(j&&J)return Y>=te?U:W;if(j)return U;if(J)return W}const f=c,I=[];for(let F=-60;F<=60;F++){const O=F/60*f,U={x:s.x+p*O,y:s.y+m*O},Y=mae({pos:U,segments:A,dir:d,keepoutRadius:c}),W=A6e(s,U,A);I.push({pos:U,clearance:Y,dist:Math.abs(O),pathClear:W,index:F})}const C=I.filter(F=>F.pathClear),y=I.findIndex(F=>F.index===0),x=y>=0?y:Math.floor(I.length/2);let E=null;for(let F=x+1;F<I.length-1;F++){const O=I[F-1],U=I[F],Y=I[F+1];if(U.clearance>=O.clearance&&U.clearance>=Y.clearance){E=U;break}}let B=null;for(let F=x-1;F>0;F--){const O=I[F-1],U=I[F],Y=I[F+1];if(U.clearance>=O.clearance&&U.clearance>=Y.clearance){B=U;break}}let S=null,Q=null;if(C.length>0){const F=C.findIndex(U=>U.index===0),O=F>=0?F:Math.floor(C.length/2);for(let U=O+1;U<C.length-1;U++){const Y=C[U-1],W=C[U],te=C[U+1];if(W.clearance>=Y.clearance&&W.clearance>=te.clearance){S=W;break}}for(let U=O-1;U>0;U--){const Y=C[U-1],W=C[U],te=C[U+1];if(W.clearance>=Y.clearance&&W.clearance>=te.clearance){Q=W;break}}}const w=[E,B,S,Q,I.find(F=>F.index===0)].filter(F=>F!=null),M=new Set,k=w.filter(F=>{const O=`${F.pos.x.toFixed(6)},${F.pos.y.toFixed(6)}`;return!M.has(O)&&(M.add(O),!0)});if(k.length===0){let F=I[0];if(!F)return null;for(const O of I)O.clearance>F.clearance&&(F=O);return Math.sqrt((F.pos.x-s.x)**2+(F.pos.y-s.y)**2)>l?F.pos:null}let R;if(_<.15*c){R=k[0];for(const F of k)F.clearance>R.clearance&&(R=F)}else{const F=k.filter(U=>U.pathClear),O=F.length>0?F:k;R=O[0];for(const U of O)U.clearance>R.clearance&&(R=U)}return Math.sqrt((R.pos.x-s.x)**2+(R.pos.y-s.y)**2)>l?R.pos:null})({cursorPosition:this.cursorPosition,lastCursorPosition:this.lastCursorPosition,collidingSegments:n,keepoutRadius:this.currentKeepoutRadius});this.drawPosition=o??{...this.cursorPosition};const i=this.recordedDrawPositions[this.recordedDrawPositions.length-1];if(i&&this.drawPosition){const r={x:i.x,y:i.y,z:i.z},s={x:this.drawPosition.x,y:this.drawPosition.y,z:this.cursorPosition.z};this.segmentIntersectsOtherRoutes(r,s)&&(this.drawPosition={...this.cursorPosition})}this.recordedDrawPositions.push({x:this.drawPosition.x,y:this.drawPosition.y,z:this.cursorPosition.z})}getStepDistance(){return this.currentKeepoutRadius/2}getJumperAtCurrentSegmentStart(){return this.currentTraceSegmentT>W3?null:this.currentTraceJumperSegments.get(this.currentTraceSegmentIndex)??null}stepCursorForward(){if(!this.currentTrace||!this.cursorPosition)return"end";const e=this.currentTrace.route;let n=this.getStepDistance();for(;n>0;){if(this.currentTraceSegmentIndex>=e.length-1)return"end";const o=this.getJumperAtCurrentSegmentStart();if(o){const u=e[this.currentTraceSegmentIndex],g=e[this.currentTraceSegmentIndex+1],h=Math.sqrt((u.x-o.start.x)**2+(u.y-o.start.y)**2),d=Math.sqrt((u.x-o.end.x)**2+(u.y-o.end.y)**2),p=h<=d?o.start:o.end,m=h<=d?o.end:o.start;return this.recordedDrawPositions.push({x:p.x,y:p.y,z:u.z,insideJumperPad:!0}),this.recordedDrawPositions.push({x:m.x,y:m.y,z:g.z,insideJumperPad:!0}),this.cursorPosition={x:m.x,y:m.y,z:g.z},this.currentTraceSegmentIndex++,this.currentTraceSegmentT=0,"jumper"}const i=e[this.currentTraceSegmentIndex],r=e[this.currentTraceSegmentIndex+1],s=r.x-i.x,a=r.y-i.y,A=Math.sqrt(s*s+a*a);if(A===0){this.currentTraceSegmentIndex++,this.currentTraceSegmentT=0;continue}const c=this.currentTraceSegmentT*A,l=A-c;if(n<=l){const u=c+n;return this.currentTraceSegmentT=u/A,this.cursorPosition={x:i.x+s*this.currentTraceSegmentT,y:i.y+a*this.currentTraceSegmentT,z:i.z},"stepped"}if(n-=l,this.currentTraceSegmentIndex++,this.currentTraceSegmentT=0,this.currentTraceSegmentIndex>=e.length-1){const u=e[e.length-1];return this.cursorPosition={...u},"end"}}return"stepped"}getCollidingSegments(e){if(!this.currentTrace)return[];const n=this.currentTrace.rootConnectionName??this.currentTrace.connectionName,o=2*this.currentKeepoutRadius,i=[],r=this.obstacleSHI.searchArea(e.x,e.y,o,o).filter(a=>a.__zLayers?.includes(e.z));for(const a of r){if(a.__zLayers&&!a.__zLayers.includes(e.z)||a.connectedTo.includes(n)||a.obstacleId&&this.input.connMap.areIdsConnected(n,a.obstacleId))continue;let A=!1;for(const c of a.connectedTo)if(this.input.connMap.areIdsConnected(n,c)){A=!0;break}A||i.push(...c6e(a))}const s=this.hdRouteSHI.getConflictingRoutesNearPoint({x:e.x,y:e.y,z:e.z},o);for(const{conflictingRoute:a}of s){const A=a.rootConnectionName??a.connectionName;if(A===n||this.input.connMap.areIdsConnected(n,A))continue;const c=a.traceThickness??.15;i.push(...qZn(a.route,c,{x:e.x,y:e.y},o,a.jumpers))}return i}positionHasCollision(e,n=0){const o=this.getCollidingSegments(e);for(const i of o)if(wc(e,i.start,i.end)<=this.currentKeepoutRadius+n)return!0;return!1}segmentIntersectsOtherRoutes(e,n){if(!this.currentTrace)return!1;const o=this.currentTrace.rootConnectionName??this.currentTrace.connectionName,i=[...this.unprocessedRoutes,...this.smoothedCursorRoutes,...this.processedRoutes];for(const r of i)if((r.rootConnectionName??r.connectionName)!==o)for(let s=0;s<r.route.length-1;s++){const a=r.route[s],A=r.route[s+1];if((a.z===e.z||A.z===e.z)&&(!a.insideJumperPad||!A.insideJumperPad)&&Uh({x:e.x,y:e.y},{x:n.x,y:n.y},{x:a.x,y:a.y},{x:A.x,y:A.y}))return!0}return!1}finalizeCurrentTrace(){if(!this.currentTrace)return;const e=this.currentTrace.route[this.currentTrace.route.length-1],n=this.recordedDrawPositions[this.recordedDrawPositions.length-1];n&&n.x===e.x&&n.y===e.y||this.recordedDrawPositions.push({...e});const o=(function(r,s){if(r.length<4)return r;let a=[...r],A=!0;for(;A;){A=!1;for(let c=0;c<a.length-1&&!A;c++){const l=a[c],u=a[c+1];if(l.z===u.z)for(let g=c+2;g<a.length-1&&!A;g++){if(g===c+1)continue;const h=a[g],d=a[g+1];if(h.z!==d.z||l.z!==h.z)continue;const p=XZn(l,u,h,d);if(p){if(eeo(a,c+1,g,s))continue;const m=[];for(let _=0;_<=c;_++)m.push(a[_]);m.push({x:p.x,y:p.y,z:l.z});for(let _=g+1;_<a.length;_++)m.push(a[_]);a=m,A=!0}}}}return a})(this.simplifyRoute(this.recordedDrawPositions,this.currentTrace.jumpers),this.currentTrace.jumpers),i={connectionName:this.currentTrace.connectionName,rootConnectionName:this.currentTrace.rootConnectionName,traceThickness:this.currentTrace.traceThickness,viaDiameter:this.currentTrace.viaDiameter,route:o,vias:[...this.currentTrace.vias],jumpers:this.currentTrace.jumpers};this.processedRoutes.push(i),this.hdRouteSHI.removeRoute(this.currentTrace.connectionName),this.hdRouteSHI.addRoute(i),this.currentTrace=null,this.cursorPosition=null,this.lastCursorPosition=null,this.drawPosition=null,this.recordedDrawPositions=[]}isJumperEndpoint(e,n){if(!n||n.length===0)return!1;for(const o of n)if(Math.abs(e.x-o.start.x)<W3&&Math.abs(e.y-o.start.y)<W3||Math.abs(e.x-o.end.x)<W3&&Math.abs(e.y-o.end.y)<W3)return!0;return!1}simplifyRoute(e,n){if(e.length<=2)return e;const o=[e[0]];for(let i=1;i<e.length-1;i++){const r=o[o.length-1],s=e[i],a=e[i+1];if(this.isJumperEndpoint(s,n)){o.push(s);continue}if(s.z!==r.z||s.z!==a.z){o.push(s);continue}const A=s.x-r.x,c=s.y-r.y,l=a.x-s.x,u=A*(a.y-s.y)-c*l;Math.abs(u)>1e-6&&o.push(s)}return o.push(e[e.length-1]),o}createBoardOutlineRoutes(){const e=[];if(!this.input.srj)return e;const{outline:n,bounds:o}=this.input.srj;let i;i=n&&n.length>=3?n:[{x:o.minX,y:o.minY},{x:o.maxX,y:o.minY},{x:o.maxX,y:o.maxY},{x:o.minX,y:o.maxY}];const r=this.input.srj.layerCount??2;for(let s=0;s<i.length;s++){const a=i[s],A=i[(s+1)%i.length];for(let c=0;c<r;c++)e.push({connectionName:`__board_outline___${s}_z${c}`,traceThickness:.01,viaDiameter:0,route:[{x:a.x,y:a.y,z:c},{x:A.x,y:A.y,z:c}],vias:[]})}return e}visualize(){const e={lines:[],points:[],rects:[],circles:[],coordinateSystem:"cartesian",title:`Trace Keepout Solver (radius: ${this.currentKeepoutRadius.toFixed(2)})`};for(const n of this.originalHdRoutes)if(n.route.length!==0)for(let o=0;o<n.route.length-1;o++){const i=n.route[o],r=n.route[o+1];i.z===r.z&&e.lines.push({points:[{x:i.x,y:i.y},{x:r.x,y:r.y}],strokeColor:"rgba(0,0,0,0.25)",strokeWidth:1.5*(n.traceThickness??.15)})}if(this.input.jumpers)for(const n of this.input.jumpers){for(const o of n.pads){const i=o.connectedTo.length>0?o.connectedTo.join(", "):"unused",r=o.connectedTo.length>0?this.input.colorMap[o.connectedTo[0]]||"#888888":"rgba(128, 128, 128, 0.5)";e.rects.push({center:o.center,width:o.width,height:o.height,fill:r,stroke:"rgba(0, 0, 0, 0.5)",label:`Jumper pad (${i})`})}n.pads.length>=2&&e.lines.push({points:[n.pads[0].center,n.pads[1].center],strokeColor:"rgba(100, 100, 100, 0.8)",strokeWidth:.2,label:"Jumper body"})}for(const n of this.input.obstacles){let o="rgba(128, 128, 128, 0.2)";const i=n.__zLayers?.includes(0),r=n.__zLayers?.includes(1);i&&r?o="rgba(128, 0, 128, 0.2)":i?o="rgba(255, 0, 0, 0.2)":r&&(o="rgba(0, 0, 255, 0.2)"),e.rects.push({center:n.center,width:n.width,height:n.height,fill:o,label:`Obstacle (Z: ${n.__zLayers?.join(", ")})`})}if(this.input.srj){const{outline:n,bounds:o}=this.input.srj;let i;i=n&&n.length>=3?n:[{x:o.minX,y:o.minY},{x:o.maxX,y:o.minY},{x:o.maxX,y:o.maxY},{x:o.minX,y:o.maxY}];for(let r=0;r<i.length;r++){const s=i[r],a=i[(r+1)%i.length];e.lines.push({points:[{x:s.x,y:s.y},{x:a.x,y:a.y}],strokeColor:"rgba(0, 128, 0, 0.6)",strokeWidth:.1,label:"Board outline"})}}for(const n of this.processedRoutes){if(n.route.length===0)continue;const o=this.input.colorMap[n.connectionName]||"#888888",i=new Set;if(n.jumpers&&n.jumpers.length>0)for(const r of n.jumpers)for(let s=0;s<n.route.length-1;s++){const a=n.route[s],A=n.route[s+1],c=Math.abs(a.x-r.start.x)<W3&&Math.abs(a.y-r.start.y)<W3&&Math.abs(A.x-r.end.x)<W3&&Math.abs(A.y-r.end.y)<W3,l=Math.abs(a.x-r.end.x)<W3&&Math.abs(a.y-r.end.y)<W3&&Math.abs(A.x-r.start.x)<W3&&Math.abs(A.y-r.start.y)<W3;if(c||l){i.add(s);break}}for(let r=0;r<n.route.length-1;r++){const s=n.route[r],a=n.route[r+1];i.has(r)?e.lines.push({points:[{x:s.x,y:s.y},{x:a.x,y:a.y}],strokeColor:"rgba(128, 128, 128, 0.6)",strokeDash:"2 2",label:`${n.connectionName} (jumper segment - fixed)`}):s.z===a.z&&e.lines.push({points:[{x:s.x,y:s.y},{x:a.x,y:a.y}],strokeColor:s.z===0?"red":"blue",strokeWidth:n.traceThickness,label:`${n.connectionName} (z=${s.z})`})}for(const r of n.vias)e.circles.push({center:{x:r.x,y:r.y},radius:n.viaDiameter/2,fill:"rgba(255, 0, 255, 0.5)",label:`${n.connectionName} via`});if(n.jumpers&&n.jumpers.length>0){const r=_x(n.jumpers,{color:o,label:n.connectionName});e.rects.push(...r.rects??[]),e.lines.push(...r.lines??[])}}if(this.currentTrace&&this.recordedDrawPositions.length>0){this.input.colorMap[this.currentTrace.connectionName];for(let n=0;n<this.recordedDrawPositions.length-1;n++){const o=this.recordedDrawPositions[n],i=this.recordedDrawPositions[n+1];e.lines.push({points:[{x:o.x,y:o.y},{x:i.x,y:i.y}],strokeColor:"green",strokeWidth:this.currentTrace.traceThickness})}if(this.cursorPosition&&(e.circles.push({center:{x:this.cursorPosition.x,y:this.cursorPosition.y},radius:this.currentKeepoutRadius,stroke:"orange",fill:"none"}),e.points.push({x:this.cursorPosition.x,y:this.cursorPosition.y,color:"orange",label:"Cursor"}),this.lastCursorPosition)){const n=this.cursorPosition.x-this.lastCursorPosition.x,o=this.cursorPosition.y-this.lastCursorPosition.y,i=Math.sqrt(n*n+o*o),r=i>1e-4?{x:n/i,y:o/i}:{x:1,y:0},s=this.currentKeepoutRadius/4,a={x:this.cursorPosition.x-r.x*s,y:this.cursorPosition.y-r.y*s},A={x:this.cursorPosition.x+r.x*s,y:this.cursorPosition.y+r.y*s};e.lines.push({points:[a,A],strokeColor:"cyan",strokeWidth:.05,label:"Projected segment"})}this.drawPosition&&e.points.push({x:this.drawPosition.x,y:this.drawPosition.y,color:"lime",label:"Draw"});for(const n of this.lastCollidingSegments)e.lines.push({points:[{x:n.start.x,y:n.start.y},{x:n.end.x,y:n.end.y}],strokeColor:"rgba(255, 0, 255, 0.8)",strokeWidth:.02,label:"Colliding segment"})}if(!this.solved){for(const n of this.smoothedCursorRoutes)if(n.route.length!==0)for(let o=0;o<n.route.length-1;o++){const i=n.route[o],r=n.route[o+1];i.z===r.z&&e.lines.push({points:[{x:i.x,y:i.y},{x:r.x,y:r.y}],strokeColor:"gray"})}}return e}getRedrawnHdRoutes(){return this.redrawnHdRoutes}},g1t=class extends yr{constructor(e){super(),this.input=e,this.unprocessedObstacles=c7(this.input.srj.obstacles,this.input.srj.layerCount).filter(n=>n.offBoardConnectsTo&&n.offBoardConnectsTo.length>0),this.unprocessedObstacles.forEach((n,o)=>{n.obstacleId=n.obstacleId??`__obs${o}`}),this.offBoardConnMap=new W7e({}),this.offBoardConnMap.addConnections(this.unprocessedObstacles.filter(n=>n.offBoardConnectsTo?.length).map(n=>[n.obstacleId,...n.offBoardConnectsTo??[]])),this.nodeTree=new B7e(this.input.capacityMeshNodes)}input;getSolverName(){return"RelateNodesToOffBoardConnectionsSolver"}unprocessedObstacles;nodeTree;offBoardConnMap;nodesInNet=new Map;lastProcessedObstacle;_step(){const e=this.unprocessedObstacles.pop();if(this.lastProcessedObstacle=e,!e)return void(this.solved=!0);const n=this.offBoardConnMap.getNetConnectedToId(e.obstacleId),o=this.nodeTree.getNodesInArea(e.center.x,e.center.y,.01,.01).filter(a=>a.availableZ.some(A=>e.__zLayers?.includes(A))).filter(a=>Math.abs(a.center.x-e.center.x)<.01&&Math.abs(a.center.y-e.center.y)<.01),i=o.map(a=>a.capacityMeshNodeId),r=this.nodesInNet.get(n)??[],s=[...r.map(a=>a.capacityMeshNodeId),...i];for(const a of r)a._offBoardConnectedCapacityMeshNodeIds=s;for(const a of o)a._offBoardConnectedCapacityMeshNodeIds=s,a._offBoardConnectionId=n;this.nodesInNet.set(n,[...r,...o])}getOutput(){return{capacityNodes:this.input.capacityMeshNodes}}visualize(){const e={rects:[],lines:[],points:[],circles:[]},n=new Set;for(const[o,i]of this.nodesInNet)for(const r of i)n.add(r.capacityMeshNodeId);for(const o of this.input.capacityMeshNodes)n.has(o.capacityMeshNodeId)||e.rects.push({center:o.center,width:o.width-.1,height:o.height-.1,fill:"rgba(0, 0, 0, 0.2)"});this.lastProcessedObstacle&&e.rects.push({center:this.lastProcessedObstacle.center,width:this.lastProcessedObstacle.width,height:this.lastProcessedObstacle.height,fill:"rgba(255, 0, 0, 0.5)"});for(const[o,i]of this.nodesInNet.entries()){for(const r of i)e.rects.push({center:r.center,width:r.width,height:r.height,fill:Fz(o,.2),label:`OffBoardConn: ${o}`});for(const r of i)for(const s of i)r.capacityMeshNodeId!==s.capacityMeshNodeId&&e.lines.push({points:[r.center,s.center],strokeColor:Fz(o,1)})}return e}},Cae=.1,yae=.1;function xae(t,e,n,o,i,r){return(i-t)*(o-e)-(r-e)*(n-t)}function Eae(t,e,n,o,i,r){return Math.min(t,n)<=i&&i<=Math.max(t,n)&&Math.min(e,o)<=r&&r<=Math.max(e,o)}function teo(t,e,n,o,i,r,s,a){const A=xae(i,r,s,a,t,e),c=xae(i,r,s,a,n,o),l=xae(t,e,n,o,i,r),u=xae(t,e,n,o,s,a);return(A>0&&c<0||A<0&&c>0)&&(l>0&&u<0||l<0&&u>0)||!(A!==0||!Eae(i,r,s,a,t,e))||!(c!==0||!Eae(i,r,s,a,n,o))||!(l!==0||!Eae(t,e,n,o,i,r))||!(u!==0||!Eae(t,e,n,o,s,a))}function neo(t,e,n,o,i,r){const s=i-n,a=r-o,A=t-n,c=e-o,l=s*s+a*a;if(l===0)return{x:n,y:o,distSq:A*A+c*c};let u=(A*s+c*a)/l;u=Math.max(0,Math.min(1,u));const g=n+u*s,h=o+u*a,d=t-g,p=e-h;return{x:g,y:h,distSq:d*d+p*p}}var oeo=class extends yr{getSolverName(){return"SimpleHighDensitySolver"}unsolvedNodes;allNodes;routes;colorMap;traceWidth;viaDiameter;numMovablePoints;currentNode=null;lastNode=null;currentNodeStep=0;routesInProgress=[];pushMargin;currentNodeBounds=null;constructor({nodePortPoints:e,colorMap:n,traceWidth:o=.1,viaDiameter:i=.3,pushMargin:r=.3,numMovablePoints:s=2}){if(super(),s<1||s>3)throw new Error(`numMovablePoints must be 1, 2, or 3, got ${s}`);this.allNodes=[...e],this.unsolvedNodes=[...e],this.colorMap=n??{},this.routes=[],this.traceWidth=o,this.viaDiameter=i,this.numMovablePoints=s,this.pushMargin=r,this.MAX_ITERATIONS=10*e.length+1}_step(){if(this.currentNode===null){if(this.unsolvedNodes.length===0)return void(this.solved=!0);this.lastNode=this.currentNode,this.currentNode=this.unsolvedNodes.pop(),this.currentNodeStep=0,this.routesInProgress=[],this._initializeRoutesForCurrentNode()}this.currentNodeStep>0&&this._runForceDirectedStep(),this.currentNodeStep++,this.currentNodeStep>=10&&(this._finalizeRoutesForCurrentNode(),this.lastNode=this.currentNode,this.currentNode=null)}_initializeRoutesForCurrentNode(){const e=this.currentNode,n=e.center.x-e.width/2,o=e.center.x+e.width/2,i=e.center.y-e.height/2,r=e.center.y+e.height/2;this.currentNodeBounds={minX:n,maxX:o,minY:i,maxY:r};const s=new Map;for(const a of e.portPoints)s.has(a.connectionName)||s.set(a.connectionName,[]),s.get(a.connectionName).push({x:a.x,y:a.y,z:a.z,rootConnectionName:a.rootConnectionName});for(const[a,A]of s){if(A.length<2)continue;const c=A[0],l=A[A.length-1],u=c.z,g=l.x-c.x,h=l.y-c.y,d=Math.sqrt(g*g+h*h),p=d>0?g/d:0,m=d>0?h/d:0,_=[];this.numMovablePoints>=1&&_.push({x:c.x+p*yae,y:c.y+m*yae,z:u,rootConnectionName:c.rootConnectionName,connectionName:a}),this.numMovablePoints>=2&&_.push({x:l.x-p*yae,y:l.y-m*yae,z:u,rootConnectionName:c.rootConnectionName,connectionName:a}),this.numMovablePoints>=3&&_.push({x:c.x+g/2,y:c.y+h/2,z:u,rootConnectionName:c.rootConnectionName,connectionName:a}),this.routesInProgress.push({connectionName:a,rootConnectionName:c.rootConnectionName,startPoint:{x:c.x,y:c.y,z:u},endPoint:{x:l.x,y:l.y,z:u},movablePoints:_})}}_runForceDirectedStep(){const e=this.currentNodeBounds,n=[];for(const A of this.routesInProgress)n.push(...A.movablePoints);const o=new Map;for(const A of n)o.set(A,{fx:0,fy:0});const i=.3+this.pushMargin,r=new Map;for(const A of this.routesInProgress){const c=[{x:A.startPoint.x,y:A.startPoint.y,movablePoint:null}];A.movablePoints.length===1?c.push({x:A.movablePoints[0].x,y:A.movablePoints[0].y,movablePoint:A.movablePoints[0]}):A.movablePoints.length===2?(c.push({x:A.movablePoints[0].x,y:A.movablePoints[0].y,movablePoint:A.movablePoints[0]}),c.push({x:A.movablePoints[1].x,y:A.movablePoints[1].y,movablePoint:A.movablePoints[1]})):A.movablePoints.length===3&&(c.push({x:A.movablePoints[0].x,y:A.movablePoints[0].y,movablePoint:A.movablePoints[0]}),c.push({x:A.movablePoints[2].x,y:A.movablePoints[2].y,movablePoint:A.movablePoints[2]}),c.push({x:A.movablePoints[1].x,y:A.movablePoints[1].y,movablePoint:A.movablePoints[1]})),c.push({x:A.endPoint.x,y:A.endPoint.y,movablePoint:null}),r.set(A,c)}for(const A of n){const c=o.get(A),l=A.x-e.minX,u=e.maxX-A.x,g=e.maxY-A.y,h=A.y-e.minY;l<i&&(c.fx+=Cae*(i-l)),u<i&&(c.fx-=Cae*(i-u)),h<i&&(c.fy+=Cae*(i-h)),g<i&&(c.fy-=Cae*(i-g));for(const d of this.routesInProgress){if(d.rootConnectionName===A.rootConnectionName)continue;const p=r.get(d);for(let m=0;m<p.length-1;m++){const _=p[m],f=p[m+1],I=neo(A.x,A.y,_.x,_.y,f.x,f.y),C=Math.sqrt(I.distSq);if(C>0&&C<2*i){const y=A.x-I.x,x=A.y-I.y,E=.002/I.distSq,B=E*y,S=E*x;c.fx+=B,c.fy+=S;const Q=_.movablePoint,w=f.movablePoint;if(Q&&w){const M=o.get(Q),k=o.get(w);M.fx-=B/2,M.fy-=S/2,k.fx-=B/2,k.fy-=S/2}else if(Q){const M=o.get(Q);M.fx-=B,M.fy-=S}else if(w){const M=o.get(w);M.fx-=B,M.fy-=S}}}}}const s=A=>A.movablePoint?{x:A.movablePoint.x,y:A.movablePoint.y}:{x:A.x,y:A.y},a=A=>{let c=null;for(const h of this.routesInProgress)if(h.movablePoints.includes(A)){c=h;break}if(!c)return!1;const l=r.get(c);let u=-1;for(let h=0;h<l.length;h++)if(l[h].movablePoint===A){u=h;break}if(u===-1)return!1;const g=[];if(u>0){const h=s(l[u-1]);g.push({ax:h.x,ay:h.y,bx:A.x,by:A.y})}if(u<l.length-1){const h=s(l[u+1]);g.push({ax:A.x,ay:A.y,bx:h.x,by:h.y})}for(const h of this.routesInProgress){if(h.rootConnectionName===c.rootConnectionName)continue;const d=r.get(h);for(let p=0;p<d.length-1;p++){const m=s(d[p]),_=s(d[p+1]);for(const f of g)if(teo(f.ax,f.ay,f.bx,f.by,m.x,m.y,_.x,_.y))return!0}}return!1};for(const A of n){const c=o.get(A);A.forceX=c.fx,A.forceY=c.fy;const l=A.x,u=A.y;A.x+=c.fx,A.y+=c.fy,A.x=Math.max(e.minX,Math.min(e.maxX,A.x)),A.y=Math.max(e.minY,Math.min(e.maxY,A.y)),a(A)&&(A.x=l,A.y=u)}}_finalizeRoutesForCurrentNode(){for(const e of this.routesInProgress){const{connectionName:n,rootConnectionName:o,startPoint:i,endPoint:r,movablePoints:s}=e,a=[{x:i.x,y:i.y,z:i.z}];s.length===1?a.push({x:s[0].x,y:s[0].y,z:s[0].z}):s.length===2?(a.push({x:s[0].x,y:s[0].y,z:s[0].z}),a.push({x:s[1].x,y:s[1].y,z:s[1].z})):s.length===3&&(a.push({x:s[0].x,y:s[0].y,z:s[0].z}),a.push({x:s[2].x,y:s[2].y,z:s[2].z}),a.push({x:s[1].x,y:s[1].y,z:s[1].z})),a.push({x:r.x,y:r.y,z:r.z});const A={connectionName:n,rootConnectionName:o,traceThickness:this.traceWidth,viaDiameter:this.viaDiameter,route:a,vias:[]};this.routes.push(A)}this.routesInProgress=[]}_getNodeBounds(e){return{minX:e.center.x-e.width/2,maxX:e.center.x+e.width/2,minY:e.center.y-e.height/2,maxY:e.center.y+e.height/2}}visualize(){const e={lines:[],points:[],rects:[],circles:[]};for(const n of this.unsolvedNodes){if(n===this.currentNode)continue;const o=this._getNodeBounds(n);e.rects.push({center:{x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2},width:o.maxX-o.minX,height:o.maxY-o.minY,fill:"rgba(0, 0, 0, 0.08)",stroke:"rgba(0, 0, 0, 0.2)",label:n.capacityMeshNodeId})}if(this.lastNode){const n=this._getNodeBounds(this.lastNode);e.rects.push({center:{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2},width:n.maxX-n.minX,height:n.maxY-n.minY,fill:"rgba(0, 200, 0, 0.15)",stroke:"rgba(0, 0, 255, 0.6)"})}if(this.currentNode){const n=this._getNodeBounds(this.currentNode);e.rects.push({center:{x:(n.minX+n.maxX)/2,y:(n.minY+n.maxY)/2},width:n.maxX-n.minX,height:n.maxY-n.minY,fill:"rgba(0, 200, 0, 0.15)",stroke:"rgba(0, 200, 0, 0.6)"})}for(const n of this.unsolvedNodes){const o=new Map;for(const i of n.portPoints)o.has(i.connectionName)||o.set(i.connectionName,[]),o.get(i.connectionName).push({x:i.x,y:i.y});for(const[i,r]of o)r.length<2||e.lines.push({points:r.map(s=>({x:s.x,y:s.y})),label:i,strokeColor:"gray",strokeWidth:this.traceWidth})}for(const n of this.routes){const o=Kse(n.route,n.connectionName,this.colorMap[n.connectionName]);for(const r of o)e.lines.push({points:r.points,label:r.connectionName,strokeColor:r.z===0?r.color:Es(r.color,.75),layer:`z${r.z}`,strokeWidth:n.traceThickness,strokeDash:r.z!==0?"10, 5":void 0});const i=n.route;for(let r=0;r<i.length;r++){const s=i[r],a=r===0,A=r===i.length-1,c=!a&&!A;let l;l=a?"start":A?"end":`M${r}`,e.points.push({x:s.x,y:s.y,label:l,color:c?"orange":"blue"})}}for(const n of this.routesInProgress){const{startPoint:o,endPoint:i,movablePoints:r,connectionName:s}=n,a=this.colorMap[s]??"gray",A=[{x:o.x,y:o.y}];r.length===1?A.push({x:r[0].x,y:r[0].y}):r.length===2?(A.push({x:r[0].x,y:r[0].y}),A.push({x:r[1].x,y:r[1].y})):r.length===3&&(A.push({x:r[0].x,y:r[0].y}),A.push({x:r[2].x,y:r[2].y}),A.push({x:r[1].x,y:r[1].y})),A.push({x:i.x,y:i.y}),e.lines.push({points:A,label:s,strokeColor:a,strokeWidth:this.traceWidth}),e.points.push({x:o.x,y:o.y,label:"start",color:"blue"});for(let c=0;c<r.length;c++){const l=r[c];if(e.points.push({x:l.x,y:l.y,label:`M${c+1}`,color:"orange"}),l.forceX!==void 0&&l.forceY!==void 0&&Math.sqrt(l.forceX*l.forceX+l.forceY*l.forceY)>.001){e.lines.push({points:[{x:l.x,y:l.y},{x:l.x+l.forceX*5,y:l.y+l.forceY*5}],strokeColor:"red",strokeWidth:.02,label:`F${c+1}`});const g=.05,h=l.x+l.forceX*5,d=l.y+l.forceY*5,p=Math.atan2(l.forceY,l.forceX);e.lines.push({points:[{x:h,y:d},{x:h-g*Math.cos(p-Math.PI/6),y:d-g*Math.sin(p-Math.PI/6)}],strokeColor:"red",strokeWidth:.02}),e.lines.push({points:[{x:h,y:d},{x:h-g*Math.cos(p+Math.PI/6),y:d-g*Math.sin(p+Math.PI/6)}],strokeColor:"purple",strokeWidth:.02})}}e.points.push({x:i.x,y:i.y,label:"end",color:"blue"})}return e}},d1t=({connMap:t,connectionsWithResults:e,inputNodes:n,obstacles:o})=>{const i=o.filter(a=>a.offBoardConnectsTo?.length);if(i.length===0)return;const r=new TD({});r.addConnections(i.map((a,A)=>[a.obstacleId??`__obs${A}`,...a.offBoardConnectsTo??[]]));const s=new Map(n.map(a=>[a.capacityMeshNodeId,a]));for(const a of e){if(!a.path)continue;const A=a.connection.rootConnectionName??a.connection.name,c=new Set;for(const l of a.path){const u=s.get(l.currentNodeId);if(u?._offBoardConnectionId&&c.add(u._offBoardConnectionId),l.throughNodeId){const g=s.get(l.throughNodeId);g?._offBoardConnectionId&&c.add(g._offBoardConnectionId)}}for(const l of c){const u=r.getIdsConnectedToNet(l);u?.length&&t.addConnections([[A,...u]])}}};function T5(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved}}var ieo=class extends yr{constructor(e,n={}){super(),this.srj=e,this.opts=n,this.srj=e,this.opts={...n},this.viaDiameter=om(e).padDiameter,this.minTraceWidth=e.minTraceWidth;const o=this.opts;if(this.effort=o.effort??1,this.MAX_ITERATIONS=1e8*this.effort,o.capacityDepth===void 0){const i=e.bounds.maxX-e.bounds.minX,r=e.bounds.maxY-e.bounds.minY,s=Math.max(i,r),a=o.targetMinCapacity??.5;o.capacityDepth=$Q(s,a)}this.connMap=Jm(e),this.colorMap=Jf(e,this.connMap),this.cacheProvider=o.cacheProvider===void 0?tB():o.cacheProvider===null?null:o.cacheProvider,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={}}srj;opts;getSolverName(){return"AssignableAutoroutingPipeline2"}netToPointPairsSolver;nodeSolver;nodeTargetMerger;edgeSolver;relateNodesToOffBoardConnections;colorMap;highDensityRouteSolver;simpleHighDensityRouteSolver;highDensitySolver;highDensityStitchSolver;singleLayerNodeMerger;offboardPathFragmentSolver;strawSolver;deadEndSolver;traceSimplificationSolver;traceKeepoutSolver;traceWidthSolver;availableSegmentPointSolver;portPointPathingSolver;multiSectionPortPointOptimizer;viaDiameter;minTraceWidth;effort;startTimeOfPhase;endTimeOfPhase;timeSpentOnPhase;activeSubSolver=null;connMap;srjWithPointPairs;capacityNodes=null;capacityEdges=null;cacheProvider=null;pipelineDef=[T5("netToPointPairsSolver",J7e,e=>[e.srj,e.colorMap,JQ(e.srj)],{onSolved:e=>{e.srjWithPointPairs=e.netToPointPairsSolver?.getNewSimpleRouteJson(),e.colorMap=Jf(e.srjWithPointPairs,this.connMap),e.connMap=Jm(e.srjWithPointPairs)}}),T5("nodeSolver",qF,e=>[{simpleRouteJson:e.srjWithPointPairs,maxGapFillPasses:4}],{onSolved:e=>{e.capacityNodes=e.nodeSolver?.getOutput().meshNodes??[]}}),T5("relateNodesToOffBoardConnections",g1t,e=>[{capacityMeshNodes:e.capacityNodes,srj:e.srj}],{onSolved:e=>{e.capacityNodes=e.relateNodesToOffBoardConnections?.getOutput().capacityNodes}}),T5("edgeSolver",WQ,e=>[e.capacityNodes],{onSolved:e=>{e.capacityEdges=e.edgeSolver?.edges}}),T5("availableSegmentPointSolver",kD,e=>[{nodes:e.capacityNodes,edges:e.capacityEdges||[],traceWidth:e.minTraceWidth,colorMap:e.colorMap,shouldReturnCrampedPortPoints:!1}]),T5("portPointPathingSolver",z7e,e=>{const n=e.capacityNodes.map(r=>({capacityMeshNodeId:r.capacityMeshNodeId,center:r.center,width:r.width,height:r.height,portPoints:[],availableZ:r.availableZ,_containsTarget:r._containsTarget,_containsObstacle:r._containsObstacle,_offBoardConnectionId:r._offBoardConnectionId,_offBoardConnectedCapacityMeshNodeIds:r._offBoardConnectedCapacityMeshNodeIds})),o=new Map(n.map(r=>[r.capacityMeshNodeId,r])),i=e.availableSegmentPointSolver;for(const r of i.sharedEdgeSegments)for(const s of r.portPoints){const[a,A]=s.nodeIds,c={portPointId:s.segmentPortPointId,x:s.x,y:s.y,z:s.availableZ[0]??0,connectionNodeIds:[a,A],distToCentermostPortOnZ:s.distToCentermostPortOnZ,connectsToOffBoardNode:r.nodeIds.some(u=>o.get(u)?._offBoardConnectionId)},l=o.get(a);l&&l.portPoints.push(c)}return[{simpleRouteJson:e.srjWithPointPairs,inputNodes:n,capacityMeshNodes:e.capacityNodes,colorMap:e.colorMap,numShuffleSeeds:100*e.effort,hyperParameters:{JUMPER_PF_FN_ENABLED:!1,NODE_PF_FACTOR:100,NODE_PF_MAX_PENALTY:100,CENTER_OFFSET_DIST_PENALTY_FACTOR:0,FORCE_CENTER_FIRST:!0}}]},{onSolved:e=>{const n=e.portPointPathingSolver;n&&d1t({connMap:e.connMap,connectionsWithResults:n.connectionsWithResults,inputNodes:n.inputNodes,obstacles:e.srj.obstacles})}}),T5("multiSectionPortPointOptimizer",nZn,e=>{const n=e.portPointPathingSolver;return[{simpleRouteJson:e.srjWithPointPairs,inputNodes:n.inputNodes,capacityMeshNodes:e.capacityNodes,capacityMeshEdges:e.capacityEdges,colorMap:e.colorMap,initialConnectionResults:n.connectionsWithResults,initialAssignedPortPoints:n.assignedPortPoints,initialNodeAssignedPortPoints:n.nodeAssignedPortPoints}]}),T5("highDensitySolver",oeo,e=>[{nodePortPoints:e.multiSectionPortPointOptimizer?.getNodesWithPortPoints()??e.portPointPathingSolver?.getNodesWithPortPoints()??[],colorMap:e.colorMap,viaDiameter:e.viaDiameter,traceWidth:e.minTraceWidth,connMap:e.connMap}]),T5("highDensityStitchSolver",j7e,e=>[{connections:e.srjWithPointPairs.connections,hdRoutes:e.highDensitySolver.routes,colorMap:e.colorMap,layerCount:e.srj.layerCount,defaultViaDiameter:e.viaDiameter}]),T5("traceSimplificationSolver",j8,e=>[{hdRoutes:e.highDensityStitchSolver?.mergedHdRoutes??e.highDensitySolver?.routes??e.highDensityRouteSolver?.routes,obstacles:e.srj.obstacles,connMap:e.connMap,colorMap:e.colorMap,outline:e.srj.outline,defaultViaDiameter:e.viaDiameter,layerCount:e.srj.layerCount,iterations:2}]),T5("traceKeepoutSolver",u1t,e=>[{hdRoutes:e.traceSimplificationSolver?.simplifiedHdRoutes??[],obstacles:e.srj.obstacles,connMap:e.connMap,colorMap:e.colorMap,srj:e.srj}]),T5("traceWidthSolver",aL,e=>[{hdRoutes:e.traceKeepoutSolver?.redrawnHdRoutes??[],connection:e.srj.connections,obstacles:e.srj.obstacles,connMap:e.connMap,colorMap:e.colorMap,minTraceWidth:e.minTraceWidth,obstacleMargin:e.srj.defaultObstacleMargin??.15,layerCount:e.srj.layerCount}])];getConstructorParams(){return[this.srj,this.opts]}currentPipelineStepIndex=0;_step(){const e=this.pipelineDef[this.currentPipelineStepIndex];if(!e)return void(this.solved=!0);if(this.activeSubSolver)return this.activeSubSolver.step(),void(this.activeSubSolver.solved?(this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null));const n=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...n),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now()}solveUntilPhase(e){for(;this.getCurrentPhase()!==e;)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();const e=this.netToPointPairsSolver?.visualize(),n=this.nodeSolver?.visualize(),o=this.nodeTargetMerger?.visualize(),i=this.singleLayerNodeMerger?.visualize(),r=this.strawSolver?.visualize(),s=this.edgeSolver?.visualize(),a=this.deadEndSolver?.visualize(),A=this.availableSegmentPointSolver?.visualize(),c=this.offboardPathFragmentSolver?.visualize(),l=this.portPointPathingSolver?.visualize(),u=this.multiSectionPortPointOptimizer?.visualize(),g=this.highDensityRouteSolver?.visualize(),h=this.highDensitySolver?.visualize(),d=this.simpleHighDensityRouteSolver?.visualize(),p=this.highDensityStitchSolver?.visualize(),m=this.traceSimplificationSolver?.visualize(),_=this.traceKeepoutSolver?.visualize(),f=this.traceWidthSolver?.visualize(),I=this.srj.outline,C=[];if(C.push({points:[{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.minY??-50},{x:this.srj.bounds?.maxX??50,y:this.srj.bounds?.minY??-50},{x:this.srj.bounds?.maxX??50,y:this.srj.bounds?.maxY??50},{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.maxY??50},{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.minY??-50}],strokeColor:"rgba(255,0,0,0.25)"}),I&&I.length>=2){const B=I.map(S=>({x:S.x,y:S.y}));B.push({...B[0]}),C.push({points:B,strokeColor:"rgba(0, 136, 255, 0.95)"})}const y=z8(this.srj),x={points:[...this.srj.connections.flatMap(B=>B.pointsToConnect.map(S=>({...S,layer:J8(S,this.srj.layerCount),label:`${B.name} ${S.pcb_port_id??""}`})))],rects:[...(this.srj.obstacles??[]).filter(B=>!B.isCopperPour).map(B=>({...B,fill:B.layers?.includes("top")?"rgba(255,0,0,0.25)":B.layers?.includes("bottom")?"rgba(0,0,255,0.25)":"rgba(255,0,0,0.25)",layer:r7(B,this.srj.layerCount),label:y(B)}))],lines:C},E=[x,e,n,o,i,r,s,a,A,c,l,u,g?Il(x,g):null,h?Il(x,h):null,d?Il(x,d):null,p,m,_,f,this.solved?Il({lines:C},mx(this.getOutputSimpleRouteJson())):null].filter(Boolean);return Il(...E)}preview(){const e=this.highDensitySolver?.routes??this.simpleHighDensityRouteSolver?.routes??this.highDensityRouteSolver?.routes;if(e){const n=[];for(let o=e.length-1;o>=0;o--){const i=e[o];if(n.push({points:i.route.map(r=>({x:r.x,y:r.y})),strokeColor:this.colorMap[i.connectionName]}),n.length>200)break}return{lines:n}}if(this.portPointPathingSolver){const n=[];for(const o of this.portPointPathingSolver.connectionsWithResults)o.path&&n.push({points:o.path.map(i=>({x:i.point.x,y:i.point.y})),strokeColor:this.colorMap[o.connection.name]});return{lines:n}}return this.netToPointPairsSolver?this.netToPointPairsSolver?.visualize():{}}_getOutputHdRoutes(){return this.traceWidthSolver?.hdRoutesWithWidths??this.traceKeepoutSolver?.redrawnHdRoutes??this.traceSimplificationSolver?.simplifiedHdRoutes??this.highDensityStitchSolver?.mergedHdRoutes??this.highDensitySolver?.routes??this.simpleHighDensityRouteSolver?.routes??this.highDensityRouteSolver?.routes}getConnectedOffboardObstacles(){const e={},n=new Set(this.srj.connections.flatMap(o=>o.__rootConnectionNames??[o.name]));for(const[o,i]of this.srj.obstacles.entries()){if(!i.offBoardConnectsTo?.length)continue;const r=i.obstacleId??`__obs${o}`,s=this.connMap.getNetConnectedToId(r);if(!s)continue;const a=this.connMap.getIdsConnectedToNet(s).find(A=>n.has(A));a&&(e[r]=a)}return e}getOutputSimplifiedPcbTraces(){if(!this.solved||!this.highDensityRouteSolver&&!this.simpleHighDensityRouteSolver&&!this.highDensitySolver)throw new Error("Cannot get output before solving is complete");const e=[],n=this._getOutputHdRoutes();for(const o of this.netToPointPairsSolver?.newConnections??[]){const i=o.__netConnectionName??this.srj.connections.find(s=>s.name===o.name)?.__netConnectionName,r=n.filter(s=>s.connectionName===o.name);for(let s=0;s<r.length;s++){const a=r[s],A={type:"pcb_trace",pcb_trace_id:`${o.name}_${s}`,connection_name:i??o.__rootConnectionNames?.[0]??o.name,route:nB(a,this.srj.layerCount)};e.push(A)}}return e}getOutputSimpleRouteJson(){return{...this.srj,traces:this.getOutputSimplifiedPcbTraces()}}},reo=class extends yr{getSolverName(){return"MultipleHighDensityRouteStitchSolver2"}unsolvedRoutes;mergedHdRoutes=[];colorMap={};defaultTraceThickness;defaultViaDiameter;constructor(e){super(),this.colorMap=e.colorMap??{};const n=e.hdRoutes[0];this.defaultTraceThickness=n?.traceThickness??.15,this.defaultViaDiameter=n?.viaDiameter??e.defaultViaDiameter??.3;const o=new Map;for(const r of e.connectionPathResults)o.set(r.connection.name,r);const i=new Map;for(const r of e.hdRoutes){const s=i.get(r.connectionName);s?s.push(r):i.set(r.connectionName,[r])}this.unsolvedRoutes=[];for(const[r,s]of i.entries()){const a=e.connections.find(g=>g.name===r);if(!a)continue;const A=o.get(r);let c=[];A?.path&&(c=A.path.map(g=>g.currentNodeId));const l={...a.pointsToConnect[0],z:Kr(tI(a.pointsToConnect[0]),e.layerCount)},u={...a.pointsToConnect[1],z:Kr(tI(a.pointsToConnect[1]),e.layerCount)};this.unsolvedRoutes.push({connectionName:r,hdRoutes:s,nodeOrder:c,start:l,end:u})}this.MAX_ITERATIONS=1e5}_step(){const e=this.unsolvedRoutes.pop();if(!e)return void(this.solved=!0);const n=this.stitchOrderedRoutes(e);this.mergedHdRoutes.push(n)}stitchOrderedRoutes(e){const{connectionName:n,hdRoutes:o,nodeOrder:i,start:r,end:s}=e;if(o.length===0)return{connectionName:n,traceThickness:this.defaultTraceThickness,viaDiameter:this.defaultViaDiameter,route:[r,s],vias:[],jumpers:[]};let a;a=i.length>0?this.orderRoutesByNodePath(o,i,r,n):this.orderRoutesByProximity(o,r);const A=[],c=[],l=[];A.push({x:r.x,y:r.y,z:r.z});for(let g=0;g<a.length;g++){const h=a[g],d=A[A.length-1],p=h.route[0],m=h.route[h.route.length-1],_=no(d,p),f=no(d,m),I=Math.min(_,f);if(g>0&&I>1)continue;let C;C=_<=f?[...h.route]:[...h.route].reverse(),C.length>0&&no(d,C[0])<.001&&(C=C.slice(1)),A.push(...C),c.push(...h.vias),h.jumpers&&l.push(...h.jumpers)}const u=no(A[A.length-1],s);return u>.001&&u<1&&A.push({x:s.x,y:s.y,z:s.z}),{connectionName:n,rootConnectionName:o[0]?.rootConnectionName,traceThickness:o[0]?.traceThickness??this.defaultTraceThickness,viaDiameter:o[0]?.viaDiameter??this.defaultViaDiameter,route:A,vias:c,jumpers:l}}orderRoutesByNodePath(e,n,o,i){if(e.length===0)return[];const r=new Set(e);let s=null,a=1/0;for(const _ of r){const f=_.route[0],I=_.route[_.route.length-1],C=Math.min(no(o,f),no(o,I));C<a&&(a=C,s=_)}if(!s)return[];r.delete(s);const A=s.route[0],c=s.route[s.route.length-1];let l,u;no(o,A)<=no(o,c)?(l=A,u=c):(l=c,u=A);const g=(_,f)=>{let I=0;for(const C of r){if(C===f)continue;const y=C.route[0],x=C.route[C.route.length-1];(no(_,y)<10||no(_,x)<10)&&I++}return I},h=[s];let d=u;for(;r.size>0;){let _=null,f=1/0,I=-1;for(const C of r){const y=C.route[0],x=C.route[C.route.length-1],E=no(d,y),B=no(d,x),S=Math.min(E,B);if(S>=10)continue;const Q=g(E<=B?x:y,C),w=Q===0,M=I===0,k=S-f;let R=!1;R=_===null||!!(!w&&M&&k<5)||!(w&&!M&&k>-5)&&S<f,R&&(f=S,_=C,I=Q)}if(!_)break;{h.push(_),r.delete(_);const C=_.route[0],y=_.route[_.route.length-1];d=no(d,C)<=no(d,y)?y:C}}const p=[];for(d=l;r.size>0;){let _=null,f=1/0,I=-1;const C=no(d,o);for(const y of r){const x=y.route[0],E=y.route[y.route.length-1],B=no(d,x),S=no(d,E),Q=Math.min(B,S);if(Q>=10)continue;const w=B<=S?E:x;if(no(w,o)>C+2)continue;const M=g(w,y),k=M===0,R=I===0,F=Q-f;let O=!1;O=_===null||!!(!k&&R&&F<5)||!(k&&!R&&F>-5)&&Q<f,O&&(f=Q,_=y,I=M)}if(!_)break;{p.unshift(_),r.delete(_);const y=_.route[0],x=_.route[_.route.length-1];d=no(d,y)<=no(d,x)?x:y}}const m=[...p,...h];if(r.size>0){const _=[...r].map(f=>{const I=f.route[0],C=f.route[f.route.length-1];return`start=(${I.x.toFixed(2)},${I.y.toFixed(2)}) end=(${C.x.toFixed(2)},${C.y.toFixed(2)})`});console.warn(`[StitchSolver] Skipped ${r.size} routes for connection ${e[0]?.connectionName??"?"}, skipped routes: ${_.join("; ")}`)}return m}orderRoutesByProximity(e,n){const o=new Set(e),i=[];let r=n;for(;o.size>0;){let s=null,a=1/0,A=!1;for(const c of o){const l=c.route[0],u=c.route[c.route.length-1],g=no(r,l),h=no(r,u);g<a&&(a=g,s=c,A=!1),h<a&&(a=h,s=c,A=!0)}if(!s)break;{i.push(s),o.delete(s);const c=s.route[0],l=s.route[s.route.length-1];r=A?c:l}}return i}visualize(){const e={points:[],lines:[],circles:[],rects:[],title:"Multiple High Density Route Stitch Solver 2"};for(const[n,o]of this.mergedHdRoutes.entries()){const i=this.colorMap[o.connectionName]??`hsl(120, 100%, ${40+10*n%40}%)`;for(let r=0;r<o.route.length-1;r++){const s=o.route[r],a=o.route[r+1],A=s.z!==0?Es(i,.5):i;e.lines?.push({points:[{x:s.x,y:s.y},{x:a.x,y:a.y}],strokeColor:A,strokeWidth:o.traceThickness})}for(const r of o.route){const s=r.z!==0?Es(i,.5):i;e.points?.push({x:r.x,y:r.y,color:s})}for(const r of o.vias)e.circles?.push({center:{x:r.x,y:r.y},radius:o.viaDiameter/2,fill:i});if(o.jumpers&&o.jumpers.length>0){const r=_x(o.jumpers,{color:i,label:o.connectionName});e.rects.push(...r.rects??[]),e.lines.push(...r.lines??[])}}for(const n of this.unsolvedRoutes){const o=this.colorMap[n.connectionName]??"gray";e.points?.push({x:n.start.x,y:n.start.y,color:o,label:`${n.connectionName} Start`},{x:n.end.x,y:n.end.y,color:o,label:`${n.connectionName} End`});for(let i=0;i<n.hdRoutes.length;i++){const r=n.hdRoutes[i];if(r.route.length>1&&e.lines?.push({points:r.route.map(s=>({x:s.x,y:s.y})),strokeColor:Es(o,.5),strokeDash:"10 5",label:`segment ${i}`}),r.jumpers&&r.jumpers.length>0){const s=_x(r.jumpers,{color:o,label:r.connectionName});e.rects.push(...s.rects??[]),e.lines.push(...s.lines??[])}}}return e}},seo=Object.create,h1t=Object.defineProperty,aeo=Object.getOwnPropertyDescriptor,p1t=Object.getOwnPropertyNames,Aeo=Object.getPrototypeOf,ceo=Object.prototype.hasOwnProperty,YD=(t,e)=>function(){return e||(0,t[p1t(t)[0]])((e={exports:{}}).exports,e),e.exports},m1t=(t,e,n)=>(n=t!=null?seo(Aeo(t)):{},((o,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of p1t(i))ceo.call(o,a)||a===r||h1t(o,a,{get:()=>i[a],enumerable:!(s=aeo(i,a))||s.enumerable});return o})(t&&t.__esModule?n:h1t(n,"default",{value:t,enumerable:!0}),t)),leo=YD({"node_modules/is-buffer/index.js"(t,e){function n(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}e.exports=function(o){return o!=null&&(n(o)||(function(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&n(i.slice(0,0))})(o)||!!o._isBuffer)}}}),ueo=YD({"node_modules/kind-of/index.js"(t,e){var n=leo(),o=Object.prototype.toString;e.exports=function(i){if(i===void 0)return"undefined";if(i===null)return"null";if(i===!0||i===!1||i instanceof Boolean)return"boolean";if(typeof i=="string"||i instanceof String)return"string";if(typeof i=="number"||i instanceof Number)return"number";if(typeof i=="function"||i instanceof Function)return"function";if(Array.isArray!==void 0&&Array.isArray(i))return"array";if(i instanceof RegExp)return"regexp";if(i instanceof Date)return"date";var r=o.call(i);return r==="[object RegExp]"?"regexp":r==="[object Date]"?"date":r==="[object Arguments]"?"arguments":r==="[object Error]"?"error":n(i)?"buffer":r==="[object Set]"?"set":r==="[object WeakSet]"?"weakset":r==="[object Map]"?"map":r==="[object WeakMap]"?"weakmap":r==="[object Symbol]"?"symbol":r==="[object Int8Array]"?"int8array":r==="[object Uint8Array]"?"uint8array":r==="[object Uint8ClampedArray]"?"uint8clampedarray":r==="[object Int16Array]"?"int16array":r==="[object Uint16Array]"?"uint16array":r==="[object Int32Array]"?"int32array":r==="[object Uint32Array]"?"uint32array":r==="[object Float32Array]"?"float32array":r==="[object Float64Array]"?"float64array":"object"}}}),geo=YD({"node_modules/rename-keys/index.js"(t,e){(function(){function n(o,i){if(typeof i!="function")return o;var r={};for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[i(s,o[s])||s]=o[s]);return r}e!==void 0&&e.exports?e.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):window.rename=n})()}}),deo=YD({"node_modules/deep-rename-keys/index.js"(t,e){var n=ueo(),o=geo();e.exports=function i(r,s){var a=n(r);if(a!=="object"&&a!=="array")throw new Error("expected an object");var A=[];for(var c in a==="object"&&(r=o(r,s),A={}),r)if(r.hasOwnProperty(c)){var l=r[c];n(l)==="object"||n(l)==="array"?A[c]=i(l,s):A[c]=l}return A}}}),_1t=YD({"node_modules/eventemitter3/index.js"(t,e){var n=Object.prototype.hasOwnProperty,o="~";function i(){}function r(a,A,c){this.fn=a,this.context=A,this.once=c||!1}function s(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(o=!1)),s.prototype.eventNames=function(){var a,A,c=[];if(this._eventsCount===0)return c;for(A in a=this._events)n.call(a,A)&&c.push(o?A.slice(1):A);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(a)):c},s.prototype.listeners=function(a,A){var c=o?o+a:a,l=this._events[c];if(A)return!!l;if(!l)return[];if(l.fn)return[l.fn];for(var u=0,g=l.length,h=new Array(g);u<g;u++)h[u]=l[u].fn;return h},s.prototype.emit=function(a,A,c,l,u,g){var h=o?o+a:a;if(!this._events[h])return!1;var d,p,m=this._events[h],_=arguments.length;if(m.fn){switch(m.once&&this.removeListener(a,m.fn,void 0,!0),_){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,A),!0;case 3:return m.fn.call(m.context,A,c),!0;case 4:return m.fn.call(m.context,A,c,l),!0;case 5:return m.fn.call(m.context,A,c,l,u),!0;case 6:return m.fn.call(m.context,A,c,l,u,g),!0}for(p=1,d=new Array(_-1);p<_;p++)d[p-1]=arguments[p];m.fn.apply(m.context,d)}else{var f,I=m.length;for(p=0;p<I;p++)switch(m[p].once&&this.removeListener(a,m[p].fn,void 0,!0),_){case 1:m[p].fn.call(m[p].context);break;case 2:m[p].fn.call(m[p].context,A);break;case 3:m[p].fn.call(m[p].context,A,c);break;case 4:m[p].fn.call(m[p].context,A,c,l);break;default:if(!d)for(f=1,d=new Array(_-1);f<_;f++)d[f-1]=arguments[f];m[p].fn.apply(m[p].context,d)}}return!0},s.prototype.on=function(a,A,c){var l=new r(A,c||this),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.once=function(a,A,c){var l=new r(A,c||this,!0),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.removeListener=function(a,A,c,l){var u=o?o+a:a;if(!this._events[u])return this;if(!A)return--this._eventsCount===0?this._events=new i:delete this._events[u],this;var g=this._events[u];if(g.fn)g.fn!==A||l&&!g.once||c&&g.context!==c||(--this._eventsCount===0?this._events=new i:delete this._events[u]);else{for(var h=0,d=[],p=g.length;h<p;h++)(g[h].fn!==A||l&&!g[h].once||c&&g[h].context!==c)&&d.push(g[h]);d.length?this._events[u]=d.length===1?d[0]:d:--this._eventsCount===0?this._events=new i:delete this._events[u]}return this},s.prototype.removeAllListeners=function(a){var A;return a?(A=o?o+a:a,this._events[A]&&(--this._eventsCount===0?this._events=new i:delete this._events[A])):(this._events=new i,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prototype.setMaxListeners=function(){return this},s.prefixed=o,s.EventEmitter=s,e!==void 0&&(e.exports=s)}}),heo=YD({"node_modules/xml-lexer/dist/lexer.js"(t,e){function n(c,l,u){return l in c?Object.defineProperty(c,l,{value:u,enumerable:!0,configurable:!0,writable:!0}):c[l]=u,c}var o=_1t(),i=function(){},r={data:"state-data",cdata:"state-cdata",tagBegin:"state-tag-begin",tagName:"state-tag-name",tagEnd:"state-tag-end",attributeNameStart:"state-attribute-name-start",attributeName:"state-attribute-name",attributeNameEnd:"state-attribute-name-end",attributeValueBegin:"state-attribute-value-begin",attributeValue:"state-attribute-value"},s={lt:"action-lt",gt:"action-gt",space:"action-space",equal:"action-equal",quote:"action-quote",slash:"action-slash",char:"action-char",error:"action-error"},a={text:"text",openTag:"open-tag",closeTag:"close-tag",attributeName:"attribute-name",attributeValue:"attribute-value"},A={" ":s.space,"	":s.space,"\n":s.space,"\r":s.space,"<":s.lt,">":s.gt,'"':s.quote,"'":s.quote,"=":s.equal,"/":s.slash};e.exports={State:r,Action:s,Type:a,create:function(c){var l,u,g,h,d,p,m,_,f,I;c=Object.assign({debug:!1},c);var C=new o,y=r.data,x="",E="",B="",S="",Q="",w="",M=function(R,F){if(E[0]!=="?"&&E[0]!=="!"){var O={type:R,value:F};c.debug&&console.log("emit:",O),C.emit("data",O)}};C.stateMachine=(n(I={},r.data,(n(l={},s.lt,function(){x.trim()&&M(a.text,x),E="",Q=!1,y=r.tagBegin}),n(l,s.char,function(R){x+=R}),l)),n(I,r.cdata,n({},s.char,function(R){(x+=R).substr(-3)==="]]>"&&(M(a.text,x.slice(0,-3)),x="",y=r.data)})),n(I,r.tagBegin,(n(u={},s.space,i),n(u,s.char,function(R){E=R,y=r.tagName}),n(u,s.slash,function(){E="",Q=!0}),u)),n(I,r.tagName,(n(g={},s.space,function(){Q?y=r.tagEnd:(y=r.attributeNameStart,M(a.openTag,E))}),n(g,s.gt,function(){M(Q?a.closeTag:a.openTag,E),x="",y=r.data}),n(g,s.slash,function(){y=r.tagEnd,M(a.openTag,E)}),n(g,s.char,function(R){(E+=R)==="![CDATA["&&(y=r.cdata,x="",E="")}),g)),n(I,r.tagEnd,(n(h={},s.gt,function(){M(a.closeTag,E),x="",y=r.data}),n(h,s.char,i),h)),n(I,r.attributeNameStart,(n(d={},s.char,function(R){B=R,y=r.attributeName}),n(d,s.gt,function(){x="",y=r.data}),n(d,s.space,i),n(d,s.slash,function(){Q=!0,y=r.tagEnd}),d)),n(I,r.attributeName,(n(p={},s.space,function(){y=r.attributeNameEnd}),n(p,s.equal,function(){M(a.attributeName,B),y=r.attributeValueBegin}),n(p,s.gt,function(){S="",M(a.attributeName,B),M(a.attributeValue,S),x="",y=r.data}),n(p,s.slash,function(){Q=!0,S="",M(a.attributeName,B),M(a.attributeValue,S),y=r.tagEnd}),n(p,s.char,function(R){B+=R}),p)),n(I,r.attributeNameEnd,(n(m={},s.space,i),n(m,s.equal,function(){M(a.attributeName,B),y=r.attributeValueBegin}),n(m,s.gt,function(){S="",M(a.attributeName,B),M(a.attributeValue,S),x="",y=r.data}),n(m,s.char,function(R){S="",M(a.attributeName,B),M(a.attributeValue,S),B=R,y=r.attributeName}),m)),n(I,r.attributeValueBegin,(n(_={},s.space,i),n(_,s.quote,function(R){w=R,S="",y=r.attributeValue}),n(_,s.gt,function(){M(a.attributeValue,S=""),x="",y=r.data}),n(_,s.char,function(R){w="",S=R,y=r.attributeValue}),_)),n(I,r.attributeValue,(n(f={},s.space,function(R){w?S+=R:(M(a.attributeValue,S),y=r.attributeNameStart)}),n(f,s.quote,function(R){w===R?(M(a.attributeValue,S),y=r.attributeNameStart):S+=R}),n(f,s.gt,function(R){w?S+=R:(M(a.attributeValue,S),x="",y=r.data)}),n(f,s.slash,function(R){w?S+=R:(M(a.attributeValue,S),Q=!0,y=r.tagEnd)}),n(f,s.char,function(R){S+=R}),f)),I);var k=function(R){c.debug&&console.log(y,R);var F=C.stateMachine[y],O=F[(function(U){return A[U]||s.char})(R)]||F[s.error]||F[s.char];O(R)};return C.write=function(R){for(var F=R.length,O=0;O<F;O++)k(R[O])},C}}}}),peo=YD({"node_modules/xml-reader/dist/reader.js"(t,e){var n=_1t(),o=heo(),i=o.Type,r={element:"element",text:"text"},s=function(A){return Object.assign({name:"",type:r.element,value:"",parent:null,attributes:{},children:[]},A)},a=function(A){A=Object.assign({stream:!1,parentNodes:!0,doneEvent:"done",tagPrefix:"tag:",emitTopLevelOnly:!1,debug:!1},A);var c=void 0,l=void 0,u=void 0,g=void 0,h=new n,d=function(p){switch(p.type){case i.openTag:if(u===null)(u=l).name=p.value;else{var m=s({name:p.value,parent:u});u.children.push(m),u=m}break;case i.closeTag:var _=u.parent;if(A.parentNodes||(u.parent=null),u.name!==p.value)break;A.stream&&_===l&&(l.children=[],u.parent=null),A.emitTopLevelOnly&&_!==l||(h.emit(A.tagPrefix+u.name,u),h.emit("tag",u.name,u)),u===l&&(c.removeAllListeners("data"),h.emit(A.doneEvent,u),l=null),u=_;break;case i.text:u&&u.children.push(s({type:r.text,value:p.value,parent:A.parentNodes?u:null}));break;case i.attributeName:g=p.value,u.attributes[g]="";break;case i.attributeValue:u.attributes[g]=p.value}};return h.reset=function(){(c=o.create({debug:A.debug})).on("data",d),l=s(),u=null,g="",h.parse=c.write},h.reset(),h};e.exports={parseSync:function(A,c){c=Object.assign({},c,{stream:!1,tagPrefix:":"});var l=a(c),u=void 0;return l.on("done",function(g){u=g}),l.parse(A),u},create:a,NodeType:r}}}),meo=(m1t(deo()),m1t(peo()),class{MAX_ITERATIONS=1e5;solved=!1;failed=!1;iterations=0;progress=0;error=null;activeSubSolver;failedSubSolvers;timeToSolve;stats={};_setupDone=!1;setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(t){throw this.error=`${this.constructor.name} error: ${t}`,this.failed=!0,t}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.constructor.name} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){const t=Date.now();for(;!this.solved&&!this.failed;)this.step();const e=Date.now();this.timeToSolve=e-t}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}}),l6e=t=>t?`hsl(${(e=>{let n=0;for(let o=0;o<e.length;o++)n=779*e.charCodeAt(o)+((n<<5)-n);return n})(t)%360}, 100%, 50%)`:"rgba(0, 0, 0, 0.5)",_eo=t=>[[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY}],[{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY}],[{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}],[{x:t.minX,y:t.maxY},{x:t.minX,y:t.minY}]];function f1t(t,e){const{minX:n,maxX:o,minY:i,maxY:r}=e,s=o-n,a=r-i,A=1e-6;return Math.abs(t.y-r)<A?t.x-n:Math.abs(t.x-o)<A?s+(r-t.y):Math.abs(t.y-i)<A?s+a+(o-t.x):Math.abs(t.x-n)<A?2*s+a+(t.y-i):0}function I1t(t,e){const{minX:n,maxX:o,minY:i,maxY:r}=e,s=1e-6,a=Math.abs(t.y-r)<s,A=Math.abs(t.y-i)<s,c=Math.abs(t.x-o)<s,l=Math.abs(t.x-n)<s;if(a&&c)return{x:-Math.SQRT1_2,y:-Math.SQRT1_2};if(a&&l)return{x:Math.SQRT1_2,y:-Math.SQRT1_2};if(A&&c)return{x:-Math.SQRT1_2,y:Math.SQRT1_2};if(A&&l)return{x:Math.SQRT1_2,y:Math.SQRT1_2};if(a)return{x:0,y:-1};if(A)return{x:0,y:1};if(c)return{x:-1,y:0};if(l)return{x:1,y:0};const u=(i+r)/2,g=(n+o)/2-t.x,h=u-t.y,d=Math.hypot(g,h);return d>0?{x:g/d,y:h/d}:{x:0,y:-1}}function Bae(t,e,n,o,i,r,s,a,A,c){for(let l=0;l<=c;l++){const u=l/c,g=1-u,h=g*g,d=h*g,p=u*u,m=p*u,_=2*l;A[_]=d*t+3*h*u*n+3*g*p*i+m*s,A[_+1]=d*e+3*h*u*o+3*g*p*r+m*a}}function feo(t,e,n,o,i){const r=[];for(let s=0;s<=i;s++){const a=s/i,A=1-a,c=A*A,l=c*A,u=a*a,g=u*a;r.push({x:l*t.x+3*c*a*e.x+3*A*u*n.x+g*o.x,y:l*t.y+3*c*a*e.y+3*A*u*n.y+g*o.y})}return r}function bae(t,e,n,o,i,r){const s=i-n,a=r-o,A=s*s+a*a;if(A===0){const g=t-n,h=e-o;return g*g+h*h}const c=Math.max(0,Math.min(1,((t-n)*s+(e-o)*a)/A)),l=t-(n+c*s),u=e-(o+c*a);return l*l+u*u}function Sae(t,e,n,o,i,r,s,a){const A=(s-i)*(e-r)-(a-r)*(t-i),c=(s-i)*(o-r)-(a-r)*(n-i),l=(n-t)*(r-e)-(o-e)*(i-t),u=(n-t)*(a-e)-(o-e)*(s-t);return(A>0&&c<0||A<0&&c>0)&&(l>0&&u<0||l<0&&u>0)?0:Math.min(bae(t,e,i,r,s,a),bae(n,o,i,r,s,a),bae(i,r,t,e,n,o),bae(s,a,t,e,n,o))}function Ieo(t,e,n,o,i,r,s,a){const A=(s-i)*(e-r)-(a-r)*(t-i),c=(s-i)*(o-r)-(a-r)*(n-i),l=(n-t)*(r-e)-(o-e)*(i-t),u=(n-t)*(a-e)-(o-e)*(s-t);return(A>0&&c<0||A<0&&c>0)&&(l>0&&u<0||l<0&&u>0)}function Ceo(t,e,n,o,i){const r=g=>(g%i+i)%i,s=r(t),a=r(e),A=r(n),c=r(o),[l,u]=s<a?[s,a]:[a,s];return A>l&&A<u&&c>l&&c<u}function C1t(t,e){let n=1/0,o=-1/0,i=1/0,r=-1/0;for(let s=0;s<e;s++){const a=t[2*s],A=t[2*s+1];a<n&&(n=a),a>o&&(o=a),A<i&&(i=A),A>r&&(r=A)}return{minX:n,maxX:o,minY:i,maxY:r}}var y1t=class extends meo{constructor(e){super(),this.problem=e;for(const n of this.problem.obstacles)n.outerSegments=_eo(n);this.precomputeObstacles()}outputTraces=[];traces=[];optimizationStep=0;maxOptimizationSteps=100;sampledPoints=[];traceBounds=[];obstacleSegments=new Float64Array(0);obstacleNetworkIds=[];numObstacleSegments=0;collisionPairs=[];lastCost=1/0;stagnantSteps=0;effectiveTraceToTraceSpacing=0;getConstructorParams(){return this.problem}precomputeObstacles(){const{obstacles:e}=this.problem;let n=0;for(const i of e)i.outerSegments&&(n+=i.outerSegments.length);this.obstacleSegments=new Float64Array(4*n),this.obstacleNetworkIds=[],this.numObstacleSegments=n;let o=0;for(const i of e)if(i.outerSegments)for(const r of i.outerSegments)this.obstacleSegments[o++]=r[0].x,this.obstacleSegments[o++]=r[0].y,this.obstacleSegments[o++]=r[1].x,this.obstacleSegments[o++]=r[1].y,this.obstacleNetworkIds.push(i.networkId)}initializeTraces(){const{bounds:e,waypointPairs:n}=this.problem,{minX:o,maxX:i,minY:r,maxY:s}=e,a=i-o,A=s-r,c=2*a+2*A,l=(function(m){return{x:(m.minX+m.maxX)/2,y:(m.minY+m.maxY)/2}})(e),u=n.map((m,_)=>({pair:m,t1:f1t(m.start,e),t2:f1t(m.end,e),idx:_})),g=u.map(()=>[]),h=u.map(()=>[]);for(const m of u)for(const _ of u)if(m.idx!==_.idx){if(m.pair.networkId&&_.pair.networkId&&m.pair.networkId===_.pair.networkId)continue;Ceo(_.t1,_.t2,m.t1,m.t2,c)&&(g[m.idx].push(_.idx),h[_.idx].push(m.idx))}const d=g.map(m=>m.length),p=Math.max(...d,1);this.traces=u.map(({pair:m,t1:_,t2:f,idx:I})=>{const C=I1t(m.start,e),y=I1t(m.end,e),x=Math.hypot(m.end.x-m.start.x,m.end.y-m.start.y),E=d[I]/p,B=(m.start.x+m.end.x)/2,S=(m.start.y+m.end.y)/2,Q=x*(.25+.15*(1-Math.hypot(B-l.x,S-l.y)/Math.hypot(a/2,A/2)))*(1-.3*E),w=.05*Math.min(a,A),M=Math.max(w,Q),k=Math.max(w,Q);return{waypointPair:m,ctrl1:{x:m.start.x+M*C.x,y:m.start.y+M*C.y},ctrl2:{x:m.end.x+k*y.x,y:m.end.y+k*y.y},networkId:m.networkId,t1:_,t2:f,perpDir1:C,perpDir2:y,d1:M,d2:k,containedBy:g[I],contains:h[I]}}),this.sampledPoints=this.traces.map(()=>new Float64Array(12)),this.traceBounds=this.traces.map(()=>({minX:0,maxX:0,minY:0,maxY:0})),this.updateSampledTraces(),this.updateCollisionPairs()}updateSampledTraces(){for(let e=0;e<this.traces.length;e++){const n=this.traces[e];Bae(n.waypointPair.start.x,n.waypointPair.start.y,n.ctrl1.x,n.ctrl1.y,n.ctrl2.x,n.ctrl2.y,n.waypointPair.end.x,n.waypointPair.end.y,this.sampledPoints[e],5),this.traceBounds[e]=C1t(this.sampledPoints[e],6)}}updateSingleTraceSample(e){const n=this.traces[e];Bae(n.waypointPair.start.x,n.waypointPair.start.y,n.ctrl1.x,n.ctrl1.y,n.ctrl2.x,n.ctrl2.y,n.waypointPair.end.x,n.waypointPair.end.y,this.sampledPoints[e],5),this.traceBounds[e]=C1t(this.sampledPoints[e],6)}updateControlPointsFromDistances(e){const n=this.traces[e],{minX:o,maxX:i,minY:r,maxY:s}=this.problem.bounds,a=1e-6;let A=n.waypointPair.start.x+n.d1*n.perpDir1.x,c=n.waypointPair.start.y+n.d1*n.perpDir1.y,l=n.waypointPair.end.x+n.d2*n.perpDir2.x,u=n.waypointPair.end.y+n.d2*n.perpDir2.y;const g=n.waypointPair.start;Math.abs(g.x-o)<a&&(A=Math.max(A,o)),Math.abs(g.x-i)<a&&(A=Math.min(A,i)),Math.abs(g.y-r)<a&&(c=Math.max(c,r)),Math.abs(g.y-s)<a&&(c=Math.min(c,s));const h=n.waypointPair.end;Math.abs(h.x-o)<a&&(l=Math.max(l,o)),Math.abs(h.x-i)<a&&(l=Math.min(l,i)),Math.abs(h.y-r)<a&&(u=Math.max(u,r)),Math.abs(h.y-s)<a&&(u=Math.min(u,s)),A=Math.max(o,Math.min(i,A)),c=Math.max(r,Math.min(s,c)),l=Math.max(o,Math.min(i,l)),u=Math.max(r,Math.min(s,u)),n.ctrl1.x=A,n.ctrl1.y=c,n.ctrl2.x=l,n.ctrl2.y=u}updateCollisionPairs(){const e=this.effectiveTraceToTraceSpacing;this.collisionPairs=[];for(let n=0;n<this.traces.length;n++)for(let o=n+1;o<this.traces.length;o++){const i=this.traces[n],r=this.traces[o];if(i.networkId&&r.networkId&&i.networkId===r.networkId)continue;const s=this.traceBounds[n],a=this.traceBounds[o];s.maxX+e>=a.minX&&a.maxX+e>=s.minX&&s.maxY+e>=a.minY&&a.maxY+e>=s.minY&&this.collisionPairs.push([n,o])}}computeTotalCost(){const{preferredObstacleToTraceSpacing:e}=this.problem,n=this.effectiveTraceToTraceSpacing,o=n**2,i=e**2;let r=0;for(const[s,a]of this.collisionPairs){const A=this.sampledPoints[s],c=this.sampledPoints[a];for(let l=0;l<5;l++){const u=A[2*l],g=A[2*l+1],h=A[2*(l+1)],d=A[2*(l+1)+1];for(let p=0;p<5;p++){const m=Sae(u,g,h,d,c[2*p],c[2*p+1],c[2*(p+1)],c[2*(p+1)+1]);m<o&&(r+=(n-Math.sqrt(m))**2,m<1e-18&&(r+=20*o))}}}for(let s=0;s<this.traces.length;s++){const a=this.traces[s],A=this.sampledPoints[s],c=this.traceBounds[s];for(let l=0;l<this.numObstacleSegments;l++){if(a.networkId&&this.obstacleNetworkIds[l]&&a.networkId===this.obstacleNetworkIds[l])continue;const u=4*l,g=this.obstacleSegments[u],h=this.obstacleSegments[u+1],d=this.obstacleSegments[u+2],p=this.obstacleSegments[u+3],m=Math.min(g,d),_=Math.max(g,d),f=Math.min(h,p),I=Math.max(h,p);if(!(c.maxX+e<m||_+e<c.minX||c.maxY+e<f||I+e<c.minY))for(let C=0;C<5;C++){const y=Sae(A[2*C],A[2*C+1],A[2*(C+1)],A[2*(C+1)+1],g,h,d,p);y<i&&(r+=(e-Math.sqrt(y))**2,y<1e-18&&(r+=20*i))}}}return r}computeCostForTrace(e){const{preferredObstacleToTraceSpacing:n}=this.problem,o=this.effectiveTraceToTraceSpacing,i=o**2,r=n**2,s=this.traces[e],a=this.sampledPoints[e],A=this.traceBounds[e];let c=0;for(let l=0;l<this.traces.length;l++){if(l===e)continue;const u=this.traces[l];if(s.networkId&&u.networkId&&s.networkId===u.networkId)continue;const g=this.traceBounds[l];if(A.maxX+o<g.minX||g.maxX+o<A.minX||A.maxY+o<g.minY||g.maxY+o<A.minY)continue;const h=this.sampledPoints[l];for(let d=0;d<5;d++){const p=a[2*d],m=a[2*d+1],_=a[2*(d+1)],f=a[2*(d+1)+1];for(let I=0;I<5;I++){const C=Sae(p,m,_,f,h[2*I],h[2*I+1],h[2*(I+1)],h[2*(I+1)+1]);C<i&&(c+=(o-Math.sqrt(C))**2,C<1e-18&&(c+=20*i))}}}for(let l=0;l<this.numObstacleSegments;l++){if(s.networkId&&this.obstacleNetworkIds[l]&&s.networkId===this.obstacleNetworkIds[l])continue;const u=4*l,g=this.obstacleSegments[u],h=this.obstacleSegments[u+1],d=this.obstacleSegments[u+2],p=this.obstacleSegments[u+3],m=Math.min(g,d),_=Math.max(g,d),f=Math.min(h,p),I=Math.max(h,p);if(!(A.maxX+n<m||_+n<A.minX||A.maxY+n<f||I+n<A.minY))for(let C=0;C<5;C++){const y=Sae(a[2*C],a[2*C+1],a[2*(C+1)],a[2*(C+1)+1],g,h,d,p);y<r&&(c+=(n-Math.sqrt(y))**2,y<1e-18&&(c+=20*r))}}return c}tracesIntersect(e,n){const o=this.traces[e],i=this.traces[n],r=15,s=new Float64Array(32),a=new Float64Array(32);Bae(o.waypointPair.start.x,o.waypointPair.start.y,o.ctrl1.x,o.ctrl1.y,o.ctrl2.x,o.ctrl2.y,o.waypointPair.end.x,o.waypointPair.end.y,s,r),Bae(i.waypointPair.start.x,i.waypointPair.start.y,i.ctrl1.x,i.ctrl1.y,i.ctrl2.x,i.ctrl2.y,i.waypointPair.end.x,i.waypointPair.end.y,a,r);for(let A=0;A<r;A++){const c=s[2*A],l=s[2*A+1],u=s[2*(A+1)],g=s[2*(A+1)+1];for(let h=0;h<r;h++)if(Ieo(c,l,u,g,a[2*h],a[2*h+1],a[2*(h+1)],a[2*(h+1)+1]))return!0}return!1}findIntersectingPairs(){const e=[];for(let n=0;n<this.traces.length;n++)for(let o=n+1;o<this.traces.length;o++){const i=this.traces[n],r=this.traces[o];if(i.networkId&&r.networkId&&i.networkId===r.networkId)continue;const s=this.traceBounds[n],a=this.traceBounds[o];s.maxX<a.minX||a.maxX<s.minX||s.maxY<a.minY||a.maxY<s.minY||this.tracesIntersect(n,o)&&e.push([n,o])}return e}resolveIntersections(){const{bounds:e,preferredTraceToTraceSpacing:n}=this.problem,{minX:o,maxX:i,minY:r,maxY:s}=e,a=Math.min(i-o,s-r),A=.02*a,c=1.5*a,l=this.findIntersectingPairs();if(l.length===0)return 0;let u=0;for(const[g,h]of l){const d=this.traces[g],p=this.traces[h];if(!this.tracesIntersect(g,h))continue;let m,_;d.containedBy.includes(h)?(m=h,_=g):p.containedBy.includes(g)||(d.d1+d.d2)/2<(p.d1+p.d2)/2?(m=g,_=h):(m=h,_=g);const f=this.traces[m],I=this.traces[_],C=f.d1,y=f.d2,x=I.d1,E=I.d2,B=2*n,S=[{innerMult:1,outerMult:0},{innerMult:0,outerMult:1},{innerMult:.5,outerMult:.5},{innerMult:2,outerMult:0},{innerMult:1,outerMult:1},{innerMult:3,outerMult:0},{innerMult:2,outerMult:1},{innerMult:4,outerMult:0}];let Q=this.computeTotalCost(),w=null;for(const M of S)if(f.d1=C,f.d2=y,I.d1=x,I.d2=E,I.d1=Math.min(c,x+B*M.innerMult),I.d2=Math.min(c,E+B*M.innerMult),f.d1=Math.max(A,C-B*M.outerMult),f.d2=Math.max(A,y-B*M.outerMult),this.updateControlPointsFromDistances(_),this.updateControlPointsFromDistances(m),this.updateSingleTraceSample(_),this.updateSingleTraceSample(m),!this.tracesIntersect(m,_)){const k=this.computeTotalCost();(w===null||k<Q)&&(Q=k,w=M)}w?(I.d1=Math.min(c,x+B*w.innerMult),I.d2=Math.min(c,E+B*w.innerMult),f.d1=Math.max(A,C-B*w.outerMult),f.d2=Math.max(A,y-B*w.outerMult),this.updateControlPointsFromDistances(_),this.updateControlPointsFromDistances(m),this.updateSingleTraceSample(_),this.updateSingleTraceSample(m),u++):(f.d1=C,f.d2=y,I.d1=x,I.d2=E,this.updateControlPointsFromDistances(m),this.updateControlPointsFromDistances(_),this.updateSingleTraceSample(m),this.updateSingleTraceSample(_))}return u}optimizeStep(){const{bounds:e}=this.problem,{minX:n,maxX:o,minY:i,maxY:r}=e,s=Math.min(o-n,r-i),a=this.effectiveTraceToTraceSpacing,A=4*(1-this.optimizationStep/this.maxOptimizationSteps)+.5,c=.02*s,l=1.5*s,u=[];for(let g=0;g<this.traces.length;g++)u.push({idx:g,cost:this.computeCostForTrace(g)});u.sort((g,h)=>h.cost-g.cost);for(const{idx:g,cost:h}of u){if(h===0)continue;const d=this.traces[g],p=h>100?2:1,m=[A*p,1.5*A*p,.5*A];for(const _ of m){const f=h>100?[_,-_,2*_,2*-_,3*_,3*-_,2*a,2*-a]:[_,-_,2*_,2*-_];let I=this.computeCostForTrace(g),C=d.d1,y=d.d2;const x=d.d1,E=d.d2;for(const B of f){d.d1=Math.max(c,Math.min(l,x+B)),this.updateControlPointsFromDistances(g),this.updateSingleTraceSample(g);const S=this.computeCostForTrace(g);S<I&&(I=S,C=d.d1,y=E),d.d1=x,this.updateControlPointsFromDistances(g),d.d2=Math.max(c,Math.min(l,E+B)),this.updateControlPointsFromDistances(g),this.updateSingleTraceSample(g);const Q=this.computeCostForTrace(g);Q<I&&(I=Q,C=x,y=d.d2),d.d2=E,this.updateControlPointsFromDistances(g),d.d1=Math.max(c,Math.min(l,x+B)),d.d2=Math.max(c,Math.min(l,E+B)),this.updateControlPointsFromDistances(g),this.updateSingleTraceSample(g);const w=this.computeCostForTrace(g);w<I&&(I=w,C=d.d1,y=d.d2),d.d1=x,d.d2=E,this.updateControlPointsFromDistances(g),d.d1=Math.max(c,Math.min(l,x+B)),d.d2=Math.max(c,Math.min(l,E-B)),this.updateControlPointsFromDistances(g),this.updateSingleTraceSample(g);const M=this.computeCostForTrace(g);M<I&&(I=M,C=d.d1,y=d.d2),d.d1=x,d.d2=E,this.updateControlPointsFromDistances(g)}if(d.d1=C,d.d2=y,this.updateControlPointsFromDistances(g),this.updateSingleTraceSample(g),I<.9*h)break}}this.optimizationStep%10==0&&this.updateCollisionPairs()}buildOutputTraces(){this.outputTraces=this.traces.map(e=>({waypointPair:e.waypointPair,points:feo(e.waypointPair.start,e.ctrl1,e.ctrl2,e.waypointPair.end,20),networkId:e.networkId}))}_step(){if(this.traces.length===0&&(this.effectiveTraceToTraceSpacing=3*this.problem.preferredTraceToTraceSpacing,this.initializeTraces(),this.lastCost=this.computeTotalCost(),this.stagnantSteps=0),this.optimizationStep<this.maxOptimizationSteps){const n=3+-2*(this.optimizationStep/this.maxOptimizationSteps);this.effectiveTraceToTraceSpacing=this.problem.preferredTraceToTraceSpacing*n,this.optimizeStep(),this.optimizationStep++,this.optimizationStep%10==0&&this.resolveIntersections()>0&&this.updateCollisionPairs();const o=this.computeTotalCost();o===0?this.optimizationStep=this.maxOptimizationSteps:o>=.99*this.lastCost?(this.stagnantSteps++,this.stagnantSteps>10&&(this.resolveIntersections()>0?(this.updateCollisionPairs(),this.stagnantSteps=0):this.stagnantSteps>15&&(this.optimizationStep=this.maxOptimizationSteps))):this.stagnantSteps=0,this.lastCost=o}this.optimizationStep>=this.maxOptimizationSteps&&(this.resolveIntersections(),this.buildOutputTraces(),this.solved=!0)}visualize(){return this.traces.length>0&&this.buildOutputTraces(),((e,n=[])=>{const o={arrows:[],circles:[],lines:[],rects:[],coordinateSystem:"cartesian",points:[],texts:[],title:"Curvy Trace Problem"};o.lines.push({points:[{x:e.bounds.minX,y:e.bounds.minY},{x:e.bounds.maxX,y:e.bounds.minY},{x:e.bounds.maxX,y:e.bounds.maxY},{x:e.bounds.minX,y:e.bounds.maxY},{x:e.bounds.minX,y:e.bounds.minY}],strokeColor:"rgba(0, 0, 0, 0.1)"});for(const i of e.waypointPairs)o.points.push({...i.start,label:`start ${i.networkId??""}`,color:l6e(i.networkId)}),o.points.push({...i.end,label:`end ${i.networkId??""}`,color:l6e(i.networkId)});for(const i of e.obstacles)o.rects.push({center:i.center,width:i.maxX-i.minX,height:i.maxY-i.minY,fill:"rgba(128, 128, 128, 0.3)",stroke:"rgba(128, 128, 128, 0.8)",label:`netId: ${i.networkId}`});for(const i of n)o.lines.push({points:i.points,strokeColor:l6e(i.networkId)});return o})(this.problem,this.outputTraces)}},x1t=class extends yr{getSolverName(){return"CurvyIntraNodeSolver"}nodeWithPortPoints;colorMap;traceWidth;viaDiameter;adjacentObstacles;routes=[];curvyTraceSolver;phase="initializing";constructor(e){super(),this.nodeWithPortPoints=e.nodeWithPortPoints,this.colorMap=e.colorMap??{},this.traceWidth=e.traceWidth??.15,this.viaDiameter=e.viaDiameter??.3,this.adjacentObstacles=e.adjacentObstacles??[],this.MAX_ITERATIONS=1e3}_step(){switch(this.phase){case"initializing":this._initializeCurvySolver();break;case"solving":this._stepCurvySolver();break;case"done":this.solved=!0}}_initializeCurvySolver(){const e=this.nodeWithPortPoints,n={minX:e.center.x-e.width/2,minY:e.center.y-e.height/2,maxX:e.center.x+e.width/2,maxY:e.center.y+e.height/2},o=new Map;for(const s of e.portPoints)o.has(s.connectionName)||o.set(s.connectionName,[]),o.get(s.connectionName).push(s);const i=[];for(const[s,a]of o){if(a.length<2)continue;const A=a[0],c=a[a.length-1];i.push({start:{x:A.x,y:A.y},end:{x:c.x,y:c.y},networkId:s})}if(i.length===0)return void(this.phase="done");const r={bounds:n,waypointPairs:i,obstacles:this.adjacentObstacles.map(s=>({minX:s.minX,minY:s.minY,maxX:s.maxX,maxY:s.maxY,center:{x:(s.minX+s.maxX)/2,y:(s.minY+s.maxY)/2},networkId:s.networkId})),preferredTraceToTraceSpacing:2*this.traceWidth,preferredObstacleToTraceSpacing:2*this.traceWidth};this.curvyTraceSolver=new y1t(r),this.phase="solving"}_stepCurvySolver(){this.curvyTraceSolver?(this.activeSubSolver=this.curvyTraceSolver,this.curvyTraceSolver.step(),this.curvyTraceSolver.solved?(this._convertOutputTraces(),this.phase="done"):this.curvyTraceSolver.failed&&(this.error=this.curvyTraceSolver.error,this.failed=!0)):this.phase="done"}_convertOutputTraces(){if(!this.curvyTraceSolver)return;const e=this.nodeWithPortPoints,n=new Map;for(const o of e.portPoints){const i=o.connectionName;n.has(i)||n.set(i,{connectionName:o.connectionName,rootConnectionName:o.rootConnectionName,z:o.z})}for(const o of this.curvyTraceSolver.outputTraces){const i=o.networkId??"",r=n.get(i);if(!r)continue;const s={connectionName:r.connectionName,rootConnectionName:r.rootConnectionName,traceThickness:this.traceWidth,viaDiameter:this.viaDiameter,route:o.points.map(a=>({x:a.x,y:a.y,z:r.z})),vias:[]};this.routes.push(s)}}getConstructorParams(){return{nodeWithPortPoints:this.nodeWithPortPoints,colorMap:this.colorMap,traceWidth:this.traceWidth,viaDiameter:this.viaDiameter,adjacentObstacles:this.adjacentObstacles}}visualize(){const e={lines:[],points:[],rects:[],circles:[]},n=this.nodeWithPortPoints;e.rects.push({center:n.center,width:n.width,height:n.height,fill:"rgba(0, 200, 0, 0.1)",stroke:"rgba(0, 200, 0, 0.5)",label:n.capacityMeshNodeId});for(const o of this.adjacentObstacles)e.rects.push({center:{x:(o.minX+o.maxX)/2,y:(o.minY+o.maxY)/2},width:o.maxX-o.minX,height:o.maxY-o.minY,fill:"rgba(255, 0, 0, 0.1)",stroke:"rgba(255, 0, 0, 0.3)",label:`obstacle: ${o.networkId??""}`});if(this.curvyTraceSolver){const o=this.curvyTraceSolver.visualize();o.lines&&e.lines.push(...o.lines),o.points&&e.points.push(...o.points),o.rects&&e.rects.push(...o.rects),o.circles&&e.circles.push(...o.circles)}for(const o of this.routes){const i=this.colorMap[o.connectionName]??"gray";e.lines.push({points:o.route.map(r=>({x:r.x,y:r.y})),strokeColor:i,strokeWidth:this.traceWidth,label:o.connectionName})}for(const o of n.portPoints){const i=this.colorMap[o.connectionName]??"gray";e.points.push({x:o.x,y:o.y,color:i,label:o.connectionName})}return e}},yeo=Object.create,E1t=Object.defineProperty,xeo=Object.getOwnPropertyDescriptor,B1t=Object.getOwnPropertyNames,Eeo=Object.getPrototypeOf,Beo=Object.prototype.hasOwnProperty,j3=(t,e)=>function(){return e||(0,t[B1t(t)[0]])((e={exports:{}}).exports,e),e.exports},Qae=j3({"node_modules/binary-search-bounds/search-bounds.js"(t,e){function n(A,c,l,u,g){for(var h=g+1;u<=g;){var d=u+g>>>1,p=A[d];(l!==void 0?l(p,c):p-c)>=0?(h=d,g=d-1):u=d+1}return h}function o(A,c,l,u,g){for(var h=g+1;u<=g;){var d=u+g>>>1,p=A[d];(l!==void 0?l(p,c):p-c)>0?(h=d,g=d-1):u=d+1}return h}function i(A,c,l,u,g){for(var h=u-1;u<=g;){var d=u+g>>>1,p=A[d];(l!==void 0?l(p,c):p-c)<0?(h=d,u=d+1):g=d-1}return h}function r(A,c,l,u,g){for(var h=u-1;u<=g;){var d=u+g>>>1,p=A[d];(l!==void 0?l(p,c):p-c)<=0?(h=d,u=d+1):g=d-1}return h}function s(A,c,l,u,g){for(;u<=g;){var h=u+g>>>1,d=A[h],p=l!==void 0?l(d,c):d-c;if(p===0)return h;p<=0?u=h+1:g=h-1}return-1}function a(A,c,l,u,g,h){return typeof l=="function"?h(A,c,l,u===void 0?0:0|u,g===void 0?A.length-1:0|g):h(A,c,void 0,l===void 0?0:0|l,u===void 0?A.length-1:0|u)}e.exports={ge:function(A,c,l,u,g){return a(A,c,l,u,g,n)},gt:function(A,c,l,u,g){return a(A,c,l,u,g,o)},lt:function(A,c,l,u,g){return a(A,c,l,u,g,i)},le:function(A,c,l,u,g){return a(A,c,l,u,g,r)},eq:function(A,c,l,u,g){return a(A,c,l,u,g,s)}}}}),u6e=j3({"node_modules/two-product/two-product.js"(t,e){e.exports=function(o,i,r){var s=o*i,a=n*o,A=a-(a-o),c=o-A,l=n*i,u=l-(l-i),g=i-u,h=c*g-(s-A*u-c*u-A*g);return r?(r[0]=h,r[1]=s,r):[h,s]};var n=+(Math.pow(2,27)+1)}}),b1t=j3({"node_modules/robust-sum/robust-sum.js"(t,e){e.exports=function(n,o){var i=0|n.length,r=0|o.length;if(i===1&&r===1)return(function(B,S){var Q=B+S,w=Q-B,M=Q-w,k=S-w,R=B-M,F=R+k;return F?[F,Q]:[Q]})(n[0],o[0]);var s,a,A=new Array(i+r),c=0,l=0,u=0,g=Math.abs,h=n[l],d=g(h),p=o[u],m=g(p);d<m?(a=h,(l+=1)<i&&(d=g(h=n[l]))):(a=p,(u+=1)<r&&(m=g(p=o[u]))),l<i&&d<m||u>=r?(s=h,(l+=1)<i&&(d=g(h=n[l]))):(s=p,(u+=1)<r&&(m=g(p=o[u])));for(var _,f,I=s+a,C=I-s,y=a-C,x=y,E=I;l<i&&u<r;)d<m?(s=h,(l+=1)<i&&(d=g(h=n[l]))):(s=p,(u+=1)<r&&(m=g(p=o[u]))),(y=(a=x)-(C=(I=s+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_;for(;l<i;)(y=(a=x)-(C=(I=(s=h)+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_,(l+=1)<i&&(h=n[l]);for(;u<r;)(y=(a=x)-(C=(I=(s=p)+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_,(u+=1)<r&&(p=o[u]);return x&&(A[c++]=x),E&&(A[c++]=E),c||(A[c++]=0),A.length=c,A}}}),beo=j3({"node_modules/two-sum/two-sum.js"(t,e){e.exports=function(n,o,i){var r=n+o,s=r-n,a=o-s,A=n-(r-s);return i?(i[0]=A+a,i[1]=r,i):[A+a,r]}}}),S1t=j3({"node_modules/robust-scale/robust-scale.js"(t,e){var n=u6e(),o=beo();e.exports=function(i,r){var s=i.length;if(s===1){var a=n(i[0],r);return a[0]?a:[a[1]]}var A=new Array(2*s),c=[.1,.1],l=[.1,.1],u=0;n(i[0],r,c),c[0]&&(A[u++]=c[0]);for(var g=1;g<s;++g){n(i[g],r,l);var h=c[1];o(h,l[0],c),c[0]&&(A[u++]=c[0]);var d=l[1],p=c[1],m=d+p,_=p-(m-d);c[1]=m,_&&(A[u++]=_)}return c[1]&&(A[u++]=c[1]),u===0&&(A[u++]=0),A.length=u,A}}}),Q1t=j3({"node_modules/robust-subtract/robust-diff.js"(t,e){e.exports=function(n,o){var i=0|n.length,r=0|o.length;if(i===1&&r===1)return(function(B,S){var Q=B+S,w=Q-B,M=Q-w,k=S-w,R=B-M,F=R+k;return F?[F,Q]:[Q]})(n[0],-o[0]);var s,a,A=new Array(i+r),c=0,l=0,u=0,g=Math.abs,h=n[l],d=g(h),p=-o[u],m=g(p);d<m?(a=h,(l+=1)<i&&(d=g(h=n[l]))):(a=p,(u+=1)<r&&(m=g(p=-o[u]))),l<i&&d<m||u>=r?(s=h,(l+=1)<i&&(d=g(h=n[l]))):(s=p,(u+=1)<r&&(m=g(p=-o[u])));for(var _,f,I=s+a,C=I-s,y=a-C,x=y,E=I;l<i&&u<r;)d<m?(s=h,(l+=1)<i&&(d=g(h=n[l]))):(s=p,(u+=1)<r&&(m=g(p=-o[u]))),(y=(a=x)-(C=(I=s+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_;for(;l<i;)(y=(a=x)-(C=(I=(s=h)+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_,(l+=1)<i&&(h=n[l]);for(;u<r;)(y=(a=x)-(C=(I=(s=p)+a)-s))&&(A[c++]=y),x=E-((_=E+I)-(f=_-E))+(I-f),E=_,(u+=1)<r&&(p=-o[u]);return x&&(A[c++]=x),E&&(A[c++]=E),c||(A[c++]=0),A.length=c,A}}}),Seo=j3({"node_modules/robust-orientation/orientation.js"(t,e){var n=u6e(),o=b1t(),i=S1t(),r=Q1t();function s(p,m,_,f){return function(I,C,y){var x=p(p(m(C[1],y[0]),m(-y[1],C[0])),p(m(I[1],C[0]),m(-C[1],I[0]))),E=p(m(I[1],y[0]),m(-y[1],I[0])),B=f(x,E);return B[B.length-1]}}function a(p,m,_,f){return function(I,C,y,x){var E=p(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),C[2]),p(_(p(m(C[1],x[0]),m(-x[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),x[2]))),p(_(p(m(C[1],x[0]),m(-x[1],C[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),x[2])))),B=p(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),x[2]))),p(_(p(m(C[1],y[0]),m(-y[1],C[0])),I[2]),p(_(p(m(I[1],y[0]),m(-y[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),y[2])))),S=f(E,B);return S[S.length-1]}}function A(p,m,_,f){return function(I,C,y,x,E){var B=p(p(p(_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),y[2]),p(_(p(m(y[1],E[0]),m(-E[1],y[0])),-x[2]),_(p(m(y[1],x[0]),m(-x[1],y[0])),E[2]))),C[3]),p(_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),C[2]),p(_(p(m(C[1],E[0]),m(-E[1],C[0])),-x[2]),_(p(m(C[1],x[0]),m(-x[1],C[0])),E[2]))),-y[3]),_(p(_(p(m(y[1],E[0]),m(-E[1],y[0])),C[2]),p(_(p(m(C[1],E[0]),m(-E[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),E[2]))),x[3]))),p(_(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),C[2]),p(_(p(m(C[1],x[0]),m(-x[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),x[2]))),-E[3]),p(_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),C[2]),p(_(p(m(C[1],E[0]),m(-E[1],C[0])),-x[2]),_(p(m(C[1],x[0]),m(-x[1],C[0])),E[2]))),I[3]),_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-x[2]),_(p(m(I[1],x[0]),m(-x[1],I[0])),E[2]))),-C[3])))),p(p(_(p(_(p(m(C[1],E[0]),m(-E[1],C[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),E[2]))),x[3]),p(_(p(_(p(m(C[1],x[0]),m(-x[1],C[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),x[2]))),-E[3]),_(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),C[2]),p(_(p(m(C[1],x[0]),m(-x[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),x[2]))),I[3]))),p(_(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),x[2]))),-C[3]),p(_(p(_(p(m(C[1],x[0]),m(-x[1],C[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),x[2]))),y[3]),_(p(_(p(m(C[1],y[0]),m(-y[1],C[0])),I[2]),p(_(p(m(I[1],y[0]),m(-y[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),y[2]))),-x[3]))))),S=p(p(p(_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),y[2]),p(_(p(m(y[1],E[0]),m(-E[1],y[0])),-x[2]),_(p(m(y[1],x[0]),m(-x[1],y[0])),E[2]))),I[3]),_(p(_(p(m(x[1],E[0]),m(-E[1],x[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-x[2]),_(p(m(I[1],x[0]),m(-x[1],I[0])),E[2]))),-y[3])),p(_(p(_(p(m(y[1],E[0]),m(-E[1],y[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),E[2]))),x[3]),_(p(_(p(m(y[1],x[0]),m(-x[1],y[0])),I[2]),p(_(p(m(I[1],x[0]),m(-x[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),x[2]))),-E[3]))),p(p(_(p(_(p(m(y[1],E[0]),m(-E[1],y[0])),C[2]),p(_(p(m(C[1],E[0]),m(-E[1],C[0])),-y[2]),_(p(m(C[1],y[0]),m(-y[1],C[0])),E[2]))),I[3]),_(p(_(p(m(y[1],E[0]),m(-E[1],y[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-y[2]),_(p(m(I[1],y[0]),m(-y[1],I[0])),E[2]))),-C[3])),p(_(p(_(p(m(C[1],E[0]),m(-E[1],C[0])),I[2]),p(_(p(m(I[1],E[0]),m(-E[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),E[2]))),y[3]),_(p(_(p(m(C[1],y[0]),m(-y[1],C[0])),I[2]),p(_(p(m(I[1],y[0]),m(-y[1],I[0])),-C[2]),_(p(m(I[1],C[0]),m(-C[1],I[0])),y[2]))),-E[3])))),Q=f(B,S);return Q[Q.length-1]}}function c(p){return(p===3?s:p===4?a:A)(o,n,i,r)}var l=c(3),u=c(4),g=[function(){return 0},function(){return 0},function(p,m){return m[0]-p[0]},function(p,m,_){var f,I=(p[1]-_[1])*(m[0]-_[0]),C=(p[0]-_[0])*(m[1]-_[1]),y=I-C;if(I>0){if(C<=0)return y;f=I+C}else{if(!(I<0)||C>=0)return y;f=-(I+C)}var x=33306690738754716e-32*f;return y>=x||y<=-x?y:l(p,m,_)},function(p,m,_,f){var I=p[0]-f[0],C=m[0]-f[0],y=_[0]-f[0],x=p[1]-f[1],E=m[1]-f[1],B=_[1]-f[1],S=p[2]-f[2],Q=m[2]-f[2],w=_[2]-f[2],M=C*B,k=y*E,R=y*x,F=I*B,O=I*E,U=C*x,Y=S*(M-k)+Q*(R-F)+w*(O-U),W=7771561172376103e-31*((Math.abs(M)+Math.abs(k))*Math.abs(S)+(Math.abs(R)+Math.abs(F))*Math.abs(Q)+(Math.abs(O)+Math.abs(U))*Math.abs(w));return Y>W||-Y>W?Y:u(p,m,_,f)}];function h(p){var m=g[p.length];return m||(m=g[p.length]=c(p.length)),m.apply(void 0,p)}function d(p,m,_,f,I,C,y){return function(x,E,B,S,Q){switch(arguments.length){case 0:case 1:return 0;case 2:return f(x,E);case 3:return I(x,E,B);case 4:return C(x,E,B,S);case 5:return y(x,E,B,S,Q)}for(var w=new Array(arguments.length),M=0;M<arguments.length;++M)w[M]=arguments[M];return p(w)}}(function(){for(;g.length<=5;)g.push(c(g.length));e.exports=d.apply(void 0,[h].concat(g));for(var p=0;p<=5;++p)e.exports[p]=g[p]})()}}),Qeo=j3({"node_modules/cdt2d/lib/monotone.js"(t,e){var n=Qae(),o=Seo()[3];function i(g,h,d,p,m){this.a=g,this.b=h,this.idx=d,this.lowerIds=p,this.upperIds=m}function r(g,h,d,p){this.a=g,this.b=h,this.type=d,this.idx=p}function s(g,h){var d=g.a[0]-h.a[0]||g.a[1]-h.a[1]||g.type-h.type;return d||(g.type!==0&&(d=o(g.a,g.b,h.b))?d:g.idx-h.idx)}function a(g,h){return o(g.a,g.b,h)}function A(g,h,d,p,m){for(var _=n.lt(h,p,a),f=n.gt(h,p,a),I=_;I<f;++I){for(var C=h[I],y=C.lowerIds,x=y.length;x>1&&o(d[y[x-2]],d[y[x-1]],p)>0;)g.push([y[x-1],y[x-2],m]),x-=1;y.length=x,y.push(m);var E=C.upperIds;for(x=E.length;x>1&&o(d[E[x-2]],d[E[x-1]],p)<0;)g.push([E[x-2],E[x-1],m]),x-=1;E.length=x,E.push(m)}}function c(g,h){var d;return(d=g.a[0]<h.a[0]?o(g.a,g.b,h.a):o(h.b,h.a,g.a))?d:(d=h.b[0]<g.b[0]?o(g.a,g.b,h.b):o(h.b,h.a,g.b))||g.idx-h.idx}function l(g,h,d){var p=n.le(g,d,c),m=g[p],_=m.upperIds,f=_[_.length-1];m.upperIds=[f],g.splice(p+1,0,new i(d.a,d.b,d.idx,[f],_))}function u(g,h,d){var p=d.a;d.a=d.b,d.b=p;var m=n.eq(g,d,c),_=g[m];g[m-1].upperIds=_.upperIds,g.splice(m,1)}e.exports=function(g,h){for(var d=g.length,p=h.length,m=[],_=0;_<d;++_)m.push(new r(g[_],null,0,_));for(_=0;_<p;++_){var f=h[_],I=g[f[0]],C=g[f[1]];I[0]<C[0]?m.push(new r(I,C,2,_),new r(C,I,1,_)):I[0]>C[0]&&m.push(new r(C,I,2,_),new r(I,C,1,_))}m.sort(s);for(var y=m[0].a[0]-(1+Math.abs(m[0].a[0]))*Math.pow(2,-52),x=[new i([y,1],[y,0],-1,[],[])],E=[],B=(_=0,m.length);_<B;++_){var S=m[_],Q=S.type;Q===0?A(E,x,g,S.a,S.idx):Q===2?l(x,g,S):u(x,g,S)}return E}}}),veo=j3({"node_modules/cdt2d/lib/triangulation.js"(t,e){var n=Qae();function o(s,a){this.stars=s,this.edges=a}e.exports=function(s,a){for(var A=new Array(s),c=0;c<s;++c)A[c]=[];return new o(A,a)};var i=o.prototype;function r(s,a,A){for(var c=1,l=s.length;c<l;c+=2)if(s[c-1]===a&&s[c]===A)return s[c-1]=s[l-2],s[c]=s[l-1],void(s.length=l-2)}i.isConstraint=(function(){var s=[0,0];function a(A,c){return A[0]-c[0]||A[1]-c[1]}return function(A,c){return s[0]=Math.min(A,c),s[1]=Math.max(A,c),n.eq(this.edges,s,a)>=0}})(),i.removeTriangle=function(s,a,A){var c=this.stars;r(c[s],a,A),r(c[a],A,s),r(c[A],s,a)},i.addTriangle=function(s,a,A){var c=this.stars;c[s].push(a,A),c[a].push(A,s),c[A].push(s,a)},i.opposite=function(s,a){for(var A=this.stars[a],c=1,l=A.length;c<l;c+=2)if(A[c]===s)return A[c-1];return-1},i.flip=function(s,a){var A=this.opposite(s,a),c=this.opposite(a,s);this.removeTriangle(s,a,A),this.removeTriangle(a,s,c),this.addTriangle(s,c,A),this.addTriangle(a,A,c)},i.edges=function(){for(var s=this.stars,a=[],A=0,c=s.length;A<c;++A)for(var l=s[A],u=0,g=l.length;u<g;u+=2)a.push([l[u],l[u+1]]);return a},i.cells=function(){for(var s=this.stars,a=[],A=0,c=s.length;A<c;++A)for(var l=s[A],u=0,g=l.length;u<g;u+=2){var h=l[u],d=l[u+1];A<Math.min(h,d)&&a.push([A,h,d])}return a}}}),weo=j3({"node_modules/robust-in-sphere/in-sphere.js"(t,e){var n=u6e(),o=b1t(),i=Q1t(),r=S1t();function s(d){return(d===3?a:d===4?A:d===5?c:l)(o,i,n,r)}function a(d,p,m,_){return function(f,I,C){var y=m(f[0],f[0]),x=_(y,I[0]),E=_(y,C[0]),B=m(I[0],I[0]),S=_(B,f[0]),Q=_(B,C[0]),w=m(C[0],C[0]),M=_(w,f[0]),k=_(w,I[0]),R=d(p(k,Q),p(S,x)),F=p(M,E),O=p(R,F);return O[O.length-1]}}function A(d,p,m,_){return function(f,I,C,y){var x=d(m(f[0],f[0]),m(f[1],f[1])),E=_(x,I[0]),B=_(x,C[0]),S=_(x,y[0]),Q=d(m(I[0],I[0]),m(I[1],I[1])),w=_(Q,f[0]),M=_(Q,C[0]),k=_(Q,y[0]),R=d(m(C[0],C[0]),m(C[1],C[1])),F=_(R,f[0]),O=_(R,I[0]),U=_(R,y[0]),Y=d(m(y[0],y[0]),m(y[1],y[1])),W=_(Y,f[0]),te=_(Y,I[0]),j=_(Y,C[0]),J=d(d(_(p(j,U),I[1]),d(_(p(te,k),-C[1]),_(p(O,M),y[1]))),d(_(p(te,k),f[1]),d(_(p(W,S),-I[1]),_(p(w,E),y[1])))),oe=d(d(_(p(j,U),f[1]),d(_(p(W,S),-C[1]),_(p(F,B),y[1]))),d(_(p(O,M),f[1]),d(_(p(F,B),-I[1]),_(p(w,E),C[1])))),ie=p(J,oe);return ie[ie.length-1]}}function c(d,p,m,_){return function(f,I,C,y,x){var E=d(m(f[0],f[0]),d(m(f[1],f[1]),m(f[2],f[2]))),B=_(E,I[0]),S=_(E,C[0]),Q=_(E,y[0]),w=_(E,x[0]),M=d(m(I[0],I[0]),d(m(I[1],I[1]),m(I[2],I[2]))),k=_(M,f[0]),R=_(M,C[0]),F=_(M,y[0]),O=_(M,x[0]),U=d(m(C[0],C[0]),d(m(C[1],C[1]),m(C[2],C[2]))),Y=_(U,f[0]),W=_(U,I[0]),te=_(U,y[0]),j=_(U,x[0]),J=d(m(y[0],y[0]),d(m(y[1],y[1]),m(y[2],y[2]))),oe=_(J,f[0]),ie=_(J,I[0]),ne=_(J,C[0]),le=_(J,x[0]),ge=d(m(x[0],x[0]),d(m(x[1],x[1]),m(x[2],x[2]))),_e=_(ge,f[0]),ue=_(ge,I[0]),fe=_(ge,C[0]),pe=_(ge,y[0]),ye=d(d(d(_(d(_(p(pe,le),C[1]),d(_(p(fe,j),-y[1]),_(p(ne,te),x[1]))),I[2]),d(_(d(_(p(pe,le),I[1]),d(_(p(ue,O),-y[1]),_(p(ie,F),x[1]))),-C[2]),_(d(_(p(fe,j),I[1]),d(_(p(ue,O),-C[1]),_(p(W,R),x[1]))),y[2]))),d(_(d(_(p(ne,te),I[1]),d(_(p(ie,F),-C[1]),_(p(W,R),y[1]))),-x[2]),d(_(d(_(p(pe,le),I[1]),d(_(p(ue,O),-y[1]),_(p(ie,F),x[1]))),f[2]),_(d(_(p(pe,le),f[1]),d(_(p(_e,w),-y[1]),_(p(oe,Q),x[1]))),-I[2])))),d(d(_(d(_(p(ue,O),f[1]),d(_(p(_e,w),-I[1]),_(p(k,B),x[1]))),y[2]),d(_(d(_(p(ie,F),f[1]),d(_(p(oe,Q),-I[1]),_(p(k,B),y[1]))),-x[2]),_(d(_(p(ne,te),I[1]),d(_(p(ie,F),-C[1]),_(p(W,R),y[1]))),f[2]))),d(_(d(_(p(ne,te),f[1]),d(_(p(oe,Q),-C[1]),_(p(Y,S),y[1]))),-I[2]),d(_(d(_(p(ie,F),f[1]),d(_(p(oe,Q),-I[1]),_(p(k,B),y[1]))),C[2]),_(d(_(p(W,R),f[1]),d(_(p(Y,S),-I[1]),_(p(k,B),C[1]))),-y[2]))))),Me=d(d(d(_(d(_(p(pe,le),C[1]),d(_(p(fe,j),-y[1]),_(p(ne,te),x[1]))),f[2]),_(d(_(p(pe,le),f[1]),d(_(p(_e,w),-y[1]),_(p(oe,Q),x[1]))),-C[2])),d(_(d(_(p(fe,j),f[1]),d(_(p(_e,w),-C[1]),_(p(Y,S),x[1]))),y[2]),_(d(_(p(ne,te),f[1]),d(_(p(oe,Q),-C[1]),_(p(Y,S),y[1]))),-x[2]))),d(d(_(d(_(p(fe,j),I[1]),d(_(p(ue,O),-C[1]),_(p(W,R),x[1]))),f[2]),_(d(_(p(fe,j),f[1]),d(_(p(_e,w),-C[1]),_(p(Y,S),x[1]))),-I[2])),d(_(d(_(p(ue,O),f[1]),d(_(p(_e,w),-I[1]),_(p(k,B),x[1]))),C[2]),_(d(_(p(W,R),f[1]),d(_(p(Y,S),-I[1]),_(p(k,B),C[1]))),-x[2])))),ve=p(ye,Me);return ve[ve.length-1]}}function l(d,p,m,_){return function(f,I,C,y,x,E){var B=d(d(m(f[0],f[0]),m(f[1],f[1])),d(m(f[2],f[2]),m(f[3],f[3]))),S=_(B,I[0]),Q=_(B,C[0]),w=_(B,y[0]),M=_(B,x[0]),k=_(B,E[0]),R=d(d(m(I[0],I[0]),m(I[1],I[1])),d(m(I[2],I[2]),m(I[3],I[3]))),F=_(R,f[0]),O=_(R,C[0]),U=_(R,y[0]),Y=_(R,x[0]),W=_(R,E[0]),te=d(d(m(C[0],C[0]),m(C[1],C[1])),d(m(C[2],C[2]),m(C[3],C[3]))),j=_(te,f[0]),J=_(te,I[0]),oe=_(te,y[0]),ie=_(te,x[0]),ne=_(te,E[0]),le=d(d(m(y[0],y[0]),m(y[1],y[1])),d(m(y[2],y[2]),m(y[3],y[3]))),ge=_(le,f[0]),_e=_(le,I[0]),ue=_(le,C[0]),fe=_(le,x[0]),pe=_(le,E[0]),ye=d(d(m(x[0],x[0]),m(x[1],x[1])),d(m(x[2],x[2]),m(x[3],x[3]))),Me=_(ye,f[0]),ve=_(ye,I[0]),he=_(ye,C[0]),Qe=_(ye,y[0]),Pe=_(ye,E[0]),we=d(d(m(E[0],E[0]),m(E[1],E[1])),d(m(E[2],E[2]),m(E[3],E[3]))),Te=_(we,f[0]),Re=_(we,I[0]),Ee=_(we,C[0]),ke=_(we,y[0]),Ce=_(we,x[0]),Le=d(d(d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),C[2]),_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),-y[2])),d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),x[2]),_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),-E[2]))),I[3]),d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),I[2]),_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),-y[2])),d(_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),x[2]),_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),-E[2]))),-C[3]),_(d(d(_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),I[2]),_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),x[2]),_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),-E[2]))),y[3]))),d(d(_(d(d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),I[2]),_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),y[2]),_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),-E[2]))),-x[3]),_(d(d(_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),I[2]),_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),-C[2])),d(_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),y[2]),_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),-x[2]))),E[3])),d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),I[2]),_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),-y[2])),d(_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),x[2]),_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),-E[2]))),f[3]),_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-y[2])),d(_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),x[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-E[2]))),-I[3])))),d(d(d(_(d(d(_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),x[2]),_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),-E[2]))),y[3]),_(d(d(_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),f[2]),_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),y[2]),_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),-E[2]))),-x[3])),d(_(d(d(_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),f[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-I[2])),d(_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),y[2]),_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),-x[2]))),E[3]),_(d(d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),I[2]),_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),y[2]),_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),-E[2]))),f[3]))),d(d(_(d(d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),f[2]),_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),y[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-E[2]))),-I[3]),_(d(d(_(d(_(p(ke,pe),I[1]),d(_(p(Re,W),-y[1]),_(p(_e,U),E[1]))),f[2]),_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),y[2]),_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),-E[2]))),C[3])),d(_(d(d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),f[2]),_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-E[2]))),-y[3]),_(d(d(_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),f[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-I[2])),d(_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-y[2]))),E[3]))))),Ye=d(d(d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),C[2]),_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),-y[2])),d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),x[2]),_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),-E[2]))),f[3]),d(_(d(d(_(d(_(p(Ce,Pe),y[1]),d(_(p(ke,pe),-x[1]),_(p(Qe,fe),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-y[2])),d(_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),x[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-E[2]))),-C[3]),_(d(d(_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),x[2]),_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),-E[2]))),y[3]))),d(d(_(d(d(_(d(_(p(ke,pe),C[1]),d(_(p(Ee,ne),-y[1]),_(p(ue,oe),E[1]))),f[2]),_(d(_(p(ke,pe),f[1]),d(_(p(Te,k),-y[1]),_(p(ge,w),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),y[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-E[2]))),-x[3]),_(d(d(_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),f[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-C[2])),d(_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),y[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-x[2]))),E[3])),d(_(d(d(_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),I[2]),_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),x[2]),_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),-E[2]))),f[3]),_(d(d(_(d(_(p(Ce,Pe),C[1]),d(_(p(Ee,ne),-x[1]),_(p(he,ie),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-C[2])),d(_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),x[2]),_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),-E[2]))),-I[3])))),d(d(d(_(d(d(_(d(_(p(Ce,Pe),I[1]),d(_(p(Re,W),-x[1]),_(p(ve,Y),E[1]))),f[2]),_(d(_(p(Ce,Pe),f[1]),d(_(p(Te,k),-x[1]),_(p(Me,M),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),x[2]),_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),-E[2]))),C[3]),_(d(d(_(d(_(p(Ee,ne),I[1]),d(_(p(Re,W),-C[1]),_(p(J,O),E[1]))),f[2]),_(d(_(p(Ee,ne),f[1]),d(_(p(Te,k),-C[1]),_(p(j,Q),E[1]))),-I[2])),d(_(d(_(p(Re,W),f[1]),d(_(p(Te,k),-I[1]),_(p(F,S),E[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-E[2]))),-x[3])),d(_(d(d(_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),f[2]),_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),-I[2])),d(_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-x[2]))),E[3]),_(d(d(_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),I[2]),_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),-C[2])),d(_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),y[2]),_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),-x[2]))),f[3]))),d(d(_(d(d(_(d(_(p(Qe,fe),C[1]),d(_(p(he,ie),-y[1]),_(p(ue,oe),x[1]))),f[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-C[2])),d(_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),y[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-x[2]))),-I[3]),_(d(d(_(d(_(p(Qe,fe),I[1]),d(_(p(ve,Y),-y[1]),_(p(_e,U),x[1]))),f[2]),_(d(_(p(Qe,fe),f[1]),d(_(p(Me,M),-y[1]),_(p(ge,w),x[1]))),-I[2])),d(_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),y[2]),_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),-x[2]))),C[3])),d(_(d(d(_(d(_(p(he,ie),I[1]),d(_(p(ve,Y),-C[1]),_(p(J,O),x[1]))),f[2]),_(d(_(p(he,ie),f[1]),d(_(p(Me,M),-C[1]),_(p(j,Q),x[1]))),-I[2])),d(_(d(_(p(ve,Y),f[1]),d(_(p(Me,M),-I[1]),_(p(F,S),x[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-x[2]))),-y[3]),_(d(d(_(d(_(p(ue,oe),I[1]),d(_(p(_e,U),-C[1]),_(p(J,O),y[1]))),f[2]),_(d(_(p(ue,oe),f[1]),d(_(p(ge,w),-C[1]),_(p(j,Q),y[1]))),-I[2])),d(_(d(_(p(_e,U),f[1]),d(_(p(ge,w),-I[1]),_(p(F,S),y[1]))),C[2]),_(d(_(p(J,O),f[1]),d(_(p(j,Q),-I[1]),_(p(F,S),C[1]))),-y[2]))),x[3]))))),tt=p(Le,Ye);return tt[tt.length-1]}}var u=[function(){return 0},function(){return 0},function(){return 0}];function g(d){var p=u[d.length];return p||(p=u[d.length]=s(d.length)),p.apply(void 0,d)}function h(d,p,m,_,f,I,C,y){return function(x,E,B,S,Q,w){switch(arguments.length){case 0:case 1:return 0;case 2:return _(x,E);case 3:return f(x,E,B);case 4:return I(x,E,B,S);case 5:return C(x,E,B,S,Q);case 6:return y(x,E,B,S,Q,w)}for(var M=new Array(arguments.length),k=0;k<arguments.length;++k)M[k]=arguments[k];return d(M)}}(function(){for(;u.length<=6;)u.push(s(u.length));e.exports=h.apply(void 0,[g].concat(u));for(var d=0;d<=6;++d)e.exports[d]=u[d]})()}}),Peo=j3({"node_modules/cdt2d/lib/delaunay.js"(t,e){var n=weo()[4];Qae();function o(i,r,s,a,A,c){var l=r.opposite(a,A);if(!(l<0)){if(A<a){var u=a;a=A,A=u,u=c,c=l,l=u}r.isConstraint(a,A)||n(i[a],i[A],i[c],i[l])<0&&s.push(a,A)}}e.exports=function(i,r){for(var s=[],a=i.length,A=r.stars,c=0;c<a;++c)for(var l=A[c],u=1;u<l.length;u+=2)if(!((p=l[u])<c)&&!r.isConstraint(c,p)){for(var g=l[u-1],h=-1,d=1;d<l.length;d+=2)if(l[d-1]===p){h=l[d];break}h<0||n(i[c],i[p],i[g],i[h])<0&&s.push(c,p)}for(;s.length>0;){for(var p=s.pop(),m=(g=-1,h=-1,l=A[c=s.pop()],1);m<l.length;m+=2){var _=l[m-1],f=l[m];_===p?h=f:f===p&&(g=_)}g<0||h<0||n(i[c],i[p],i[g],i[h])>=0||(r.flip(c,p),o(i,r,s,g,c,h),o(i,r,s,c,h,g),o(i,r,s,h,p,g),o(i,r,s,p,g,h))}}}}),Meo=j3({"node_modules/cdt2d/lib/filter.js"(t,e){var n=Qae();function o(r,s,a,A,c,l,u){this.cells=r,this.neighbor=s,this.flags=A,this.constraint=a,this.active=c,this.next=l,this.boundary=u}function i(r,s){return r[0]-s[0]||r[1]-s[1]||r[2]-s[2]}e.exports=function(r,s,a){var A=(function(y,x){for(var E=y.cells(),B=E.length,S=0;S<B;++S){var Q=(te=E[S])[0],w=te[1],M=te[2];w<M?w<Q&&(te[0]=w,te[1]=M,te[2]=Q):M<Q&&(te[0]=M,te[1]=Q,te[2]=w)}E.sort(i);var k=new Array(B);for(S=0;S<k.length;++S)k[S]=0;var R=[],F=[],O=new Array(3*B),U=new Array(3*B),Y=null;x&&(Y=[]);var W=new o(E,O,U,k,R,F,Y);for(S=0;S<B;++S)for(var te=E[S],j=0;j<3;++j){Q=te[j],w=te[(j+1)%3];var J=O[3*S+j]=W.locate(w,Q,y.opposite(w,Q)),oe=U[3*S+j]=y.isConstraint(Q,w);J<0&&(oe?F.push(S):(R.push(S),k[S]=1),x&&Y.push([w,Q,-1]))}return W})(r,a);if(s===0)return a?A.cells.concat(A.boundary):A.cells;for(var c=1,l=A.active,u=A.next,g=A.flags,h=A.cells,d=A.constraint,p=A.neighbor;l.length>0||u.length>0;){for(;l.length>0;){var m=l.pop();if(g[m]!==-c){g[m]=c,h[m];for(var _=0;_<3;++_){var f=p[3*m+_];f>=0&&g[f]===0&&(d[3*m+_]?u.push(f):(l.push(f),g[f]=c))}}}var I=u;u=l,l=I,u.length=0,c=-c}var C=(function(y,x,E){for(var B=0,S=0;S<y.length;++S)x[S]===E&&(y[B++]=y[S]);return y.length=B,y})(h,g,s);return a?C.concat(A.boundary):C},o.prototype.locate=(function(){var r=[0,0,0];return function(s,a,A){var c=s,l=a,u=A;return a<A?a<s&&(c=a,l=A,u=s):A<s&&(c=A,l=s,u=a),c<0?-1:(r[0]=c,r[1]=l,r[2]=u,n.eq(this.cells,r,i))}})()}}),Deo=j3({"node_modules/cdt2d/cdt2d.js"(t,e){var n=Qeo(),o=veo(),i=Peo(),r=Meo();function s(c){return[Math.min(c[0],c[1]),Math.max(c[0],c[1])]}function a(c,l){return c[0]-l[0]||c[1]-l[1]}function A(c,l,u){return l in c?c[l]:u}e.exports=function(c,l,u){Array.isArray(l)?(u=u||{},l=l||[]):(u=l||{},l=[]);var g=!!A(u,"delaunay",!0),h=!!A(u,"interior",!0),d=!!A(u,"exterior",!0),p=!!A(u,"infinity",!1);if(!h&&!d||c.length===0)return[];var m=n(c,l);if(g||h!==d||p){for(var _=o(c.length,(function(C){return C.map(s).sort(a)})(l)),f=0;f<m.length;++f){var I=m[f];_.addTriangle(I[0],I[1],I[2])}return g&&i(c,_),d?h?p?r(_,0,p):_.cells():r(_,1,p):r(_,-1)}return m}}}),v1t=t=>t.map(e=>({connectionId:e.connectionId,startRegionId:e.startRegion.regionId,endRegionId:e.endRegion.regionId,mutuallyConnectedNetworkId:e.mutuallyConnectedNetworkId})),w1t=t=>({ports:t.ports.map(e=>({portId:e.portId,region1Id:e.region1.regionId,region2Id:e.region2.regionId,d:e.d})),regions:t.regions.map(e=>({regionId:e.regionId,pointIds:e.ports.map(n=>n.portId),d:e.d}))}),g6e=({port:t,boundaryRegionMap:e})=>{let n=e.get(t.portId);if(!n){const o=typeof t.d?.x=="number"?t.d.x:0,i=typeof t.d?.y=="number"?t.d.y:0;n={regionId:`__section_boundary__${t.portId}`,ports:[],d:{isBoundaryRegion:!0,boundaryPortId:t.portId,...t.d,center:{x:o,y:i},bounds:{minX:o-.05,maxX:o+.05,minY:i-.05,maxY:i+.05}},assignments:[]},e.set(t.portId,n)}return n},Neo=t=>{const{sectionRoute:e,graph:n}=t,o=new Set(n.ports.map(a=>a.portId)),i=e.globalRoute.path.slice(e.sectionStartIndex,e.sectionEndIndex+1).filter(a=>o.has(a.port.portId)),r=[];let s=e.sectionConnection.startRegion;for(let a=0;a<i.length;a++){const A=i[a],c=n.ports.find(u=>u.portId===A.port.portId),l=c.region1===s?c.region2:c.region1;r.push({port:c,g:0,h:0,f:0,hops:a,ripRequired:A.ripRequired,parent:a>0?r[a-1]:void 0,lastPort:a>0?r[a-1].port:void 0,lastRegion:a>0?s:void 0,nextRegion:l}),s=l}return{connection:e.sectionConnection,path:r,requiredRip:e.globalRoute.requiredRip}},Reo=(t,e)=>{let n=-1,o=-1;for(let i=0;i<t.path.length;i++){const r=t.path[i];(r.lastRegion&&e.has(r.lastRegion.regionId)||r.nextRegion&&e.has(r.nextRegion.regionId))&&(n===-1&&(n=i),o=i)}return n===-1?null:{startIndex:n,endIndex:o}},Teo=t=>{const{graph:e,solvedRoutes:n,centralRegion:o,expansionHopsFromCentralRegion:i}=t,r=(({centralRegion:d,expansionHopsFromCentralRegion:p})=>{const m=new Set([d.regionId]),_=[{region:d,hops:0}];for(;_.length>0;){const{region:f,hops:I}=_.shift();if(!(I>=p+1))for(const C of f.ports){const y=C.region1===f?C.region2:C.region1;m.has(y.regionId)||(m.add(y.regionId),_.push({region:y,hops:I+1}))}}return m})({centralRegion:o,expansionHopsFromCentralRegion:i}),s=new Map,a=new Map,A=[];for(const d of e.regions)r.has(d.regionId)&&s.set(d.regionId,{regionId:d.regionId,ports:[],d:d.d?structuredClone(d.d):d.d,assignments:[]});for(const d of e.ports){const p=r.has(d.region1.regionId),m=r.has(d.region2.regionId);if(!p&&!m)continue;if(p&&m){const C={portId:d.portId,region1:s.get(d.region1.regionId),region2:s.get(d.region2.regionId),d:d.d};C.region1.ports.push(C),C.region2.ports.push(C),A.push(C);continue}const _=p?d.region1:d.region2,f=g6e({port:d,boundaryRegionMap:a}),I={portId:d.portId,region1:s.get(_.regionId),region2:f,d:d.d};I.region1.ports.push(I),I.region2.ports.push(I),A.push(I)}const c={regions:[...s.values(),...a.values()],ports:A},l=[],u=[],g=[];for(const d of n){const p=Reo(d,r);if(!p)continue;const m=d.path[p.startIndex],_=d.path[p.endIndex];g.push({solvedRoute:d,solvedPathStartIndex:p.startIndex,solvedPathEndIndex:p.endIndex,startCandidate:m,endCandidate:_})}const h=new Map(c.regions.map(d=>[d.regionId,d]));for(const{solvedRoute:d,solvedPathStartIndex:p,solvedPathEndIndex:m,startCandidate:_,endCandidate:f}of g){let I,C,y,x;if(r.has(d.connection.startRegion.regionId))I=d.connection.startRegion.regionId,C=h.get(I);else{const Q=g6e({port:_.port,boundaryRegionMap:a});I=Q.regionId,C=Q,h.has(I)||h.set(I,Q)}if(r.has(d.connection.endRegion.regionId))y=d.connection.endRegion.regionId,x=h.get(y);else{const Q=g6e({port:f.port,boundaryRegionMap:a});y=Q.regionId,x=Q,h.has(y)||h.set(y,Q)}if(!C)throw console.error("[getSectionOfHyperGraphAsHyperGraph] CRITICAL ERROR: startRegion not found!"),console.error(`  Looking for: ${I}`),console.error(`  Route connection: ${d.connection.connectionId}`),console.error(`  Original startRegion: ${d.connection.startRegion.regionId}`),console.error(`  startCandidate port: ${_.port.portId}`),console.error("  Available regions in sectionRegionMap:",Array.from(h.keys())),new Error(`startRegion ${I} not found in sectionRegionMap`);if(!x)throw console.error("[getSectionOfHyperGraphAsHyperGraph] CRITICAL ERROR: endRegion not found!"),console.error(`  Looking for: ${y}`),console.error(`  Route connection: ${d.connection.connectionId}`),console.error(`  Original endRegion: ${d.connection.endRegion.regionId}`),console.error(`  endCandidate port: ${f.port.portId}`),console.error("  Available regions in sectionRegionMap:",Array.from(h.keys())),new Error(`endRegion ${y} not found in sectionRegionMap`);const E={connectionId:d.connection.connectionId,mutuallyConnectedNetworkId:d.connection.mutuallyConnectedNetworkId,startRegion:C,endRegion:x},B=d.path.slice(p,m+1),S={globalRoute:d,globalConnection:d.connection,sectionConnection:E,sectionStartIndex:p,sectionEndIndex:m};l.push({...S,canRemainFixedInSectionSolve:B.every(Q=>c.ports.some(w=>w.portId===Q.port.portId)),sectionRoute:Neo({sectionRoute:S,graph:c})}),u.push(E)}return{centralRegionId:o.regionId,sectionRegionIds:r,graph:c,connections:u,sectionRoutes:l}},P1t=class{heap=[];maxSize;constructor(e=[],n=1e4){if(this.maxSize=n,e.length>0){this.heap=[...e].sort((o,i)=>o.f-i.f).slice(0,this.maxSize);for(let o=Math.floor(this.heap.length/2)-1;o>=0;o--)this._siftDown(o)}}get size(){return this.heap.length}isEmpty(){return this.heap.length===0}peek(){return this.isEmpty()?null:this.heap[0]??null}peekMany(e){return[...this.heap].sort((n,o)=>n.f-o.f).slice(0,e)}dequeue(){if(this.isEmpty())return null;const e=this.heap[0],n=this.heap.pop();return this.heap.length===0&&n!==void 0||n!==void 0&&(this.heap[0]=n,this._siftDown(0)),e}enqueue(e){this.heap.length>=this.maxSize||(this.heap.push(e),this._siftUp(this.heap.length-1))}_siftUp(e){let n=e;for(;n>0;){const o=this._parentIndex(n);if(this.heap[o].f<=this.heap[n].f)break;this._swap(n,o),n=o}}_siftDown(e){let n=e;const o=this.heap.length;for(;;){const i=this._leftChildIndex(n),r=this._rightChildIndex(n);let s=n;if(i<o&&this.heap[i].f<this.heap[s].f&&(s=i),r<o&&this.heap[r].f<this.heap[s].f&&(s=r),s===n)break;this._swap(n,s),n=s}}_swap(e,n){[this.heap[e],this.heap[n]]=[this.heap[n],this.heap[e]]}_parentIndex(e){return Math.floor((e-1)/2)}_leftChildIndex(e){return 2*e+1}_rightChildIndex(e){return 2*e+2}},M1t=t=>{for(const e of t.regions)e.assignments=[];for(const e of t.ports)e.assignment=void 0},d6e=({graph:t,connections:e,solvedRoutes:n})=>{const o=new Map(t.ports.map(a=>[a.portId,a])),i=new Map(t.regions.map(a=>[a.regionId,a])),r=new Map(e.map(a=>[a.connectionId,a])),s=n.map(a=>{const A=[];for(const c of a.path){const l={port:o.get(c.port.portId),g:c.g,h:c.h,f:c.f,hops:c.hops,ripRequired:c.ripRequired};c.lastPort&&(l.lastPort=o.get(c.lastPort.portId)),c.lastRegion&&(l.lastRegion=i.get(c.lastRegion.regionId)),c.nextRegion&&(l.nextRegion=i.get(c.nextRegion.regionId));const u=A[A.length-1];u&&(l.parent=u),A.push(l)}return{path:A,connection:r.get(a.connection.connectionId),requiredRip:a.requiredRip}});M1t(t),t.solvedRoutes=s;for(const a of s)for(const A of a.path){if(A.port.assignment={solvedRoute:a,connection:a.connection},!A.lastPort||!A.lastRegion)continue;const c={regionPort1:A.lastPort,regionPort2:A.port,region:A.lastRegion,connection:a.connection,solvedRoute:a};A.lastRegion.assignments??=[],A.lastRegion.assignments.push(c)}return s},D1t=class extends zA{constructor(e){super(),this.input=e,this.graph=(o=>{if(o.ports.length>0&&"region1"in o.ports[0]&&typeof o.ports[0].region1=="object")return o;const i=new Map,r=new Map;for(const s of o.regions){const{assignments:a,...A}=s;r.set(s.regionId,{...A,d:A.d?structuredClone(A.d):A.d,ports:[],assignments:void 0})}for(const s of o.ports){const a=r.get(s.region1Id??s.region1?.regionId),A=r.get(s.region2Id??s.region2?.regionId),c={portId:s.portId,region1:a,region2:A,d:s.d};i.set(s.portId,c),a.ports.push(c),A.ports.push(c)}return{ports:Array.from(i.values()),regions:Array.from(r.values())}})(e.inputGraph),M1t(this.graph),this.connections=((o,i)=>{const r=[];for(const s of o)"startRegionId"in s?r.push({connectionId:s.connectionId,mutuallyConnectedNetworkId:s.mutuallyConnectedNetworkId??s.connectionId,startRegion:i.regions.find(a=>a.regionId===s.startRegionId),endRegion:i.regions.find(a=>a.regionId===s.endRegionId)}):r.push(s);return r})(e.inputConnections,this.graph),e.inputSolvedRoutes?this.solvedRoutes=d6e({graph:this.graph,connections:this.connections,solvedRoutes:e.inputSolvedRoutes}):this.graph.solvedRoutes=this.solvedRoutes,e.greedyMultiplier!==void 0&&(this.greedyMultiplier=e.greedyMultiplier),e.rippingEnabled!==void 0&&(this.rippingEnabled=e.rippingEnabled),e.ripCost!==void 0&&(this.ripCost=e.ripCost);const n=new Set(this.solvedRoutes.map(o=>o.connection.connectionId));this.unprocessedConnections=this.connections.filter(o=>!n.has(o.connectionId)),this.candidateQueue=new P1t,this.unprocessedConnections.length===0?this.solved=!0:this.beginNewConnection()}getSolverName(){return"HyperGraphSolver"}graph;connections;candidateQueue;unprocessedConnections;solvedRoutes=[];currentConnection=null;currentEndRegion=null;greedyMultiplier=1;rippingEnabled=!1;ripCost=0;lastCandidate=null;visitedPointsForCurrentConnection=new Map;getConstructorParams(){return{inputGraph:w1t(this.graph),inputConnections:v1t(this.connections),greedyMultiplier:this.greedyMultiplier,rippingEnabled:this.rippingEnabled,ripCost:this.ripCost,inputSolvedRoutes:this.solvedRoutes}}computeH(e){return this.estimateCostToEnd(e.port)}estimateCostToEnd(e){return 0}getPortUsagePenalty(e){return 0}computeIncreasedRegionCostIfPortsAreUsed(e,n,o){return 0}getRipsRequiredForPortUsage(e,n,o){return[]}isRipRequiredForPortUsage(e,n,o){return!1}isTransitionAllowed(e,n,o){return!0}computeG(e){return e.parent.g+this.computeIncreasedRegionCostIfPortsAreUsed(e.lastRegion,e.lastPort,e.port)+(e.ripRequired?this.ripCost:0)+this.getPortUsagePenalty(e.port)}selectCandidatesForEnteringRegion(e){return e}computeRoutesToRip(e){const n=this.computeCrossingRoutes(e),o=this.computePortOverlapRoutes(e);return new Set([...n,...o])}computePortOverlapRoutes(e){const n=new Set;for(const o of e.path)o.port.assignment&&o.port.assignment.connection.mutuallyConnectedNetworkId!==e.connection.mutuallyConnectedNetworkId&&n.add(o.port.assignment.solvedRoute);return n}computeCrossingRoutes(e){const n=new Set;for(const o of e.path){if(!o.lastPort||!o.lastRegion)continue;const i=this.getRipsRequiredForPortUsage(o.lastRegion,o.lastPort,o.port);for(const r of i)n.add(r.solvedRoute)}return n}getNextCandidates(e){const n=e.nextRegion,o=e.port,i={};for(const s of n.ports){if(s===e.port||!this.isTransitionAllowed(n,o,s))continue;const a=s.assignment&&s.assignment.connection.mutuallyConnectedNetworkId!==this.currentConnection.mutuallyConnectedNetworkId||this.isRipRequiredForPortUsage(n,o,s),A={port:s,hops:e.hops+1,parent:e,lastRegion:n,nextRegion:s.region1===n?s.region2:s.region1,lastPort:o,ripRequired:a};!this.rippingEnabled&&A.ripRequired||(i[A.nextRegion.regionId]??=[],i[A.nextRegion.regionId].push(A))}const r=[];for(const s in i){const a=i[s];r.push(...this.selectCandidatesForEnteringRegion(a))}for(const s of r)s.g=this.computeG(s),s.h=this.computeH(s),s.f=s.g+s.h*this.greedyMultiplier;return r}processSolvedRoute(e){const n={path:[],connection:this.currentConnection,requiredRip:!1};let o=e,i=!1;for(;o;)i||=!!o.ripRequired,n.path.unshift(o),o=o.parent;i&&(n.requiredRip=!0);const r=this.computeRoutesToRip(n);if(r.size>0){n.requiredRip=!0;for(const s of r)this.ripSolvedRoute(s)}for(const s of n.path){if(s.port.assignment={solvedRoute:n,connection:this.currentConnection},!s.lastPort)continue;const a={regionPort1:s.lastPort,regionPort2:s.port,region:s.lastRegion,connection:this.currentConnection,solvedRoute:n};s.lastRegion.assignments?.push(a)}this.solvedRoutes.push(n),this.routeSolvedHook(n)}routeSolvedHook(e){}routeStartedHook(e){}ripSolvedRoute(e){for(const n of e.path.map(o=>o.port))n.ripCount=(n.ripCount??0)+1,n.region1.assignments=n.region1.assignments?.filter(o=>o.regionPort1!==n&&o.regionPort2!==n),n.region2.assignments=n.region2.assignments?.filter(o=>o.regionPort1!==n&&o.regionPort2!==n),n.assignment=void 0;this.solvedRoutes=this.solvedRoutes.filter(n=>n!==e),this.unprocessedConnections.push(e.connection)}beginNewConnection(){this.currentConnection=this.unprocessedConnections.shift(),this.currentEndRegion=this.currentConnection.endRegion,this.candidateQueue=new P1t,this.visitedPointsForCurrentConnection.clear(),this.routeStartedHook(this.currentConnection);for(const e of this.currentConnection.startRegion.ports)this.candidateQueue.enqueue({port:e,g:0,h:0,f:0,hops:0,ripRequired:!1,nextRegion:e.region1===this.currentConnection.startRegion?e.region2:e.region1})}_step(){let e=this.candidateQueue.dequeue();if(!e)return this.failed=!0,void(this.error="Ran out of candidates");let n=this.visitedPointsForCurrentConnection.get(e.port.portId);for(;e&&n!==void 0&&!(e.g<n)&&(e=this.candidateQueue.dequeue(),e);)n=this.visitedPointsForCurrentConnection.get(e.port.portId);if(!e)return this.failed=!0,void(this.error="Ran out of candidates");if(this.lastCandidate=e,this.visitedPointsForCurrentConnection.set(e.port.portId,e.g),e.nextRegion===this.currentEndRegion)return this.processSolvedRoute(e),this.unprocessedConnections.length===0?void(this.solved=!0):void this.beginNewConnection();const o=this.getNextCandidates(e);for(const i of o)this.candidateQueue.enqueue(i)}};function keo(t,e){const n=t.x-e.x,o=t.y-e.y;return n*n+o*o}function h6e(t,e,n,o,i){const r=n-e,s=i-o,a=1e-6;if(Math.abs(t.y-i)<a)return t.x-e;if(Math.abs(t.x-n)<a)return r+(i-t.y);if(Math.abs(t.y-o)<a)return r+s+(n-t.x);if(Math.abs(t.x-e)<a)return 2*r+s+(t.y-o);const A=Math.abs(t.y-i),c=Math.abs(t.x-n),l=Math.abs(t.y-o),u=Math.abs(t.x-e),g=Math.min(A,c,l,u);return g===A?Math.max(0,Math.min(r,t.x-e)):g===c?r+Math.max(0,Math.min(s,i-t.y)):g===l?r+s+Math.max(0,Math.min(r,n-t.x)):2*r+s+Math.max(0,Math.min(s,t.y-o))}function Feo(t,e,n){const o=n.x-e.x,i=n.y-e.y,r=t.x-e.x,s=t.y-e.y,a=o*o+i*i,A=a>0?(c=(r*o+s*i)/a,l=0,u=1,Math.max(l,Math.min(u,c))):0;var c,l,u;return{u:A,d2:keo(t,{x:e.x+A*o,y:e.y+A*i})}}function N1t(t){const e=t.d.polygon;if(!e||e.length<3)return null;const n=t.d.polygonPerimeterCache;if(n)return n;const o=(function(i){const r=i.length,s=new Array(r),a=new Array(r+1);a[0]=0;for(let A=0;A<r;A++){const c=i[A],l=i[(A+1)%r],u=Math.hypot(l.x-c.x,l.y-c.y);s[A]=u,a[A+1]=a[A]+u}return{edgeLengths:s,cumulative:a,perimeter:a[r]}})(e);return t.d.polygonPerimeterCache=o,o}function R1t(t){const e=N1t(t);if(e)return e.perimeter;const{minX:n,maxX:o,minY:i,maxY:r}=t.d.bounds;return 2*(o-n)+2*(r-i)}function ZQ(t,e){if(t.region1===e){if(typeof t.region1T=="number")return t.region1T;const n=p6e(t.d,e);return t.region1T=n,n}if(t.region2===e){if(typeof t.region2T=="number")return t.region2T;const n=p6e(t.d,e);return t.region2T=n,n}return p6e(t.d,e)}function p6e(t,e){const n=e.d.polygon;if(n&&n.length>=3){const a=N1t(e);if(a)return(function(A,c,l,u=1e-6){let g=0,h=0,d=Number.POSITIVE_INFINITY;const p=u*u;for(let m=0;m<c.length;m++){const _=Feo(A,c[m],c[(m+1)%c.length]);if(_.d2<=p){g=m,h=_.u,d=_.d2;break}_.d2<d&&(g=m,h=_.u,d=_.d2)}return l.cumulative[g]+h*l.edgeLengths[g]})(t,n,a)}const{minX:o,maxX:i,minY:r,maxY:s}=e.d.bounds;return h6e(t,o,i,r,s)}function vae(t,e,n=1e-6){return Math.abs(t-e)<n}function ev(t,e){return(t%e+e)%e}function wae(t,e,n,o){const i=Math.abs(ev(t-e,n));return i<o||n-i<o}function T1t(t,e,n,o,i){const r=ev(t,o),s=ev(e,o),a=ev(n,o);return!(Math.abs(s-a)<i)&&(s<a?s<r&&r<a:r>s||r<a)}function m6e(t,e,n){if(typeof n=="number"&&n>0){let[a,A]=t,[c,l]=e;return a=ev(a,n),A=ev(A,n),c=ev(c,n),l=ev(l,n),wae(a,c,n,1e-6)||wae(a,l,n,1e-6)||wae(A,c,n,1e-6)||wae(A,l,n,1e-6)?!1:T1t(c,a,A,n,1e-12)!==T1t(l,a,A,n,1e-12)}const[o,i]=t[0]<t[1]?t:[t[1],t[0]],[r,s]=e[0]<e[1]?e:[e[1],e[0]];return!(vae(o,r)||vae(o,s)||vae(i,r)||vae(i,s))&&(o<r&&r<i&&i<s||r<o&&o<s&&s<i)}var k1t=t=>{let e=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const r of t){const{bounds:s}=r.d;e=Math.min(e,s.minX),n=Math.max(n,s.maxX),o=Math.min(o,s.minY),i=Math.max(i,s.maxY)}return{minX:e,maxX:n,minY:o,maxY:i}},F1t=(t,e,n,o)=>{const i={portId:t,region1:e,region2:n,d:{x:o.x,y:o.y}};return e.ports.push(i),n.ports.push(i),i},L1t=(t,e,n)=>({regionId:t,ports:[],d:{bounds:{minX:e-.2,maxX:e+.2,minY:n-.2,maxY:n+.2},center:{x:e,y:n},isPad:!1,isConnectionRegion:!0}}),tv=.01,$8=(t,e,n)=>Math.max(e,Math.min(n,t)),H1t=(t,e,n)=>e==="left"?Math.abs(t.x-n.minX)<tv:e==="right"?Math.abs(t.x-n.maxX)<tv:e==="top"?Math.abs(t.y-n.maxY)<tv:Math.abs(t.y-n.minY)<tv,Leo=(t,e,n,o)=>{const i=o.x-n.x,r=o.y-n.y,s=t-n.x,a=e-n.y,A=i*i+r*r,c=A>0?$8((s*i+a*r)/A,0,1):0,l=n.x+c*i,u=n.y+c*r,g=t-l,h=e-u;return{x:l,y:u,d2:g*g+h*h}},Heo=(t,e,n,o,i)=>{const r=n.d.polygon;if(r&&r.length>=3){const c=new Set(i);let l=null;for(let u=0;u<r.length;u++){const g=r[u],h=r[(u+1)%r.length];if(i.length>0&&!i.some(p=>H1t(g,p,o)&&H1t(h,p,o)&&c.has(p)))continue;const d=Leo(t,e,g,h);(!l||d.d2<l.d2)&&(l=d)}if(l)return l}const s=n.d.bounds,a=[];if(i.length>0)for(const c of i)c==="left"?a.push({side:c,x:s.minX,y:$8(e,s.minY,s.maxY)}):c==="right"?a.push({side:c,x:s.maxX,y:$8(e,s.minY,s.maxY)}):c==="top"?a.push({side:c,x:$8(t,s.minX,s.maxX),y:s.maxY}):a.push({side:c,x:$8(t,s.minX,s.maxX),y:s.minY});a.length===0&&a.push({side:"left",x:s.minX,y:$8(e,s.minY,s.maxY)},{side:"right",x:s.maxX,y:$8(e,s.minY,s.maxY)},{side:"top",x:$8(t,s.minX,s.maxX),y:s.maxY},{side:"bottom",x:$8(t,s.minX,s.maxX),y:s.minY});let A=null;for(const c of a){if(i.length>0&&!i.includes(c.side))continue;const l=t-c.x,u=e-c.y,g=l*l+u*u;(!A||g<A.d2)&&(A={x:c.x,y:c.y,d2:g})}return A},O1t=(t,e,n,o)=>{const i=((A,c,l)=>{const u=[];return Math.abs(A-l.minX)<tv&&u.push("left"),Math.abs(A-l.maxX)<tv&&u.push("right"),Math.abs(c-l.maxY)<tv&&u.push("top"),Math.abs(c-l.minY)<tv&&u.push("bottom"),u})(t,e,o);let r=null,s=Number.POSITIVE_INFINITY,a={x:t,y:e};for(const A of n){if(A.d.isPad||A.d.isThroughJumper)continue;const c=A.d.bounds;if(!(Math.abs(c.minX-o.minX)<.01||Math.abs(c.maxX-o.maxX)<.01||Math.abs(c.minY-o.minY)<.01||Math.abs(c.maxY-o.maxY)<.01))continue;const l=Heo(t,e,A,o,i);if(!l)continue;const u=Math.sqrt(l.d2);u<s&&(s=u,r=A,a={x:l.x,y:l.y})}return r?{region:r,portPosition:a}:null},Oeo=class extends zA{constructor(e){super(),this.input=e,this.graph=e.hyperGraphSolver.graph;const n=e.inputSolvedRoutes,o=e.hyperGraphSolver.connections;this.connections=o,this.solvedRoutes=d6e({graph:this.graph,connections:this.connections,solvedRoutes:n}),this.maxAttemptsPerRegion=e.MAX_ATTEMPTS_PER_REGION,this.maxSectionAttempts=e.MAX_ATTEMPTS_PER_SECTION??500,this.iterations+=this.iterations*(e.effort??1),this.fractionToReplace=e.FRACTION_TO_REPLACE??.2,this.alwaysRipConflicts=e.alwaysRipConflicts??!0}graph;connections;solvedRoutes;activeSection=null;baselineSectionCost=1/0;baselineGlobalCost=1/0;regionAttemptCounts=new Map;sectionAttempts=0;maxAttemptsPerRegion;maxSectionAttempts;fractionToReplace;alwaysRipConflicts;random=(e=>{let n=e;return()=>(n=1664525*n+1013904223>>>0,n/4294967295)})(31337);getSolverName(){return"HyperGraphSectionOptimizer"}getConstructorParams(){return{inputGraph:w1t(this.graph),inputConnections:v1t(this.connections),inputSolvedRoutes:this.solvedRoutes,expansionHopsFromCentralRegion:this.input.expansionHopsFromCentralRegion,maxAttemptsPerRegion:this.maxAttemptsPerRegion,maxSectionAttempts:this.maxSectionAttempts,effort:this.input.effort,fractionToReplace:this.fractionToReplace,alwaysRipConflicts:this.alwaysRipConflicts,ACCEPTABLE_COST:this.input.ACCEPTABLE_REGION_COST}}getOutput(){return this.solvedRoutes}_setup(){this.beginSectionSolve()}visualize(){return this.activeSubSolver?this.activeSubSolver.visualize():{title:"HyperGraphSectionOptimizer",points:[],lines:[],rects:[],circles:[],texts:[],polygons:[],arrows:[]}}getCostOfRegionWithAttempts(e){const n=this.regionAttemptCounts.get(e.regionId)??0;return this.input.regionCost(e)+1e4*n}computeCostOfSection({section:e,solvedRoutes:n}){if(this.input.computeSolvedGraphCost)return this.input.computeSolvedGraphCost(n);const o=this.input.createHyperGraphSolver({inputGraph:e.graph,inputConnections:e.connections,inputSolvedRoutes:n});let i=0;for(const r of o.graph.regions)i+=this.input.regionCost(r);return i}computeSolvedGraphCost(e){if(this.input.computeSolvedGraphCost)return this.input.computeSolvedGraphCost(e);const n=this.input.createHyperGraphSolver({inputGraph:this.graph,inputConnections:this.connections,inputSolvedRoutes:e});let o=0;for(const i of n.graph.regions)o+=this.input.regionCost(i);return o}determineConnectionsToRip(e,n){const o=e.sectionRoutes.map(A=>A.globalConnection.connectionId);if(this.fractionToReplace>=1)return new Set(o);const i=[...o];for(let A=i.length-1;A>0;A--){const c=Math.floor(this.random()*(A+1));[i[A],i[c]]=[i[c],i[A]]}const r=Math.max(1,Math.ceil(i.length*this.fractionToReplace)),s=new Set(i.slice(0,r));if(!this.alwaysRipConflicts)return s;const a=new Map(e.graph.regions.map(A=>[A.regionId,A]));for(const A of e.sectionRoutes)for(const c of A.sectionRoute.path){if(!c.lastPort||!c.lastRegion)continue;const l=a.get(c.lastRegion.regionId);if(!l)continue;n.currentConnection=A.globalConnection;const u=n.getRipsRequiredForPortUsage(l,c.lastPort,c.port);for(const g of u){const h=A.globalConnection.connectionId,d=g.connection.connectionId;s.has(h)||s.has(d)||s.add(this.random()<.5?h:d)}}return s}getNextCentralRegion(){let e=null,n=1/0;for(const o of this.graph.regions){if((o.assignments?.length??0)===0||(this.regionAttemptCounts.get(o.regionId)??0)>=this.maxAttemptsPerRegion||this.input.regionCost(o)<this.input.ACCEPTABLE_REGION_COST)continue;const i=this.getCostOfRegionWithAttempts(o);i>=n||(n=i,e=o)}return e}beginSectionSolve(){if(this.sectionAttempts>=this.maxSectionAttempts)return console.log(`Reached max section attempts (${this.maxSectionAttempts}), stopping optimization`),void(this.solved=!0);const e=this.getNextCentralRegion();if(!e)return void(this.solved=!0);if(this.sectionAttempts++,this.activeSection=Teo({graph:this.graph,solvedRoutes:this.solvedRoutes,centralRegion:e,expansionHopsFromCentralRegion:this.input.expansionHopsFromCentralRegion}),!this.activeSection)return;if(this.activeSection.connections.length===0)return this.regionAttemptCounts.set(e.regionId,(this.regionAttemptCounts.get(e.regionId)??0)+1),void(this.activeSection=null);const n=this.activeSection.sectionRoutes.filter(a=>a.canRemainFixedInSectionSolve),o=this.input.createHyperGraphSolver({inputGraph:this.activeSection.graph,inputConnections:this.activeSection.connections,inputSolvedRoutes:n.map(a=>a.sectionRoute)}),i=this.determineConnectionsToRip(this.activeSection,o);for(const a of this.activeSection.sectionRoutes)a.canRemainFixedInSectionSolve||i.add(a.globalConnection.connectionId);const r=this.activeSection.sectionRoutes.filter(a=>a.canRemainFixedInSectionSolve&&!i.has(a.globalConnection.connectionId)).map(a=>a.sectionRoute),s=[...r,...this.activeSection.sectionRoutes.filter(a=>i.has(a.globalConnection.connectionId)).map(a=>a.sectionRoute)];this.baselineSectionCost=this.computeCostOfSection({section:this.activeSection,solvedRoutes:s}),this.baselineGlobalCost=this.computeSolvedGraphCost(this.solvedRoutes),this.activeSubSolver=this.input.createHyperGraphSolver({inputGraph:this.activeSection.graph,inputConnections:this.activeSection.connections,inputSolvedRoutes:r});for(const a of this.activeSubSolver.connections)a.startRegion&&a.endRegion||console.error({startRegion:a.startRegion?.regionId,endRegion:a.endRegion?.regionId})}_step(){if(!this.activeSubSolver)return void this.beginSectionSolve();if(this.activeSubSolver.step(),!this.activeSection)return;if(this.activeSubSolver.failed){this.failedSubSolvers??=[],this.failedSubSolvers.push(this.activeSubSolver);const a=this.regionAttemptCounts.get(this.activeSection.centralRegionId)??0;return this.regionAttemptCounts.set(this.activeSection.centralRegionId,a+1),this.activeSubSolver=null,this.activeSection=null,this.baselineSectionCost=1/0,void(this.baselineGlobalCost=1/0)}if(!this.activeSubSolver.solved)return;const e=this.activeSubSolver.solvedRoutes,n=this.computeCostOfSection({section:this.activeSection,solvedRoutes:e}),o=(a=>{const{solvedRoutes:A,section:c,replacementSolvedRoutes:l}=a,u=new Map(l.map(g=>[g.connection.connectionId,g]));return A.map(g=>{const h=c.sectionRoutes.find(m=>m.globalConnection.connectionId===g.connection.connectionId);if(!h)return g;const d=u.get(g.connection.connectionId);if(!d)return g;const p=[...g.path.slice(0,h.sectionStartIndex),...d.path,...g.path.slice(h.sectionEndIndex+1)].map(m=>({port:m.port,g:m.g,h:m.h,f:m.f,hops:m.hops,ripRequired:m.ripRequired,lastPort:m.lastPort,lastRegion:m.lastRegion,nextRegion:m.nextRegion}));for(let m=0;m<p.length;m++)p[m].parent=m>0?p[m-1]:void 0;return{connection:g.connection,path:p,requiredRip:g.requiredRip||d.requiredRip}})})({solvedRoutes:this.solvedRoutes,section:this.activeSection,replacementSolvedRoutes:e}),i=this.computeSolvedGraphCost(o),r=n<=this.baselineSectionCost,s=i<this.baselineGlobalCost;if(r&&s){this.solvedRoutes=o;const a=this.input.hyperGraphSolver;if(!a)return;a.solvedRoutes=d6e({graph:a.graph,connections:a.connections,solvedRoutes:this.solvedRoutes});for(const A of this.activeSection.sectionRegionIds)this.regionAttemptCounts.set(A,0);this.baselineSectionCost=n,this.baselineGlobalCost=i}else{const a=this.regionAttemptCounts.get(this.activeSection.centralRegionId)??0;this.regionAttemptCounts.set(this.activeSection.centralRegionId,a+1)}this.activeSubSolver=null,this.activeSection=null,this.baselineSectionCost=1/0,this.baselineGlobalCost=1/0}};function AL(t,e){return Array.isArray(e)?[t.a*e[0]+t.c*e[1]+t.e,t.b*e[0]+t.d*e[1]+t.f]:{x:t.a*e.x+t.c*e.y+t.e,y:t.b*e.x+t.d*e.y+t.f}}function G1t(t){return t===void 0}function Pae(t,e=0){return{a:1,c:0,e:t,b:0,d:1,f:e}}function _6e(...t){const e=(n,o)=>({a:n.a*o.a+n.c*o.b,c:n.a*o.c+n.c*o.d,e:n.a*o.e+n.c*o.f+n.e,b:n.b*o.a+n.d*o.b,d:n.b*o.c+n.d*o.d,f:n.b*o.e+n.d*o.f+n.f});switch((t=Array.isArray(t[0])?t[0]:t).length){case 0:throw new Error("no matrices provided");case 1:return t[0];case 2:return e(t[0],t[1]);default:{const[n,o,...i]=t;return _6e(e(n,o),...i)}}}var{cos:Geo,sin:Yeo}=Math,f6e=t=>({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2}),Y1t=(t,e)=>{const n=t.regions.map(s=>{const{bounds:a,center:A,...c}=s.d,l=[{x:a.minX,y:a.minY},{x:a.maxX,y:a.minY},{x:a.minX,y:a.maxY},{x:a.maxX,y:a.maxY}].map(h=>AL(e,h)),u={minX:Math.min(...l.map(h=>h.x)),maxX:Math.max(...l.map(h=>h.x)),minY:Math.min(...l.map(h=>h.y)),maxY:Math.max(...l.map(h=>h.y))},g=AL(e,A);return{...s,ports:[],d:{...c,bounds:u,center:g}}}),o=new Map;for(let s=0;s<t.regions.length;s++)o.set(t.regions[s],n[s]);const i=t.ports.map(s=>{const a=AL(e,s.d),A=o.get(s.region1),c=o.get(s.region2),l={...s,region1:A,region2:c,d:a};return A.ports.push(l),c.ports.push(l),l}),r=t.jumperLocations?.map(s=>{const a=AL(e,s.center),A=s.padRegions.map(h=>o.get(h)),c=AL(e,{x:1,y:0}),l=AL(e,{x:0,y:0}),u=c.x-l.x,g=c.y-l.y;return{center:a,orientation:Math.abs(g)>Math.abs(u)?s.orientation==="horizontal"?"vertical":"horizontal":s.orientation,padRegions:A}});return{regions:n,ports:i,...r&&{jumperLocations:r}}},I6e=(t,e=.8)=>{let n=0;for(let o=0;o<t.length;o++)n=17777*t.charCodeAt(o)+((n<<5)-n);return`hsla(${Math.abs(n)%360}, 70%, 50%, ${e})`},Ueo=t=>{const e=(i=>{const r=((s,a)=>{const A={arrows:[],circles:[],title:"Jumper Graph",lines:[],points:[],rects:[],texts:[],polygons:[],coordinateSystem:"cartesian"};for(const c of s.regions){const{bounds:l,isPad:u,isThroughJumper:g,isConnectionRegion:h,polygon:d}=c.d,p=(l.minX+l.maxX)/2,m=(l.minY+l.maxY)/2,_=l.maxX-l.minX,f=l.maxY-l.minY;let I;if(I=h?"rgba(255, 100, 255, 0.6)":g?"rgba(100, 200, 100, 0.5)":u?"rgba(255, 200, 100, 0.5)":"rgba(200, 200, 255, 0.1)",d&&d.length>=3){const C=d;A.polygons.push({points:C,fill:I})}else A.rects.push({center:{x:p,y:m},width:_-.1,height:f-.1,fill:I})}if(!a?.hidePortPoints)for(const c of s.ports){const l=c.region1.regionId.split(":").pop()??c.region1.regionId,u=c.region2.regionId.split(":").pop()??c.region2.regionId;A.circles.push({center:{x:c.d.x,y:c.d.y},radius:.05,fill:"rgba(128, 128, 128, 0.5)",label:`${l}-${u}`})}if(!a?.hideRegionPortLines)for(const c of s.ports){const l={x:(c.region1.d.bounds.minX+c.region1.d.bounds.maxX)/2,y:(c.region1.d.bounds.minY+c.region1.d.bounds.maxY)/2},u={x:(c.region2.d.bounds.minX+c.region2.d.bounds.maxX)/2,y:(c.region2.d.bounds.minY+c.region2.d.bounds.maxY)/2};A.lines.push({points:[l,{x:c.d.x,y:c.d.y},u],strokeColor:"rgba(100, 100, 100, 0.3)"})}if(a?.connections&&!a?.hideConnectionLines)for(const c of a.connections){const l=c.startRegion,u=c.endRegion,g={x:(l.d.bounds.minX+l.d.bounds.maxX)/2,y:(l.d.bounds.minY+l.d.bounds.maxY)/2},h={x:(u.d.bounds.minX+u.d.bounds.maxX)/2,y:(u.d.bounds.minY+u.d.bounds.maxY)/2},d=(g.x+h.x)/2,p=(g.y+h.y)/2;A.lines.push({points:[g,h],strokeColor:"rgba(255, 50, 150, 0.8)",strokeDash:"3 3"}),A.points.push({x:d,y:p,color:"rgba(200, 0, 100, 1)",label:c.connectionId})}return A})(i.graph,{connections:i.connections,...i.hideInitialGeometry?{hideRegionPortLines:!0,hideConnectionLines:!0,hidePortPoints:!0}:{}});if(!i.hideInitialGeometry)for(const s of r.polygons)s.stroke="rgba(128, 128, 128, 0.5)",s.strokeWidth=.03;i.title&&(r.title=i.title);for(const s of i.priorSolvedRoutes??[]){const a=s.path.map(A=>{const c=A.port;return{x:c.d.x,y:c.d.y}});a.length!==0&&r.lines.push({points:a,strokeColor:"rgba(80, 80, 80, 0.45)",strokeDash:"4 4"})}for(const s of i.solvedRoutes){const a=I6e(s.connection.connectionId),A=[];for(const c of s.path){const l=c.port;A.push({x:l.d.x,y:l.d.y})}A.length>0&&r.lines.push({points:A,strokeColor:a})}return r})({graph:{regions:t.graph.regions,ports:t.graph.ports},connections:t.connections,solvedRoutes:t.solvedRoutes,hideInitialGeometry:t.iterations>0});if(t.currentConnection&&!t.solved){const i=I6e(t.currentConnection.connectionId),r=t.currentConnection.startRegion,s=t.currentConnection.endRegion;if(!r?.d||!s?.d)return e;const a={x:(r.d.bounds.minX+r.d.bounds.maxX)/2,y:(r.d.bounds.minY+r.d.bounds.maxY)/2},A={x:(s.d.bounds.minX+s.d.bounds.maxX)/2,y:(s.d.bounds.minY+s.d.bounds.maxY)/2};e.lines.push({points:[a,A],strokeColor:i,strokeDash:"10 5"}),e.points.push({x:a.x-.1,y:a.y+.1,color:i,label:[t.currentConnection.connectionId,"start"].join(`
`)}),e.points.push({x:A.x-.1,y:A.y+.1,color:i,label:[t.currentConnection.connectionId,"end"].join(`
`)})}const n=t.candidateQueue.peekMany(10);for(let i=0;i<n.length;i++){const r=n[i],s=r.port,a=i===0;e.points.push({x:s.d.x,y:s.d.y,color:a?"green":"rgba(128, 128, 128, 0.25)",label:[r.port.portId,`g: ${r.g.toFixed(2)}`,`h: ${r.h.toFixed(2)}`,`f: ${r.f.toFixed(2)}`].join(`
`)})}const o=n[0];if(!t.solved&&o&&t.currentConnection){const i=I6e(t.currentConnection.connectionId),r=[];let s=o;for(;s;){const a=s.port;r.unshift({x:a.d.x,y:a.d.y}),s=s.parent}r.length>1&&e.lines.push({points:r,strokeColor:i})}return e},Keo=.034685181009478865,Veo=0,zeo=4.072520483177124,Jeo=0,Weo=35.38577539020022,jeo=.5518001238069296,$eo=class extends D1t{getSolverName(){return"JumperGraphSolver"}UNIT_OF_COST="hops";portUsagePenalty=Keo;portUsagePenaltySq=Veo;crossingPenalty=zeo;crossingPenaltySq=Jeo;ripCost=Weo;baseMaxIterations=4e3;additionalMaxIterationsPerConnection=2e3;additionalMaxIterationsPerCrossing=2e3;constructor(e){super({greedyMultiplier:jeo,rippingEnabled:!0,...e}),this.ripCost=e.ripCost??this.ripCost,this.portUsagePenalty=e.portUsagePenalty??this.portUsagePenalty,this.crossingPenalty=e.crossingPenalty??this.crossingPenalty,this.baseMaxIterations=e.baseMaxIterations??this.baseMaxIterations,this.additionalMaxIterationsPerConnection=e.additionalMaxIterationsPerConnection??this.additionalMaxIterationsPerConnection;const n=(function(o,i){if(i.length<2)return 0;let r=1/0,s=-1/0,a=1/0,A=-1/0;for(const h of o.regions){const d=h;d.d?.bounds?(r=Math.min(r,d.d.bounds.minX),s=Math.max(s,d.d.bounds.maxX),a=Math.min(a,d.d.bounds.minY),A=Math.max(A,d.d.bounds.maxY)):d.d?.center&&(r=Math.min(r,d.d.center.x),s=Math.max(s,d.d.center.x),a=Math.min(a,d.d.center.y),A=Math.max(A,d.d.center.y))}const c=new Map;for(const h of o.regions){const d=h;d.d?.center&&c.set(h.regionId,d.d.center)}const l=[],u=2*(s-r)+2*(A-a);for(const h of i){let d,p;if("startRegion"in h&&h.startRegion){const f=h.startRegion,I=h.endRegion;d=f.d?.center,p=I.d?.center}else"startRegionId"in h&&(d=c.get(h.startRegionId),p=c.get(h.endRegionId));if(!d||!p)continue;const m=h6e(d,r,s,a,A),_=h6e(p,r,s,a,A);l.push([m,_])}let g=0;for(let h=0;h<l.length;h++)for(let d=h+1;d<l.length;d++)m6e(l[h],l[d],u)&&g++;return g})(this.graph,e.inputConnections);this.MAX_ITERATIONS=this.baseMaxIterations+e.inputConnections.length*this.additionalMaxIterationsPerConnection+n*this.additionalMaxIterationsPerCrossing,this.populateDistanceToEndMaps()}populateDistanceToEndMaps(){const e=new Set(this.connections.map(n=>n.endRegion));for(const n of e){const o=new Map,i=[];for(o.set(n.regionId,0),i.push({region:n,distance:0});i.length>0;){const{region:r,distance:s}=i.shift();for(const a of r.ports){const A=a.region1===r?a.region2:a.region1;o.has(A.regionId)||(o.set(A.regionId,s+1),i.push({region:A,distance:s+1}))}}for(const r of this.graph.ports){r.distanceToEndMap||(r.distanceToEndMap={});const s=o.get(r.region1.regionId)??1/0,a=o.get(r.region2.regionId)??1/0;r.distanceToEndMap[n.regionId]=Math.min(s,a)}}}estimateCostToEnd(e){const n=this.currentEndRegion.regionId;return e.distanceToEndMap[n]}getPortUsagePenalty(e){const n=e.ripCount??0;return n*this.portUsagePenalty+n*this.portUsagePenaltySq}isTransitionAllowed(e,n,o){if(!e.d.isPad)return!0;const i=r=>!!(r.region1===e?r.region2:r.region1).d.isThroughJumper;return i(n)||i(o)}computeIncreasedRegionCostIfPortsAreUsed(e,n,o){if(e.d.isPad){const r=(e.assignments??[]).filter(s=>s.connection.mutuallyConnectedNetworkId!==this.currentConnection.mutuallyConnectedNetworkId).length;return r>0?r*this.crossingPenalty+r*this.crossingPenaltySq:0}const i=(function(r,s,a){const A=R1t(r),c=[ZQ(s,r),ZQ(a,r)];let l=0;const u=r.assignments??[];for(const g of u)m6e(c,[ZQ(g.regionPort1,r),ZQ(g.regionPort2,r)],A)&&l++;return l})(e,n,o);return i*this.crossingPenalty+i*this.crossingPenaltySq}getRipsRequiredForPortUsage(e,n,o){if(e.d.isPad)return(e.assignments??[]).filter(s=>s.connection.mutuallyConnectedNetworkId!==this.currentConnection.mutuallyConnectedNetworkId);const i=(function(s,a,A){const c=R1t(s),l=[ZQ(a,s),ZQ(A,s)],u=[],g=s.assignments??[];for(const h of g)m6e(l,[ZQ(h.regionPort1,s),ZQ(h.regionPort2,s)],c)&&u.push(h);return u})(e,n,o),r=i.filter(s=>s.connection.mutuallyConnectedNetworkId!==this.currentConnection.mutuallyConnectedNetworkId);if(!e.d.isThroughJumper)return r;for(const s of e.assignments??[])s.connection.mutuallyConnectedNetworkId!==this.currentConnection.mutuallyConnectedNetworkId&&r.push(s);return r}isRipRequiredForPortUsage(e,n,o){if(!e.d.isThroughJumper&&!e.d.isPad)return!1;for(const i of e.assignments??[])if(i.connection.mutuallyConnectedNetworkId!==this.currentConnection.mutuallyConnectedNetworkId)return!0;return!1}routeSolvedHook(e){}routeStartedHook(e){}visualize(){return Ueo(this)}},qeo={padWidth:.8,outerPadHeight:.5,innerPadHeight:.4,leftPadCenterX:-.9,rightPadCenterX:.9,row1CenterY:-1.2,row2CenterY:-.4,row3CenterY:.4,row4CenterY:1.2},Xeo=({cols:t,rows:e,marginX:n,marginY:o,innerColChannelPointCount:i=1,innerRowChannelPointCount:r=1,regionsBetweenPads:s=!1,outerPaddingX:a=.5,outerPaddingY:A=.5,outerChannelXPointCount:c,outerChannelYPointCount:l,orientation:u="vertical",center:g,bounds:h,parallelTracesUnderJumperCount:d=2})=>{const p=[],m=[],{padWidth:_,outerPadHeight:f,innerPadHeight:I,leftPadCenterX:C,rightPadCenterX:y,row1CenterY:x,row2CenterY:E,row3CenterY:B,row4CenterY:S}=qeo,Q=_/2,w=f/2,M=I/2,k=y-C+_,R=k+n,F=S-x+f,O=F+o;let U=a,Y=A;if(h){const _e=t*k+(t-1)*n,ue=e*F+(e-1)*o;U=((u==="horizontal"?h.maxY-h.minY:h.maxX-h.minX)-_e)/2,Y=((u==="horizontal"?h.maxX-h.minX:h.maxY-h.minY)-ue)/2}const W=c,te=l,j=[],J=[],oe=(_e,ue,fe,pe)=>({regionId:_e,ports:[],d:{bounds:ue,center:f6e(ue),isPad:fe,isThroughJumper:pe}}),ie=(_e,ue,fe)=>{const pe=ue.d.bounds,ye=fe.d.bounds;let Me,ve;Math.abs(pe.maxX-ye.minX)<.001?(Me=pe.maxX,ve=(Math.max(pe.minY,ye.minY)+Math.min(pe.maxY,ye.maxY))/2):Math.abs(pe.minX-ye.maxX)<.001?(Me=pe.minX,ve=(Math.max(pe.minY,ye.minY)+Math.min(pe.maxY,ye.maxY))/2):Math.abs(pe.maxY-ye.minY)<.001?(Me=(Math.max(pe.minX,ye.minX)+Math.min(pe.maxX,ye.maxX))/2,ve=pe.maxY):(Me=(Math.max(pe.minX,ye.minX)+Math.min(pe.maxX,ye.maxX))/2,ve=pe.minY);const he={portId:_e,region1:ue,region2:fe,d:{x:Me,y:ve}};return ue.ports.push(he),fe.ports.push(he),he},ne=(_e,ue,fe,pe)=>{if(pe<=0)return[];if(pe===1)return[ie(_e,ue,fe)];const ye=ue.d.bounds,Me=fe.d.bounds,ve=[];let he,Qe,Pe,we;Math.abs(ye.maxX-Me.minX)<.001?(he=!0,Qe=ye.maxX,Pe=Math.max(ye.minY,Me.minY),we=Math.min(ye.maxY,Me.maxY)):Math.abs(ye.minX-Me.maxX)<.001?(he=!0,Qe=ye.minX,Pe=Math.max(ye.minY,Me.minY),we=Math.min(ye.maxY,Me.maxY)):Math.abs(ye.maxY-Me.minY)<.001?(he=!1,Qe=ye.maxY,Pe=Math.max(ye.minX,Me.minX),we=Math.min(ye.maxX,Me.maxX)):(he=!1,Qe=ye.minY,Pe=Math.max(ye.minX,Me.minX),we=Math.min(ye.maxX,Me.maxX));for(let Te=0;Te<pe;Te++){const Re=Pe+(Te+.5)/pe*(we-Pe),Ee={portId:`${_e}:${Te}`,region1:ue,region2:fe,d:{x:he?Qe:Re,y:he?Re:Qe}};ue.ports.push(Ee),fe.ports.push(Ee),ve.push(Ee)}return ve};for(let _e=0;_e<e;_e++){j[_e]=[];for(let ue=0;ue<t;ue++){const fe=`cell_${_e}_${ue}`,pe=ue*R,ye=-_e*O,Me=pe+C,ve=ye+x,he=pe+C,Qe=ye+E,Pe=pe+C,we=ye+B,Te=pe+C,Re=ye+S,Ee=pe+y,ke=ye+S,Ce=pe+y,Le=ye+B,Ye=pe+y,tt=ye+E,At=pe+y,at=ye+x,nt=(zi,bi,Ar)=>({minX:zi-Q,maxX:zi+Q,minY:bi-Ar,maxY:bi+Ar}),gt=nt(Me,ve,w),bt=nt(he,Qe,M),Ct=nt(Pe,we,M),Dt=nt(Te,Re,w),kt=nt(Ee,ke,w),it=nt(Ce,Le,M),Yt=nt(Ye,tt,M),pn=nt(At,at,w),be={minX:gt.maxX,maxX:pn.minX,minY:gt.minY,maxY:Dt.maxY},et=.3,It={minX:Me,maxX:At,minY:ve-et/2,maxY:ve+et/2},Bt={minX:he,maxX:Ye,minY:Qe-et/2,maxY:Qe+et/2},mt={minX:Pe,maxX:Ce,minY:we-et/2,maxY:we+et/2},st={minX:Te,maxX:Ee,minY:Re-et/2,maxY:Re+et/2},xt=gt.minX,Xe=pn.maxX,Ze=gt.minY,dt=Dt.maxY,Ut=oe(`${fe}:pad1`,gt,!0),Wt=oe(`${fe}:pad2`,bt,!0),Xt=oe(`${fe}:pad3`,Ct,!0),Jt=oe(`${fe}:pad4`,Dt,!0),yn=oe(`${fe}:pad5`,kt,!0),An=oe(`${fe}:pad6`,it,!0),kn=oe(`${fe}:pad7`,Yt,!0),$n=oe(`${fe}:pad8`,pn,!0),ht=oe(`${fe}:underjumper`,be,!1),Kt=oe(`${fe}:throughjumper1`,It,!1,!0),rn=oe(`${fe}:throughjumper2`,Bt,!1,!0),Lt=oe(`${fe}:throughjumper3`,mt,!1,!0),Ho=oe(`${fe}:throughjumper4`,st,!1,!0);p.push(Ut,Wt,Xt,Jt,yn,An,kn,$n,ht,Kt,rn,Lt,Ho);const Ao=(Me+At)/2,qe=(ve+Re)/2;J.push({center:{x:Ao,y:qe},orientation:"vertical",padRegions:[Ut,Wt,Xt,Jt,yn,An,kn,$n]});let vt=null,qt=null,Zt=null,nn=null,zn=null,Nn=null;s&&(vt=oe(`${fe}:L-BP12`,{minX:gt.minX,maxX:gt.maxX,minY:gt.maxY,maxY:bt.minY},!1),qt=oe(`${fe}:L-BP23`,{minX:bt.minX,maxX:bt.maxX,minY:bt.maxY,maxY:Ct.minY},!1),Zt=oe(`${fe}:L-BP34`,{minX:Ct.minX,maxX:Ct.maxX,minY:Ct.maxY,maxY:Dt.minY},!1),nn=oe(`${fe}:R-BP87`,{minX:pn.minX,maxX:pn.maxX,minY:pn.maxY,maxY:Yt.minY},!1),zn=oe(`${fe}:R-BP76`,{minX:Yt.minX,maxX:Yt.maxX,minY:Yt.maxY,maxY:it.minY},!1),Nn=oe(`${fe}:R-BP65`,{minX:it.minX,maxX:it.maxX,minY:it.maxY,maxY:kt.minY},!1),p.push(vt,qt,Zt,nn,zn,Nn));const Co=ue===0,ei=_e===e-1,ro=ue===t-1;let To;ro?To=Xe+U:To=(ue+1)*R+C-Q;let yo=null;_e===0&&(yo=oe(`${fe}:T`,{minX:Co?xt-U:xt,maxX:To,minY:dt,maxY:dt+Y},!1),p.push(yo));let Ro=null;Ro=oe(`${fe}:B`,{minX:Co?xt-U:xt,maxX:To,minY:Ze-(ei?Y:o),maxY:Ze},!1),p.push(Ro);let On=null;Co&&(On=oe(`${fe}:L`,{minX:xt-U,maxX:xt,minY:Ze,maxY:dt},!1),p.push(On));const uo=oe(`${fe}:R`,{minX:Xe,maxX:To,minY:Ze,maxY:dt},!1);if(p.push(uo),j[_e][ue]={pad1:Ut,pad2:Wt,pad3:Xt,pad4:Jt,pad5:yn,pad6:An,pad7:kn,pad8:$n,underjumper:ht,throughjumper1:Kt,throughjumper2:rn,throughjumper3:Lt,throughjumper4:Ho,top:yo,bottom:Ro,left:On,right:uo,leftBP12:vt,leftBP23:qt,leftBP34:Zt,rightBP87:nn,rightBP76:zn,rightBP65:Nn},yo)if(On&&m.push(...ne(`${fe}:T-L`,yo,On,W)),m.push(...ne(`${fe}:T-R`,yo,uo,ro?W:i)),m.push(ie(`${fe}:T-P4`,yo,Jt)),m.push(ie(`${fe}:T-P5`,yo,yn)),s){const zi=ht.d.bounds,bi=(zi.maxX-zi.minX)/(d+1);for(let Ar=1;Ar<=d;Ar++){const ws={portId:`${fe}:T-UJ${Ar}`,region1:yo,region2:ht,d:{x:zi.minX+bi*Ar,y:zi.maxY}};yo.ports.push(ws),ht.ports.push(ws),m.push(ws)}}else m.push(ie(`${fe}:T-UJ`,yo,ht));if(Ro)if(On&&m.push(...ne(`${fe}:B-L`,Ro,On,W)),m.push(...ne(`${fe}:B-R`,Ro,uo,ro?W:i)),m.push(ie(`${fe}:B-P1`,Ro,Ut)),m.push(ie(`${fe}:B-P8`,Ro,$n)),s){const zi=ht.d.bounds,bi=(zi.maxX-zi.minX)/(d+1);for(let Ar=1;Ar<=d;Ar++){const ws={portId:`${fe}:B-UJ${Ar}`,region1:Ro,region2:ht,d:{x:zi.minX+bi*Ar,y:zi.minY}};Ro.ports.push(ws),ht.ports.push(ws),m.push(ws)}}else m.push(ie(`${fe}:B-UJ`,Ro,ht));On&&(m.push(ie(`${fe}:L-P1`,On,Ut)),m.push(ie(`${fe}:L-P2`,On,Wt)),m.push(ie(`${fe}:L-P3`,On,Xt)),m.push(ie(`${fe}:L-P4`,On,Jt))),m.push(ie(`${fe}:R-P5`,uo,yn)),m.push(ie(`${fe}:R-P6`,uo,An)),m.push(ie(`${fe}:R-P7`,uo,kn)),m.push(ie(`${fe}:R-P8`,uo,$n)),s&&(On&&(m.push(ie(`${fe}:L-BP12`,On,vt)),m.push(ie(`${fe}:L-BP23`,On,qt)),m.push(ie(`${fe}:L-BP34`,On,Zt))),m.push(ie(`${fe}:UJ-LBP12`,vt,ht)),m.push(ie(`${fe}:UJ-LBP23`,qt,ht)),m.push(ie(`${fe}:UJ-LBP34`,Zt,ht)),m.push(ie(`${fe}:R-BP87`,uo,nn)),m.push(ie(`${fe}:R-BP76`,uo,zn)),m.push(ie(`${fe}:R-BP65`,uo,Nn)),m.push(ie(`${fe}:UJ-RBP87`,nn,ht)),m.push(ie(`${fe}:UJ-RBP76`,zn,ht)),m.push(ie(`${fe}:UJ-RBP65`,Nn,ht)));const Oo={portId:`${fe}:TJ1-P1`,region1:Kt,region2:Ut,d:{x:Me,y:ve}};Kt.ports.push(Oo),Ut.ports.push(Oo),m.push(Oo);const ko={portId:`${fe}:TJ1-P8`,region1:Kt,region2:$n,d:{x:At,y:at}};Kt.ports.push(ko),$n.ports.push(ko),m.push(ko);const Ko={portId:`${fe}:TJ2-P2`,region1:rn,region2:Wt,d:{x:he,y:Qe}};rn.ports.push(Ko),Wt.ports.push(Ko),m.push(Ko);const mi={portId:`${fe}:TJ2-P7`,region1:rn,region2:kn,d:{x:Ye,y:tt}};rn.ports.push(mi),kn.ports.push(mi),m.push(mi);const Fo={portId:`${fe}:TJ3-P3`,region1:Lt,region2:Xt,d:{x:Pe,y:we}};Lt.ports.push(Fo),Xt.ports.push(Fo),m.push(Fo);const Nr={portId:`${fe}:TJ3-P6`,region1:Lt,region2:An,d:{x:Ce,y:Le}};Lt.ports.push(Nr),An.ports.push(Nr),m.push(Nr);const Rs={portId:`${fe}:TJ4-P4`,region1:Ho,region2:Jt,d:{x:Te,y:Re}};Ho.ports.push(Rs),Jt.ports.push(Rs),m.push(Rs);const ur={portId:`${fe}:TJ4-P5`,region1:Ho,region2:yn,d:{x:Ee,y:ke}};if(Ho.ports.push(ur),yn.ports.push(ur),m.push(ur),ue>0){const zi=j[_e][ue-1];m.push(ie(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:R-P1`,zi.right,Ut)),m.push(ie(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:R-P2`,zi.right,Wt)),m.push(ie(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:R-P3`,zi.right,Xt)),m.push(ie(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:R-P4`,zi.right,Jt)),s&&(m.push(ie(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:R-LBP12`,zi.right,vt)),m.push(ie(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:R-LBP23`,zi.right,qt)),m.push(ie(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:R-LBP34`,zi.right,Zt))),yo&&zi.top&&m.push(...ne(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:T-T`,zi.top,yo,te)),Ro&&zi.bottom&&m.push(...ne(`cell_${_e}_${ue-1}->cell_${_e}_${ue}:B-B`,zi.bottom,Ro,ei?te:r))}if(_e>0){const zi=j[_e-1][ue];if(On&&m.push(...ne(`cell_${_e-1}_${ue}->cell_${_e}_${ue}:B-L`,zi.bottom,On,W)),m.push(ie(`cell_${_e-1}_${ue}->cell_${_e}_${ue}:B-P4`,zi.bottom,Jt)),s){const bi=ht.d.bounds,Ar=(bi.maxX-bi.minX)/(d+1);for(let ws=1;ws<=d;ws++){const ds=bi.minX+Ar*ws,Et={portId:`cell_${_e-1}_${ue}->cell_${_e}_${ue}:B-UJ${ws}`,region1:zi.bottom,region2:ht,d:{x:ds,y:bi.maxY}};zi.bottom.ports.push(Et),ht.ports.push(Et),m.push(Et)}}else m.push(ie(`cell_${_e-1}_${ue}->cell_${_e}_${ue}:B-UJ`,zi.bottom,ht));m.push(ie(`cell_${_e-1}_${ue}->cell_${_e}_${ue}:B-P5`,zi.bottom,yn)),m.push(...ne(`cell_${_e-1}_${ue}->cell_${_e}_${ue}:B-R`,zi.bottom,uo,ro?W:i))}}}let le={regions:p,ports:m,jumperLocations:J};const ge=u==="horizontal";if(ge||g!==void 0||h!==void 0){const _e=k1t(le.regions),ue=f6e(_e),fe=[];let pe;pe=g||(h?f6e(h):ue),fe.push(Pae(pe.x,pe.y)),ge&&fe.push((function(Me,ve,he){const Qe=Geo(Me),Pe=Yeo(Me),we={a:Qe,c:-Pe,e:0,b:Pe,d:Qe,f:0};return G1t(ve)||G1t(he)?we:_6e([Pae(ve,he),we,Pae(-ve,-he)])})(-Math.PI/2)),fe.push(Pae(-ue.x,-ue.y));const ye=(function(...Me){return _6e(...Me)})(...fe);le=Y1t(le,ye)}return le},U1t=!0,eJ={CCW:-1,CW:1,NOT_ORIENTABLE:0},Zeo=2*Math.PI,Mae=Object.freeze({__proto__:null,BOUNDARY:2,CCW:U1t,CONTAINS:3,CW:!1,END_VERTEX:2,INSIDE:1,INTERLACE:4,NOT_VERTEX:0,ORIENTATION:eJ,OUTSIDE:0,OVERLAP_OPPOSITE:2,OVERLAP_SAME:1,PIx2:Zeo,START_VERTEX:1}),u7=1e-6;function K1t(t){u7=t}function V1t(){return u7}function C6e(t){return t<u7&&t>-u7}function UD(t,e){return t-e<u7&&t-e>-u7}function z1t(t,e){return t-e>u7}function J1t(t,e){return t-e<-u7}var Ve={Utils:Object.freeze({__proto__:null,DECIMALS:3,EQ:UD,EQ_0:C6e,GE:function(t,e){return t-e>-u7},GT:z1t,LE:function(t,e){return t-e<u7},LT:J1t,getTolerance:V1t,setTolerance:K1t}),Errors:void 0,Matrix:void 0,Planar_set:void 0,Point:void 0,Vector:void 0,Line:void 0,Circle:void 0,Segment:void 0,Arc:void 0,Box:void 0,Edge:void 0,Face:void 0,Ray:void 0,Ray_shooting:void 0,Multiline:void 0,Polygon:void 0,Distance:void 0,Inversion:void 0};for(let t in Mae)Ve[t]=Mae[t];Object.defineProperty(Ve,"DP_TOL",{get:function(){return V1t()},set:function(t){K1t(t)}});var ld=class{static get ILLEGAL_PARAMETERS(){return new ReferenceError("Illegal Parameters")}static get ZERO_DIVISION(){return new Error("Zero division")}static get UNRESOLVED_BOUNDARY_CONFLICT(){return new Error("Unresolved boundary conflict in boolean operation")}static get INFINITE_LOOP(){return new Error("Infinite loop")}static get CANNOT_COMPLETE_BOOLEAN_OPERATION(){return new Error("Cannot complete boolean operation")}static get CANNOT_INVOKE_ABSTRACT_METHOD(){return new Error("Abstract method cannot be invoked")}static get OPERATION_IS_NOT_SUPPORTED(){return new Error("Operation is not supported")}static get UNSUPPORTED_SHAPE_TYPE(){return new Error("Unsupported shape type")}};Ve.Errors=ld;var y6e=class{constructor(e,n){this.first=e,this.last=n||this.first}[Symbol.iterator](){let e;return{next:()=>(e=e?e.next:this.first,{value:e,done:e===void 0})}}get size(){let e=0;for(let n of this)e++;return e}toArray(e=void 0,n=void 0){let o=[],i=e||this.first,r=n||this.last,s=i;if(s===void 0)return o;do o.push(s),s=s.next;while(s!==r.next);return o}append(e){return this.isEmpty()?this.first=e:(e.prev=this.last,this.last.next=e),this.last=e,this.last.next=void 0,this.first.prev=void 0,this}insert(e,n){if(this.isEmpty())this.first=e,this.last=e;else if(n==null)e.next=this.first,this.first.prev=e,this.first=e;else{let o=n.next;n.next=e,o&&(o.prev=e),e.prev=n,e.next=o,this.last===n&&(this.last=e)}return this.last.next=void 0,this.first.prev=void 0,this}remove(e){return e===this.first&&e===this.last?(this.first=void 0,this.last=void 0):(e.prev&&(e.prev.next=e.next),e.next&&(e.next.prev=e.prev),e===this.first&&(this.first=e.next),e===this.last&&(this.last=e.prev)),this}isEmpty(){return this.first===void 0}static testInfiniteLoop(e){let n=e,o=e;do{if(n!=e&&n===o)throw ld.INFINITE_LOOP;n=n.next,o=o.next.next}while(n!=e)}},W1t={stroke:"black"},eto=class{constructor(t=W1t){for(const e in t)this[e]=t[e];this.stroke=t.stroke??W1t.stroke}toAttributesString(){return Object.keys(this).reduce((t,e)=>t+(this[e]!==void 0?this.toAttrString(e,this[e]):""),"")}toAttrString(t,e){const n=t==="className"?"class":this.convertCamelToKebabCase(t);return e===null?`${n} `:`${n}="${e.toString()}" `}convertCamelToKebabCase(t){return t.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join("-").toLowerCase()}};function KD(t){return new eto(t).toAttributesString()}function cL(t,e){let n=[],[o,i,r]=t.standard,[s,a,A]=e.standard,c=o*a-i*s,l=r*a-i*A,u=o*A-r*s;if(!Ve.Utils.EQ_0(c)){let g,h;i===0?(g=r/o,h=u/c):a===0?(g=A/s,h=u/c):o===0?(g=l/c,h=r/i):s===0?(g=l/c,h=A/a):(g=l/c,h=u/c),n.push(new Ve.Point(g,h))}return n}function VD(t,e){let n=[],o=e.pc.projectionOn(t),i=e.pc.distanceTo(o)[0];if(Ve.Utils.EQ(i,e.r))n.push(o);else if(Ve.Utils.LT(i,e.r)){let r,s,a=Math.sqrt(e.r*e.r-i*i);r=t.norm.rotate90CCW().multiply(a),s=o.translate(r),n.push(s),r=t.norm.rotate90CW().multiply(a),s=o.translate(r),n.push(s)}return n}function lL(t,e){let n=[];for(let o of e.toSegments()){let i=tJ(o,t);for(let r of i)iIt(r,n)||n.push(r)}return n}function Dae(t,e){let n=[];if(lL(t,e.box).length===0)return n;let o=VD(t,new Ve.Circle(e.pc,e.r));for(let i of o)i.on(e)&&n.push(i);return n}function tJ(t,e){let n=[];return t.ps.on(e)&&n.push(t.ps),t.pe.on(e)&&!t.isZeroLength()&&n.push(t.pe),n.length>0||t.isZeroLength()||t.ps.leftTo(e)&&t.pe.leftTo(e)||!t.ps.leftTo(e)&&!t.pe.leftTo(e)?n:cL(new Ve.Line(t.ps,t.pe),e)}function Nae(t,e){let n=[];if(t.isZeroLength())return t.ps.on(e)&&n.push(t.ps),n;if(e.isZeroLength())return e.ps.on(t)&&n.push(e.ps),n;let o=new Ve.Line(t.ps,t.pe),i=new Ve.Line(e.ps,e.pe);if(o.incidentTo(i))t.ps.on(e)&&n.push(t.ps),t.pe.on(e)&&n.push(t.pe),!e.ps.on(t)||e.ps.equalTo(t.ps)||e.ps.equalTo(t.pe)||n.push(e.ps),!e.pe.on(t)||e.pe.equalTo(t.ps)||e.pe.equalTo(t.pe)||n.push(e.pe);else{let r=cL(o,i);r.length>0&&j1t(r[0],t)&&j1t(r[0],e)&&n.push(r[0])}return n}function j1t(t,e){const n=e.box;return Ve.Utils.LE(t.x,n.xmax)&&Ve.Utils.GE(t.x,n.xmin)&&Ve.Utils.LE(t.y,n.ymax)&&Ve.Utils.GE(t.y,n.ymin)}function Rae(t,e){let n=[];if(t.isZeroLength()){let[i,r]=t.ps.distanceTo(e.pc);return Ve.Utils.EQ(i,e.r)&&n.push(t.ps),n}let o=VD(new Ve.Line(t.ps,t.pe),e);for(let i of o)i.on(t)&&n.push(i);return n}function uL(t,e){let n=[];if(t.isZeroLength())return t.ps.on(e)&&n.push(t.ps),n;let o=VD(new Ve.Line(t.ps,t.pe),new Ve.Circle(e.pc,e.r));for(let i of o)i.on(t)&&i.on(e)&&n.push(i);return n}function $1t(t,e){let n=[],o=new Ve.Vector(t.pc,e.pc),i=t.r,r=e.r;if(Ve.Utils.EQ_0(i)||Ve.Utils.EQ_0(r))return n;if(Ve.Utils.EQ_0(o.x)&&Ve.Utils.EQ_0(o.y)&&Ve.Utils.EQ(i,r))return n.push(t.pc.translate(-i,0)),n;let s,a=t.pc.distanceTo(e.pc)[0];if(Ve.Utils.GT(a,i+r)||Ve.Utils.LT(a,Math.abs(i-r)))return n;if(o.x/=a,o.y/=a,Ve.Utils.EQ(a,i+r)||Ve.Utils.EQ(a,Math.abs(i-r)))return s=t.pc.translate(i*o.x,i*o.y),n.push(s),n;let A=i*i/(2*a)-r*r/(2*a)+a/2,c=t.pc.translate(A*o.x,A*o.y),l=Math.sqrt(i*i-A*A);return s=c.translate(o.rotate90CCW().multiply(l)),n.push(s),s=c.translate(o.rotate90CW().multiply(l)),n.push(s),n}function q1t(t,e){let n=[];if(t.pc.equalTo(e.pc)&&Ve.Utils.EQ(t.r,e.r)){let s;return s=t.start,s.on(e)&&n.push(s),s=t.end,s.on(e)&&n.push(s),s=e.start,s.on(t)&&n.push(s),s=e.end,s.on(t)&&n.push(s),n}let o=new Ve.Circle(t.pc,t.r),i=new Ve.Circle(e.pc,e.r),r=o.intersect(i);for(let s of r)s.on(t)&&s.on(e)&&n.push(s);return n}function x6e(t,e){let n=[];if(e.pc.equalTo(t.pc)&&Ve.Utils.EQ(e.r,t.r))return n.push(t.start),n.push(t.end),n;let o=$1t(e,new Ve.Circle(t.pc,t.r));for(let i of o)i.on(t)&&n.push(i);return n}function X1t(t,e){return t.isSegment?Nae(t.shape,e):uL(e,t.shape)}function Z1t(t,e){return t.isSegment?uL(t.shape,e):q1t(t.shape,e)}function eIt(t,e){return t.isSegment?tJ(t.shape,e):Dae(e,t.shape)}function tto(t,e){return t.isSegment?Rae(t.shape,e):x6e(t.shape,e)}function E6e(t,e){let n=[];for(let o of e.edges)for(let i of X1t(o,t))n.push(i);return n}function B6e(t,e){let n=[];for(let o of e.edges)for(let i of Z1t(o,t))n.push(i);return n}function nJ(t,e){let n=[];if(e.isEmpty())return n;for(let o of e.edges)for(let i of eIt(o,t))iIt(i,n)||n.push(i);return t.sortPoints(n)}function tIt(t,e){let n=[];if(e.isEmpty())return n;for(let o of e.edges)for(let i of tto(o,t))n.push(i);return n}function nIt(t,e){return t.isSegment?X1t(e,t.shape):t.isArc?Z1t(e,t.shape):t.isLine?eIt(e,t.shape):t.isRay?(n=e,o=t.shape,n.isSegment?b6e(o,n.shape):S6e(o,n.shape)):[];var n,o}function oIt(t,e){let n=[];if(e.isEmpty()||t.shape.box.not_intersect(e.box))return n;let o=e.edges.search(t.shape.box);for(let i of o)n=[...n,...nIt(t,i)];return n}function iIt(t,e){return e.some(n=>n.equalTo(t))}function nv(t){return new Ve.Line(t.start,t.norm)}function b6e(t,e){return tJ(e,nv(t)).filter(n=>t.contains(n))}function S6e(t,e){return Dae(nv(t),e).filter(n=>t.contains(n))}function rIt(t,e){return VD(nv(t),e).filter(n=>t.contains(n))}function sIt(t,e){return cL(nv(t),e).filter(n=>t.contains(n))}function aIt(t,e){return nJ(nv(t),e).filter(n=>t.contains(n))}function AIt(t,e){if(t.intersect&&t.intersect instanceof Function)return t.intersect(e);throw ld.UNSUPPORTED_SHAPE_TYPE}function gL(t,e){let n=[];for(let o of e)n=[...n,...AIt(t,o.shape)];return n}var zD=class zte extends y6e{constructor(...e){if(super(),this.isInfinite=!1,e.length===1&&e[0]instanceof Array&&e[0].length>0){const n=e[0],o=n.length,i=s=>s instanceof Ve.Segment||s instanceof Ve.Arc||s instanceof Ve.Ray,r=s=>s instanceof Ve.Segment||s instanceof Ve.Arc;if(!(o===1&&(s=>s instanceof Ve.Segment||s instanceof Ve.Arc||s instanceof Ve.Ray||s instanceof Ve.Line)(n[0])||o>1&&i(n[0])&&i(n[o-1])&&n.slice(1,o-1).every(r)))throw Ve.Errors.ILLEGAL_PARAMETERS;this.isInfinite=n.some(s=>s instanceof Ve.Ray||s instanceof Ve.Line);for(let s of n){let a=new Ve.Edge(s);this.append(a)}this.setArcLength()}}get edges(){return[...this]}get box(){return this.edges.reduce((e,n)=>e.merge(n.box),new Ve.Box)}get vertices(){let e=this.edges.map(n=>n.start);return e.push(this.last.end),e}get length(){if(this.isEmpty())return 0;if(this.isInfinite)return Number.POSITIVE_INFINITY;let e=0;for(let n of this)e+=n.length;return e}clone(){return new zte(this.toShapes())}setArcLength(){for(let e of this)this.setOneEdgeArcLength(e)}setOneEdgeArcLength(e){e===this.first?e.arc_length=0:e.arc_length=e.prev.arc_length+e.prev.length}pointAtLength(e){if(e>this.length||e<0||this.isInfinite)return null;let n=null;for(let o of this)if(e>=o.arc_length&&(o===this.last||e<o.next.arc_length)){n=o.pointAtLength(e-o.arc_length);break}return n}addVertex(e,n){let o=n.shape.split(e);if(o[0]===null)return n.prev;if(o[1]===null)return n;let i=new Ve.Edge(o[0]),r=n.prev;return this.insert(i,r),n.shape=o[1],i}getChain(e,n){let o=[];for(let i=e;i!==n.next;i=i.next)o.push(i);return o}split(e){for(let n of e){let o=this.findEdgeByPoint(n);this.addVertex(n,o)}return this}findEdgeByPoint(e){let n;for(let o of this)if(o.shape.contains(e)){n=o;break}return n}distanceTo(e){if(e instanceof Point){const[n,o]=Ve.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ve.Line){const[n,o]=Ve.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ve.Circle){const[n,o]=Ve.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ve.Segment){const[n,o]=Ve.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ve.Arc){const[n,o]=Ve.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ve.Multiline)return Ve.Distance.multiline2multiline(this,e);throw Ve.Errors.UNSUPPORTED_SHAPE_TYPE}intersect(e){return e instanceof Ve.Multiline?(function(n,o){let i=[];for(let r of n)for(let s of o)i=[...i,...AIt(r.shape,s.shape)];return i})(this,e):gL(e,this)}contains(e){if(e instanceof Ve.Point)return this.edges.some(n=>n.shape.contains(e));throw Ve.Errors.UNSUPPORTED_SHAPE_TYPE}translate(e){return new zte(this.edges.map(n=>n.shape.translate(e)))}rotate(e=0,n=new Ve.Point){return new zte(this.edges.map(o=>o.shape.rotate(e,n)))}transform(e=new Ve.Matrix){return new zte(this.edges.map(n=>n.shape.transform(e)))}toShapes(){return this.edges.map(e=>e.shape.clone())}toJSON(){return this.edges.map(e=>e.toJSON())}svgPoints(){return this.vertices.map(e=>`${e.x},${e.y}`).join(" ")}dpath(){let e=`M${this.first.start.x},${this.first.start.y}`;for(let n of this)e+=n.svg();return e}svg(e={}){let n=`
<path ${KD({fill:"none",...e})} d="`;n+=`
M${this.first.start.x},${this.first.start.y}`;for(let o of this)n+=o.svg();return n+=`" >
</path>`,n}};Ve.Multiline=zD;function dL(t,e,n){let o=n.length,i=t.shape.split(e);if(i.length===0)return;let r=0;r=i[0]===null?0:i[1]===null?t.shape.length:i[0].length;let s,a=0;UD(r,0)&&(a|=1),UD(r,t.shape.length)&&(a|=2),s=r===1/0?i[0].coord(e):2&a&&t.next&&t.next.arc_length===0?0:t.arc_length+r,n.push({id:o,pt:e,arc_length:s,edge_before:t,edge_after:void 0,face:t.face,is_vertex:a})}function oJ(t){t.int_points1_sorted=ov(t.int_points1),t.int_points2_sorted=ov(t.int_points2)}function ov(t){let e=new Map,n=0;for(let o of t)e.has(o.face)||(e.set(o.face,n),n++);for(let o of t)o.faceId=e.get(o.face);return t.slice().sort(nto)}function nto(t,e){return t.faceId<e.faceId?-1:t.faceId>e.faceId?1:t.arc_length<e.arc_length?-1:t.arc_length>e.arc_length?1:0}function Q6e(t){if(t.int_points1.length<2)return;let e,n,o,i,r=!1;for(let s=0;s<t.int_points1_sorted.length;s++)if(t.int_points1_sorted[s].id!==-1){e=t.int_points1_sorted[s],n=t.int_points2[e.id];for(let a=s+1;a<t.int_points1_sorted.length&&(o=t.int_points1_sorted[a],UD(o.arc_length,e.arc_length));a++)o.id!==-1&&(i=t.int_points2[o.id],i.id!==-1&&o.edge_before===e.edge_before&&o.edge_after===e.edge_after&&i.edge_before===n.edge_before&&i.edge_after===n.edge_after&&(o.id=-1,i.id=-1,r=!0))}n=t.int_points2_sorted[0],e=t.int_points1[n.id];for(let s=1;s<t.int_points2_sorted.length;s++){let a=t.int_points2_sorted[s];if(a.id===-1)continue;if(n.id===-1||!UD(a.arc_length,n.arc_length)){n=a,e=t.int_points1[n.id];continue}let A=t.int_points1[a.id];A.edge_before===e.edge_before&&A.edge_after===e.edge_after&&a.edge_before===n.edge_before&&a.edge_after===n.edge_after&&(A.id=-1,a.id=-1,r=!0)}r&&(t.int_points1=t.int_points1.filter(s=>s.id>=0),t.int_points2=t.int_points2.filter(s=>s.id>=0),t.int_points1.forEach((s,a)=>s.id=a),t.int_points2.forEach((s,a)=>s.id=a))}function v6e(t){for(let e of t)e.edge_before&&(e.edge_before.bvStart=void 0,e.edge_before.bvEnd=void 0,e.edge_before.bv=void 0,e.edge_before.overlap=void 0),e.edge_after&&(e.edge_after.bvStart=void 0,e.edge_after.bvEnd=void 0,e.edge_after.bv=void 0,e.edge_after.overlap=void 0);for(let e of t)e.edge_before&&(e.edge_before.bvEnd=2),e.edge_after&&(e.edge_after.bvStart=2)}function w6e(t,e){for(let n of t)n.edge_before&&n.edge_before.setInclusion(e),n.edge_after&&n.edge_after.setInclusion(e)}function hL(t,e,n){let o,i,r=1;if(t.length===1)return 1;o=t[e];for(let s=e+1;s<t.length&&o.face===n&&(i=t[s],i.pt.equalTo(o.pt)&&i.edge_before===o.edge_before&&i.edge_after===o.edge_after);s++)r++;return r}function pL(t,e){if(e){for(let n of e){let o=n.edge_before;if(n.is_vertex=0,o.shape.start&&o.shape.start.equalTo(n.pt)&&(n.is_vertex|=1),o.shape.end&&o.shape.end.equalTo(n.pt)&&(n.is_vertex|=2),1&n.is_vertex){n.edge_before=o.prev,o.prev&&(n.is_vertex=2);continue}if(2&n.is_vertex)continue;let i=t.addVertex(n.pt,o);n.edge_before=i}for(let n of e)n.edge_before?n.edge_after=n.edge_before.next:t instanceof zD&&1&n.is_vertex&&(n.edge_after=t.first)}}function cIt(t,e,n){const o=t.edge_before,i=e.edge_after,r=n.length;o.next=n[0],n[0].prev=o,n[r-1].next=i,i.prev=n[r-1]}Ve.multiline=(...t)=>new Ve.Multiline(...t);var{INSIDE:g7,OUTSIDE:d7,BOUNDARY:jf,OVERLAP_SAME:oto,OVERLAP_OPPOSITE:ito}=Mae,{NOT_VERTEX:Ghr,START_VERTEX:lIt,END_VERTEX:uIt}=Mae;function P6e(t,e){let n=e.clone().reverse(),[o]=iJ(t,n,3,!0);return o}function gIt(t,e){let[n]=iJ(t,e,2,!0);return n}function dIt(t,e){let[n,o]=iJ(t,e,2,!1),i=[];for(let s of n.faces)i=[...i,...[...s.edges].map(a=>a.shape)];let r=[];for(let s of o.faces)r=[...r,...[...s.edges].map(a=>a.shape)];return[i,r]}function M6e(t,e){let[n]=iJ(t,e,3,!1),o=[];for(let i of n.faces)o=[...o,...[...i.edges].map(r=>r.shape)];return o}function hIt(t,e){let n=t.clone(),o=e.clone(),i=pIt(n,o);return oJ(i),pL(n,i.int_points1_sorted),pL(o,i.int_points2_sorted),Q6e(i),oJ(i),[i.int_points1_sorted.map(r=>r.pt),i.int_points2_sorted.map(r=>r.pt)]}function rto(t,e,n,o){let i=mIt(t,n.int_points1),r=mIt(e,n.int_points2);for(_It(i,e),_It(r,t),v6e(n.int_points1),v6e(n.int_points2),w6e(n.int_points1,e),w6e(n.int_points2,t);sto(t,e,n.int_points1,n.int_points1_sorted,n.int_points2,n););(function(s){let a,A,c,l=s.int_points1.length;for(let u=0;u<l;u++){let g=s.int_points1_sorted[u];g.face!==a&&(A=u,a=g.face);let h,d=u,p=hL(s.int_points1_sorted,u,a);h=d+p<l&&s.int_points1_sorted[d+p].face===a?d+p:A;let m=hL(s.int_points1_sorted,h,a);c=null;for(let E=h;E<h+m;E++){let B=s.int_points1_sorted[E];if(B.face===a&&s.int_points2[B.id].face===s.int_points2[g.id].face){c=B;break}}if(c===null)continue;let _=g.edge_after,f=c.edge_before;if(_.bv!==2||f.bv!==2||_!==f)continue;let I=s.int_points2[g.id],C=s.int_points2[c.id],y=I.edge_after,x=C.edge_before;y.bv===2&&x.bv===2&&y===x||(I=s.int_points2[c.id],C=s.int_points2[g.id],y=I.edge_after,x=C.edge_before),y.bv===2&&x.bv===2&&y===x&&_.setOverlap(y)}})(n),D6e(t,o,n.int_points1_sorted,!0),D6e(e,o,n.int_points2_sorted,!1),fIt(t,i,o,!0),fIt(e,r,o,!1)}function iJ(t,e,n,o){let i=t.clone(),r=e.clone(),s=pIt(i,r);return oJ(s),pL(i,s.int_points1_sorted),pL(r,s.int_points2_sorted),Q6e(s),oJ(s),rto(i,r,s,n),o&&(function(a,A,c){(function(l,u,g,h){for(let d of u.faces){for(let p of d)l.edges.add(p);h.find(p=>p.face===d)===void 0&&l.addFace(d.first,d.last)}})(a,A,0,c.int_points2),(function(l,u,g){if(g.int_points1.length!==0)for(let h=0;h<g.int_points1.length;h++){let d=g.int_points1[h],p=g.int_points2[h];if(d.edge_before!==void 0&&d.edge_after===void 0&&p.edge_before===void 0&&p.edge_after!==void 0&&(d.edge_before.next=p.edge_after,p.edge_after.prev=d.edge_before,d.edge_after=p.edge_after,p.edge_before=d.edge_before),p.edge_before!==void 0&&p.edge_after===void 0&&d.edge_before===void 0&&d.edge_after!==void 0&&(p.edge_before.next=d.edge_after,d.edge_after.prev=p.edge_before,p.edge_after=d.edge_after,d.edge_before=p.edge_before),d.edge_before!==void 0&&d.edge_after===void 0)for(let m of g.int_points1_sorted)m!==d&&m.edge_before===void 0&&m.edge_after!==void 0&&m.pt.equalTo(d.pt)&&(d.edge_before.next=m.edge_after,m.edge_after.prev=d.edge_before,d.edge_after=m.edge_after,m.edge_before=d.edge_before);if(p.edge_before!==void 0&&p.edge_after===void 0)for(let m of g.int_points2_sorted)m!==p&&m.edge_before===void 0&&m.edge_after!==void 0&&m.pt.equalTo(p.pt)&&(p.edge_before.next=m.edge_after,m.edge_after.prev=p.edge_before,p.edge_after=m.edge_after,m.edge_before=p.edge_before)}})(0,0,c),N6e(a,c.int_points1),N6e(A,c.int_points2),R6e(a,c.int_points1,c.int_points2),R6e(a,c.int_points2,c.int_points1)})(i,r,s),[i,r]}function pIt(t,e){let n={int_points1:[],int_points2:[]};for(let o of t.edges){let i=e.edges.search(o.box);for(let r of i){let s=o.shape.intersect(r.shape);for(let a of s)dL(o,a,n.int_points1),dL(r,a,n.int_points2)}}return n}function mIt(t,e){let n=[];for(let o of t.faces)e.find(i=>i.face===o)||n.push(o);return n}function _It(t,e){for(let n of t)n.first.bv=n.first.bvStart=n.first.bvEnd=void 0,n.first.setInclusion(e)}function sto(t,e,n,o,i,r){let s,a,A,c=o.length,l=!1;for(let u=0;u<c;u++){let g=o[u];g.face!==s&&(a=u,s=g.face);let h,d=u,p=hL(o,u,s);h=d+p<c&&o[d+p].face===s?d+p:a;let m=hL(o,h,s);A=null;for(let I=h;I<h+m;I++){let C=o[I];if(C.face===s&&i[C.id].face===i[g.id].face){A=C;break}}if(A===null)continue;let _=g.edge_after,f=A.edge_before;if(_.bv!==jf||f.bv==jf)if(_.bv==jf||f.bv!==jf){if(_.bv===jf&&f.bv===jf&&_!=f||_.bv===g7&&f.bv===d7||_.bv===d7&&f.bv===g7){let I=_.next;for(;I!=f;)I.bvStart=void 0,I.bvEnd=void 0,I.bv=void 0,I.setInclusion(e),I=I.next}if(_.bv===jf&&f.bv===jf&&_!=f){let I,C=_.next;for(;C!=f;){if(C.bv!=jf){if(I===void 0)I=C.bv;else if(C.bv!=I)throw ld.UNRESOLVED_BOUNDARY_CONFLICT}C=C.next}I!=null&&(_.bv=I,f.bv=I);continue}if(_.bv===g7&&f.bv===d7||_.bv===d7&&f.bv===g7){let I=_;for(;I!=f;){if(I.bvStart===_.bv&&I.bvEnd===f.bv){let[C,y]=I.shape.distanceTo(e);if(C<10*Ve.DP_TOL){dL(I,y.ps,n);let x=n[n.length-1];if(x.is_vertex&lIt)x.edge_after=I,x.edge_before=I.prev,I.bvStart=jf,I.bv=void 0,I.setInclusion(e);else if(x.is_vertex&uIt)x.edge_after=I.next,I.bvEnd=jf,I.bv=void 0,I.setInclusion(e);else{let S=e.addVertex(x.pt,I);x.edge_before=S,x.edge_after=S.next,S.setInclusion(e),S.next.bvStart=jf,S.next.bvEnd=void 0,S.next.bv=void 0,S.next.setInclusion(e)}let E=e.findEdgeByPoint(y.pe);dL(E,y.pe,i);let B=i[i.length-1];if(B.is_vertex&lIt)B.edge_after=E,B.edge_before=E.prev;else if(B.is_vertex&uIt)B.edge_after=E.next;else{let S=i.find(w=>w.edge_after===E),Q=e.addVertex(B.pt,E);B.edge_before=Q,B.edge_after=Q.next,S&&(S.edge_after=Q),Q.bvStart=void 0,Q.bvEnd=jf,Q.bv=void 0,Q.setInclusion(t),Q.next.bvStart=jf,Q.next.bvEnd=void 0,Q.next.bv=void 0,Q.next.setInclusion(t)}oJ(r),l=!0;break}}I=I.next}if(l)break;throw ld.UNRESOLVED_BOUNDARY_CONFLICT}}else f.bv=_.bv;else _.bv=f.bv}return l}function D6e(t,e,n,o){if(!n)return;let i,r,s,a;for(let A=0;A<n.length;A++){if(s=n[A],s.face!==i&&(r=A,i=s.face),i.isEmpty())continue;let c,l=A,u=hL(n,A,i);c=l+u<n.length&&n[l+u].face===s.face?l+u:r,a=n[c];let g=c,h=hL(n,g,i),d=s.edge_after,p=a.edge_before;if(d.bv===g7&&p.bv===g7&&e===1||d.bv===d7&&p.bv===d7&&e===2||(d.bv===d7||p.bv===d7)&&e===3&&!o||(d.bv===g7||p.bv===g7)&&e===3&&o||d.bv===jf&&p.bv===jf&&d.overlap&oto&&o||d.bv===jf&&p.bv===jf&&d.overlap&ito){t.removeChain(i,d,p);for(let m=l;m<l+u;m++)n[m].edge_after=void 0;for(let m=g;m<g+h;m++)n[m].edge_before=void 0}A+=u-1}}function N6e(t,e){for(let n of e)t.faces.delete(n.face),n.face=void 0,n.edge_before&&(n.edge_before.face=void 0),n.edge_after&&(n.edge_after.face=void 0)}function R6e(t,e,n){for(let o of e){if(o.edge_before===void 0||o.edge_after===void 0||o.face||o.edge_after.face||o.edge_before.face)continue;let i=o.edge_after,r=o.edge_before;try{y6e.testInfiniteLoop(i)}catch{throw ld.CANNOT_COMPLETE_BOOLEAN_OPERATION}let s=t.addFace(i,r);for(let a of e)a.edge_before&&a.edge_after&&a.edge_before.face===s&&a.edge_after.face===s&&(a.face=s);for(let a of n)a.edge_before&&a.edge_after&&a.edge_before.face===s&&a.edge_after.face===s&&(a.face=s)}}function fIt(t,e,n,o){for(let i of e){let r=i.first.bv;(n===1&&r===g7||n===3&&r===g7&&o||n===3&&r===d7&&!o||n===2&&r===d7)&&t.deleteFace(i)}}var ato=Object.freeze({__proto__:null,BOOLEAN_INTERSECT:2,BOOLEAN_SUBTRACT:3,BOOLEAN_UNION:1,calculateIntersections:hIt,innerClip:dIt,intersect:gIt,outerClip:M6e,removeNotRelevantChains:D6e,removeOldFaces:N6e,restoreFaces:R6e,subtract:P6e,unify:function(t,e){let[n]=iJ(t,e,1,!0);return n}}),Ato=RegExp("T.F..FFF.|T.F...F.."),cto=RegExp("T........|.T.......|...T.....|....T...."),lto=RegExp("FT.......|F..T.....|F...T...."),uto=RegExp("T.F..F..."),gto=RegExp("T.F..F...|.TF..F...|..FT.F...|..F.TF..."),mL=class{constructor(){this.m=new Array(9).fill(void 0)}get I2I(){return this.m[0]}set I2I(e){this.m[0]=e}get I2B(){return this.m[1]}set I2B(e){this.m[1]=e}get I2E(){return this.m[2]}set I2E(e){this.m[2]=e}get B2I(){return this.m[3]}set B2I(e){this.m[3]=e}get B2B(){return this.m[4]}set B2B(e){this.m[4]=e}get B2E(){return this.m[5]}set B2E(e){this.m[5]=e}get E2I(){return this.m[6]}set E2I(e){this.m[6]=e}get E2B(){return this.m[7]}set E2B(e){this.m[7]=e}get E2E(){return this.m[8]}set E2E(e){this.m[8]=e}toString(){return this.m.map(e=>e instanceof Array&&e.length>0?"T":e instanceof Array&&e.length===0?"F":"*").join("")}equal(){return Ato.test(this.toString())}intersect(){return cto.test(this.toString())}touch(){return lto.test(this.toString())}inside(){return uto.test(this.toString())}covered(){return gto.test(this.toString())}};function rJ(t,e){let n,o=new Ve.Ray(e),i=new Ve.Line(o.pt,o.norm);const r=new Ve.Box(o.box.xmin-Ve.DP_TOL,o.box.ymin-Ve.DP_TOL,o.box.xmax+Ve.DP_TOL,o.box.ymax+Ve.DP_TOL);if(t.box.not_intersect(r))return Ve.OUTSIDE;let s=t.edges.search(r);if(s.length===0)return Ve.OUTSIDE;for(let l of s)if(l.shape.contains(e))return Ve.BOUNDARY;let a=[...t.faces],A=[];for(let l of s)for(let u of o.intersect(l.shape)){if(u.equalTo(e))return Ve.BOUNDARY;A.push({pt:u,edge:l,face_index:a.indexOf(l.face)})}A.sort((l,u)=>J1t(l.pt.x,u.pt.x)?-1:z1t(l.pt.x,u.pt.x)?1:l.face_index<u.face_index?-1:l.face_index>u.face_index?1:l.edge.arc_length<u.edge.arc_length?-1:l.edge.arc_length>u.edge.arc_length?1:0);let c=0;for(let l=0;l<A.length;l++){let u=A[l];if(u.pt.equalTo(u.edge.shape.start)){if(l>0&&u.pt.equalTo(A[l-1].pt)&&u.face_index===A[l-1].face_index&&u.edge.prev===A[l-1].edge)continue;let g=u.edge.prev;for(;C6e(g.length);)g=g.prev;let h=g.shape.tangentInEnd(),d=u.pt.translate(h),p=u.edge.shape.tangentInStart(),m=u.pt.translate(p),_=d.leftTo(i),f=m.leftTo(i);(_&&!f||!_&&f)&&c++}else if(u.pt.equalTo(u.edge.shape.end)){if(l>0&&u.pt.equalTo(A[l-1].pt)&&u.face_index===A[l-1].face_index&&u.edge.next===A[l-1].edge)continue;let g=u.edge.next;for(;C6e(g.length);)g=g.next;let h=g.shape.tangentInStart(),d=u.pt.translate(h),p=u.edge.shape.tangentInEnd(),m=u.pt.translate(p),_=d.leftTo(i),f=m.leftTo(i);(_&&!f||!_&&f)&&c++}else if(u.edge.shape instanceof Ve.Segment)c++;else{let g=u.edge.shape.box;UD(u.pt.y,g.ymin)||UD(u.pt.y,g.ymax)||c++}}return n=c%2==1?1:0,n}function IIt(t,e){return _L(t,e).intersect()}function CIt(t,e){return _L(t,e).inside()}function yIt(t,e){return _L(t,e).covered()}function xIt(t,e){return yIt(e,t)}function _L(t,e){return t instanceof Ve.Line&&e instanceof Ve.Line?(function(n,o){let i=new mL,r=cL(n,o);return r.length===0?n.contains(o.pt)&&o.contains(n.pt)?(i.I2I=[n],i.I2E=[],i.E2I=[]):(i.I2I=[],i.I2E=[n],i.E2I=[o]):(i.I2I=r,i.I2E=n.split(r),i.E2I=o.split(r)),i})(t,e):t instanceof Ve.Line&&e instanceof Ve.Circle?(function(n,o){let i=new mL,r=VD(n,o);if(r.length===0)i.I2I=[],i.I2B=[],i.I2E=[n],i.E2I=[o];else if(r.length===1)i.I2I=[],i.I2B=r,i.I2E=n.split(r),i.E2I=[o];else{let s=new zD([n]),a=n.sortPoints(r);s.split(a);let A=s.toShapes();i.I2I=[A[1]],i.I2B=a,i.I2E=[A[0],A[2]],i.E2I=new Ve.Polygon([o.toArc()]).cutWithLine(n)}return i})(t,e):t instanceof Ve.Line&&e instanceof Ve.Box?(function(n,o){let i=new mL,r=lL(n,o);if(r.length===0)i.I2I=[],i.I2B=[],i.I2E=[n],i.E2I=[o];else if(r.length===1)i.I2I=[],i.I2B=r,i.I2E=n.split(r),i.E2I=[o];else{let s=new zD([n]),a=n.sortPoints(r);s.split(a);let A=s.toShapes();o.toSegments().some(c=>c.contains(r[0])&&c.contains(r[1]))?(i.I2I=[],i.I2B=[A[1]],i.I2E=[A[0],A[2]],i.E2I=[o]):(i.I2I=[A[1]],i.I2B=a,i.I2E=[A[0],A[2]],i.E2I=new Ve.Polygon(o.toSegments()).cutWithLine(n))}return i})(t,e):t instanceof Ve.Line&&e instanceof Ve.Polygon?(function(n,o){let i=new mL,r=nJ(n,o),s=new zD([n]),a=r.length>0?r.slice():n.sortPoints(r);return s.split(a),[...s].forEach(A=>A.setInclusion(o)),i.I2I=[...s].filter(A=>A.bv===Ve.INSIDE).map(A=>A.shape),i.I2B=[...s].slice(1).map(A=>A.bv===Ve.BOUNDARY?A.shape:A.shape.start),i.I2E=[...s].filter(A=>A.bv===Ve.OUTSIDE).map(A=>A.shape),i.E2I=o.cutWithLine(n),i})(t,e):(t instanceof Ve.Segment||t instanceof Ve.Arc)&&e instanceof Ve.Polygon?EIt(t,e):(t instanceof Ve.Segment||t instanceof Ve.Arc)&&(e instanceof Ve.Circle||e instanceof Ve.Box)?EIt(t,new Ve.Polygon(e)):t instanceof Ve.Polygon&&e instanceof Ve.Polygon?Tae(t,e):(t instanceof Ve.Circle||t instanceof Ve.Box)&&(e instanceof Ve.Circle||e instanceof Ve.Box)?Tae(new Ve.Polygon(t),new Ve.Polygon(e)):(t instanceof Ve.Circle||t instanceof Ve.Box)&&e instanceof Ve.Polygon?Tae(new Ve.Polygon(t),e):t instanceof Ve.Polygon&&(e instanceof Ve.Circle||e instanceof Ve.Box)?Tae(t,new Ve.Polygon(e)):void 0}function EIt(t,e){let n=new mL,o=(function(s,a){return s instanceof Ve.Line?nJ(s,a):s instanceof Ve.Segment?E6e(s,a):s instanceof Ve.Arc?B6e(s,a):[]})(t,e),i=o.length>0?o.slice():t.sortPoints(o),r=new zD([t]);r.split(i),[...r].forEach(s=>s.setInclusion(e)),n.I2I=[...r].filter(s=>s.bv===Ve.INSIDE).map(s=>s.shape),n.I2B=[...r].slice(1).map(s=>s.bv===Ve.BOUNDARY?s.shape:s.shape.start),n.I2E=[...r].filter(s=>s.bv===Ve.OUTSIDE).map(s=>s.shape),n.B2I=[],n.B2B=[],n.B2E=[];for(let s of[t.start,t.end])switch(rJ(e,s)){case Ve.INSIDE:n.B2I.push(s);break;case Ve.BOUNDARY:n.B2B.push(s);break;case Ve.OUTSIDE:n.B2E.push(s)}return n}function Tae(t,e){let n=new mL,[o,i]=hIt(t,e),r=gIt(t,e),s=P6e(t,e),a=P6e(e,t),[A,c]=dIt(t,e),l=M6e(t,e),u=M6e(e,t);return n.I2I=r.isEmpty()?[]:[r],n.I2B=c,n.I2E=s.isEmpty()?[]:[s],n.B2I=A,n.B2B=o,n.B2E=l,n.E2I=a.isEmpty()?[]:[a],n.E2B=u,n}var dto=Object.freeze({__proto__:null,contain:function(t,e){return CIt(e,t)},cover:xIt,covered:yIt,disjoint:function(t,e){return!IIt(t,e)},equal:function(t,e){return _L(t,e).equal()},inside:CIt,intersect:IIt,relate:_L,touch:function(t,e){return _L(t,e).touch()}}),sJ=class Tk{constructor(e=1,n=0,o=0,i=1,r=0,s=0){this.a=e,this.b=n,this.c=o,this.d=i,this.tx=r,this.ty=s}fromMatrix3x3(e){const[n,o,i]=e[0],[r,s,a]=e[1];return new Tk(n,r,o,s,i,a)}toMatrix3x3(){return[[this.a,this.c,this.tx],[this.b,this.d,this.ty],[0,0,1]]}clone(){return new Tk(this.a,this.b,this.c,this.d,this.tx,this.ty)}transform(e){return[e[0]*this.a+e[1]*this.c+this.tx,e[0]*this.b+e[1]*this.d+this.ty]}multiply(e){return new Tk(this.a*e.a+this.c*e.b,this.b*e.a+this.d*e.b,this.a*e.c+this.c*e.d,this.b*e.c+this.d*e.d,this.a*e.tx+this.c*e.ty+this.tx,this.b*e.tx+this.d*e.ty+this.ty)}translate(...e){let n,o;if(e.length!=1||isNaN(e[0].x)||isNaN(e[0].y)){if(e.length!==2||typeof e[0]!="number"||typeof e[1]!="number")throw ld.ILLEGAL_PARAMETERS;n=e[0],o=e[1]}else n=e[0].x,o=e[0].y;return this.multiply(new Tk(1,0,0,1,n,o))}rotate(e,n=0,o=0){let i=Math.cos(e),r=Math.sin(e);return this.translate(n,o).multiply(new Tk(i,r,-r,i,0,0)).translate(-n,-o)}scale(e,n){return this.multiply(new Tk(e,0,0,n,0,0))}equalTo(e){return!!Ve.Utils.EQ(this.tx,e.tx)&&!!Ve.Utils.EQ(this.ty,e.ty)&&!!Ve.Utils.EQ(this.a,e.a)&&!!Ve.Utils.EQ(this.b,e.b)&&!!Ve.Utils.EQ(this.c,e.c)&&!!Ve.Utils.EQ(this.d,e.d)}};Ve.Matrix=sJ,Ve.matrix=(...t)=>new Ve.Matrix(...t);var hto=class{constructor(e,n){this.low=e,this.high=n}get max(){return this.clone()}less_than(e){return this.low<e.low||this.low===e.low&&this.high<e.high}equal_to(e){return this.low===e.low&&this.high===e.high}intersect(e){return!this.not_intersect(e)}not_intersect(e){return this.high<e.low||e.high<this.low}merge(e){const n=this.low===void 0?e.low:this.low<e.low?this.low:e.low,o=this.high===void 0?e.high:this.high>e.high?this.high:e.high,i=this.clone();return i.low=n,i.high=o,i}output(){return[this.low,this.high]}comparable_less_than(e,n){return e<n}},pto=class t5n extends hto{clone(){return new t5n(this.low,this.high)}},iv=class{constructor(e,n,o=null,i=null,r=null,s=0){if(this.left=o,this.right=i,this.parent=r,this.color=s,this.item={key:void 0,values:[]},n!==void 0&&this.item.values.push(n),e!==void 0)if(Array.isArray(e)){const[a,A]=e;if(!Number.isNaN(a)&&!Number.isNaN(A)){let c=a,l=A;c>l&&([c,l]=[l,c]),this.item.key=new pto(c,l)}}else this.item.key=e;this.max=this.item.key?this.item.key.max:void 0}isNil(){return this.item.key===void 0&&this.item.values.length===0&&this.left===null&&this.right===null&&this.color===0}requireKey(){if(!this.item.key)throw new Error("Node key is undefined (nil/sentinel). Operation is not applicable.");return this.item.key}less_than(e){const n=this.requireKey(),o=e.requireKey();return n.less_than(o)}_value_equal(e){const n=this.item.values[0],o=e.item.values[0];return n&&o&&n.equal_to?n.equal_to(o):n===o}equal_to(e){const n=this.requireKey(),o=e.requireKey();return n.equal_to(o)}intersect(e){const n=this.requireKey(),o=e.requireKey();return n.intersect(o)}copy_data(e){this.item.key=e.item.key,this.item.values=e.item.values.slice()}update_max(){this.max=this.item.key?this.item.key.max:void 0,this.right&&this.right.max&&(this.max=this.max?this.max.merge(this.right.max):this.right.max),this.left&&this.left.max&&(this.max=this.max?this.max.merge(this.left.max):this.left.max)}not_intersect_left_subtree(e){if(!this.left)return!0;const n=this.left.max?this.left.max.high:this.left.item.key.high,o=this.requireKey(),i=e.requireKey();return o.comparable_less_than(n,i.low)}not_intersect_right_subtree(e){if(!this.right)return!0;const n=this.right.max?this.right.max.low:this.right.item.key.low,o=this.requireKey(),i=e.requireKey();return o.comparable_less_than(i.high,n)}},T6e=class n5n{constructor(){this.root=null,this.nil_node=new iv}get size(){let e=0;return this.tree_walk(this.root,n=>e+=n.item.values.length),e}get keys(){const e=[];return this.tree_walk(this.root,n=>e.push(n.item.key.output())),e}get values(){const e=[];return this.tree_walk(this.root,n=>{for(const o of n.item.values)e.push(o)}),e}get items(){const e=[];return this.tree_walk(this.root,n=>{const o=n.item.key.output();for(const i of n.item.values)e.push({key:o,value:i})}),e}isEmpty(){return this.root==null||this.root===this.nil_node}clear(){this.root=null}insert(e,n=e){if(e===void 0)return;const o=this.tree_search(this.root,new iv(e));if(o)return o.item.values.push(n),o;const i=new iv(e,n,this.nil_node,this.nil_node,null,1);return this.tree_insert(i),this.recalc_max(i),i}exist(e,n=e){const o=this.tree_search(this.root,new iv(e));return!!o&&(arguments.length<2||n===e||o.item.values.some(i=>i&&i.equal_to?i.equal_to(n):i===n))}remove(e,n=e){const o=this.tree_search(this.root,new iv(e));if(!o)return;if(arguments.length<2)return this.tree_delete(o),o;const i=o.item.values.findIndex(r=>r&&r.equal_to?r.equal_to(n):r===n);return i>=0?(o.item.values.splice(i,1),o.item.values.length===0&&this.tree_delete(o),o):void 0}search(e,n=(o,i)=>o===i?i.output():o){const o=new iv(e),i=[];this.tree_search_interval(this.root,o,i);const r=[];for(const s of i)for(const a of s.item.values)r.push(n(a,s.item.key));return r}intersect_any(e){const n=new iv(e);return this.tree_find_any_interval(this.root,n)}forEach(e){this.tree_walk(this.root,n=>{for(const o of n.item.values)e(n.item.key,o)})}map(e){const n=new n5n;return this.tree_walk(this.root,o=>{for(const i of o.item.values)n.insert(o.item.key,e(i,o.item.key))}),n}*iterate(e,n=(o,i)=>o===i?i.output():o){let o=null;for(e?o=this.tree_search_nearest_forward(this.root,new iv(e)):this.root&&(o=this.local_minimum(this.root));o;){for(const i of o.item.values)yield n(i,o.item.key);o=this.tree_successor(o)}}recalc_max(e){let n=e;for(;n.parent!=null;)n.parent.update_max(),n=n.parent}tree_insert(e){let n=this.root,o=null;if(this.root==null||this.root===this.nil_node)this.root=e;else{for(;n!==this.nil_node;)o=n,n=e.less_than(n)?n.left:n.right;e.parent=o,e.less_than(o)?o.left=e:o.right=e}this.insert_fixup(e)}insert_fixup(e){let n,o;for(n=e;n!==this.root&&n.parent.color===1;)n.parent===n.parent.parent.left?(o=n.parent.parent.right,o.color===1?(n.parent.color=0,o.color=0,n.parent.parent.color=1,n=n.parent.parent):(n===n.parent.right&&(n=n.parent,this.rotate_left(n)),n.parent.color=0,n.parent.parent.color=1,this.rotate_right(n.parent.parent))):(o=n.parent.parent.left,o.color===1?(n.parent.color=0,o.color=0,n.parent.parent.color=1,n=n.parent.parent):(n===n.parent.left&&(n=n.parent,this.rotate_right(n)),n.parent.color=0,n.parent.parent.color=1,this.rotate_left(n.parent.parent)));this.root.color=0}tree_delete(e){let n,o;n=e.left===this.nil_node||e.right===this.nil_node?e:this.tree_successor(e),o=n.left!==this.nil_node?n.left:n.right,o.parent=n.parent,n===this.root?this.root=o:(n===n.parent.left?n.parent.left=o:n.parent.right=o,n.parent.update_max()),this.recalc_max(o),n!==e&&(e.copy_data(n),e.update_max(),this.recalc_max(e)),n.color===0&&this.delete_fixup(o)}delete_fixup(e){let n,o=e;for(;o!==this.root&&o.parent!=null&&o.color===0;)o===o.parent.left?(n=o.parent.right,n.color===1&&(n.color=0,o.parent.color=1,this.rotate_left(o.parent),n=o.parent.right),n.left.color===0&&n.right.color===0?(n.color=1,o=o.parent):(n.right.color===0&&(n.color=1,n.left.color=0,this.rotate_right(n),n=o.parent.right),n.color=o.parent.color,o.parent.color=0,n.right.color=0,this.rotate_left(o.parent),o=this.root)):(n=o.parent.left,n.color===1&&(n.color=0,o.parent.color=1,this.rotate_right(o.parent),n=o.parent.left),n.left.color===0&&n.right.color===0?(n.color=1,o=o.parent):(n.left.color===0&&(n.color=1,n.right.color=0,this.rotate_left(n),n=o.parent.left),n.color=o.parent.color,o.parent.color=0,n.left.color=0,this.rotate_right(o.parent),o=this.root));o.color=0}tree_search(e,n){if(e!=null&&e!==this.nil_node)return n.equal_to(e)?e:n.less_than(e)?this.tree_search(e.left,n):this.tree_search(e.right,n)}tree_search_nearest_forward(e,n){let o=null,i=e;for(;i&&i!==this.nil_node;)i.less_than(n)?i.intersect(n)?(o=i,i=i.left):i=i.right:(o&&!i.less_than(o)||(o=i),i=i.left);return o||null}tree_search_interval(e,n,o){e!=null&&e!==this.nil_node&&(e.left===this.nil_node||e.not_intersect_left_subtree(n)||this.tree_search_interval(e.left,n,o),e.intersect(n)&&o.push(e),e.right===this.nil_node||e.not_intersect_right_subtree(n)||this.tree_search_interval(e.right,n,o))}tree_find_any_interval(e,n){let o=!1;return e!=null&&e!==this.nil_node&&(e.left===this.nil_node||e.not_intersect_left_subtree(n)||(o=this.tree_find_any_interval(e.left,n)),o||(o=e.intersect(n)),o||e.right===this.nil_node||e.not_intersect_right_subtree(n)||(o=this.tree_find_any_interval(e.right,n))),o}local_minimum(e){let n=e;for(;n.left!=null&&n.left!==this.nil_node;)n=n.left;return n}local_maximum(e){let n=e;for(;n.right!=null&&n.right!==this.nil_node;)n=n.right;return n}tree_successor(e){let n,o,i;if(e.right!==this.nil_node)n=this.local_minimum(e.right);else{for(o=e,i=e.parent;i!=null&&i.right===o;)o=i,i=i.parent;n=i}return n}rotate_left(e){const n=e.right;e.right=n.left,n.left!==this.nil_node&&(n.left.parent=e),n.parent=e.parent,e===this.root?this.root=n:e===e.parent.left?e.parent.left=n:e.parent.right=n,n.left=e,e.parent=n,e!==null&&e!==this.nil_node&&e.update_max(),n!=null&&n!==this.nil_node&&n.update_max()}rotate_right(e){const n=e.left;e.left=n.right,n.right!==this.nil_node&&(n.right.parent=e),n.parent=e.parent,e===this.root?this.root=n:e===e.parent.left?e.parent.left=n:e.parent.right=n,n.right=e,e.parent=n,e!==null&&e!==this.nil_node&&e.update_max(),n!=null&&n!==this.nil_node&&n.update_max()}tree_walk(e,n){e!=null&&e!==this.nil_node&&(this.tree_walk(e.left,n),n(e),this.tree_walk(e.right,n))}testRedBlackProperty(){let e=!0;return this.tree_walk(this.root,function(n){n.color===1&&(n.left.color===0&&n.right.color===0||(e=!1))}),e}testBlackHeightProperty(e){let n=0,o=0,i=0;if(e.color===0&&n++,o=e.left!==this.nil_node?this.testBlackHeightProperty(e.left):1,i=e.right!==this.nil_node?this.testBlackHeightProperty(e.right):1,o!==i)throw new Error("Red-black height property violated");return n+=o,n}},mto=class extends Set{constructor(e){super(e),this.index=new T6e,this.forEach(n=>this.index.insert(n))}add(e){let n=this.size;const{key:o,value:i}=e,r=o||e.box,s=i||e;return super.add(s),this.size>n&&this.index.insert(r,s),this}delete(e){const{key:n,value:o}=e,i=n||e.box,r=o||e;let s=super.delete(r);return s&&this.index.remove(i,r),s}clear(){super.clear(),this.index=new T6e}search(e){return this.index.search(e)}hit(e){let n=new Ve.Box(e.x-1,e.y-1,e.x+1,e.y+1);return this.index.search(n).filter(o=>e.on(o))}svg(){return[...this].reduce((e,n)=>e+n.svg(),"")}};Ve.PlanarSet=mto;var rv=class{get name(){throw ld.CANNOT_INVOKE_ABSTRACT_METHOD}get box(){throw ld.CANNOT_INVOKE_ABSTRACT_METHOD}clone(){throw ld.CANNOT_INVOKE_ABSTRACT_METHOD}translate(...e){return this.transform(new sJ().translate(...e))}rotate(e,n=new Ve.Point){return this.transform(new sJ().rotate(e,n.x,n.y))}scale(e,n){return this.transform(new sJ().scale(e,n))}transform(...e){throw ld.CANNOT_INVOKE_ABSTRACT_METHOD}toJSON(){return Object.assign({},this,{name:this.name})}svg(e={}){throw ld.CANNOT_INVOKE_ABSTRACT_METHOD}};Ve.Point=class o5n extends rv{constructor(...e){if(super(),this.x=0,this.y=0,e.length!==0){if(e.length===1&&e[0]instanceof Array&&e[0].length===2){let n=e[0];if(typeof n[0]=="number"&&typeof n[1]=="number")return this.x=n[0],void(this.y=n[1])}if(e.length===1&&e[0]instanceof Object&&e[0].name==="point"){let{x:n,y:o}=e[0];return this.x=n,void(this.y=o)}if(e.length===2&&typeof e[0]=="number"&&typeof e[1]=="number")return this.x=e[0],void(this.y=e[1]);throw ld.ILLEGAL_PARAMETERS}}get box(){return new Ve.Box(this.x,this.y,this.x,this.y)}clone(){return new Ve.Point(this.x,this.y)}get vertices(){return[this.clone()]}equalTo(e){return Ve.Utils.EQ(this.x,e.x)&&Ve.Utils.EQ(this.y,e.y)}lessThan(e){return!!Ve.Utils.LT(this.y,e.y)||!(!Ve.Utils.EQ(this.y,e.y)||!Ve.Utils.LT(this.x,e.x))}transform(e){return new Ve.Point(e.transform([this.x,this.y]))}projectionOn(e){if(this.equalTo(e.pt))return this.clone();let n=new Ve.Vector(this,e.pt);if(Ve.Utils.EQ_0(n.cross(e.norm)))return e.pt.clone();let o=n.dot(e.norm),i=e.norm.multiply(o);return this.translate(i)}leftTo(e){let n=new Ve.Vector(e.pt,this);return Ve.Utils.GT(n.dot(e.norm),0)}distanceTo(e){if(e instanceof o5n){let n=e.x-this.x,o=e.y-this.y;return[Math.sqrt(n*n+o*o),new Ve.Segment(this,e)]}return e instanceof Ve.Line?Ve.Distance.point2line(this,e):e instanceof Ve.Circle?Ve.Distance.point2circle(this,e):e instanceof Ve.Segment?Ve.Distance.point2segment(this,e):e instanceof Ve.Arc?Ve.Distance.point2arc(this,e):e instanceof Ve.Polygon?Ve.Distance.point2polygon(this,e):e instanceof Ve.PlanarSet?Ve.Distance.shape2planarSet(this,e):e instanceof Ve.Multiline?Ve.Distance.shape2multiline(this,e):void 0}on(e){if(e instanceof Ve.Point)return this.equalTo(e);if(e.contains&&e.contains instanceof Function)return e.contains(this);throw Ve.Errors.UNSUPPORTED_SHAPE_TYPE}get name(){return"point"}svg(e={}){const n=e.r??3;return`
<circle cx="${this.x}" cy="${this.y}" r="${n}"
            ${KD({fill:"red",...e})} />`}},Ve.point=(...t)=>new Ve.Point(...t),Ve.Vector=class extends rv{constructor(...t){if(super(),this.x=0,this.y=0,t.length!==0){if(t.length===1&&t[0]instanceof Array&&t[0].length===2){let e=t[0];if(typeof e[0]=="number"&&typeof e[1]=="number")return this.x=e[0],void(this.y=e[1])}if(t.length===1&&t[0]instanceof Object&&t[0].name==="vector"){let{x:e,y:n}=t[0];return this.x=e,void(this.y=n)}if(t.length===1&&t[0]instanceof Object&&t[0].name==="segment"){let{start:e,end:n}=t[0];return this.x=n.x-e.x,void(this.y=n.y-e.y)}if(t.length===2){let e=t[0],n=t[1];if(typeof e=="number"&&typeof n=="number")return this.x=e,void(this.y=n);if(e instanceof Ve.Point&&n instanceof Ve.Point)return this.x=n.x-e.x,void(this.y=n.y-e.y)}throw ld.ILLEGAL_PARAMETERS}}clone(){return new Ve.Vector(this.x,this.y)}get slope(){let t=Math.atan2(this.y,this.x);return t<0&&(t=2*Math.PI+t),t}get length(){return Math.sqrt(this.dot(this))}isZeroLength(){return Ve.Utils.EQ_0(this.length)}equalTo(t){return Ve.Utils.EQ(this.x,t.x)&&Ve.Utils.EQ(this.y,t.y)}multiply(t){return new Ve.Vector(t*this.x,t*this.y)}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}normalize(){if(this.isZeroLength())throw ld.ZERO_DIVISION;return new Ve.Vector(this.x/this.length,this.y/this.length)}rotate(t,e=new Ve.Point){if(e.x===0&&e.y===0)return this.transform(new sJ().rotate(t));throw ld.OPERATION_IS_NOT_SUPPORTED}transform(t){return new Ve.Vector(t.transform([this.x,this.y]))}rotate90CCW(){return new Ve.Vector(-this.y,this.x)}rotate90CW(){return new Ve.Vector(this.y,-this.x)}invert(){return new Ve.Vector(-this.x,-this.y)}add(t){return new Ve.Vector(this.x+t.x,this.y+t.y)}subtract(t){return new Ve.Vector(this.x-t.x,this.y-t.y)}angleTo(t){let e=this.normalize(),n=t.normalize(),o=Math.atan2(e.cross(n),e.dot(n));return o<0&&(o+=2*Math.PI),o}projectionOn(t){let e=t.normalize(),n=this.dot(e);return e.multiply(n)}get name(){return"vector"}};var BIt=(...t)=>new Ve.Vector(...t);Ve.vector=BIt,Ve.Segment=class dit extends rv{constructor(...e){if(super(),this.ps=new Ve.Point,this.pe=new Ve.Point,e.length!==0){if(e.length===1&&e[0]instanceof Array&&e[0].length===4){let n=e[0];return this.ps=new Ve.Point(n[0],n[1]),void(this.pe=new Ve.Point(n[2],n[3]))}if(e.length===1&&e[0]instanceof Object&&e[0].name==="segment"){let{ps:n,pe:o}=e[0];return this.ps=new Ve.Point(n.x,n.y),void(this.pe=new Ve.Point(o.x,o.y))}if(!(e.length===1&&e[0]instanceof Ve.Point)){if(e.length===2&&e[0]instanceof Ve.Point&&e[1]instanceof Ve.Point)return this.ps=e[0].clone(),void(this.pe=e[1].clone());if(e.length===4)return this.ps=new Ve.Point(e[0],e[1]),void(this.pe=new Ve.Point(e[2],e[3]));throw ld.ILLEGAL_PARAMETERS}this.ps=e[0].clone()}}clone(){return new Ve.Segment(this.start,this.end)}get start(){return this.ps}get end(){return this.pe}get vertices(){return[this.ps.clone(),this.pe.clone()]}get length(){return this.start.distanceTo(this.end)[0]}get slope(){return new Ve.Vector(this.start,this.end).slope}get box(){return new Ve.Box(Math.min(this.start.x,this.end.x),Math.min(this.start.y,this.end.y),Math.max(this.start.x,this.end.x),Math.max(this.start.y,this.end.y))}equalTo(e){return this.ps.equalTo(e.ps)&&this.pe.equalTo(e.pe)}contains(e){return Ve.Utils.EQ_0(this.distanceToPoint(e))}intersect(e){return e instanceof Ve.Point?this.contains(e)?[e]:[]:e instanceof Ve.Line?tJ(this,e):e instanceof Ve.Ray?b6e(e,this):e instanceof Ve.Segment?Nae(this,e):e instanceof Ve.Circle?Rae(this,e):e instanceof Ve.Box?(function(n,o){let i=[];for(let r of o.toSegments()){let s=Nae(r,n);for(let a of s)i.push(a)}return i})(this,e):e instanceof Ve.Arc?uL(this,e):e instanceof Ve.Polygon?E6e(this,e):e instanceof Ve.Multiline?gL(this,e):void 0}distanceTo(e){if(e instanceof Ve.Point){let[n,o]=Ve.Distance.point2segment(e,this);return o=o.reverse(),[n,o]}if(e instanceof Ve.Circle){let[n,o]=Ve.Distance.segment2circle(this,e);return[n,o]}if(e instanceof Ve.Line){let[n,o]=Ve.Distance.segment2line(this,e);return[n,o]}if(e instanceof Ve.Segment){let[n,o]=Ve.Distance.segment2segment(this,e);return[n,o]}if(e instanceof Ve.Arc){let[n,o]=Ve.Distance.segment2arc(this,e);return[n,o]}if(e instanceof Ve.Polygon){let[n,o]=Ve.Distance.shape2polygon(this,e);return[n,o]}if(e instanceof Ve.PlanarSet){let[n,o]=Ve.Distance.shape2planarSet(this,e);return[n,o]}if(e instanceof Ve.Multiline)return Ve.Distance.shape2multiline(this,e)}tangentInStart(){return new Ve.Vector(this.start,this.end).normalize()}tangentInEnd(){return new Ve.Vector(this.end,this.start).normalize()}reverse(){return new dit(this.end,this.start)}split(e){return this.start.equalTo(e)?[null,this.clone()]:this.end.equalTo(e)?[this.clone(),null]:[new Ve.Segment(this.start,e),new Ve.Segment(e,this.end)]}middle(){return new Ve.Point((this.start.x+this.end.x)/2,(this.start.y+this.end.y)/2)}pointAtLength(e){if(e>this.length||e<0)return null;if(e==0)return this.start;if(e==this.length)return this.end;let n=e/this.length;return new Ve.Point((this.end.x-this.start.x)*n+this.start.x,(this.end.y-this.start.y)*n+this.start.y)}distanceToPoint(e){let[n,...o]=Ve.Distance.point2segment(e,this);return n}definiteIntegral(e=0){return(this.end.x-this.start.x)*(this.start.y-e+(this.end.y-e))/2}transform(e=new Ve.Matrix){return new dit(this.ps.transform(e),this.pe.transform(e))}isZeroLength(){return this.ps.equalTo(this.pe)}sortPoints(e){return new Ve.Line(this.start,this.end).sortPoints(e)}get name(){return"segment"}svg(e={}){return`
<line x1="${this.start.x}" y1="${this.start.y}" x2="${this.end.x}" y2="${this.end.y}" ${KD(e)} />`}},Ve.segment=(...t)=>new Ve.Segment(...t);var{vector:aJ}=Ve;Ve.Line=class i5n extends rv{constructor(...e){if(super(),this.pt=new Ve.Point,this.norm=new Ve.Vector(0,1),e.length!==0){if(e.length===1&&e[0]instanceof Object&&e[0].name==="line"){let{pt:n,norm:o}=e[0];return this.pt=new Ve.Point(n),void(this.norm=new Ve.Vector(o))}if(e.length===2){let n=e[0],o=e[1];if(n instanceof Ve.Point&&o instanceof Ve.Point)return this.pt=n,this.norm=i5n.points2norm(n,o),void(this.norm.dot(aJ(this.pt.x,this.pt.y))>=0&&this.norm.invert());if(n instanceof Ve.Point&&o instanceof Ve.Vector){if(Ve.Utils.EQ_0(o.x)&&Ve.Utils.EQ_0(o.y))throw ld.ILLEGAL_PARAMETERS;return this.pt=n.clone(),this.norm=o.clone(),this.norm=this.norm.normalize(),void(this.norm.dot(aJ(this.pt.x,this.pt.y))>=0&&this.norm.invert())}if(n instanceof Ve.Vector&&o instanceof Ve.Point){if(Ve.Utils.EQ_0(n.x)&&Ve.Utils.EQ_0(n.y))throw ld.ILLEGAL_PARAMETERS;return this.pt=o.clone(),this.norm=n.clone(),this.norm=this.norm.normalize(),void(this.norm.dot(aJ(this.pt.x,this.pt.y))>=0&&this.norm.invert())}}throw ld.ILLEGAL_PARAMETERS}}clone(){return new Ve.Line(this.pt,this.norm)}get start(){}get end(){}get length(){return Number.POSITIVE_INFINITY}get box(){return new Ve.Box(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY)}get middle(){}get slope(){return new Ve.Vector(this.norm.y,-this.norm.x).slope}get standard(){return[this.norm.x,this.norm.y,this.norm.dot(aJ(this.pt.x,this.pt.y))]}parallelTo(e){return Ve.Utils.EQ_0(this.norm.cross(e.norm))}incidentTo(e){return this.parallelTo(e)&&this.pt.on(e)}contains(e){if(this.pt.equalTo(e))return!0;let n=new Ve.Vector(this.pt,e);return Ve.Utils.EQ_0(this.norm.dot(n))}coord(e){return aJ(e.x,e.y).cross(this.norm)}intersect(e){return e instanceof Ve.Point?this.contains(e)?[e]:[]:e instanceof Ve.Line?cL(this,e):e instanceof Ve.Ray?sIt(e,this):e instanceof Ve.Circle?VD(this,e):e instanceof Ve.Box?lL(this,e):e instanceof Ve.Segment?tJ(e,this):e instanceof Ve.Arc?Dae(this,e):e instanceof Ve.Polygon?nJ(this,e):e instanceof Ve.Multiline?gL(this,e):void 0}distanceTo(e){if(e instanceof Ve.Point){let[n,o]=Ve.Distance.point2line(e,this);return o=o.reverse(),[n,o]}if(e instanceof Ve.Circle){let[n,o]=Ve.Distance.circle2line(e,this);return o=o.reverse(),[n,o]}if(e instanceof Ve.Segment){let[n,o]=Ve.Distance.segment2line(e,this);return[n,o.reverse()]}if(e instanceof Ve.Arc){let[n,o]=Ve.Distance.arc2line(e,this);return[n,o.reverse()]}if(e instanceof Ve.Polygon){let[n,o]=Ve.Distance.shape2polygon(this,e);return[n,o]}}split(e){if(e instanceof Ve.Point)return[new Ve.Ray(e,this.norm),new Ve.Ray(e,this.norm)];{let n=new Ve.Multiline([this]),o=this.sortPoints(e);return n.split(o),n.toShapes()}}rotate(e,n=new Ve.Point){return new Ve.Line(this.pt.rotate(e,n),this.norm.rotate(e))}transform(e){return new Ve.Line(this.pt.transform(e),this.norm.clone())}sortPoints(e){return e.slice().sort((n,o)=>this.coord(n)<this.coord(o)?-1:this.coord(n)>this.coord(o)?1:0)}get name(){return"line"}svg(e,n={}){let o=lL(this,e);if(o.length===0)return"";let i=o[0],r=o.length===2?o[1]:o.find(s=>!s.equalTo(i));return r===void 0&&(r=i),new Ve.Segment(i,r).svg(n)}static points2norm(e,n){if(e.equalTo(n))throw ld.ILLEGAL_PARAMETERS;return new Ve.Vector(e,n).normalize().rotate90CCW()}},Ve.line=(...t)=>new Ve.Line(...t),Ve.Circle=class extends rv{constructor(...t){if(super(),this.pc=new Ve.Point,this.r=1,t.length===1&&t[0]instanceof Object&&t[0].name==="circle"){let{pc:e,r:n}=t[0];this.pc=new Ve.Point(e),this.r=n}else{let[e,n]=[...t];e&&e instanceof Ve.Point&&(this.pc=e.clone()),n!==void 0&&(this.r=n)}}clone(){return new Ve.Circle(this.pc.clone(),this.r)}get center(){return this.pc}get box(){return new Ve.Box(this.pc.x-this.r,this.pc.y-this.r,this.pc.x+this.r,this.pc.y+this.r)}contains(t){return t instanceof Ve.Point?Ve.Utils.LE(t.distanceTo(this.center)[0],this.r):t instanceof Ve.Segment?Ve.Utils.LE(t.start.distanceTo(this.center)[0],this.r)&&Ve.Utils.LE(t.end.distanceTo(this.center)[0],this.r):t instanceof Ve.Arc?this.intersect(t).length===0&&Ve.Utils.LE(t.start.distanceTo(this.center)[0],this.r)&&Ve.Utils.LE(t.end.distanceTo(this.center)[0],this.r):t instanceof Ve.Circle?this.intersect(t).length===0&&Ve.Utils.LE(t.r,this.r)&&Ve.Utils.LE(t.center.distanceTo(this.center)[0],this.r):void 0}toArc(t=!0){return new Ve.Arc(this.center,this.r,Math.PI,-Math.PI,t)}scale(t,e){if(t!==e||this.pc.x!==0||this.pc.y!==0)throw ld.OPERATION_IS_NOT_SUPPORTED;return new Ve.Circle(this.pc,this.r*t)}transform(t=new Ve.Matrix){return new Ve.Circle(this.pc.transform(t),this.r)}intersect(t){return t instanceof Ve.Point?this.contains(t)?[t]:[]:t instanceof Ve.Line?VD(t,this):t instanceof Ve.Ray?rIt(t,this):t instanceof Ve.Segment?Rae(t,this):t instanceof Ve.Circle?$1t(t,this):t instanceof Ve.Box?(function(e,n){let o=[];for(let i of n.toSegments()){let r=Rae(i,e);for(let s of r)o.push(s)}return o})(this,t):t instanceof Ve.Arc?x6e(t,this):t instanceof Ve.Polygon?tIt(this,t):t instanceof Ve.Multiline?gL(this,t):void 0}distanceTo(t){if(t instanceof Ve.Point){let[e,n]=Ve.Distance.point2circle(t,this);return n=n.reverse(),[e,n]}if(t instanceof Ve.Circle){let[e,n]=Ve.Distance.circle2circle(this,t);return[e,n]}if(t instanceof Ve.Line){let[e,n]=Ve.Distance.circle2line(this,t);return[e,n]}if(t instanceof Ve.Segment){let[e,n]=Ve.Distance.segment2circle(t,this);return n=n.reverse(),[e,n]}if(t instanceof Ve.Arc){let[e,n]=Ve.Distance.arc2circle(t,this);return n=n.reverse(),[e,n]}if(t instanceof Ve.Polygon){let[e,n]=Ve.Distance.shape2polygon(this,t);return[e,n]}if(t instanceof Ve.PlanarSet){let[e,n]=Ve.Distance.shape2planarSet(this,t);return[e,n]}if(t instanceof Ve.Multiline){let[e,n]=Ve.Distance.shape2multiline(this,t);return[e,n]}}get name(){return"circle"}svg(t={}){return`
<circle cx="${this.pc.x}" cy="${this.pc.y}" r="${this.r}"
                ${KD({fill:"none",...t})} />`}},Ve.circle=(...t)=>new Ve.Circle(...t),Ve.Arc=class extends rv{constructor(...t){if(super(),this.pc=new Ve.Point,this.r=1,this.startAngle=0,this.endAngle=2*Math.PI,this.counterClockwise=!0,t.length!==0)if(t.length===1&&t[0]instanceof Object&&t[0].name==="arc"){let{pc:e,r:n,startAngle:o,endAngle:i,counterClockwise:r}=t[0];this.pc=new Ve.Point(e.x,e.y),this.r=n,this.startAngle=o,this.endAngle=i,this.counterClockwise=r}else{let[e,n,o,i,r]=[...t];e&&e instanceof Ve.Point&&(this.pc=e.clone()),n!==void 0&&(this.r=n),o!==void 0&&(this.startAngle=o),i!==void 0&&(this.endAngle=i),r!==void 0&&(this.counterClockwise=r)}}clone(){return new Ve.Arc(this.pc.clone(),this.r,this.startAngle,this.endAngle,this.counterClockwise)}get sweep(){let t=this.startAngle,e=this.endAngle;if(Ve.Utils.EQ(Math.abs(t-e),Ve.PIx2))return Ve.PIx2;Math.abs(t)>Ve.PIx2&&(t-=Math.trunc(t/Ve.PIx2)*Ve.PIx2),t<0&&(t+=Ve.PIx2),Math.abs(e)>Ve.PIx2&&(e-=Math.trunc(e/Ve.PIx2)*Ve.PIx2),e<0&&(e+=Ve.PIx2);let n=this.counterClockwise?e-t:t-e;return n<0&&(n+=Ve.PIx2),n}get start(){return new Ve.Point(this.pc.x+this.r,this.pc.y).rotate(this.startAngle,this.pc)}get end(){return new Ve.Point(this.pc.x+this.r,this.pc.y).rotate(this.endAngle,this.pc)}get center(){return this.pc.clone()}get vertices(){return[this.start.clone(),this.end.clone()]}get length(){return Math.abs(this.sweep*this.r)}get box(){let t=this.breakToFunctional().reduce((e,n)=>e.merge(n.start.box),new Ve.Box);return t=t.merge(this.end.box),t}contains(t){if(!Ve.Utils.EQ(this.pc.distanceTo(t)[0],this.r))return!1;if(t.equalTo(this.start))return!0;let e=new Ve.Vector(this.pc,t).slope,n=new Ve.Arc(this.pc,this.r,this.startAngle,e,this.counterClockwise);return Ve.Utils.LE(n.length,this.length)}split(t){if(this.start.equalTo(t))return[null,this.clone()];if(this.end.equalTo(t))return[this.clone(),null];let e=new Ve.Vector(this.pc,t).slope;return[new Ve.Arc(this.pc,this.r,this.startAngle,e,this.counterClockwise),new Ve.Arc(this.pc,this.r,e,this.endAngle,this.counterClockwise)]}middle(){let t=this.counterClockwise?this.startAngle+this.sweep/2:this.startAngle-this.sweep/2;return new Ve.Arc(this.pc,this.r,this.startAngle,t,this.counterClockwise).end}pointAtLength(t){if(t>this.length||t<0)return null;if(t===0)return this.start;if(t===this.length)return this.end;let e=t/this.length,n=this.counterClockwise?this.startAngle+this.sweep*e:this.startAngle-this.sweep*e;return new Ve.Arc(this.pc,this.r,this.startAngle,n,this.counterClockwise).end}chordHeight(){return(1-Math.cos(Math.abs(this.sweep/2)))*this.r}intersect(t){return t instanceof Ve.Point?this.contains(t)?[t]:[]:t instanceof Ve.Line?Dae(t,this):t instanceof Ve.Ray?S6e(t,this):t instanceof Ve.Circle?x6e(this,t):t instanceof Ve.Segment?uL(t,this):t instanceof Ve.Box?(function(e,n){let o=[];for(let i of n.toSegments()){let r=uL(i,e);for(let s of r)o.push(s)}return o})(this,t):t instanceof Ve.Arc?q1t(this,t):t instanceof Ve.Polygon?B6e(this,t):t instanceof Ve.Multiline?gL(this,t):void 0}distanceTo(t){if(t instanceof Ve.Point){let[e,n]=Ve.Distance.point2arc(t,this);return n=n.reverse(),[e,n]}if(t instanceof Ve.Circle){let[e,n]=Ve.Distance.arc2circle(this,t);return[e,n]}if(t instanceof Ve.Line){let[e,n]=Ve.Distance.arc2line(this,t);return[e,n]}if(t instanceof Ve.Segment){let[e,n]=Ve.Distance.segment2arc(t,this);return n=n.reverse(),[e,n]}if(t instanceof Ve.Arc){let[e,n]=Ve.Distance.arc2arc(this,t);return[e,n]}if(t instanceof Ve.Polygon){let[e,n]=Ve.Distance.shape2polygon(this,t);return[e,n]}if(t instanceof Ve.PlanarSet){let[e,n]=Ve.Distance.shape2planarSet(this,t);return[e,n]}if(t instanceof Ve.Multiline)return Ve.Distance.shape2multiline(this,t)}breakToFunctional(){let t=[],e=[0,Math.PI/2,Math.PI,3*Math.PI/2],n=this.startAngle,o=this.endAngle;Ve.Utils.EQ(Math.abs(n-o),Ve.PIx2)&&(o=n),Math.abs(n)>Ve.PIx2&&(n-=Math.trunc(n/Ve.PIx2)*Ve.PIx2),n<0&&(n+=Ve.PIx2),Math.abs(o)>Ve.PIx2&&(o-=Math.trunc(o/Ve.PIx2)*Ve.PIx2),o<0&&(o+=Ve.PIx2);let i,r,s,a=n;this.counterClockwise?(r=Math.ceil(n/(Math.PI/2))%4,s=1):(r=Math.floor(n/(Math.PI/2))%4,s=-1);for(let A=0,c=r;A<4;A++,c=(c+s+4)%4){if(i=e[c],i===a)continue;let l=this.counterClockwise?i-n:n-i;if(l<0&&(l+=Ve.PIx2),l>this.sweep)break;t.push(new Ve.Arc(this.pc,this.r,a,i,this.counterClockwise)),a=i}return t.length===0?(t.push(this),t):(i=o,a!==i&&t.push(new Ve.Arc(this.pc,this.r,a,i,this.counterClockwise)),t)}tangentInStart(){let t=new Ve.Vector(this.pc,this.start),e=this.counterClockwise?Math.PI/2:-Math.PI/2;return t.rotate(e).normalize()}tangentInEnd(){let t=new Ve.Vector(this.pc,this.end),e=this.counterClockwise?-Math.PI/2:Math.PI/2;return t.rotate(e).normalize()}reverse(){return new Ve.Arc(this.pc,this.r,this.endAngle,this.startAngle,!this.counterClockwise)}transform(t=new Ve.Matrix){let e=this.start.transform(t),n=this.end.transform(t),o=this.pc.transform(t),i=this.counterClockwise;return t.a*t.d<0&&(i=!i),Ve.Arc.arcSE(o,e,n,i)}static arcSE(t,e,n,o){let{vector:i}=Ve,r=i(t,e).slope,s=i(t,n).slope;Ve.Utils.EQ(r,s)&&(s+=2*Math.PI,o=!0);let a=i(t,e).length;return new Ve.Arc(t,a,r,s,o)}definiteIntegral(t=0){return this.breakToFunctional().reduce((e,n)=>e+n.circularSegmentDefiniteIntegral(t),0)}circularSegmentDefiniteIntegral(t){let e=new Ve.Segment(this.start,this.end).definiteIntegral(t),n=Ve.Utils.EQ(this.sweep,Ve.PIx2)?0:this.circularSegmentArea();return this.counterClockwise?e-n:e+n}circularSegmentArea(){return .5*this.r*this.r*(this.sweep-Math.sin(this.sweep))}sortPoints(t){let{vector:e}=Ve;return t.slice().sort((n,o)=>{let i=e(this.pc,n).slope,r=e(this.pc,o).slope;return i<r?-1:i>r?1:0})}get name(){return"arc"}svg(t={}){let e=this.sweep<=Math.PI?"0":"1",n=this.counterClockwise?"1":"0";return Ve.Utils.EQ(this.sweep,2*Math.PI)?new Ve.Circle(this.pc,this.r).svg(t):`
<path d="M${this.start.x},${this.start.y}
                             A${this.r},${this.r} 0 ${e},${n} ${this.end.x},${this.end.y}"
                    ${KD({fill:"none",...t})} />`}},Ve.arc=(...t)=>new Ve.Arc(...t),Ve.Box=class Jte extends rv{constructor(e=void 0,n=void 0,o=void 0,i=void 0){super(),this.xmin=e,this.ymin=n,this.xmax=o,this.ymax=i}clone(){return new Jte(this.xmin,this.ymin,this.xmax,this.ymax)}get low(){return new Ve.Point(this.xmin,this.ymin)}get high(){return new Ve.Point(this.xmax,this.ymax)}get max(){return this.clone()}get center(){return new Ve.Point((this.xmin+this.xmax)/2,(this.ymin+this.ymax)/2)}get width(){return Math.abs(this.xmax-this.xmin)}get height(){return Math.abs(this.ymax-this.ymin)}get box(){return this.clone()}not_intersect(e){return this.xmax<e.xmin||this.xmin>e.xmax||this.ymax<e.ymin||this.ymin>e.ymax}intersect(e){return!this.not_intersect(e)}merge(e){return new Jte(this.xmin===void 0?e.xmin:Math.min(this.xmin,e.xmin),this.ymin===void 0?e.ymin:Math.min(this.ymin,e.ymin),this.xmax===void 0?e.xmax:Math.max(this.xmax,e.xmax),this.ymax===void 0?e.ymax:Math.max(this.ymax,e.ymax))}less_than(e){return!!this.low.lessThan(e.low)||!(!this.low.equalTo(e.low)||!this.high.lessThan(e.high))}equal_to(e){return this.low.equalTo(e.low)&&this.high.equalTo(e.high)}output(){return this.clone()}comparable_less_than(e,n){return e.lessThan(n)}set(e,n,o,i){this.xmin=e,this.ymin=n,this.xmax=o,this.ymax=i}extend(e){return e<=0?this.clone():new Jte(this.xmin-e,this.ymin-e,this.xmax+e,this.ymax+e)}toPoints(){return[new Ve.Point(this.xmin,this.ymin),new Ve.Point(this.xmax,this.ymin),new Ve.Point(this.xmax,this.ymax),new Ve.Point(this.xmin,this.ymax)]}toSegments(){let e=this.toPoints();return[new Ve.Segment(e[0],e[1]),new Ve.Segment(e[1],e[2]),new Ve.Segment(e[2],e[3]),new Ve.Segment(e[3],e[0])]}rotate(e,n=new Ve.Point){throw ld.OPERATION_IS_NOT_SUPPORTED}transform(e=new Ve.Matrix){return this.toPoints().map(n=>n.transform(e)).reduce((n,o)=>n.merge(o.box),new Jte)}contains(e){return e instanceof Ve.Point?e.x>=this.xmin&&e.x<=this.xmax&&e.y>=this.ymin&&e.y<=this.ymax:e instanceof Ve.Segment?e.vertices.every(n=>this.contains(n)):e instanceof Ve.Box?e.toSegments().every(n=>this.contains(n)):e instanceof Ve.Circle?this.contains(e.box):e instanceof Ve.Arc?e.vertices.every(n=>this.contains(n))&&this.toSegments().every(n=>uL(n,e).length===0):!(e instanceof Ve.Line||e instanceof Ve.Ray)&&(e instanceof Ve.Multiline?e.toShapes().every(n=>this.contains(n)):e instanceof Ve.Polygon?this.contains(e.box):void 0)}distanceTo(e){const n=this.toSegments().map(i=>i.distanceTo(e));let o=[Number.MAX_SAFE_INTEGER,null];return n.forEach(i=>{i[0]<o[0]&&(o=i)}),o}get name(){return"box"}svg(e={}){const n=this.xmax-this.xmin,o=this.ymax-this.ymin;return`
<rect x="${this.xmin}" y="${this.ymin}" width="${n}" height="${o}"
                ${KD({fill:"none",...e})} />`}},Ve.box=(...t)=>new Ve.Box(...t),Ve.Edge=class{constructor(t){this.shape=t,this.next=void 0,this.prev=void 0,this.face=void 0,this.arc_length=0,this.bvStart=void 0,this.bvEnd=void 0,this.bv=void 0,this.overlap=void 0}get start(){return this.shape.start}get end(){return this.shape.end}get length(){return this.shape.length}get box(){return this.shape.box}get isSegment(){return this.shape instanceof Ve.Segment}get isArc(){return this.shape instanceof Ve.Arc}get isLine(){return this.shape instanceof Ve.Line}get isRay(){return this.shape instanceof Ve.Ray}middle(){return this.shape.middle()}pointAtLength(t){return this.shape.pointAtLength(t)}contains(t){return this.shape.contains(t)}setInclusion(t){if(this.bv!==void 0)return this.bv;if(this.shape instanceof Ve.Line||this.shape instanceof Ve.Ray)return this.bv=Ve.OUTSIDE,this.bv;if(this.bvStart===void 0&&(this.bvStart=rJ(t,this.start)),this.bvEnd===void 0&&(this.bvEnd=rJ(t,this.end)),this.bvStart===Ve.OUTSIDE||this.bvEnd==Ve.OUTSIDE)this.bv=Ve.OUTSIDE;else if(this.bvStart===Ve.INSIDE||this.bvEnd==Ve.INSIDE)this.bv=Ve.INSIDE;else{let e=rJ(t,this.middle());this.bv=e}return this.bv}setOverlap(t){let e,n=this.shape,o=t.shape;n instanceof Ve.Segment&&o instanceof Ve.Segment?n.start.equalTo(o.start)&&n.end.equalTo(o.end)?e=Ve.OVERLAP_SAME:n.start.equalTo(o.end)&&n.end.equalTo(o.start)&&(e=Ve.OVERLAP_OPPOSITE):(n instanceof Ve.Arc&&o instanceof Ve.Arc||n instanceof Ve.Segment&&o instanceof Ve.Arc||n instanceof Ve.Arc&&o instanceof Ve.Segment)&&(n.start.equalTo(o.start)&&n.end.equalTo(o.end)&&n.middle().equalTo(o.middle())?e=Ve.OVERLAP_SAME:n.start.equalTo(o.end)&&n.end.equalTo(o.start)&&n.middle().equalTo(o.middle())&&(e=Ve.OVERLAP_OPPOSITE)),this.overlap===void 0&&(this.overlap=e),t.overlap===void 0&&(t.overlap=e)}svg(){if(this.shape instanceof Ve.Segment)return` L${this.shape.end.x},${this.shape.end.y}`;if(this.shape instanceof Ve.Arc){let t,e=this.shape,n=e.counterClockwise?"1":"0";if(Ve.Utils.EQ(e.sweep,2*Math.PI)){let o=e.counterClockwise?1:-1,i=new Ve.Arc(e.pc,e.r,e.startAngle,e.startAngle+o*Math.PI,e.counterClockwise),r=new Ve.Arc(e.pc,e.r,e.startAngle+o*Math.PI,e.endAngle,e.counterClockwise);return t="0",` A${i.r},${i.r} 0 ${t},${n} ${i.end.x},${i.end.y}
                    A${r.r},${r.r} 0 ${t},${n} ${r.end.x},${r.end.y}`}return t=e.sweep<=Math.PI?"0":"1",` A${e.r},${e.r} 0 ${t},${n} ${e.end.x},${e.end.y}`}}toJSON(){return this.shape.toJSON()}};var _to=class extends y6e{constructor(e,n){super(e,n),this.setCircularLinks()}setCircularLinks(){this.isEmpty()||(this.last.next=this.first,this.first.prev=this.last)}[Symbol.iterator](){let e;return{next:()=>{let n=e||this.first,o=!this.first||!!e&&e===this.first;return e=n?n.next:void 0,{value:n,done:o}}}}append(e){return super.append(e),this.setCircularLinks(),this}insert(e,n){return super.insert(e,n),this.setCircularLinks(),this}remove(e){return super.remove(e),this}};Ve.Face=class Wte extends _to{constructor(e,...n){if(super(),this._box=void 0,this._orientation=void 0,n.length!==0){if(n.length===1){if(n[0]instanceof Array){let o=n[0];if(o.length===0)return;if(o.every(i=>i instanceof Ve.Point)){let i=Wte.points2segments(o);this.shapes2face(e.edges,i)}else if(o.every(i=>i instanceof Array&&i.length===2)){let i=o.map(s=>new Ve.Point(s[0],s[1])),r=Wte.points2segments(i);this.shapes2face(e.edges,r)}else if(o.every(i=>i instanceof Ve.Segment||i instanceof Ve.Arc))this.shapes2face(e.edges,o);else if(o.every(i=>i.name==="segment"||i.name==="arc")){let i=[];for(let r of o){let s;s=r.name==="segment"?new Ve.Segment(r):new Ve.Arc(r),i.push(s)}this.shapes2face(e.edges,i)}}else if(n[0]instanceof Wte){let o=n[0];this.first=o.first,this.last=o.last;for(let i of o)e.edges.add(i)}else if(n[0]instanceof Ve.Circle)this.shapes2face(e.edges,[n[0].toArc(U1t)]);else if(n[0]instanceof Ve.Box){let o=n[0];this.shapes2face(e.edges,[new Ve.Segment(new Ve.Point(o.xmin,o.ymin),new Ve.Point(o.xmax,o.ymin)),new Ve.Segment(new Ve.Point(o.xmax,o.ymin),new Ve.Point(o.xmax,o.ymax)),new Ve.Segment(new Ve.Point(o.xmax,o.ymax),new Ve.Point(o.xmin,o.ymax)),new Ve.Segment(new Ve.Point(o.xmin,o.ymax),new Ve.Point(o.xmin,o.ymin))])}}n.length===2&&n[0]instanceof Ve.Edge&&n[1]instanceof Ve.Edge&&(this.first=n[0],this.last=n[1],this.last.next=this.first,this.first.prev=this.last,this.setArcLength())}}get edges(){return this.toArray()}get vertices(){return this.edges.map(e=>e.shape.start.clone())}get shapes(){return this.edges.map(e=>e.shape.clone())}get box(){if(this._box===void 0){let e=new Ve.Box;for(let n of this)e=e.merge(n.box);this._box=e}return this._box}get perimeter(){return this.last.arc_length+this.last.length}pointAtLength(e){if(e>this.perimeter||e<0)return null;let n=null;for(let o of this)if(e>=o.arc_length&&(o===this.last||e<o.next.arc_length)){n=o.pointAtLength(e-o.arc_length);break}return n}static points2segments(e){let n=[];for(let o=0;o<e.length;o++)e[o].equalTo(e[(o+1)%e.length])||n.push(new Ve.Segment(e[o],e[(o+1)%e.length]));return n}shapes2face(e,n){for(let o of n){let i=new Ve.Edge(o);this.append(i),e.add(i)}}append(e){return super.append(e),this.setOneEdgeArcLength(e),e.face=this,this}insert(e,n){return super.insert(e,n),this.setOneEdgeArcLength(e),e.face=this,this}remove(e){return super.remove(e),this.setArcLength(),this}merge_with_next_edge(e){return e.shape.end.x=e.next.shape.end.x,e.shape.end.y=e.next.shape.end.y,this.remove(e.next),this}reverse(){let e=[],n=this.last;do n.shape=n.shape.reverse(),e.push(n),n=n.prev;while(n!==this.last);this.first=void 0,this.last=void 0;for(let o of e)this.first===void 0?(o.prev=o,o.next=o,this.first=o,this.last=o):(o.prev=this.last,this.last.next=o,this.last=o,this.last.next=this.first,this.first.prev=this.last),this.setOneEdgeArcLength(o);this._orientation!==void 0&&(this._orientation=void 0,this._orientation=this.orientation())}setArcLength(){for(let e of this)this.setOneEdgeArcLength(e),e.face=this}setOneEdgeArcLength(e){e===this.first?e.arc_length=0:e.arc_length=e.prev.arc_length+e.prev.length}area(){return Math.abs(this.signedArea())}signedArea(){let e=0,n=this.box.ymin;for(let o of this)e+=o.shape.definiteIntegral(n);return e}orientation(){if(this._orientation===void 0){let e=this.signedArea();Ve.Utils.EQ_0(e)?this._orientation=eJ.NOT_ORIENTABLE:Ve.Utils.LT(e,0)?this._orientation=eJ.CCW:this._orientation=eJ.CW}return this._orientation}isSimple(e){return Wte.getSelfIntersections(this,e,!0).length===0}static getSelfIntersections(e,n,o=!1){let i=[];for(let r of e){let s=n.search(r.box);for(let a of s){if(r===a||a.face!==e||r.shape instanceof Ve.Segment&&a.shape instanceof Ve.Segment&&(r.next===a||r.prev===a))continue;let A=r.shape.intersect(a.shape);for(let c of A)if((!c.equalTo(r.start)||!c.equalTo(a.end)||a!==r.prev)&&(!c.equalTo(r.end)||!c.equalTo(a.start)||a!==r.next)&&(i.push(c),o))break;if(i.length>0&&o)break}if(i.length>0&&o)break}return i}findEdgeByPoint(e){let n;for(let o of this)if(!e.equalTo(o.shape.start)&&(e.equalTo(o.shape.end)||o.shape.contains(e))){n=o;break}return n}toPolygon(){return new Ve.Polygon(this.shapes)}toJSON(){return this.edges.map(e=>e.toJSON())}svg(){let e=`M${this.first.start.x},${this.first.start.y}`;for(let n of this)e+=n.svg();return e+=" z",e}},Ve.Ray=class r5n extends rv{constructor(...e){if(super(),this.pt=new Ve.Point,this.norm=new Ve.Vector(0,1),e.length!==0&&(e.length>=1&&e[0]instanceof Ve.Point&&(this.pt=e[0].clone()),e.length!==1)){if(!(e.length===2&&e[1]instanceof Ve.Vector))throw ld.ILLEGAL_PARAMETERS;this.norm=e[1].clone()}}clone(){return new r5n(this.pt,this.norm)}get slope(){return new Ve.Vector(this.norm.y,-this.norm.x).slope}get box(){let e=this.slope;return new Ve.Box(e>Math.PI/2&&e<3*Math.PI/2?Number.NEGATIVE_INFINITY:this.pt.x,e>=0&&e<=Math.PI?this.pt.y:Number.NEGATIVE_INFINITY,e>=Math.PI/2&&e<=3*Math.PI/2?this.pt.x:Number.POSITIVE_INFINITY,e>=Math.PI&&e<=2*Math.PI||e===0?this.pt.y:Number.POSITIVE_INFINITY)}get start(){return this.pt}get end(){}get length(){return Number.POSITIVE_INFINITY}contains(e){if(this.pt.equalTo(e))return!0;let n=new Ve.Vector(this.pt,e);return Ve.Utils.EQ_0(this.norm.dot(n))&&Ve.Utils.GE(n.cross(this.norm),0)}coord(e){return BIt(e.x,e.y).cross(this.norm)}split(e){return this.contains(e)?this.pt.equalTo(e)?[this]:[new Ve.Segment(this.pt,e),new Ve.Ray(e,this.norm)]:[]}intersect(e){return e instanceof Ve.Point?this.contains(e)?[e]:[]:e instanceof Ve.Segment?b6e(this,e):e instanceof Ve.Arc?S6e(this,e):e instanceof Ve.Line?sIt(this,e):e instanceof Ve.Ray?(o=e,cL(nv(n=this),nv(o)).filter(i=>n.contains(i)).filter(i=>o.contains(i))):e instanceof Ve.Circle?rIt(this,e):e instanceof Ve.Box?(function(i,r){return lL(nv(i),r).filter(s=>i.contains(s))})(this,e):e instanceof Ve.Polygon?aIt(this,e):e instanceof Ve.Multiline?gL(this,e):void 0;var n,o}rotate(e,n=new Ve.Point){return new Ve.Ray(this.pt.rotate(e,n),this.norm.rotate(e))}transform(e){return new Ve.Ray(this.pt.transform(e),this.norm.clone())}get name(){return"ray"}svg(e,n={}){let o=lL(new Ve.Line(this.pt,this.norm),e);return o=o.filter(i=>this.contains(i)),o.length===0||o.length===2?"":new Ve.Segment(this.pt,o[0]).svg(n)}},Ve.ray=(...t)=>new Ve.Ray(...t),Ve.Polygon=class YM{constructor(){this.faces=new Ve.PlanarSet,this.edges=new Ve.PlanarSet;let e=[...arguments];if(e.length===1&&(e[0]instanceof Array&&e[0].length>0||e[0]instanceof Ve.Circle||e[0]instanceof Ve.Box)){let n=e[0];if(e[0]instanceof Array&&e[0].every(o=>o instanceof Array))if(n.every(o=>o instanceof Array&&o.length===2&&typeof o[0]=="number"&&typeof o[1]=="number"))this.faces.add(new Ve.Face(this,n));else for(let o of n)if(o instanceof Array&&o[0]instanceof Array&&o[0].every(i=>i instanceof Array&&i.length===2&&typeof i[0]=="number"&&typeof i[1]=="number"))for(let i of o)this.faces.add(new Ve.Face(this,i));else this.faces.add(new Ve.Face(this,o));else this.faces.add(new Ve.Face(this,n))}}get box(){return[...this.faces].reduce((e,n)=>e.merge(n.box),new Ve.Box)}get vertices(){return[...this.faces].flatMap(e=>e.vertices)}clone(){let e=new YM;for(let n of this.faces)e.addFace(n.shapes);return e}createFromArray(e){const n=new YM;return e.forEach(o=>[...o.faces].forEach(i=>n.addFace(i.shapes))),n}isEmpty(){return this.edges.size===0||this.faces.size===0}isValid(){let e=!0;for(let n of this.faces)if(!n.isSimple(this.edges)){e=!1;break}return e}area(){let e=[...this.faces].reduce((n,o)=>n+o.signedArea(),0);return Math.abs(e)}addFace(...e){let n=new Ve.Face(this,...e);return this.faces.add(n),n}deleteFace(e){for(let n of e)this.edges.delete(n);return this.faces.delete(e)}recreateFaces(){this.faces.clear();for(let o of this.edges)o.face=null;let e,n=!0;for(;n;){n=!1;for(let o of this.edges)if(o.face===null){e=o,n=!0;break}if(n){let o=e;do o=o.next;while(o.next!==e);this.addFace(e,o)}}}removeChain(e,n,o){if(o.next!==n){for(let i=n;i!==o.next;i=i.next)if(e.remove(i),this.edges.delete(i),e.isEmpty()){this.deleteFace(e);break}}else this.deleteFace(e)}addVertex(e,n){let o=n.shape.split(e);if(o[0]===null)return n.prev;if(o[1]===null)return n;let i=new Ve.Edge(o[0]),r=n.prev;return n.face.insert(i,r),this.edges.delete(n),this.edges.add(i),n.shape=o[1],this.edges.add(n),i}removeEndVertex(e){const n=e.next;n!==e&&(e.face.merge_with_next_edge(e),this.edges.delete(n))}cut(e){const n=this.splitToIslands().flatMap(o=>o._cutSingleIsland(e)).filter(o=>o.isValid()&&o.isEmpty()===!1);return this.createFromArray(n)}_cutSingleIsland(e){let n=this.clone();const o=e.clone();let i,r,s={int_points1:[],int_points2:[],int_points1_sorted:[],int_points2_sorted:[]};for(let a of o.edges)for(let A of n.edges){let c=nIt(a,A);for(let l of c)dL(a,l,s.int_points1),dL(A,l,s.int_points2)}if(s.int_points1.length===0)return n;s.int_points1_sorted=ov(s.int_points1),s.int_points2_sorted=ov(s.int_points2),pL(o,s.int_points1_sorted),pL(n,s.int_points2_sorted),Q6e(s),s.int_points1_sorted=ov(s.int_points1),s.int_points2_sorted=ov(s.int_points2),v6e(s.int_points1),w6e(s.int_points1,n);for(let a of s.int_points1_sorted)a.edge_before&&a.edge_after&&a.edge_before.bv===a.edge_after.bv&&(s.int_points2[a.id]=-1,a.id=-1);if(s.int_points1=s.int_points1.filter(a=>a.id>=0),s.int_points2=s.int_points2.filter(a=>a.id>=0),s.int_points1.forEach((a,A)=>{a.id=A}),s.int_points2.forEach((a,A)=>{a.id=A}),s.int_points1.length===0)return n;s.int_points1_sorted=ov(s.int_points1),s.int_points2_sorted=ov(s.int_points2);for(let a=1;a<s.int_points1_sorted.length;a++)if(r=s.int_points1_sorted[a],i=s.int_points1_sorted[a-1],r.edge_before&&r.edge_before.bv===1){let A=i.edge_after,c=r.edge_before,l=o.getChain(A,c);cIt(s.int_points2[i.id],s.int_points2[r.id],l),l.forEach(u=>n.edges.add(u)),l=l.reverse().map(u=>new Ve.Edge(u.shape.reverse()));for(let u=0;u<l.length-1;u++)l[u].next=l[u+1],l[u+1].prev=l[u];cIt(s.int_points2[r.id],s.int_points2[i.id],l),l.forEach(u=>n.edges.add(u))}return n.recreateFaces(),n}cutWithLine(e){let n=new zD([e]);return this.cut(n)}findEdgeByPoint(e){let n;for(let o of this.faces)if(n=o.findEdgeByPoint(e),n!==void 0)break;return n}splitToIslands(){if(this.isEmpty())return[];let e=this.toArray();e.sort((i,r)=>r.area()-i.area());let n=[...e[0].faces][0].orientation(),o=e.filter(i=>[...i.faces][0].orientation()===n);for(let i of e){let r=[...i.faces][0];if(r.orientation()!==n){for(let s of o)if(r.shapes.every(a=>s.contains(a))){s.addFace(r.shapes);break}}}return o}rearrange(){if(this.faces.size<=1)return this.clone();const e=this.splitToIslands(),n=new YM;return e.forEach(o=>{o.faces.forEach(i=>n.addFace(i.shapes))}),n}orientation(){return this.isEmpty()?eJ.NOT_ORIENTABLE:[...this.faces][0].orientation()}isOuter(e){return e.orientation()===this.orientation()}isMultiPolygon(){let e=0;return this.faces.forEach(n=>{this.isOuter(n)&&e++}),e>1}reverse(){for(let e of this.faces)e.reverse();return this}contains(e){if(e instanceof Ve.Point){let n=rJ(this,e);return n===1||n===2}return xIt(this,e)}distanceTo(e){if(e instanceof Ve.Point){let[n,o]=Ve.Distance.point2polygon(e,this);return o=o.reverse(),[n,o]}if(e instanceof Ve.Circle||e instanceof Ve.Line||e instanceof Ve.Segment||e instanceof Ve.Arc){let[n,o]=Ve.Distance.shape2polygon(e,this);return o=o.reverse(),[n,o]}if(e instanceof Ve.Polygon){let n,o,i=[Number.POSITIVE_INFINITY,new Ve.Segment];for(let r of this.edges){let s=i[0];[n,o]=Ve.Distance.shape2planarSet(r.shape,e.edges,s),Ve.Utils.LT(n,s)&&(i=[n,o])}return i}}intersect(e){return e instanceof Ve.Point?this.contains(e)?[e]:[]:e instanceof Ve.Line?nJ(e,this):e instanceof Ve.Ray?aIt(e,this):e instanceof Ve.Circle?tIt(e,this):e instanceof Ve.Segment?E6e(e,this):e instanceof Ve.Arc?B6e(e,this):e instanceof Ve.Polygon?(function(n,o){let i=[];if(n.isEmpty()||o.isEmpty()||n.box.not_intersect(o.box))return i;for(let r of n.edges)i=[...i,...oIt(r,o)];return i})(e,this):e instanceof Ve.Multiline?(function(n,o){let i=[];if(o.isEmpty()||n.size===0)return i;for(let r of n)i=[...i,...oIt(r,o)];return i})(e,this):void 0}translate(e){let n=new YM;for(let o of this.faces)n.addFace(o.shapes.map(i=>i.translate(e)));return n}rotate(e=0,n=new Ve.Point){let o=new YM;for(let i of this.faces)o.addFace(i.shapes.map(r=>r.rotate(e,n)));return o}scale(e,n){let o=new YM;for(let i of this.faces)o.addFace(i.shapes.map(r=>r.scale(e,n)));return o}transform(e=new Ve.Matrix){let n=new YM;for(let o of this.faces)n.addFace(o.shapes.map(i=>i.transform(e)));return n}toJSON(){return[...this.faces].map(e=>e.toJSON())}toArray(){return[...this.faces].map(e=>e.toPolygon())}dpath(){return[...this.faces].reduce((e,n)=>e+n.svg(),"")}svg(e={}){let n=`
<path ${KD({fillRule:"evenodd",fill:"lightcyan",...e})} d="`;for(let o of this.faces)n+=`
${o.svg()}`;return n+=`" >
</path>`,n}},Ve.polygon=(...t)=>new Ve.Polygon(...t);var{Circle:k6e,Line:bIt,Point:SIt,Vector:kae,Utils:F6e}=Ve;Ve.Inversion=class Kye{constructor(e){this.circle=e}get inversion_circle(){return this.circle}static inversePoint(e,n){const o=new kae(e.pc,n),i=e.r*e.r,r=o.dot(o);return F6e.EQ_0(r)?new SIt(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY):e.pc.translate(o.multiply(i/r))}static inverseCircle(e,n){const o=e.pc.distanceTo(n.pc)[0];if(F6e.EQ(o,n.r)){let i=e.r*e.r/(2*n.r),r=new kae(e.pc,n.pc);r=r.normalize();let s=e.pc.translate(r.multiply(i));return new bIt(s,r)}{let i=new kae(e.pc,n.pc),r=e.r*e.r/(i.dot(i)-n.r*n.r),s=e.pc.translate(i.multiply(r)),a=Math.abs(r)*n.r;return new k6e(s,a)}}static inverseLine(e,n){const[o,i]=e.pc.distanceTo(n);if(F6e.EQ_0(o))return n.clone();{let r=e.r*e.r/(2*o),s=new kae(e.pc,i.end);return s=s.multiply(r/o),new k6e(e.pc.translate(s),r)}}inverse(e){return e instanceof SIt?Kye.inversePoint(this.circle,e):e instanceof k6e?Kye.inverseCircle(this.circle,e):e instanceof bIt?Kye.inverseLine(this.circle,e):void 0}},Ve.inversion=t=>new Ve.Inversion(t),Ve.Distance=class Tr{static point2point(e,n){return e.distanceTo(n)}static point2line(e,n){let o=e.projectionOn(n);return[new Ve.Vector(e,o).length,new Ve.Segment(e,o)]}static point2circle(e,n){let[o,i]=e.distanceTo(n.center);if(Ve.Utils.EQ_0(o))return[n.r,new Ve.Segment(e,n.toArc().start)];{let r=Math.abs(o-n.r),s=new Ve.Vector(n.pc,e).normalize().multiply(n.r),a=n.pc.translate(s);return[r,new Ve.Segment(e,a)]}}static point2segment(e,n){if(n.start.equalTo(n.end))return Tr.point2point(e,n.start);let o,i,r=new Ve.Vector(n.start,n.end),s=new Ve.Vector(n.start,e),a=new Ve.Vector(n.end,e),A=r.dot(s),c=-r.dot(a);if(Ve.Utils.GE(A,0)&&Ve.Utils.GE(c,0)){let l=n.tangentInStart();return o=Math.abs(l.cross(s)),i=n.start.translate(l.multiply(l.dot(s))),[o,new Ve.Segment(e,i)]}return A<0?e.distanceTo(n.start):e.distanceTo(n.end)}static point2arc(e,n){let o,i,r=new Ve.Circle(n.pc,n.r),s=[];return[o,i]=Tr.point2circle(e,r),i.end.on(n)&&s.push(Tr.point2circle(e,r)),s.push(Tr.point2point(e,n.start)),s.push(Tr.point2point(e,n.end)),Tr.sort(s),s[0]}static point2edge(e,n){return n.shape instanceof Ve.Segment?Tr.point2segment(e,n.shape):Tr.point2arc(e,n.shape)}static segment2line(e,n){let o=e.intersect(n);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];let i=[];return i.push(Tr.point2line(e.start,n)),i.push(Tr.point2line(e.end,n)),Tr.sort(i),i[0]}static segment2segment(e,n){let o=Nae(e,n);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];let i,r,s=[];return[i,r]=Tr.point2segment(n.start,e),s.push([i,r.reverse()]),[i,r]=Tr.point2segment(n.end,e),s.push([i,r.reverse()]),s.push(Tr.point2segment(e.start,n)),s.push(Tr.point2segment(e.end,n)),Tr.sort(s),s[0]}static segment2circle(e,n){let o=e.intersect(n);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];let i=new Ve.Line(e.ps,e.pe),[r,s]=Tr.point2line(n.center,i);if(Ve.Utils.GE(r,n.r)&&s.end.on(e))return Tr.point2circle(s.end,n);{let[a,A]=Tr.point2circle(e.start,n),[c,l]=Tr.point2circle(e.end,n);return Ve.Utils.LT(a,c)?[a,A]:[c,l]}}static segment2arc(e,n){let o=e.intersect(n);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];let i=new Ve.Line(e.ps,e.pe),r=new Ve.Circle(n.pc,n.r),[s,a]=Tr.point2line(r.center,i);if(Ve.Utils.GE(s,r.r)&&a.end.on(e)){let[u,g]=Tr.point2circle(a.end,r);if(g.end.on(n))return[u,g]}let A,c,l=[];return l.push(Tr.point2arc(e.start,n)),l.push(Tr.point2arc(e.end,n)),[A,c]=Tr.point2segment(n.start,e),l.push([A,c.reverse()]),[A,c]=Tr.point2segment(n.end,e),l.push([A,c.reverse()]),Tr.sort(l),l[0]}static circle2circle(e,n){let o=e.intersect(n);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];if(e.center.equalTo(n.center)){let i=e.toArc(),r=n.toArc();return Tr.point2point(i.start,r.start)}{let i=new Ve.Line(e.center,n.center),r=i.intersect(e),s=i.intersect(n),a=[];return a.push(Tr.point2point(r[0],s[0])),a.push(Tr.point2point(r[0],s[1])),a.push(Tr.point2point(r[1],s[0])),a.push(Tr.point2point(r[1],s[1])),Tr.sort(a),a[0]}}static circle2line(e,n){let o=e.intersect(n);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];let[i,r]=Tr.point2line(e.center,n),[s,a]=Tr.point2circle(r.end,e);return a=a.reverse(),[s,a]}static arc2line(e,n){let o=n.intersect(e);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];let i=new Ve.Circle(e.center,e.r),[r,s]=Tr.point2line(i.center,n);if(!Ve.Utils.GE(r,i.r)){let a=[];return a.push(Tr.point2line(e.start,n)),a.push(Tr.point2line(e.end,n)),Tr.sort(a),a[0]}{let[a,A]=Tr.point2circle(s.end,i);if(A.end.on(e))return[a,A]}}static arc2circle(e,n){let o=e.intersect(n);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];let i=new Ve.Circle(e.center,e.r),[r,s]=Tr.circle2circle(i,n);if(s.start.on(e))return[r,s];{let a=[];return a.push(Tr.point2circle(e.start,n)),a.push(Tr.point2circle(e.end,n)),Tr.sort(a),a[0]}}static arc2arc(e,n){let o=e.intersect(n);if(o.length>0)return[0,new Ve.Segment(o[0],o[0])];let i=new Ve.Circle(e.center,e.r),r=new Ve.Circle(n.center,n.r),[s,a]=Tr.circle2circle(i,r);if(a.start.on(e)&&a.end.on(n))return[s,a];{let A,c,l=[];return[A,c]=Tr.point2arc(e.start,n),c.end.on(n)&&l.push([A,c]),[A,c]=Tr.point2arc(e.end,n),c.end.on(n)&&l.push([A,c]),[A,c]=Tr.point2arc(n.start,e),c.end.on(e)&&l.push([A,c.reverse()]),[A,c]=Tr.point2arc(n.end,e),c.end.on(e)&&l.push([A,c.reverse()]),[A,c]=Tr.point2point(e.start,n.start),l.push([A,c]),[A,c]=Tr.point2point(e.start,n.end),l.push([A,c]),[A,c]=Tr.point2point(e.end,n.start),l.push([A,c]),[A,c]=Tr.point2point(e.end,n.end),l.push([A,c]),Tr.sort(l),l[0]}}static point2polygon(e,n){let o=[Number.POSITIVE_INFINITY,new Ve.Segment];for(let i of n.edges){let[r,s]=Tr.point2edge(e,i);Ve.Utils.LT(r,o[0])&&(o=[r,s])}return o}static shape2polygon(e,n){let o=[Number.POSITIVE_INFINITY,new Ve.Segment];for(let i of n.edges){let[r,s]=e.distanceTo(i.shape);Ve.Utils.LT(r,o[0])&&(o=[r,s])}return o}static polygon2polygon(e,n){let o=[Number.POSITIVE_INFINITY,new Ve.Segment];for(let i of e.edges)for(let r of n.edges){let[s,a]=i.shape.distanceTo(r.shape);Ve.Utils.LT(s,o[0])&&(o=[s,a])}return o}static box2box_minmax(e,n){let o=Math.max(Math.max(e.xmin-n.xmax,0),Math.max(n.xmin-e.xmax,0)),i=Math.max(Math.max(e.ymin-n.ymax,0),Math.max(n.ymin-e.ymax,0)),r=o*o+i*i,s=e.merge(n),a=s.xmax-s.xmin,A=s.ymax-s.ymin;return[r,a*a+A*A]}static minmax_tree_process_level(e,n,o,i){let r,s;for(let A of n){[r,s]=Tr.box2box_minmax(e.box,A.item.key);for(let c of A.item.values)c instanceof Ve.Edge?i.insert([r,s],c.shape):i.insert([r,s],c);Ve.Utils.LT(s,o)&&(o=s)}if(n.length===0)return o;let a=[...n.map(A=>A.left.isNil()?void 0:A.left).filter(A=>A!==void 0),...n.map(A=>A.right.isNil()?void 0:A.right).filter(A=>A!==void 0)].filter(A=>{let[c,l]=Tr.box2box_minmax(e.box,A.max);return Ve.Utils.LE(c,o)});return o=Tr.minmax_tree_process_level(e,a,o,i)}static minmax_tree(e,n,o){let i=new T6e,r=[n.index.root],s=o<Number.POSITIVE_INFINITY?o*o:Number.POSITIVE_INFINITY;return s=Tr.minmax_tree_process_level(e,r,s,i),i}static minmax_tree_calc_distance(e,n,o){let i,r;if(n!=null&&!n.isNil()){if([i,r]=Tr.minmax_tree_calc_distance(e,n.left,o),r)return[i,r];if(Ve.Utils.LT(i[0],Math.sqrt(n.item.key.low)))return[i,!0];let[s,a]=Tr.distanceToArray(e,n.item.values);return Ve.Utils.LT(s,i[0])&&(i=[s,a]),[i,r]=Tr.minmax_tree_calc_distance(e,n.right,i),[i,r]}return[o,!1]}static shape2planarSet(e,n,o=Number.POSITIVE_INFINITY){let i=[o,new Ve.Segment],r=!1;if(n instanceof Ve.PlanarSet){let s=Tr.minmax_tree(e,n,o);[i,r]=Tr.minmax_tree_calc_distance(e,s.root,i)}return i}static sort(e){e.sort((n,o)=>Ve.Utils.LT(n[0],o[0])?-1:Ve.Utils.GT(n[0],o[0])?1:0)}static distance(e,n){return e.distanceTo(n)}static distanceToArray(e,n){let o=[Number.POSITIVE_INFINITY,new Ve.Segment];for(let i of n){let[r,s]=e.distanceTo(i);Ve.Utils.LT(r,o[0])&&(o=[r,s])}return o}static shape2multiline(e,n){let o=[Number.POSITIVE_INFINITY,new Ve.Segment];for(let i of n){let[r,s]=Tr.distance(e,i.shape);Ve.Utils.LT(r,o[0])&&(o=[r,s])}return o}static multiline2multiline(e,n){let o=[Number.POSITIVE_INFINITY,new Ve.Segment];for(let i of e)for(let r of n){let[s,a]=Tr.distance(i.shape,r.shape);Ve.Utils.LT(s,o[0])&&(o=[s,a])}return o}};var{Multiline:fto,Point:QIt,Segment:Ito,Polygon:vIt}=Ve;function L6e(t){return new QIt(t.split(" ").map(Number))}function wIt(t){return t.split(", ").map(L6e)}function H6e(t){const e=wIt(t);let n=[];for(let o=0;o<e.length-1;o++)n.push(new Ito(e[o],e[o+1]));return new fto(n)}function PIt(t){const e=t.replace(/\(\(/,"").replace(/\)\)$/,"").split("), ("),n=new vIt;let o;return e.forEach((i,r)=>{let s=i.split(", ").map(A=>new QIt(A.split(" ").map(Number)));const a=n.addFace(s);r===0?o=a.orientation():a.orientation()===o&&a.reverse()}),n}function Cto(t){return t.startsWith("POLYGON")?PIt(t.replace(/^POLYGON /,"")):(function(e){const n=e.split(/\)\), \(\(/).map(i=>"(("+i+"))").map(PIt),o=new vIt;return n.reduce((i,r)=>[...i,...r?.faces],[]).forEach(i=>o.addFace([...i?.shapes])),o})(t.replace(/^MULTIPOLYGON \(\(\((.*)\)\)\)$/,"$1"))}function MIt(t){return t.split(`
`)?.every(e=>e.includes("POINT"))}function DIt(t){return t.split(`
`)?.every(e=>e.includes("LINESTRING"))}Ve.isWktString=function(t){return t.startsWith("POINT")||MIt(t)||t.startsWith("LINESTRING")||DIt(t)||t.startsWith("MULTILINESTRING")||t.startsWith("POLYGON")||t.startsWith("MULTIPOINT")||t.startsWith("MULTIPOLYGON")||t.startsWith("GEOMETRYCOLLECTION")},Ve.parseWKT=function t(e){if(e.startsWith("POINT"))return L6e(e.replace(/^POINT \(/,"").replace(/\)$/,""));if(e.startsWith("MULTIPOINT"))return wIt(e.replace(/^MULTIPOINT \(/,"").replace(/\)$/,""));if(e.startsWith("LINESTRING"))return H6e(e.replace(/^LINESTRING \(/,"").replace(/\)$/,""));if(e.startsWith("MULTILINESTRING"))return(function(n){return n.replace(/\(\(/,"").replace(/\)\)$/,"").split("), (").map(H6e)})(e.replace(/^MULTILINESTRING /,""));if(e.startsWith("POLYGON")||e.startsWith("MULTIPOLYGON"))return Cto(e);if(e.startsWith("GEOMETRYCOLLECTION")){const n=/(?<type>POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \((?:[^\(\)]|\([^\)]*\))*\)/g,o=e.match(n);return o[0].startsWith("GEOMETRYCOLLECTION")&&(o[0]=o[0].replace("GEOMETRYCOLLECTION (","")),o.map(t).map(i=>i instanceof Array?i:[i]).reduce((i,r)=>[...i,...r],[])}return MIt(e)?(function(n){return n.split(`
`).map(o=>o.match(/\(([^)]+)\)/)[1]).map(L6e)})(e):DIt(e)?(function(n){return n.split(`
`).map(o=>o.match(/\(([^)]+)\)/)[1]).map(H6e).reduce((o,i)=>[...o,...i],[])})(e):[]},Ve.BooleanOperations=ato,Ve.Relations=dto,JD=Deo(),NIt=1,O6e=JD!=null?yeo(Eeo(JD)):{},((t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of B1t(e))Beo.call(t,i)||i===n||E1t(t,i,{get:()=>e[i],enumerable:!(o=xeo(e,i))||o.enumerable})})(!NIt&&JD&&JD.__esModule?O6e:E1t(O6e,"default",{value:JD,enumerable:!0}),JD);var JD,NIt,O6e,yto=Object.create,RIt=Object.defineProperty,xto=Object.getOwnPropertyDescriptor,TIt=Object.getOwnPropertyNames,Eto=Object.getPrototypeOf,Bto=Object.prototype.hasOwnProperty,WD=(t,e)=>function(){return e||(0,t[TIt(t)[0]])((e={exports:{}}).exports,e),e.exports},kIt=(t,e,n)=>(n=t!=null?yto(Eto(t)):{},((o,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of TIt(i))Bto.call(o,a)||a===r||RIt(o,a,{get:()=>i[a],enumerable:!(s=xto(i,a))||s.enumerable});return o})(t&&t.__esModule?n:RIt(n,"default",{value:t,enumerable:!0}),t)),bto=WD({"node_modules/is-buffer/index.js"(t,e){function n(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}e.exports=function(o){return o!=null&&(n(o)||(function(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&n(i.slice(0,0))})(o)||!!o._isBuffer)}}}),Sto=WD({"node_modules/kind-of/index.js"(t,e){var n=bto(),o=Object.prototype.toString;e.exports=function(i){if(i===void 0)return"undefined";if(i===null)return"null";if(i===!0||i===!1||i instanceof Boolean)return"boolean";if(typeof i=="string"||i instanceof String)return"string";if(typeof i=="number"||i instanceof Number)return"number";if(typeof i=="function"||i instanceof Function)return"function";if(Array.isArray!==void 0&&Array.isArray(i))return"array";if(i instanceof RegExp)return"regexp";if(i instanceof Date)return"date";var r=o.call(i);return r==="[object RegExp]"?"regexp":r==="[object Date]"?"date":r==="[object Arguments]"?"arguments":r==="[object Error]"?"error":n(i)?"buffer":r==="[object Set]"?"set":r==="[object WeakSet]"?"weakset":r==="[object Map]"?"map":r==="[object WeakMap]"?"weakmap":r==="[object Symbol]"?"symbol":r==="[object Int8Array]"?"int8array":r==="[object Uint8Array]"?"uint8array":r==="[object Uint8ClampedArray]"?"uint8clampedarray":r==="[object Int16Array]"?"int16array":r==="[object Uint16Array]"?"uint16array":r==="[object Int32Array]"?"int32array":r==="[object Uint32Array]"?"uint32array":r==="[object Float32Array]"?"float32array":r==="[object Float64Array]"?"float64array":"object"}}}),Qto=WD({"node_modules/rename-keys/index.js"(t,e){(function(){function n(o,i){if(typeof i!="function")return o;var r={};for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[i(s,o[s])||s]=o[s]);return r}e!==void 0&&e.exports?e.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):window.rename=n})()}}),vto=WD({"node_modules/deep-rename-keys/index.js"(t,e){var n=Sto(),o=Qto();e.exports=function i(r,s){var a=n(r);if(a!=="object"&&a!=="array")throw new Error("expected an object");var A=[];for(var c in a==="object"&&(r=o(r,s),A={}),r)if(r.hasOwnProperty(c)){var l=r[c];n(l)==="object"||n(l)==="array"?A[c]=i(l,s):A[c]=l}return A}}}),FIt=WD({"node_modules/eventemitter3/index.js"(t,e){var n=Object.prototype.hasOwnProperty,o="~";function i(){}function r(a,A,c){this.fn=a,this.context=A,this.once=c||!1}function s(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(o=!1)),s.prototype.eventNames=function(){var a,A,c=[];if(this._eventsCount===0)return c;for(A in a=this._events)n.call(a,A)&&c.push(o?A.slice(1):A);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(a)):c},s.prototype.listeners=function(a,A){var c=o?o+a:a,l=this._events[c];if(A)return!!l;if(!l)return[];if(l.fn)return[l.fn];for(var u=0,g=l.length,h=new Array(g);u<g;u++)h[u]=l[u].fn;return h},s.prototype.emit=function(a,A,c,l,u,g){var h=o?o+a:a;if(!this._events[h])return!1;var d,p,m=this._events[h],_=arguments.length;if(m.fn){switch(m.once&&this.removeListener(a,m.fn,void 0,!0),_){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,A),!0;case 3:return m.fn.call(m.context,A,c),!0;case 4:return m.fn.call(m.context,A,c,l),!0;case 5:return m.fn.call(m.context,A,c,l,u),!0;case 6:return m.fn.call(m.context,A,c,l,u,g),!0}for(p=1,d=new Array(_-1);p<_;p++)d[p-1]=arguments[p];m.fn.apply(m.context,d)}else{var f,I=m.length;for(p=0;p<I;p++)switch(m[p].once&&this.removeListener(a,m[p].fn,void 0,!0),_){case 1:m[p].fn.call(m[p].context);break;case 2:m[p].fn.call(m[p].context,A);break;case 3:m[p].fn.call(m[p].context,A,c);break;case 4:m[p].fn.call(m[p].context,A,c,l);break;default:if(!d)for(f=1,d=new Array(_-1);f<_;f++)d[f-1]=arguments[f];m[p].fn.apply(m[p].context,d)}}return!0},s.prototype.on=function(a,A,c){var l=new r(A,c||this),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.once=function(a,A,c){var l=new r(A,c||this,!0),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.removeListener=function(a,A,c,l){var u=o?o+a:a;if(!this._events[u])return this;if(!A)return--this._eventsCount===0?this._events=new i:delete this._events[u],this;var g=this._events[u];if(g.fn)g.fn!==A||l&&!g.once||c&&g.context!==c||(--this._eventsCount===0?this._events=new i:delete this._events[u]);else{for(var h=0,d=[],p=g.length;h<p;h++)(g[h].fn!==A||l&&!g[h].once||c&&g[h].context!==c)&&d.push(g[h]);d.length?this._events[u]=d.length===1?d[0]:d:--this._eventsCount===0?this._events=new i:delete this._events[u]}return this},s.prototype.removeAllListeners=function(a){var A;return a?(A=o?o+a:a,this._events[A]&&(--this._eventsCount===0?this._events=new i:delete this._events[A])):(this._events=new i,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prototype.setMaxListeners=function(){return this},s.prefixed=o,s.EventEmitter=s,e!==void 0&&(e.exports=s)}}),wto=WD({"node_modules/xml-lexer/dist/lexer.js"(t,e){function n(c,l,u){return l in c?Object.defineProperty(c,l,{value:u,enumerable:!0,configurable:!0,writable:!0}):c[l]=u,c}var o=FIt(),i=function(){},r={data:"state-data",cdata:"state-cdata",tagBegin:"state-tag-begin",tagName:"state-tag-name",tagEnd:"state-tag-end",attributeNameStart:"state-attribute-name-start",attributeName:"state-attribute-name",attributeNameEnd:"state-attribute-name-end",attributeValueBegin:"state-attribute-value-begin",attributeValue:"state-attribute-value"},s={lt:"action-lt",gt:"action-gt",space:"action-space",equal:"action-equal",quote:"action-quote",slash:"action-slash",char:"action-char",error:"action-error"},a={text:"text",openTag:"open-tag",closeTag:"close-tag",attributeName:"attribute-name",attributeValue:"attribute-value"},A={" ":s.space,"	":s.space,"\n":s.space,"\r":s.space,"<":s.lt,">":s.gt,'"':s.quote,"'":s.quote,"=":s.equal,"/":s.slash};e.exports={State:r,Action:s,Type:a,create:function(c){var l,u,g,h,d,p,m,_,f,I;c=Object.assign({debug:!1},c);var C=new o,y=r.data,x="",E="",B="",S="",Q="",w="",M=function(R,F){if(E[0]!=="?"&&E[0]!=="!"){var O={type:R,value:F};c.debug&&console.log("emit:",O),C.emit("data",O)}};C.stateMachine=(n(I={},r.data,(n(l={},s.lt,function(){x.trim()&&M(a.text,x),E="",Q=!1,y=r.tagBegin}),n(l,s.char,function(R){x+=R}),l)),n(I,r.cdata,n({},s.char,function(R){(x+=R).substr(-3)==="]]>"&&(M(a.text,x.slice(0,-3)),x="",y=r.data)})),n(I,r.tagBegin,(n(u={},s.space,i),n(u,s.char,function(R){E=R,y=r.tagName}),n(u,s.slash,function(){E="",Q=!0}),u)),n(I,r.tagName,(n(g={},s.space,function(){Q?y=r.tagEnd:(y=r.attributeNameStart,M(a.openTag,E))}),n(g,s.gt,function(){M(Q?a.closeTag:a.openTag,E),x="",y=r.data}),n(g,s.slash,function(){y=r.tagEnd,M(a.openTag,E)}),n(g,s.char,function(R){(E+=R)==="![CDATA["&&(y=r.cdata,x="",E="")}),g)),n(I,r.tagEnd,(n(h={},s.gt,function(){M(a.closeTag,E),x="",y=r.data}),n(h,s.char,i),h)),n(I,r.attributeNameStart,(n(d={},s.char,function(R){B=R,y=r.attributeName}),n(d,s.gt,function(){x="",y=r.data}),n(d,s.space,i),n(d,s.slash,function(){Q=!0,y=r.tagEnd}),d)),n(I,r.attributeName,(n(p={},s.space,function(){y=r.attributeNameEnd}),n(p,s.equal,function(){M(a.attributeName,B),y=r.attributeValueBegin}),n(p,s.gt,function(){S="",M(a.attributeName,B),M(a.attributeValue,S),x="",y=r.data}),n(p,s.slash,function(){Q=!0,S="",M(a.attributeName,B),M(a.attributeValue,S),y=r.tagEnd}),n(p,s.char,function(R){B+=R}),p)),n(I,r.attributeNameEnd,(n(m={},s.space,i),n(m,s.equal,function(){M(a.attributeName,B),y=r.attributeValueBegin}),n(m,s.gt,function(){S="",M(a.attributeName,B),M(a.attributeValue,S),x="",y=r.data}),n(m,s.char,function(R){S="",M(a.attributeName,B),M(a.attributeValue,S),B=R,y=r.attributeName}),m)),n(I,r.attributeValueBegin,(n(_={},s.space,i),n(_,s.quote,function(R){w=R,S="",y=r.attributeValue}),n(_,s.gt,function(){M(a.attributeValue,S=""),x="",y=r.data}),n(_,s.char,function(R){w="",S=R,y=r.attributeValue}),_)),n(I,r.attributeValue,(n(f={},s.space,function(R){w?S+=R:(M(a.attributeValue,S),y=r.attributeNameStart)}),n(f,s.quote,function(R){w===R?(M(a.attributeValue,S),y=r.attributeNameStart):S+=R}),n(f,s.gt,function(R){w?S+=R:(M(a.attributeValue,S),x="",y=r.data)}),n(f,s.slash,function(R){w?S+=R:(M(a.attributeValue,S),Q=!0,y=r.tagEnd)}),n(f,s.char,function(R){S+=R}),f)),I);var k=function(R){c.debug&&console.log(y,R);var F=C.stateMachine[y],O=F[(function(U){return A[U]||s.char})(R)]||F[s.error]||F[s.char];O(R)};return C.write=function(R){for(var F=R.length,O=0;O<F;O++)k(R[O])},C}}}}),Pto=WD({"node_modules/xml-reader/dist/reader.js"(t,e){var n=FIt(),o=wto(),i=o.Type,r={element:"element",text:"text"},s=function(A){return Object.assign({name:"",type:r.element,value:"",parent:null,attributes:{},children:[]},A)},a=function(A){A=Object.assign({stream:!1,parentNodes:!0,doneEvent:"done",tagPrefix:"tag:",emitTopLevelOnly:!1,debug:!1},A);var c=void 0,l=void 0,u=void 0,g=void 0,h=new n,d=function(p){switch(p.type){case i.openTag:if(u===null)(u=l).name=p.value;else{var m=s({name:p.value,parent:u});u.children.push(m),u=m}break;case i.closeTag:var _=u.parent;if(A.parentNodes||(u.parent=null),u.name!==p.value)break;A.stream&&_===l&&(l.children=[],u.parent=null),A.emitTopLevelOnly&&_!==l||(h.emit(A.tagPrefix+u.name,u),h.emit("tag",u.name,u)),u===l&&(c.removeAllListeners("data"),h.emit(A.doneEvent,u),l=null),u=_;break;case i.text:u&&u.children.push(s({type:r.text,value:p.value,parent:A.parentNodes?u:null}));break;case i.attributeName:g=p.value,u.attributes[g]="";break;case i.attributeValue:u.attributes[g]=p.value}};return h.reset=function(){(c=o.create({debug:A.debug})).on("data",d),l=s(),u=null,g="",h.parse=c.write},h.reset(),h};e.exports={parseSync:function(A,c){c=Object.assign({},c,{stream:!1,tagPrefix:":"});var l=a(c),u=void 0;return l.on("done",function(g){u=g}),l.parse(A),u},create:a,NodeType:r}}}),Mto=(kIt(vto()),kIt(Pto()),Object.create),LIt=Object.defineProperty,Dto=Object.getOwnPropertyDescriptor,HIt=Object.getOwnPropertyNames,Nto=Object.getPrototypeOf,Rto=Object.prototype.hasOwnProperty,jD=(t,e)=>function(){return e||(0,t[HIt(t)[0]])((e={exports:{}}).exports,e),e.exports},OIt=(t,e,n)=>(n=t!=null?Mto(Nto(t)):{},((o,i,r,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let a of HIt(i))Rto.call(o,a)||a===r||LIt(o,a,{get:()=>i[a],enumerable:!(s=Dto(i,a))||s.enumerable});return o})(t&&t.__esModule?n:LIt(n,"default",{value:t,enumerable:!0}),t)),Tto=jD({"node_modules/is-buffer/index.js"(t,e){function n(o){return!!o.constructor&&typeof o.constructor.isBuffer=="function"&&o.constructor.isBuffer(o)}e.exports=function(o){return o!=null&&(n(o)||(function(i){return typeof i.readFloatLE=="function"&&typeof i.slice=="function"&&n(i.slice(0,0))})(o)||!!o._isBuffer)}}}),kto=jD({"node_modules/kind-of/index.js"(t,e){var n=Tto(),o=Object.prototype.toString;e.exports=function(i){if(i===void 0)return"undefined";if(i===null)return"null";if(i===!0||i===!1||i instanceof Boolean)return"boolean";if(typeof i=="string"||i instanceof String)return"string";if(typeof i=="number"||i instanceof Number)return"number";if(typeof i=="function"||i instanceof Function)return"function";if(Array.isArray!==void 0&&Array.isArray(i))return"array";if(i instanceof RegExp)return"regexp";if(i instanceof Date)return"date";var r=o.call(i);return r==="[object RegExp]"?"regexp":r==="[object Date]"?"date":r==="[object Arguments]"?"arguments":r==="[object Error]"?"error":n(i)?"buffer":r==="[object Set]"?"set":r==="[object WeakSet]"?"weakset":r==="[object Map]"?"map":r==="[object WeakMap]"?"weakmap":r==="[object Symbol]"?"symbol":r==="[object Int8Array]"?"int8array":r==="[object Uint8Array]"?"uint8array":r==="[object Uint8ClampedArray]"?"uint8clampedarray":r==="[object Int16Array]"?"int16array":r==="[object Uint16Array]"?"uint16array":r==="[object Int32Array]"?"int32array":r==="[object Uint32Array]"?"uint32array":r==="[object Float32Array]"?"float32array":r==="[object Float64Array]"?"float64array":"object"}}}),Fto=jD({"node_modules/rename-keys/index.js"(t,e){(function(){function n(o,i){if(typeof i!="function")return o;var r={};for(var s in o)Object.prototype.hasOwnProperty.call(o,s)&&(r[i(s,o[s])||s]=o[s]);return r}e!==void 0&&e.exports?e.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):window.rename=n})()}}),Lto=jD({"node_modules/deep-rename-keys/index.js"(t,e){var n=kto(),o=Fto();e.exports=function i(r,s){var a=n(r);if(a!=="object"&&a!=="array")throw new Error("expected an object");var A=[];for(var c in a==="object"&&(r=o(r,s),A={}),r)if(r.hasOwnProperty(c)){var l=r[c];n(l)==="object"||n(l)==="array"?A[c]=i(l,s):A[c]=l}return A}}}),GIt=jD({"node_modules/eventemitter3/index.js"(t,e){var n=Object.prototype.hasOwnProperty,o="~";function i(){}function r(a,A,c){this.fn=a,this.context=A,this.once=c||!1}function s(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(o=!1)),s.prototype.eventNames=function(){var a,A,c=[];if(this._eventsCount===0)return c;for(A in a=this._events)n.call(a,A)&&c.push(o?A.slice(1):A);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(a)):c},s.prototype.listeners=function(a,A){var c=o?o+a:a,l=this._events[c];if(A)return!!l;if(!l)return[];if(l.fn)return[l.fn];for(var u=0,g=l.length,h=new Array(g);u<g;u++)h[u]=l[u].fn;return h},s.prototype.emit=function(a,A,c,l,u,g){var h=o?o+a:a;if(!this._events[h])return!1;var d,p,m=this._events[h],_=arguments.length;if(m.fn){switch(m.once&&this.removeListener(a,m.fn,void 0,!0),_){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,A),!0;case 3:return m.fn.call(m.context,A,c),!0;case 4:return m.fn.call(m.context,A,c,l),!0;case 5:return m.fn.call(m.context,A,c,l,u),!0;case 6:return m.fn.call(m.context,A,c,l,u,g),!0}for(p=1,d=new Array(_-1);p<_;p++)d[p-1]=arguments[p];m.fn.apply(m.context,d)}else{var f,I=m.length;for(p=0;p<I;p++)switch(m[p].once&&this.removeListener(a,m[p].fn,void 0,!0),_){case 1:m[p].fn.call(m[p].context);break;case 2:m[p].fn.call(m[p].context,A);break;case 3:m[p].fn.call(m[p].context,A,c);break;case 4:m[p].fn.call(m[p].context,A,c,l);break;default:if(!d)for(f=1,d=new Array(_-1);f<_;f++)d[f-1]=arguments[f];m[p].fn.apply(m[p].context,d)}}return!0},s.prototype.on=function(a,A,c){var l=new r(A,c||this),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.once=function(a,A,c){var l=new r(A,c||this,!0),u=o?o+a:a;return this._events[u]?this._events[u].fn?this._events[u]=[this._events[u],l]:this._events[u].push(l):(this._events[u]=l,this._eventsCount++),this},s.prototype.removeListener=function(a,A,c,l){var u=o?o+a:a;if(!this._events[u])return this;if(!A)return--this._eventsCount===0?this._events=new i:delete this._events[u],this;var g=this._events[u];if(g.fn)g.fn!==A||l&&!g.once||c&&g.context!==c||(--this._eventsCount===0?this._events=new i:delete this._events[u]);else{for(var h=0,d=[],p=g.length;h<p;h++)(g[h].fn!==A||l&&!g[h].once||c&&g[h].context!==c)&&d.push(g[h]);d.length?this._events[u]=d.length===1?d[0]:d:--this._eventsCount===0?this._events=new i:delete this._events[u]}return this},s.prototype.removeAllListeners=function(a){var A;return a?(A=o?o+a:a,this._events[A]&&(--this._eventsCount===0?this._events=new i:delete this._events[A])):(this._events=new i,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prototype.setMaxListeners=function(){return this},s.prefixed=o,s.EventEmitter=s,e!==void 0&&(e.exports=s)}}),Hto=jD({"node_modules/xml-lexer/dist/lexer.js"(t,e){function n(c,l,u){return l in c?Object.defineProperty(c,l,{value:u,enumerable:!0,configurable:!0,writable:!0}):c[l]=u,c}var o=GIt(),i=function(){},r={data:"state-data",cdata:"state-cdata",tagBegin:"state-tag-begin",tagName:"state-tag-name",tagEnd:"state-tag-end",attributeNameStart:"state-attribute-name-start",attributeName:"state-attribute-name",attributeNameEnd:"state-attribute-name-end",attributeValueBegin:"state-attribute-value-begin",attributeValue:"state-attribute-value"},s={lt:"action-lt",gt:"action-gt",space:"action-space",equal:"action-equal",quote:"action-quote",slash:"action-slash",char:"action-char",error:"action-error"},a={text:"text",openTag:"open-tag",closeTag:"close-tag",attributeName:"attribute-name",attributeValue:"attribute-value"},A={" ":s.space,"	":s.space,"\n":s.space,"\r":s.space,"<":s.lt,">":s.gt,'"':s.quote,"'":s.quote,"=":s.equal,"/":s.slash};e.exports={State:r,Action:s,Type:a,create:function(c){var l,u,g,h,d,p,m,_,f,I;c=Object.assign({debug:!1},c);var C=new o,y=r.data,x="",E="",B="",S="",Q="",w="",M=function(R,F){if(E[0]!=="?"&&E[0]!=="!"){var O={type:R,value:F};c.debug&&console.log("emit:",O),C.emit("data",O)}};C.stateMachine=(n(I={},r.data,(n(l={},s.lt,function(){x.trim()&&M(a.text,x),E="",Q=!1,y=r.tagBegin}),n(l,s.char,function(R){x+=R}),l)),n(I,r.cdata,n({},s.char,function(R){(x+=R).substr(-3)==="]]>"&&(M(a.text,x.slice(0,-3)),x="",y=r.data)})),n(I,r.tagBegin,(n(u={},s.space,i),n(u,s.char,function(R){E=R,y=r.tagName}),n(u,s.slash,function(){E="",Q=!0}),u)),n(I,r.tagName,(n(g={},s.space,function(){Q?y=r.tagEnd:(y=r.attributeNameStart,M(a.openTag,E))}),n(g,s.gt,function(){M(Q?a.closeTag:a.openTag,E),x="",y=r.data}),n(g,s.slash,function(){y=r.tagEnd,M(a.openTag,E)}),n(g,s.char,function(R){(E+=R)==="![CDATA["&&(y=r.cdata,x="",E="")}),g)),n(I,r.tagEnd,(n(h={},s.gt,function(){M(a.closeTag,E),x="",y=r.data}),n(h,s.char,i),h)),n(I,r.attributeNameStart,(n(d={},s.char,function(R){B=R,y=r.attributeName}),n(d,s.gt,function(){x="",y=r.data}),n(d,s.space,i),n(d,s.slash,function(){Q=!0,y=r.tagEnd}),d)),n(I,r.attributeName,(n(p={},s.space,function(){y=r.attributeNameEnd}),n(p,s.equal,function(){M(a.attributeName,B),y=r.attributeValueBegin}),n(p,s.gt,function(){S="",M(a.attributeName,B),M(a.attributeValue,S),x="",y=r.data}),n(p,s.slash,function(){Q=!0,S="",M(a.attributeName,B),M(a.attributeValue,S),y=r.tagEnd}),n(p,s.char,function(R){B+=R}),p)),n(I,r.attributeNameEnd,(n(m={},s.space,i),n(m,s.equal,function(){M(a.attributeName,B),y=r.attributeValueBegin}),n(m,s.gt,function(){S="",M(a.attributeName,B),M(a.attributeValue,S),x="",y=r.data}),n(m,s.char,function(R){S="",M(a.attributeName,B),M(a.attributeValue,S),B=R,y=r.attributeName}),m)),n(I,r.attributeValueBegin,(n(_={},s.space,i),n(_,s.quote,function(R){w=R,S="",y=r.attributeValue}),n(_,s.gt,function(){M(a.attributeValue,S=""),x="",y=r.data}),n(_,s.char,function(R){w="",S=R,y=r.attributeValue}),_)),n(I,r.attributeValue,(n(f={},s.space,function(R){w?S+=R:(M(a.attributeValue,S),y=r.attributeNameStart)}),n(f,s.quote,function(R){w===R?(M(a.attributeValue,S),y=r.attributeNameStart):S+=R}),n(f,s.gt,function(R){w?S+=R:(M(a.attributeValue,S),x="",y=r.data)}),n(f,s.slash,function(R){w?S+=R:(M(a.attributeValue,S),Q=!0,y=r.tagEnd)}),n(f,s.char,function(R){S+=R}),f)),I);var k=function(R){c.debug&&console.log(y,R);var F=C.stateMachine[y],O=F[(function(U){return A[U]||s.char})(R)]||F[s.error]||F[s.char];O(R)};return C.write=function(R){for(var F=R.length,O=0;O<F;O++)k(R[O])},C}}}}),Oto=jD({"node_modules/xml-reader/dist/reader.js"(t,e){var n=GIt(),o=Hto(),i=o.Type,r={element:"element",text:"text"},s=function(A){return Object.assign({name:"",type:r.element,value:"",parent:null,attributes:{},children:[]},A)},a=function(A){A=Object.assign({stream:!1,parentNodes:!0,doneEvent:"done",tagPrefix:"tag:",emitTopLevelOnly:!1,debug:!1},A);var c=void 0,l=void 0,u=void 0,g=void 0,h=new n,d=function(p){switch(p.type){case i.openTag:if(u===null)(u=l).name=p.value;else{var m=s({name:p.value,parent:u});u.children.push(m),u=m}break;case i.closeTag:var _=u.parent;if(A.parentNodes||(u.parent=null),u.name!==p.value)break;A.stream&&_===l&&(l.children=[],u.parent=null),A.emitTopLevelOnly&&_!==l||(h.emit(A.tagPrefix+u.name,u),h.emit("tag",u.name,u)),u===l&&(c.removeAllListeners("data"),h.emit(A.doneEvent,u),l=null),u=_;break;case i.text:u&&u.children.push(s({type:r.text,value:p.value,parent:A.parentNodes?u:null}));break;case i.attributeName:g=p.value,u.attributes[g]="";break;case i.attributeValue:u.attributes[g]=p.value}};return h.reset=function(){(c=o.create({debug:A.debug})).on("data",d),l=s(),u=null,g="",h.parse=c.write},h.reset(),h};e.exports={parseSync:function(A,c){c=Object.assign({},c,{stream:!1,tagPrefix:":"});var l=a(c),u=void 0;return l.on("done",function(g){u=g}),l.parse(A),u},create:a,NodeType:r}}});OIt(Lto()),OIt(Oto());function G6e(t,e){if(t.points)for(const n of t.points)n.step=e;if(t.lines)for(const n of t.lines)n.step=e;if(t.infiniteLines)for(const n of t.infiniteLines)n.step=e;if(t.polygons)for(const n of t.polygons)n.step=e;if(t.rects)for(const n of t.rects)n.step=e;if(t.circles)for(const n of t.circles)n.step=e;if(t.texts)for(const n of t.texts)n.step=e;return t}var AJ=class{MAX_ITERATIONS=1e5;solved=!1;failed=!1;iterations=0;progress=0;error=null;activeSubSolver;failedSubSolvers;timeToSolve;stats={};_setupDone=!1;getSolverName(){return this.constructor.name}setup(){this._setupDone||(this._setup(),this._setupDone=!0)}_setup(){}step(){if(this._setupDone||this.setup(),!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.getSolverName()} error: ${e}`,this.failed=!0,e}!this.solved&&this.iterations>=this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>=this.MAX_ITERATIONS&&(this.error=`${this.getSolverName()} ran out of iterations`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}getOutput(){return null}solve(){const e=Date.now();for(;!this.solved&&!this.failed;)this.step();const n=Date.now();this.timeToSolve=n-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}};function Fae(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved}}var Gto=class extends AJ{startTimeOfStage={};endTimeOfStage={};timeSpentOnStage={};firstIterationOfStage={};currentPipelineStageIndex=0;inputProblem;pipelineOutputs={};constructor(e){super(),this.inputProblem=e,this.MAX_ITERATIONS=1e6}_step(){const e=this.pipelineDef[this.currentPipelineStageIndex];if(!e)return void(this.solved=!0);if(this.activeSubSolver){if(this.activeSubSolver.step(),this.activeSubSolver.solved){this.endTimeOfStage[e.solverName]=performance.now(),this.timeSpentOnStage[e.solverName]=this.endTimeOfStage[e.solverName]-this.startTimeOfStage[e.solverName];const o=this.activeSubSolver.getOutput();o!==null&&(this.pipelineOutputs[e.solverName]=o),e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStageIndex++}else this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null);return}const n=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...n),this[e.solverName]=this.activeSubSolver,this.timeSpentOnStage[e.solverName]=0,this.startTimeOfStage[e.solverName]=performance.now(),this.firstIterationOfStage[e.solverName]=this.iterations}solveUntilStage(e){for(;this.getCurrentStageName().toLowerCase()!==e.toLowerCase()&&(this.step(),!this.failed&&!this.solved););}getCurrentStageName(){return this.pipelineDef[this.currentPipelineStageIndex]?.solverName??"none"}getStageProgress(){const e=this.pipelineDef.length;if(e===0)return 1;const n=this.activeSubSolver?.progress??0;return(this.currentPipelineStageIndex+n)/e}getStageStats(){const e={};for(const n of this.pipelineDef){const o=this.timeSpentOnStage[n.solverName]||0,i=this.firstIterationOfStage[n.solverName]||0,r=this.iterations,s=n.solverName===this.getCurrentStageName()?r-i:0,a=this.currentPipelineStageIndex>this.pipelineDef.findIndex(A=>A.solverName===n.solverName);e[n.solverName]={timeSpent:o,iterations:s,completed:a}}return e}initialVisualize(){return null}finalVisualize(){return null}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();let e=0;const n=this.initialVisualize();n&&(G6e(n,0),e=1);let o=null;this.solved&&(o=this.finalVisualize());const i=[n].filter(Boolean).concat(this.pipelineDef.map((r,s)=>{const a=this[r.solverName],A=a?.visualize();return A?(G6e(A,s+e),A):null}).filter(Boolean));return i.length===0?{points:[],rects:[],lines:[],circles:[],texts:[]}:(this.solved&&o&&(G6e(o,i.length+e+1),i.push(o)),i.length===1?i[0]:{points:i.flatMap(r=>r.points||[]),rects:i.flatMap(r=>r.rects||[]),lines:i.flatMap(r=>r.lines||[]),circles:i.flatMap(r=>r.circles||[]),texts:i.flatMap(r=>r.texts||[])})}preview(){return this.activeSubSolver?this.activeSubSolver.preview():super.preview()}computeProgress(){return this.getStageProgress()}getStageOutput(e){return this.pipelineOutputs[e]}getAllOutputs(){return{...this.pipelineOutputs}}hasStageOutput(e){return e in this.pipelineOutputs}getSolver(e){return this[e]}},Y6e=(t,e,n)=>(e.x-t.x)*(n.y-t.y)-(e.y-t.y)*(n.x-t.x),YIt=(t,e)=>{const n=[...new Set(t)].map(r=>{const s=e[r];return s?{i:r,x:s.x,y:s.y}:null}).filter(r=>r!==null);if(n.sort((r,s)=>r.x-s.x||r.y-s.y),n.length<=2)return n.map(r=>r.i);const o=[],i=[];for(const r of n){for(;o.length>=2;){const s=o[o.length-2],a=o[o.length-1];if(!s||!a||Y6e(s,a,r)>1e-10)break;o.pop()}o.push(r)}for(let r=n.length-1;r>=0;r--){const s=n[r];if(s){for(;i.length>=2;){const a=i[i.length-2],A=i[i.length-1];if(!a||!A||Y6e(a,A,s)>1e-10)break;i.pop()}i.push(s)}}return o.pop(),i.pop(),o.concat(i).map(r=>r.i)},UIt=t=>t!==void 0,Yto=class extends AJ{input;output=null;constructor(e){super(),this.input=e}_step(){const{regions:e,hulls:n}={regions:(o=this.input).cells.map(i=>i.map(r=>o.pts[r]).filter(UIt)),hulls:o.cells.map(i=>YIt(i,o.pts).map(r=>o.pts[r]).filter(UIt))};var o;this.output={pts:this.input.pts,validTris:this.input.validTris,regions:e,hulls:n,depths:this.input.depths},this.stats={regions:e.length},this.solved=!0}getConstructorParams(){return[this.input]}getOutput(){return this.output}visualize(){const e=this.output;return e?{points:e.pts.map(n=>({x:n.x,y:n.y,color:"#3b82f6"})),lines:e.regions.flatMap(n=>n.flatMap((o,i)=>{const r=n[(i+1)%n.length];return r?[{points:[o,r],strokeColor:"#0f766e"}]:[]})),rects:[],circles:[],texts:[{x:4,y:12,text:`regions: ${e.regions.length}`,color:"#1f2937"}]}:{points:[],lines:[],rects:[],circles:[],texts:[]}}},Lae=(t,e,n)=>{const o=Math.cos(n.ccwRotation),i=Math.sin(n.ccwRotation);return{x:n.center.x+t*o-e*i,y:n.center.y+t*i+e*o}},Uto=(t,e=[],n,o=[])=>{const i=[],{minX:r,maxX:s,minY:a,maxY:A}=t;i.push({x:r,y:a},{x:s,y:a},{x:s,y:A},{x:r,y:A});for(let c=1;c<10;c++){const l=c/10;i.push({x:r+l*(s-r),y:a}),i.push({x:s,y:a+l*(A-a)}),i.push({x:s-l*(s-r),y:A}),i.push({x:r,y:A-l*(A-a)})}for(const c of e){const l=c.diameter/2+n;for(let u=0;u<24;u++){const g=2*Math.PI*u/24;i.push({x:c.center.x+l*Math.cos(g),y:c.center.y+l*Math.sin(g)})}}for(const c of o){const l=c.width/2+n,u=c.height/2+n,g=Math.max(2,Math.ceil(Math.max(2*l,2*u)/20));for(let h=0;h<g;h++){const d=h/g;i.push(Lae(2*d*l-l,-u,c)),i.push(Lae(l,2*d*u-u,c)),i.push(Lae(l-2*d*l,u,c)),i.push(Lae(-l,u-2*d*u,c))}}return i.map((c,l)=>({x:c.x+1e-6*(l%7-3),y:c.y+1e-6*(l%5-2)}))},Kto=class extends AJ{input;output=null;constructor(e){super(),this.input=e}_step(){const e=this.input.vias??[],n=this.input.rects??[];this.output={pts:Uto(this.input.bounds,e,this.input.clearance,n)},this.stats={points:this.output.pts.length},this.solved=!0}getConstructorParams(){return[this.input]}getOutput(){return this.output}visualize(){const e=(this.output?.pts??[]).map(n=>({x:n.x,y:n.y,color:"#2563eb"}));return{points:e,lines:[],rects:[],circles:(this.input.vias??[]).map(n=>({center:{x:n.center.x,y:n.center.y},radius:n.diameter/2+this.input.clearance,stroke:"#ef4444"})),texts:[{x:this.input.bounds.minX+6,y:this.input.bounds.minY+12,text:`sample points: ${e.length}`,color:"#1f2937"}]}}},Vto=(t,e,n)=>{const o=n.x-e.x,i=n.y-e.y,r=o*o+i*i;if(r<1e-10)return Math.hypot(t.x-e.x,t.y-e.y);let s=((t.x-e.x)*o+(t.y-e.y)*i)/r;return s=Math.max(0,Math.min(1,s)),Math.hypot(t.x-e.x-s*o,t.y-e.y-s*i)},KIt=(t,e)=>{if(t.length<=3)return 0;const n=YIt(t,e),o=new Set(n),i=n.map(s=>e[s]).filter(s=>!!s);let r=0;for(const s of t){if(o.has(s))continue;const a=e[s];if(!a)continue;let A=Number.POSITIVE_INFINITY;for(let c=0;c<i.length;c++){const l=i[c],u=i[(c+1)%i.length];l&&u&&(A=Math.min(A,Vto(a,l,u)))}r=Math.max(r,A)}return r},U6e=(t,e)=>t<e?1e5*t+e:1e5*e+t,zto=(t,e)=>{const n=t.map((u,g)=>[u,t[(g+1)%t.length]]),o=e.map((u,g)=>[u,e[(g+1)%e.length]]),i=new Set;for(const[u,g]of n)if(g!==void 0)for(const[h,d]of o)d!==void 0&&u===d&&g===h&&i.add(U6e(u,g));if(i.size===0)return null;const r=[];for(const[u,g]of n)g!==void 0&&(i.has(U6e(u,g))||r.push([u,g]));for(const[u,g]of o)g!==void 0&&(i.has(U6e(u,g))||r.push([u,g]));if(r.length===0)return null;const s=new Map;for(const[u,g]of r)s.set(u,g);const a=r[0]?.[0];if(a===void 0)return null;const A=[a];let c=s.get(a),l=0;for(;c!==void 0&&c!==a&&l++<r.length+5;)A.push(c),c=s.get(c);return c!==a||A.length!==r.length?null:A},Jto=(t,e)=>t<e?1e5*t+e:1e5*e+t,Wto=class extends AJ{input;output=null;constructor(t){super(),this.input=t}_step(){const t=((e,n,o)=>{if(!e.length)return{cells:[],depths:[]};const i=e.map(([A,c,l])=>{const u=n[A],g=n[c],h=n[l];return u&&g&&h&&Y6e(u,g,h)<0?[A,l,c]:[A,c,l]});let r=!0,s=0;for(;r&&s++<800;){r=!1;const A=new Map,c=i.map(()=>new Set);for(let d=0;d<i.length;d++){const p=i[d];if(p)for(let m=0;m<p.length;m++){const _=p[m],f=p[(m+1)%p.length];if(_===void 0||f===void 0)continue;const I=Jto(_,f);if(A.has(I)){const C=A.get(I);C!==void 0&&(c[d]?.add(C),c[C]?.add(d))}else A.set(I,d)}}let l=-1,u=-1,g=null,h=Number.POSITIVE_INFINITY;for(let d=0;d<i.length;d++){const p=c[d];if(p)for(const m of p){if(m<=d)continue;const _=zto(i[d]??[],i[m]??[]);if(!_)continue;const f=KIt(_,n);f<=o+1e-6&&f<h&&(h=f,l=d,u=m,g=_)}}if(l<0||u<0||!g)break;i[l]=g,i.splice(u,1),r=!0}const a=i.map(A=>KIt(A,n));return{cells:i,depths:a}})(this.input.validTris,this.input.pts,this.input.concavityTolerance);this.output={pts:this.input.pts,validTris:this.input.validTris,cells:t.cells,depths:t.depths},this.stats={mergedCells:t.cells.length,maxDepth:t.depths.length?Math.max(...t.depths):0},this.solved=!0}getConstructorParams(){return[this.input]}getOutput(){return this.output}visualize(){const t=this.output?.cells??[];return{points:this.input.pts.map(e=>({x:e.x,y:e.y,color:"#3b82f6"})),lines:t.flatMap(e=>e.flatMap((n,o)=>{const i=this.input.pts[n],r=e[(o+1)%e.length],s=r===void 0?void 0:this.input.pts[r];return i&&s?[{points:[i,s],strokeColor:"#10b981"}]:[]})),rects:[],circles:[],texts:[{x:4,y:12,text:`merged cells: ${t.length}`,color:"#1f2937"}]}}},VIt=(t,e,n)=>{const o=2*(t.x*(e.y-n.y)+e.x*(n.y-t.y)+n.x*(t.y-e.y));if(Math.abs(o)<1e-10)return{x:0,y:0,r2:1e18};const i=t.x*t.x+t.y*t.y,r=e.x*e.x+e.y*e.y,s=n.x*n.x+n.y*n.y,a=(i*(e.y-n.y)+r*(n.y-t.y)+s*(t.y-e.y))/o,A=(i*(n.x-e.x)+r*(t.x-n.x)+s*(e.x-t.x))/o;return{x:a,y:A,r2:(t.x-a)**2+(t.y-A)**2}},jto=(t,e,n)=>[t.a,t.b,t.c].includes(e)&&[t.a,t.b,t.c].includes(n),$to=(t,e,n,o=[],i,r=[])=>t.filter(([s,a,A])=>{const c=e[s],l=e[a],u=e[A];return!c||!l||!u?!1:((g,h,d,p=[],m,_=[])=>{const{minX:f,maxX:I,minY:C,maxY:y}=d;if(g<f-.1||g>I+.1||h<C-.1||h>y+.1)return!1;for(const x of p){const E=x.diameter/2+m;if((g-x.center.x)**2+(h-x.center.y)**2<E*E-.1)return!1}for(const x of _){const E=x.width/2+m,B=x.height/2+m,S=g-x.center.x,Q=h-x.center.y,w=Math.cos(x.ccwRotation),M=Math.sin(x.ccwRotation),k=S*w+Q*M,R=-S*M+Q*w;if(Math.abs(k)<E-.1&&Math.abs(R)<B-.1)return!1}return!0})((c.x+l.x+u.x)/3,(c.y+l.y+u.y)/3,n,o,i,r)}),qto=class extends AJ{input;output=null;constructor(t){super(),this.input=t}_step(){const t=this.input.vias??[],e=this.input.rects??[],n=(i=>{const r=i.map((_,f)=>({..._,i:f}));if(r.length<3)return[];let s=Number.POSITIVE_INFINITY,a=Number.POSITIVE_INFINITY,A=Number.NEGATIVE_INFINITY,c=Number.NEGATIVE_INFINITY;for(const _ of r)s=Math.min(s,_.x),a=Math.min(a,_.y),A=Math.max(A,_.x),c=Math.max(c,_.y);const l=Math.max(A-s,c-a)||1,u=(s+A)/2,g=(a+c)/2,h={x:u-30*l,y:g-l,i:-1},d={x:u,y:g+30*l,i:-2},p={x:u+30*l,y:g-l,i:-3};let m=[{a:h,b:d,c:p,cc:VIt(h,d,p)}];for(const _ of r){const f=m.filter(y=>{const x=_.x-y.cc.x,E=_.y-y.cc.y;return x*x+E*E<y.cc.r2+1e-6}),I=new Set(f),C=[];for(const y of f){const x=[[y.a,y.b],[y.b,y.c],[y.c,y.a]];for(const[E,B]of x){let S=!1;for(const Q of f)if(Q!==y&&jto(Q,E,B)){S=!0;break}S||C.push([E,B])}}m=m.filter(y=>!I.has(y));for(const[y,x]of C)m.push({a:y,b:x,c:_,cc:VIt(y,x,_)})}return m.filter(_=>_.a.i>=0&&_.b.i>=0&&_.c.i>=0).map(_=>[_.a.i,_.b.i,_.c.i])})(this.input.pts),o=$to(n,this.input.pts,this.input.bounds,t,this.input.clearance,e);this.output={pts:this.input.pts,validTris:o},this.stats={candidateTriangles:n.length,validTriangles:o.length},this.solved=!0}getConstructorParams(){return[this.input]}getOutput(){return this.output}visualize(){const t=this.output?.validTris??[];return{points:this.input.pts.map(e=>({x:e.x,y:e.y,color:"#2563eb"})),lines:t.flatMap(([e,n,o])=>{const i=this.input.pts[e],r=this.input.pts[n],s=this.input.pts[o];return i&&r&&s?[{points:[i,r],strokeColor:"#64748b"},{points:[r,s],strokeColor:"#64748b"},{points:[s,i],strokeColor:"#64748b"}]:[]}),rects:[],circles:[],texts:[{x:this.input.bounds.minX+6,y:this.input.bounds.minY+12,text:`valid triangles: ${t.length}`,color:"#1f2937"}]}}},Xto=class extends Gto{pipelineDef=[Fae("generatePoints",Kto,t=>[t.inputProblem]),Fae("triangulate",qto,t=>{const e=t.getStageOutput("generatePoints");if(!e)throw new Error("generatePoints output missing");return[{pts:e.pts,bounds:t.inputProblem.bounds,vias:t.inputProblem.vias,rects:t.inputProblem.rects,clearance:t.inputProblem.clearance}]}),Fae("mergeCells",Wto,t=>{const e=t.getStageOutput("triangulate");if(!e)throw new Error("triangulate output missing");return[{pts:e.pts,validTris:e.validTris,concavityTolerance:t.inputProblem.concavityTolerance}]}),Fae("buildRegions",Yto,t=>{const e=t.getStageOutput("mergeCells");if(!e)throw new Error("mergeCells output missing");return[e]})];getConstructorParams(){return[this.inputProblem]}getOutput(){return this.getStageOutput("buildRegions")??null}visualize(){const t=this.getOutput();return t?{points:t.pts.map(e=>({x:e.x,y:e.y,color:"#38b6ff"})),lines:t.regions.flatMap(e=>e.map((n,o)=>{const i=e[(o+1)%e.length]??n;return{points:[{x:n.x,y:n.y},{x:i.x,y:i.y}],strokeColor:"#4ecb82"}})),rects:[],circles:(this.inputProblem.vias??[]).map(e=>({center:{x:e.center.x,y:e.center.y},radius:e.diameter/2,stroke:"#ff6b6b"})),texts:[{x:this.inputProblem.bounds.minX+8,y:this.inputProblem.bounds.minY+16,text:`regions=${t.regions.length}`,color:"#ffffff"}]}:{points:[],lines:[],rects:[],circles:[],texts:[]}}},K6e=1e-9,Zto=(t,e)=>{const n=[jIt(t)],o=[];let i=e.maxSplitsPerRegion??32;for(;n.length>0;){const r=n.pop();if(!r)continue;if(r.length<4){o.push(r);continue}const s=eno(r,e);if(!s||i<=0){o.push(r);continue}const[a,A]=nno(r,s.i,s.j);i-=1,n.push(a,A)}return o},eno=(t,e)=>{const n=ono(t);if(!n)return null;const{triangles:o}=n,i=ano(t);if(i<=K6e)return null;const r=Math.sqrt(i),s=o.map(A=>Ano(t[A[0]],t[A[1]],t[A[2]]));let a=null;for(const A of n.internalEdges){const{i:c,j:l,triA:u,triB:g}=A,h=cno(t[c],t[l])/r;if(h>e.maxNeckRatio)continue;const d=tno(u,g,o.length,n.triangleAdjacency,s),p=i-d,m=Math.min(d,p)/i;if(m<e.minSplitBalanceRatio)continue;const _=h/Math.max(m,K6e);(!a||_<a.score)&&(a={i:c,j:l,score:_})}return a?{i:a.i,j:a.j}:null},tno=(t,e,n,o,i)=>{const r=new Array(n).fill(!1),s=[t];r[e]=!0;let a=0;for(;s.length>0;){const A=s.pop();if(A===void 0||r[A])continue;r[A]=!0,a+=i[A]??0;const c=o[A]??[];for(const l of c)r[l]||s.push(l)}return a},nno=(t,e,n)=>[zIt(t,e,n),zIt(t,n,e)],zIt=(t,e,n)=>{const o=[],i=t.length;let r=e;for(o.push(t[r]);r!==n;)r=(r+1)%i,o.push(t[r]);return jIt(o)},ono=t=>{const e=t.length;if(e<3)return null;const n=new Set;for(let a=0;a<e;a++){const A=(a+1)%e;n.add(WIt(a,A))}const o=ino(t);if(!o||o.length===0)return null;const i=new Map;o.forEach((a,A)=>{for(let c=0;c<3;c++){const l=a[c],u=a[(c+1)%3],g=WIt(l,u),h=i.get(g);h?h.push(A):i.set(g,[A])}});const r=Array.from({length:o.length},()=>[]),s=[];for(const[a,A]of i.entries()){if(n.has(a)||A.length!==2)continue;const[c,l]=a.split("_"),u=Number(c),g=Number(l),h=A[0],d=A[1];s.push({i:u,j:g,triA:h,triB:d});const p=r[h],m=r[d];p&&p.push(d),m&&m.push(h)}return{triangles:o,internalEdges:s,triangleAdjacency:r}},ino=t=>{const e=t.length;if(e<3)return null;const n=Math.sign(JIt(t));if(n===0)return null;const o=[...Array(e).keys()];n<0&&o.reverse();const i=[];let r=0;for(;o.length>3&&r<e*e;){let s=!1;for(let a=0;a<o.length;a++){const A=o[(a-1+o.length)%o.length],c=o[a],l=o[(a+1)%o.length];if(A===void 0||c===void 0||l===void 0)continue;const u=t[A],g=t[c],h=t[l];if(!u||!g||!h||!rno(u,g,h))continue;let d=!1;for(const p of o){if(p===A||p===c||p===l)continue;const m=t[p];if(m&&sno(m,u,g,h)){d=!0;break}}if(!d){i.push([A,c,l]),o.splice(a,1),s=!0;break}}if(!s)return null;r+=1}if(o.length===3){const[s,a,A]=o;s!==void 0&&a!==void 0&&A!==void 0&&i.push([s,a,A])}return i},rno=(t,e,n)=>cJ(t,e,n)>K6e,sno=(t,e,n,o)=>{const i=cJ(e,n,t),r=cJ(n,o,t),s=cJ(o,e,t);return i>=-1e-9&&r>=-1e-9&&s>=-1e-9},cJ=(t,e,n)=>(e.x-t.x)*(n.y-t.y)-(e.y-t.y)*(n.x-t.x),JIt=t=>{let e=0;for(let n=0;n<t.length;n++){const o=t[n],i=t[(n+1)%t.length];o&&i&&(e+=o.x*i.y-i.x*o.y)}return e/2},ano=t=>Math.abs(JIt(t)),Ano=(t,e,n)=>Math.abs(cJ(t,e,n))/2,cno=(t,e)=>Math.hypot(t.x-e.x,t.y-e.y),WIt=(t,e)=>t<e?`${t}_${e}`:`${e}_${t}`,jIt=t=>{if(t.length<2)return t;const e=t[0],n=t[t.length-1];return e&&n&&e.x===n.x&&e.y===n.y?t.slice(0,-1):t},$3={pattern:"grid",pitchX:2.2,pitchY:1.8,staggerAxis:"x",staggerOffset:1.1,staggerOffsetX:1.1,padWidth:.9,padHeight:1,padGap:.35,viaDiameter:.3,clearance:.2,concavityTolerance:.3,boundsPadding:1.2,orientation:"horizontal",portSpacing:.25,maxNeckRatio:0,minSplitBalanceRatio:.2},lno=(t,e)=>{let n=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(const s of t)for(const a of s.padCenters){const A=e.orientation==="horizontal"?e.padWidth/2:e.padHeight/2,c=e.orientation==="horizontal"?e.padHeight/2:e.padWidth/2;a.x-A<n&&(n=a.x-A),a.y-c<o&&(o=a.y-c),a.x+A>i&&(i=a.x+A),a.y+c>r&&(r=a.y+c)}return{minX:n-e.boundsPadding,minY:o-e.boundsPadding,maxX:i+e.boundsPadding,maxY:r+e.boundsPadding}},uno=t=>t.pattern==="staggered"?(e=>{const n=[],o=[],i=e.padGap/2+e.padWidth/2,r=-(e.cols-1)*e.pitchX/2,s=-(e.rows-1)*e.pitchY/2;for(let a=0;a<e.rows;a++){const A=e.staggerAxis==="x"&&a%2==1?e.staggerOffset:0;for(let c=0;c<e.cols;c++){const l=e.staggerAxis==="y"&&c%2==1?e.staggerOffset:0,u={x:r+c*e.pitchX+A,y:s+a*e.pitchY+l},g=e.orientation==="horizontal"?{x:u.x-i,y:u.y}:{x:u.x,y:u.y-i},h=e.orientation==="horizontal"?{x:u.x+i,y:u.y}:{x:u.x,y:u.y+i};n.push({jumperId:`jumper_r${a}_c${c}`,center:u,orientation:e.orientation,padCenters:[g,h]}),o.push({center:g,diameter:e.viaDiameter},{center:h,diameter:e.viaDiameter})}}return{jumpers:n,vias:o,bounds:lno(n,e)}})(t):(e=>{const n=[],o=[],i=e.padGap/2+e.padWidth/2,r=-(e.cols-1)*e.pitchX/2,s=-(e.rows-1)*e.pitchY/2;for(let a=0;a<e.rows;a++)for(let A=0;A<e.cols;A++){const c={x:r+A*e.pitchX,y:s+a*e.pitchY},l=e.orientation==="horizontal"?{x:c.x-i,y:c.y}:{x:c.x,y:c.y-i},u=e.orientation==="horizontal"?{x:c.x+i,y:c.y}:{x:c.x,y:c.y+i},g=`jumper_r${a}_c${A}`;n.push({jumperId:g,center:c,orientation:e.orientation,padCenters:[l,u]}),o.push({center:l,diameter:e.viaDiameter},{center:u,diameter:e.viaDiameter})}return{jumpers:n,vias:o,bounds:{minX:r-i-e.padWidth/2-e.boundsPadding,maxX:r+(e.cols-1)*e.pitchX+i+e.padWidth/2+e.boundsPadding,minY:s-i-e.padHeight/2-e.boundsPadding,maxY:s+(e.rows-1)*e.pitchY+i+e.padHeight/2+e.boundsPadding}}})(t),$It=t=>({x:(t.minX+t.maxX)/2,y:(t.minY+t.maxY)/2}),V6e=t=>[{x:t.minX,y:t.minY},{x:t.maxX,y:t.minY},{x:t.maxX,y:t.maxY},{x:t.minX,y:t.maxY}],sv=(t,e,n)=>Math.abs(t-e)<=n,Hae=(t,e,n)=>sv(t.x,e.x,n)&&sv(t.y,e.y,n),gno=t=>t.map((e,n)=>{const o=(i=>{let r=Number.POSITIVE_INFINITY,s=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,A=Number.NEGATIVE_INFINITY;for(const c of i)c.x<r&&(r=c.x),c.y<s&&(s=c.y),c.x>a&&(a=c.x),c.y>A&&(A=c.y);return{minX:r,minY:s,maxX:a,maxY:A}})(e);return{regionId:`top_${n}`,ports:[],d:{bounds:o,center:$It(o),polygon:e,isPad:!1}}}),dno=t=>{const e=t.end.x-t.start.x,n=t.end.y-t.start.y;return Math.hypot(e,n)},fL=(t,e)=>({x:t.start.x+(t.end.x-t.start.x)*e,y:t.start.y+(t.end.y-t.start.y)*e}),qIt=(t,e,n)=>{const o=[];if(!t.d.polygon||!e.d.polygon)return o;for(let i=0;i<t.d.polygon.length;i++){const r=t.d.polygon[i],s=t.d.polygon[(i+1)%t.d.polygon.length];if(r&&s)for(let a=0;a<e.d.polygon.length;a++){const A=e.d.polygon[a],c=e.d.polygon[(a+1)%e.d.polygon.length];if(!A||!c)continue;const l=_no({start:r,end:s},{start:A,end:c},n);l&&(o.some(u=>mno(u,l,n))||o.push(l))}}return o},hno=(t,e)=>{const n=[];for(const o of t){let i=o,r=!0;for(;r;){r=!1;for(let s=0;s<n.length;s++){const a=n[s];if(!a)continue;const A=pno(i,a,e);if(A){i=A,n.splice(s,1),r=!0;break}}}n.push(i)}return n},pno=(t,e,n)=>{const o=t.end.x-t.start.x,i=t.end.y-t.start.y,r=e.end.x-e.start.x,s=e.end.y-e.start.y,a=o**2+i**2;if(a<=n**2||!sv(o*s-i*r,0,n))return null;const A=e.start.x-t.start.x,c=e.start.y-t.start.y,l=e.end.x-t.start.x,u=e.end.y-t.start.y,g=o*u-i*l;if(!sv(o*c-i*A,0,n)||!sv(g,0,n))return null;const h=(A*o+c*i)/a,d=(l*o+u*i)/a,p=Math.min(h,d),m=Math.max(h,d),_=n/Math.sqrt(a);if(p>1+_||m<0-_)return null;const f=Math.min(0,p),I=Math.max(1,m);return{start:fL(t,f),end:fL(t,I)}},mno=(t,e,n)=>Hae(t.start,e.start,n)&&Hae(t.end,e.end,n)||Hae(t.start,e.end,n)&&Hae(t.end,e.start,n),_no=(t,e,n)=>{const o=t.end.x-t.start.x,i=t.end.y-t.start.y,r=e.end.x-e.start.x,s=e.end.y-e.start.y,a=o**2+i**2;if(a<=n**2||!sv(o*s-i*r,0,n))return null;const A=e.start.x-t.start.x,c=e.start.y-t.start.y,l=e.end.x-t.start.x,u=e.end.y-t.start.y,g=o*u-i*l;if(!sv(o*c-i*A,0,n)||!sv(g,0,n))return null;const h=(A*o+c*i)/a,d=(l*o+u*i)/a,p=Math.max(0,Math.min(h,d)),m=Math.min(1,Math.max(h,d));return m-p<=n/Math.sqrt(a)?null:{start:fL(t,p),end:fL(t,m)}},fno=(t,e,n)=>{const o=Math.max(t.minX,e.minX),i=Math.min(t.maxX,e.maxX),r=Math.max(t.minY,e.minY),s=Math.min(t.maxY,e.maxY);return i<o-n||s<r-n?null:{minX:o,maxX:i,minY:r,maxY:s}},Ino=t=>{const e=(d=>{const p=d.orientation??$3.orientation,m=d.staggerAxis??$3.staggerAxis,_=d.padWidth??$3.padWidth,f=d.padHeight??$3.padHeight,I=d.padGap??$3.padGap,C=d.clearance??$3.clearance,y=d.colSpacing??d.pitchX??$3.pitchX,x=d.rowSpacing??d.pitchY??$3.pitchY,E=(B=_,S=f,Q=I,p==="horizontal"?{x:Q+2*B,y:S}:{x:S,y:Q+2*B});var B,S,Q;const w=C,M=((F,O,U,Y,W)=>F==="horizontal"?O==="x"?W+2*U:Y:O==="x"?Y:W+2*U)(p,m,_,f,I)/2,k=d.staggerOffset??d.staggerOffsetX??M,R={...$3,...d,orientation:p,staggerAxis:m,pitchX:Math.max(y,E.x+w),pitchY:Math.max(x,E.y+w),padWidth:_,padHeight:f,padGap:I,staggerOffset:k,staggerOffsetX:k,concavityTolerance:d.concavityTolerance??$3.concavityTolerance,clearance:C,portSpacing:d.portSpacing??$3.portSpacing,maxNeckRatio:d.maxNeckRatio??$3.maxNeckRatio,minSplitBalanceRatio:d.minSplitBalanceRatio??$3.minSplitBalanceRatio};if(R.cols<=0||R.rows<=0)throw new Error("rows and cols must be > 0");if(!Number.isFinite(R.portSpacing)||R.portSpacing<=0)throw new Error("portSpacing must be > 0");if(!Number.isFinite(R.maxNeckRatio)||R.maxNeckRatio<0)throw new Error("maxNeckRatio must be >= 0");if(!Number.isFinite(R.minSplitBalanceRatio)||R.minSplitBalanceRatio<0||R.minSplitBalanceRatio>.5)throw new Error("minSplitBalanceRatio must be between 0 and 0.5");return R})(t),n=uno(e),o=e.orientation==="horizontal"?e.padWidth:e.padHeight,i=e.orientation==="horizontal"?e.padHeight:e.padWidth,r=n.jumpers.flatMap(d=>d.padCenters.map(p=>({center:p,width:o,height:i,ccwRotation:0}))),s=new Xto({bounds:n.bounds,rects:r,clearance:0,concavityTolerance:e.concavityTolerance});s.solve();const a=s.getOutput();if(!a)throw new Error(s.error??"ConvexRegionsSolver failed");const A=((d,p)=>{if(p.maxNeckRatio<=0)return d;const m=[];for(const _ of d)m.push(...Zto(_,p));return m})(a.regions,{maxNeckRatio:e.maxNeckRatio,minSplitBalanceRatio:e.minSplitBalanceRatio}),c=gno(A),l=((d,p)=>d.flatMap(m=>{const[_,f]=m.padCenters,I=p.orientation==="horizontal"?p.padWidth/2:p.padHeight/2,C=p.orientation==="horizontal"?p.padHeight/2:p.padWidth/2,y={minX:_.x-I,maxX:_.x+I,minY:_.y-C,maxY:_.y+C},x={minX:f.x-I,maxX:f.x+I,minY:f.y-C,maxY:f.y+C},E=I/2,B=C/2,S=p.orientation==="horizontal"?{minX:Math.min(_.x,f.x),maxX:Math.max(_.x,f.x),minY:m.center.y-B,maxY:m.center.y+B}:{minX:m.center.x-E,maxX:m.center.x+E,minY:Math.min(_.y,f.y),maxY:Math.max(_.y,f.y)};return[{regionId:`${m.jumperId}_pad1`,ports:[],d:{bounds:y,center:_,polygon:V6e(y),isPad:!0,isThroughJumper:!1}},{regionId:`${m.jumperId}_bridge`,ports:[],d:{bounds:S,center:m.center,polygon:V6e(S),isPad:!1,isThroughJumper:!0}},{regionId:`${m.jumperId}_pad2`,ports:[],d:{bounds:x,center:f,polygon:V6e(x),isPad:!0,isThroughJumper:!1}}]}))(n.jumpers,{orientation:e.orientation,padWidth:e.padWidth,padHeight:e.padHeight}),u=((d,p,m=1e-5)=>{const _=[];let f=0;for(let I=0;I<d.length;I++){const C=d[I];if(C?.d.polygon)for(let y=I+1;y<d.length;y++){const x=d[y];if(!x?.d.polygon)continue;const E=qIt(C,x,m);for(const B of E){const S=dno(B),Q=Math.floor(S/p),w=Math.max(1,Q-1);for(let M=0;M<w;M++){const k=fL(B,(M+1)/(w+1));_.push({portId:"tp_"+f++,region1:C,region2:x,d:{x:k.x,y:k.y}})}}}}return _})(c,e.portSpacing),g=((d,p,m=1e-5)=>{const _=[];let f=0,I=0;const C=d.filter(x=>x.d.isPad),y=d.filter(x=>x.d.isThroughJumper&&!x.d.isPad);for(const x of C)for(const E of p){const B=qIt(x,E,m),S=hno(B,m);for(const Q of S){const w=fL(Q,.5);_.push({portId:"jp_"+f++,region1:x,region2:E,d:{x:w.x,y:w.y}})}}for(const x of y)for(const E of C){const B=fno(x.d.bounds,E.d.bounds,m);if(!B)continue;const S=$It(B);_.push({portId:"jip_"+I++,region1:E,region2:x,d:{x:S.x,y:S.y}})}return _})(l,c),h=[...u,...g];return(d=>{for(const p of d)p.region1.ports.push(p),p.region2.ports.push(p)})(h),{regions:[...c,...l],ports:h,jumperLocations:n.jumpers.map((d,p)=>({center:d.center,orientation:d.orientation,padRegions:[l[3*p],l[3*p+2]].filter(m=>!!m)})),topLayerRegions:c,jumperRegions:l,jumpers:n.jumpers,vias:n.vias,bounds:n.bounds}},Cno=class extends yr{getSolverName(){return"JumperPrepatternSolver2_HyperGraph"}constructorParams;nodeWithPortPoints;colorMap;traceWidth;obstacleMargin;hyperParameters;jumperGraphSolver=null;xyConnections=[];graphBounds=null;jumperLocations=[];solvedRoutes=[];jumpers=[];phase="jumperGraph";curvySolvers=[];currentCurvySolverIndex=0;routeInfos=[];regionCurvedPaths=new Map;constructor(t){super(),this.constructorParams=t,this.nodeWithPortPoints=t.nodeWithPortPoints,this.colorMap=t.colorMap??{},this.traceWidth=t.traceWidth??.15,this.obstacleMargin=t.obstacleMargin??.15,this.hyperParameters=t.hyperParameters??{},this.MAX_ITERATIONS=1e6,Object.keys(this.colorMap).length===0&&(this.colorMap=this._buildColorMap())}getConstructorParams(){return this.constructorParams}_buildColorMap(){const t=["#e6194b","#3cb44b","#ffe119","#4363d8","#f58231","#911eb4","#46f0f0","#f032e6","#bcf60c","#fabebe"],e={},n=new Set;for(const i of this.nodeWithPortPoints.portPoints)n.add(i.connectionName);let o=0;for(const i of Array.from(n))e[i]=t[o%t.length],o++;return e}_normalizeRegionPolygonsToBounds(t){for(const e of t.regions){const n=e.d,o=n?.polygon,i=n?.bounds;if(!o||o.length===0||!i)continue;let r=1/0,s=1/0;for(const c of o)r=Math.min(r,c.x),s=Math.min(s,c.y);const a=i.minX-r,A=i.minY-s;(Math.abs(a)>1e-12||Math.abs(A)>1e-12)&&(n.polygon=o.map(c=>({x:c.x+a,y:c.y+A}))),n.polygonPerimeterCache&&(n.polygonPerimeterCache=void 0)}return t}_getPatternConfig(){return{cols:this.hyperParameters.COLS??1,rows:this.hyperParameters.ROWS??1}}_generate0603Grid(t,e,n,o){const i=e==="horizontal"?t.rows:t.cols,r=e==="horizontal"?t.cols:t.rows,s=o.maxX-o.minX,a=o.maxY-o.minY,A=.35,c=this.hyperParameters.TRACE_CHANNELS_BETWEEN_JUMPERS??1,l=this.traceWidth*c+2*this.obstacleMargin,u=e==="horizontal"?2.15:1,g=e==="horizontal"?1:2.15,h=e==="horizontal"?"x":"y",d=n==="staggered",p=d&&h==="x"?u/2:d?g/2:0,m=Math.max(0,s-1),_=Math.max(0,a-1),f=Math.max(0,m-(d&&h==="x"?p:0)),I=Math.max(0,_-(d&&h==="y"?p:0)),C=i>1?Math.max(u+l,(f-u)/(i-1)):u,y=r>1?Math.max(g+l,(I-g)/(r-1)):g,x=Ino({cols:i,rows:r,orientation:e,pattern:n,staggerAxis:h,colSpacing:C,rowSpacing:y,padWidth:.9,padHeight:1,padGap:A,clearance:l,boundsPadding:0,maxNeckRatio:.4,minSplitBalanceRatio:.2}),E=x.bounds,B=(E.minX+E.maxX)/2,S=(E.minY+E.maxY)/2,Q=r_t((o.minX+o.maxX)/2-B,(o.minY+o.maxY)/2-S);return this._normalizeRegionPolygonsToBounds(Y1t(x,Q))}_initializeGraph(){const t=this.nodeWithPortPoints,e=this._getPatternConfig(),n=this.hyperParameters.ORIENTATION??"vertical",o=this.hyperParameters.JUMPER_TYPE??"1206x4",i=this.hyperParameters.PATTERN??"grid",r={minX:t.center.x-t.width/2,maxX:t.center.x+t.width/2,minY:t.center.y-t.height/2,maxY:t.center.y+t.height/2};let s;if(this.graphBounds=r,o==="0603"){const c=this._generate0603Grid(e,n,i,r);if(!c)return this.error=`0603 grid (${e.cols}x${e.rows}) is too large to fit in node bounds`,this.failed=!0,!1;s=c}else s=Xeo({cols:e.cols,rows:e.rows,marginX:Math.max(1.2,.3*e.cols),marginY:Math.max(1.2,.3*e.rows),outerPaddingX:.4,outerPaddingY:.4,parallelTracesUnderJumperCount:2,innerColChannelPointCount:3,innerRowChannelPointCount:3,outerChannelXPointCount:3,outerChannelYPointCount:3,regionsBetweenPads:!0,orientation:n,bounds:r});if(s.regions.length>0){let c=1/0,l=-1/0,u=1/0,g=-1/0;for(const d of s.regions){if(!d.d?.isPad)continue;const p=d.d?.bounds;p&&(c=Math.min(c,p.minX),l=Math.max(l,p.maxX),u=Math.min(u,p.minY),g=Math.max(g,p.maxY))}const h=o==="0603"?.5:1;if(c-h<r.minX||l+h>r.maxX||u-h<r.minY||g+h>r.maxY)return this.error=`baseGraph bounds (${c.toFixed(2)}, ${u.toFixed(2)}, ${l.toFixed(2)}, ${g.toFixed(2)}) exceed node bounds (${r.minX.toFixed(2)}, ${r.minY.toFixed(2)}, ${r.maxX.toFixed(2)}, ${r.maxY.toFixed(2)})`,this.failed=!0,!1}this.jumperLocations=s.jumperLocations?.map(c=>({center:c.center,orientation:c.orientation,padRegions:c.padRegions}))??[];const a=new Map;for(const c of t.portPoints){const l=a.get(c.connectionName);l?l.points.push(c):a.set(c.connectionName,{points:[c],rootConnectionName:c.rootConnectionName})}this.xyConnections=[];for(const[c,l]of Array.from(a.entries()))l.points.length<2||this.xyConnections.push({start:{x:l.points[0].x,y:l.points[0].y},end:{x:l.points[1].x,y:l.points[1].y},connectionId:c});if(this.xyConnections.length===0)return this.solved=!0,!0;const A=((c,l)=>{const u=[...c.regions],g=[...c.ports],h=[],d=k1t(c.regions);for(const p of l){const{start:m,end:_,connectionId:f}=p,I=L1t(`conn:${f}:start`,m.x,m.y);u.push(I);const C=L1t(`conn:${f}:end`,_.x,_.y);u.push(C);const y=O1t(m.x,m.y,c.regions,d);if(y){const B=F1t(`conn:${f}:start-port`,I,y.region,y.portPosition);g.push(B)}const x=O1t(_.x,_.y,c.regions,d);if(x){const B=F1t(`conn:${f}:end-port`,C,x.region,x.portPosition);g.push(B)}const E={connectionId:f,mutuallyConnectedNetworkId:f,startRegion:I,endRegion:C};h.push(E)}return{regions:u,ports:g,connections:h}})(s,this.xyConnections);return this.jumperGraphSolver=new $eo({inputGraph:{regions:A.regions,ports:A.ports},inputConnections:A.connections}),this.jumperGraphSolver.MAX_ITERATIONS*=3,!0}_step(){switch(this.phase){case"jumperGraph":this._stepJumperGraph();break;case"curvyTrace":this._stepCurvyTrace();break;case"done":this.solved=!0}}_stepJumperGraph(){if(!this.jumperGraphSolver){if(this._initializeGraph(),this.solved)return;if(!this.jumperGraphSolver)return void(this.failed=!0)}this.activeSubSolver=this.jumperGraphSolver,this.jumperGraphSolver.step(),this.jumperGraphSolver.solved?(this._initializeCurvyTraceSolvers(),this.curvySolvers.length>0?this.phase="curvyTrace":(this._finalizeCurvyTraceResults(),this.phase="done",this.solved=!0)):this.jumperGraphSolver.failed&&(this.error=this.jumperGraphSolver.error,this.failed=!0)}_stepCurvyTrace(){if(this.currentCurvySolverIndex>=this.curvySolvers.length)return this._finalizeCurvyTraceResults(),this.phase="done",void(this.solved=!0);const t=this.curvySolvers[this.currentCurvySolverIndex],e=t.solver;if(this.activeSubSolver=e,e.step(),e.solved){const n=t.regionId;this.regionCurvedPaths.has(n)||this.regionCurvedPaths.set(n,new Map);for(const o of e.outputTraces){const i=o.networkId??"",r=o.points.map(a=>({x:a.x,y:a.y})),s={path:r,start:r[0]??{x:0,y:0},end:r[r.length-1]??{x:0,y:0}};this.regionCurvedPaths.get(n).has(i)||this.regionCurvedPaths.get(n).set(i,[]),this.regionCurvedPaths.get(n).get(i).push(s)}this.currentCurvySolverIndex++}else e.failed&&this.currentCurvySolverIndex++}_initializeCurvyTraceSolvers(){if(!this.jumperGraphSolver)return;const t=new Set,e=[];for(const o of this.jumperLocations)for(const i of o.padRegions){const r=i.d.bounds,s=i.d.center;e.push({minX:r.minX,minY:r.minY,maxX:r.maxX,maxY:r.maxY,center:{x:s.x,y:s.y},networkIds:[]})}const n=new Map;for(let o=0;o<this.jumperGraphSolver.solvedRoutes.length;o++){const i=this.jumperGraphSolver.solvedRoutes[o],r=i.connection.connectionId,s=this.nodeWithPortPoints.portPoints.find(u=>u.connectionName===r)?.rootConnectionName,a=[],A=[];let c=null,l=null;for(let u=0;u<i.path.length;u++){const g=i.path[u],h=g.port,d=g.lastRegion,p=h.region1,m=h.region2;let _;if(d)p&&p.regionId!==d.regionId?_=p:m&&m.regionId!==d.regionId&&(_=m);else{const f=i.path[u+1],I=f?.lastRegion;if(I&&(p&&p.regionId===I.regionId?_=p:m&&m.regionId===I.regionId&&(_=m)),!_){const C=y=>y?.regionId?.startsWith("conn:");_=!p||C(p)||p.d?.isPad||p.d?.isThroughJumper?!m||C(m)||m.d?.isPad||m.d?.isThroughJumper?!p||p.d?.isPad||p.d?.isThroughJumper?(!m||m.d?.isPad||m.d?.isThroughJumper)&&p||m:p:m:p}}if(_&&(!c||_.regionId!==c.regionId)){if(c&&l){A.push({regionId:c.regionId,region:c,entryPort:l,exitPort:h});const f=c.regionId;n.has(f)||n.set(f,[]),n.get(f).push({regionId:c.regionId,region:c,routeIndex:o,connectionName:r,rootConnectionName:s,entryPort:l,exitPort:h})}c=_,l=h}if(d?.d?.isThroughJumper&&!t.has(d.regionId)){t.add(d.regionId);const f=d.d.bounds,I=d.d.center,C=f.maxX-f.minX>f.maxY-f.minY,y=(this.hyperParameters.JUMPER_TYPE??"1206x4")==="0603"?"0603":"1206x4_pair";C?a.push({route_type:"jumper",start:{x:f.minX,y:I.y},end:{x:f.maxX,y:I.y},footprint:y}):a.push({route_type:"jumper",start:{x:I.x,y:f.minY},end:{x:I.x,y:f.maxY},footprint:y})}}if(c&&l){const u=i.path[i.path.length-1];A.push({regionId:c.regionId,region:c,entryPort:l,exitPort:u?.port||null})}this.routeInfos.push({connectionId:r,rootConnectionName:s,jumpers:a,traversals:A})}for(let o=0;o<this.routeInfos.length;o++){const i=this.routeInfos[o],r=i.rootConnectionName??i.connectionId;for(const s of i.jumpers){const a=[s.start,s.end];for(const A of a)for(const c of e){const l=Math.abs(c.center.x-A.x),u=Math.abs(c.center.y-A.y);l<.1&&u<.1&&(c.networkIds.includes(r)||c.networkIds.push(r))}}}for(const[o,i]of n){if(i.length===0)continue;const r=i[0].region;if(r.d.isPad||r.d.isThroughJumper)continue;const s=r.d.bounds,a=[];for(const g of i)a.push({start:{x:g.entryPort.d.x,y:g.entryPort.d.y},end:{x:g.exitPort.d.x,y:g.exitPort.d.y},networkId:g.rootConnectionName??g.connectionName});const A=.01,c=e.filter(g=>g.minX<=s.maxX+A&&g.maxX>=s.minX-A&&g.minY<=s.maxY+A&&g.maxY>=s.minY-A).map(g=>{const h=i.map(p=>p.rootConnectionName??p.connectionName),d=g.networkIds.find(p=>h.includes(p));return{minX:g.minX,minY:g.minY,maxX:g.maxX,maxY:g.maxY,center:g.center,networkId:d}}),l={bounds:s,waypointPairs:a,obstacles:c,preferredTraceToTraceSpacing:2*this.traceWidth,preferredObstacleToTraceSpacing:2*this.traceWidth},u=new y1t(l);this.curvySolvers.push({solver:u,regionId:o,traversals:i.map(g=>({routeIndex:g.routeIndex,connectionName:g.connectionName,rootConnectionName:g.rootConnectionName}))})}}_finalizeCurvyTraceResults(){const t=(e,n)=>Math.sqrt((e.x-n.x)**2+(e.y-n.y)**2);for(let e=0;e<this.routeInfos.length;e++){const n=this.routeInfos[e],o=[];for(const i of n.traversals){const r=i.regionId,s=n.rootConnectionName??n.connectionId,a=this.regionCurvedPaths.get(r)?.get(s);let A=null;if(a&&a.length>0){const c={x:i.entryPort.d.x,y:i.entryPort.d.y},l=i.exitPort?{x:i.exitPort.d.x,y:i.exitPort.d.y}:null;let u=null,g=1/0;for(const h of a){const d=t(h.start,c)+(l?t(h.end,l):0);d<g&&(g=d,u=h)}u&&g<.5&&(A=u.path)}if(A&&A.length>0)for(let c=o.length>0?1:0;c<A.length;c++)o.push({x:A[c].x,y:A[c].y,z:0});else o.length===0&&o.push({x:i.entryPort.d.x,y:i.entryPort.d.y,z:0}),i.exitPort&&o.push({x:i.exitPort.d.x,y:i.exitPort.d.y,z:0})}this.solvedRoutes.push({connectionName:n.connectionId,rootConnectionName:n.rootConnectionName,traceThickness:this.traceWidth,route:o,jumpers:n.jumpers})}}getOutput(){return this.solvedRoutes}getOutputJumpers(){if(this.jumpers.length>0)return this.jumpers;const t=new Map;for(const o of this.solvedRoutes)for(const i of o.jumpers){const r=[i.start,i.end];for(const s of r){const a=`${s.x.toFixed(3)},${s.y.toFixed(3)}`,A=t.get(a)??[];o.rootConnectionName&&!A.includes(o.rootConnectionName)&&A.push(o.rootConnectionName),A.includes(o.connectionName)||A.push(o.connectionName),t.set(a,A)}}const e=this.hyperParameters.JUMPER_TYPE??"1206x4",n=W8[e==="0603"?"0603":"1206x4_pair"];for(const o of this.jumperLocations){const i=o.orientation==="horizontal",r=o.padRegions.map(a=>{const A=a.d.bounds,c=a.d.center,l=A.maxX-A.minX,u=A.maxY-A.minY,g=`${c.x.toFixed(3)},${c.y.toFixed(3)}`;return{type:"rect",center:c,width:l,height:u,layers:["top"],connectedTo:[...t.get(g)??[]]}}),s={jumper_footprint:e,center:o.center,orientation:o.orientation,width:i?n.length:n.width,height:i?n.width:n.length,pads:r};this.jumpers.push(s)}return this.jumpers=this.jumpers.filter(o=>o.pads.some(i=>i.connectedTo.length>0)),this.jumpers}visualize(){if(this.jumperGraphSolver&&!this.solved)return this.jumperGraphSolver.visualize();const t={lines:[],points:[],rects:[],circles:[]},e=this.nodeWithPortPoints,n={minX:e.center.x-e.width/2,maxX:e.center.x+e.width/2,minY:e.center.y-e.height/2,maxY:e.center.y+e.height/2};t.lines.push({points:[{x:n.minX,y:n.minY},{x:n.maxX,y:n.minY},{x:n.maxX,y:n.maxY},{x:n.minX,y:n.maxY},{x:n.minX,y:n.minY}],strokeColor:"rgba(255, 0, 0, 0.25)",strokeDash:"4 4",layer:"border"});for(const o of e.portPoints)t.points.push({x:o.x,y:o.y,label:o.connectionName,color:this.colorMap[o.connectionName]??"blue"});for(const o of this.solvedRoutes){const i=this.colorMap[o.connectionName]??"blue";for(let r=0;r<o.route.length-1;r++){const s=o.route[r],a=o.route[r+1];t.lines.push({points:[s,a],strokeColor:Es(i,.2),strokeWidth:o.traceThickness,layer:"route-layer-0"})}for(const r of o.jumpers)this._drawJumperPads(t,r,Es(i,.5))}return t}_drawJumperPads(t,e,n){const o=W8[e.footprint],i=e.end.x-e.start.x,r=e.end.y-e.start.y,s=Math.abs(i)>Math.abs(r),a=s?o.padLength:o.padWidth,A=s?o.padWidth:o.padLength;t.rects.push({center:{x:e.start.x,y:e.start.y},width:a,height:A,fill:n,stroke:"rgba(0, 0, 0, 0.5)",layer:"jumper"}),t.rects.push({center:{x:e.end.x,y:e.end.y},width:a,height:A,fill:n,stroke:"rgba(0, 0, 0, 0.5)",layer:"jumper"}),t.lines.push({points:[e.start,e.end],strokeColor:"rgba(100, 100, 100, 0.8)",strokeWidth:.3*o.padWidth,layer:"jumper-body"})}},yno=class extends Zse{constructorParams;nodeWithPortPoints;colorMap;traceWidth;obstacleMargin;connMap;baseHyperParameters;availableJumperTypes;solvedRoutes=[];jumpers=[];constructor(t){super(),this.constructorParams=t,this.nodeWithPortPoints=t.nodeWithPortPoints,this.colorMap=t.colorMap??{},this.traceWidth=t.traceWidth??.15,this.obstacleMargin=t.obstacleMargin??.15,this.connMap=t.connMap,this.baseHyperParameters=t.hyperParameters??{},this.availableJumperTypes=t.availableJumperTypes??["0603"],this.MAX_ITERATIONS=1e6,this.GREEDY_MULTIPLIER=1,this.MIN_SUBSTEPS=1e3}getConstructorParams(){return this.constructorParams}getHyperParameterDefs(){const t=[],e=this.nodeWithPortPoints,n=this.calculateMax0603ConfigWithTraceChannels(e.width,e.height,"vertical",1);t.push({name:"0603_max_rows_and_cols_vert_1trace_grid",possibleValues:[{JUMPER_TYPE:"0603",COLS:n.cols,ROWS:n.rows,ORIENTATION:"vertical",PATTERN:"grid",TRACE_CHANNELS_BETWEEN_JUMPERS:1}]});const o=this.calculateMax0603ConfigWithTraceChannels(e.width,e.height,"vertical",1,"staggered");t.push({name:"0603_max_rows_and_cols_vert_1trace_staggered",possibleValues:[{JUMPER_TYPE:"0603",COLS:o.cols,ROWS:o.rows,ORIENTATION:"vertical",PATTERN:"staggered",TRACE_CHANNELS_BETWEEN_JUMPERS:1}]});const i=this.calculateMax0603ConfigWithTraceChannels(e.width,e.height,"vertical",2);t.push({name:"0603_max_rows_and_cols_vert_2trace_grid",possibleValues:[{JUMPER_TYPE:"0603",COLS:i.cols,ROWS:i.rows,ORIENTATION:"vertical",PATTERN:"grid",TRACE_CHANNELS_BETWEEN_JUMPERS:2}]});const r=this.calculateMax0603ConfigWithTraceChannels(e.width,e.height,"vertical",2,"staggered");t.push({name:"0603_max_rows_and_cols_vert_2trace_staggered",possibleValues:[{JUMPER_TYPE:"0603",COLS:r.cols,ROWS:r.rows,ORIENTATION:"vertical",PATTERN:"staggered",TRACE_CHANNELS_BETWEEN_JUMPERS:2}]});const s=this.calculateMax0603ConfigWithTraceChannels(e.width,e.height,"horizontal",1);t.push({name:"0603_max_rows_and_cols_horz_1trace_grid",possibleValues:[{JUMPER_TYPE:"0603",COLS:s.cols,ROWS:s.rows,ORIENTATION:"horizontal",PATTERN:"grid",TRACE_CHANNELS_BETWEEN_JUMPERS:1}]});const a=this.calculateMax0603ConfigWithTraceChannels(e.width,e.height,"horizontal",1,"staggered");t.push({name:"0603_max_rows_and_cols_horz_1trace_staggered",possibleValues:[{JUMPER_TYPE:"0603",COLS:a.cols,ROWS:a.rows,ORIENTATION:"horizontal",PATTERN:"staggered",TRACE_CHANNELS_BETWEEN_JUMPERS:1}]});const A=this.calculateMax0603ConfigWithTraceChannels(e.width,e.height,"horizontal",2);t.push({name:"0603_max_rows_and_cols_horz_2trace_grid",possibleValues:[{JUMPER_TYPE:"0603",COLS:A.cols,ROWS:A.rows,ORIENTATION:"horizontal",PATTERN:"grid",TRACE_CHANNELS_BETWEEN_JUMPERS:2}]});const c=this.calculateMax0603ConfigWithTraceChannels(e.width,e.height,"horizontal",2,"staggered");return t.push({name:"0603_max_rows_and_cols_horz_2trace_staggered",possibleValues:[{JUMPER_TYPE:"0603",COLS:c.cols,ROWS:c.rows,ORIENTATION:"horizontal",PATTERN:"staggered",TRACE_CHANNELS_BETWEEN_JUMPERS:2}]}),t.push({name:"1206x4",possibleValues:[{JUMPER_TYPE:"1206x4"}]}),t.push({name:"1206x4_cols",possibleValues:[1,2,3,4,6,8,10].map(l=>({COLS:l}))}),t.push({name:"1206x4_rows",possibleValues:[1,2,3,4,8].map(l=>({ROWS:l}))}),t.push({name:"orientation",possibleValues:[{ORIENTATION:"vertical"},{ORIENTATION:"horizontal"}]}),t}isValidCombination(t){const{JUMPER_TYPE:e,COLS:n,ROWS:o}=t,i=[1,2,4,6,8],r=[1,2,3,4,6,8,10],s=[1,2,3,4,8];return e==="0603"?i.includes(n)&&i.includes(o):e==="1206x4"&&r.includes(n)&&s.includes(o)}getCombinationDefs(){return[["0603_max_rows_and_cols_vert_1trace_grid"],["0603_max_rows_and_cols_vert_1trace_staggered"],["0603_max_rows_and_cols_horz_1trace_grid"],["0603_max_rows_and_cols_horz_1trace_staggered"],["0603_max_rows_and_cols_vert_2trace_grid"],["0603_max_rows_and_cols_vert_2trace_staggered"],["0603_max_rows_and_cols_horz_2trace_grid"],["0603_max_rows_and_cols_horz_2trace_staggered"],["1206x4","1206x4_cols","1206x4_rows","orientation"]]}calculateMax0603ConfigWithTraceChannels(t,e,n,o,i="grid"){const r=this.traceWidth*o+2*this.obstacleMargin,s=n==="horizontal"?2.15:1,a=n==="horizontal"?1:2.15,A=n==="horizontal"?"x":"y",c=i==="staggered"&&A==="x"?s/2:i==="staggered"?a/2:0,l=Math.max(0,t-1),u=Math.max(0,e-1),g=Math.max(0,l-(i==="staggered"&&A==="x"?c:0)),h=Math.max(0,u-(i==="staggered"&&A==="y"?c:0)),d=s+r,p=a+r,m=Math.max(1,Math.floor(1+(g-s)/d)),_=Math.max(1,Math.floor(1+(h-a)/p));return n==="vertical"?{cols:m,rows:_}:{cols:_,rows:m}}initializeSolvers(){const t=this.getHyperParameterDefs(),e=this.getCombinationDefs();this.supervisedSolvers=[];for(const n of e){const o=n.some(s=>s.startsWith("0603_max_rows_and_cols_")),i=n.includes("1206x4");if(o&&!this.availableJumperTypes.includes("0603")||i&&!this.availableJumperTypes.includes("1206x4"))continue;const r=this.getHyperParameterCombinations(t.filter(s=>n.includes(s.name)));for(const s of r){const a=this.generateSolver(s),A=this.computeG(a);this.supervisedSolvers.push({hyperParameters:s,solver:a,h:0,g:A,f:A})}}}generateSolver(t){return new Cno({nodeWithPortPoints:this.nodeWithPortPoints,colorMap:this.colorMap,traceWidth:this.traceWidth,hyperParameters:{COLS:t.COLS,ROWS:t.ROWS,ORIENTATION:t.ORIENTATION,JUMPER_TYPE:t.JUMPER_TYPE,PATTERN:t.PATTERN,TRACE_CHANNELS_BETWEEN_JUMPERS:t.TRACE_CHANNELS_BETWEEN_JUMPERS},obstacleMargin:this.obstacleMargin})}computeG(t){const e=t.hyperParameters.COLS*t.hyperParameters.ROWS;return t.iterations/1e4+.25*e}computeH(t){return 1-(t.progress||0)}onSolve(t){this.solvedRoutes=t.solver.solvedRoutes,this.jumpers=t.solver.getOutputJumpers()}getOutput(){return this.solvedRoutes}getOutputJumpers(){return this.jumpers}visualize(){return this.winningSolver?this.winningSolver.visualize():super.visualize()}};function xno(t){return{connectionName:t.connectionName,rootConnectionName:t.rootConnectionName,regionId:t.regionId,traceThickness:t.traceThickness,viaDiameter:0,route:t.route,vias:[],jumpers:t.jumpers}}var Eno=class extends yr{getSolverName(){return"JumperHighDensitySolver"}allNodes;nodeAnalyses;routes;colorMap;traceWidth;obstacleMargin;viaDiameter;connMap;hyperParameters;availableJumperTypes;capacityMeshNodes;capacityMeshEdges;capacityMeshNodeMap;nodeAdjacencyMap;nodesWithoutCrossings;nodesWithCrossings;curvyIntraNodeSolvers;currentCurvySolverIndex;jumperSolvers;currentJumperSolverIndex;phase;jumpers=[];constructor({nodePortPoints:t,colorMap:e,traceWidth:n=.15,obstacleMargin:o=.15,viaDiameter:i=.3,connMap:r,hyperParameters:s,capacityMeshNodes:a=[],capacityMeshEdges:A=[],availableJumperTypes:c}){super(),this.allNodes=[...t],this.colorMap=e??{},this.routes=[],this.traceWidth=n,this.obstacleMargin=o,this.viaDiameter=i,this.connMap=r,this.hyperParameters=s,this.capacityMeshNodes=a,this.capacityMeshEdges=A,this.availableJumperTypes=c??["0603"],this.capacityMeshNodeMap=new Map(a.map(g=>[g.capacityMeshNodeId,g])),this.nodeAdjacencyMap=this._buildNodeAdjacencyMap(),this.nodesWithoutCrossings=[],this.nodesWithCrossings=[],this.nodeAnalyses=[],this.curvyIntraNodeSolvers=[],this.currentCurvySolverIndex=0,this.jumperSolvers=[],this.currentJumperSolverIndex=0,this.phase="analyzing",this._analyzeNodes();const l=1e3*this.nodesWithoutCrossings.length,u=1e5*this.nodesWithCrossings.length;this.MAX_ITERATIONS=l+u+100}_buildNodeAdjacencyMap(){const t=new Map;for(const e of this.capacityMeshEdges){const[n,o]=e.nodeIds;t.has(n)||t.set(n,new Set),t.has(o)||t.set(o,new Set),t.get(n).add(o),t.get(o).add(n)}return t}_analyzeNodes(){for(const t of this.allNodes){const e=Wm(t),n={node:t,hasCrossings:e.numSameLayerCrossings>0,numSameLayerCrossings:e.numSameLayerCrossings};this.nodeAnalyses.push(n),e.numSameLayerCrossings>0?this.nodesWithCrossings.push(t):this.nodesWithoutCrossings.push(t)}this.nodesWithoutCrossings.length>0?(this.phase="curvy",this._initializeCurvySolvers()):this.nodesWithCrossings.length>0?(this.phase="jumpers",this._initializeJumperSolvers()):this.phase="done"}_step(){switch(this.phase){case"analyzing":this.nodesWithoutCrossings.length>0?(this.phase="curvy",this._initializeCurvySolvers()):this.nodesWithCrossings.length>0?(this.phase="jumpers",this._initializeJumperSolvers()):this.phase="done";break;case"curvy":this._stepCurvySolvers();break;case"jumpers":this._stepJumperSolvers();break;case"done":this.solved=!0}}_getAdjacentObstacles(t){const e=[],n=this.nodeAdjacencyMap.get(t.capacityMeshNodeId);if(!n||n.size===0)return e;const o=new Map(this.allNodes.map(i=>[i.capacityMeshNodeId,i]));for(const i of n){const r=this.capacityMeshNodeMap.get(i);if(!r||!r._containsObstacle&&!r._containsTarget)continue;const s=r.center.x-r.width/2,a=r.center.y-r.height/2,A=r.center.x+r.width/2,c=r.center.y+r.height/2;let l;if(r._containsTarget)if(r._targetConnectionName)l=r._targetConnectionName;else{const u=o.get(i);u&&u.portPoints.length>0&&(l=u.portPoints[0].rootConnectionName??u.portPoints[0].connectionName)}e.push({minX:s,minY:a,maxX:A,maxY:c,networkId:l})}return e}_initializeCurvySolvers(){for(const t of this.nodesWithoutCrossings){const e=this._getAdjacentObstacles(t),n=new x1t({nodeWithPortPoints:t,colorMap:this.colorMap,traceWidth:this.traceWidth,viaDiameter:this.viaDiameter,adjacentObstacles:e});this.curvyIntraNodeSolvers.push(n)}}_stepCurvySolvers(){if(this.curvyIntraNodeSolvers.length===0)return this.phase=this.nodesWithCrossings.length>0?"jumpers":"done",void(this.phase==="jumpers"&&this._initializeJumperSolvers());const t=this.curvyIntraNodeSolvers[this.currentCurvySolverIndex];if(this.activeSubSolver=t,!t)return this.phase=this.nodesWithCrossings.length>0?"jumpers":"done",void(this.phase==="jumpers"&&this._initializeJumperSolvers());if(t.step(),t.solved){this.routes.push(...t.routes),this.currentCurvySolverIndex++;for(let e=this.currentCurvySolverIndex;e<this.curvyIntraNodeSolvers.length;e++){this.curvyIntraNodeSolvers[e];const n=this.nodesWithoutCrossings[e],o=this._getAdjacentObstacles(n),i=new x1t({nodeWithPortPoints:n,colorMap:this.colorMap,traceWidth:this.traceWidth,viaDiameter:this.viaDiameter,adjacentObstacles:o});this.curvyIntraNodeSolvers[e]=i}this.currentCurvySolverIndex>=this.curvyIntraNodeSolvers.length&&(this.phase=this.nodesWithCrossings.length>0?"jumpers":"done",this.phase==="jumpers"&&this._initializeJumperSolvers())}else t.failed&&(this.error=`CurvyIntraNodeSolver failed for node: ${t.nodeWithPortPoints.capacityMeshNodeId}: ${t.error}`,this.failed=!0)}_initializeJumperSolvers(){for(const t of this.nodesWithCrossings){const e=new yno({nodeWithPortPoints:t,colorMap:this.colorMap,traceWidth:this.traceWidth,obstacleMargin:this.obstacleMargin,connMap:this.connMap,availableJumperTypes:this.availableJumperTypes});this.jumperSolvers.push(e)}}_stepJumperSolvers(){if(this.jumperSolvers.length===0)return this.phase="done",void(this.solved=!0);const t=this.jumperSolvers[this.currentJumperSolverIndex];if(this.activeSubSolver=t,!t)return this.phase="done",void(this.solved=!0);if(t.step(),t.solved){for(const e of t.solvedRoutes)this.routes.push(xno(e));this.jumpers.push(...t.getOutputJumpers()),this.currentJumperSolverIndex++,this.currentJumperSolverIndex>=this.jumperSolvers.length&&(this.phase="done",this.solved=!0)}else t.failed&&(this.error=`HyperJumperPrepatternSolver2 failed for node: ${t.nodeWithPortPoints.capacityMeshNodeId}: ${t.error}`,this.failed=!0)}computeProgress(){const t=this.allNodes.length;if(t===0)return 1;let e=0;e+=this.currentCurvySolverIndex;const n=this.curvyIntraNodeSolvers[this.currentCurvySolverIndex];n&&(e+=n.progress),e+=this.currentJumperSolverIndex;const o=this.jumperSolvers[this.currentJumperSolverIndex];return o&&(e+=o.progress),e/t}getConstructorParams(){return{nodePortPoints:this.allNodes,colorMap:this.colorMap,traceWidth:this.traceWidth,obstacleMargin:this.obstacleMargin,viaDiameter:this.viaDiameter,connMap:this.connMap,hyperParameters:this.hyperParameters,capacityMeshNodes:this.capacityMeshNodes,capacityMeshEdges:this.capacityMeshEdges,availableJumperTypes:this.availableJumperTypes}}getOutputJumpers(){return this.jumpers}visualize(){const t={lines:[],points:[],rects:[],circles:[]};if(this.failed&&this.activeSubSolver)return this.activeSubSolver.visualize();if(this.phase==="curvy"&&this.curvyIntraNodeSolvers[this.currentCurvySolverIndex])return this.curvyIntraNodeSolvers[this.currentCurvySolverIndex].visualize();if(this.phase==="jumpers"&&this.jumperSolvers[this.currentJumperSolverIndex])return this.jumperSolvers[this.currentJumperSolverIndex].visualize();for(const e of this.routes){const n=e.rootConnectionName??e.connectionName,o=Kse(e.route,e.connectionName,this.colorMap[n]);for(const i of o)t.lines.push({points:i.points,label:i.connectionName,strokeColor:i.z===0?i.color:Es(i.color??"gray",.75),layer:`z${i.z}`,strokeWidth:e.traceThickness,strokeDash:i.z!==0?"10, 5":void 0});for(const i of e.vias)t.circles.push({center:i,radius:e.viaDiameter/2,fill:Es(this.colorMap[n]??"gray",.5),layer:"via"});if("jumpers"in e&&e.jumpers)for(const i of e.jumpers){const r=this.colorMap[n]??"gray",s=i.footprint??"1206",a=W8[s],A=i.end.x-i.start.x,c=i.end.y-i.start.y,l=Math.abs(A)>Math.abs(c),u=l?a.padLength:a.padWidth,g=l?a.padWidth:a.padLength;t.rects.push({center:i.start,width:u,height:g,fill:Es(r,.5),stroke:"rgba(0, 0, 0, 0.5)",layer:"jumper"}),t.rects.push({center:i.end,width:u,height:g,fill:Es(r,.5),stroke:"rgba(0, 0, 0, 0.5)",layer:"jumper"}),t.lines.push({points:[i.start,i.end],strokeColor:"rgba(100, 100, 100, 0.8)",strokeWidth:.3*a.padWidth,layer:"jumper-body"})}}for(const e of this.nodeAnalyses){const n=e.node;n.center.x,n.width,n.center.x,n.width,n.center.y,n.height,n.center.y,n.height,t.rects.push({center:n.center,width:n.width,height:n.height,fill:e.hasCrossings?"rgba(255, 200, 0, 0.1)":"rgba(0, 200, 0, 0.1)",stroke:e.hasCrossings?"rgba(255, 150, 0, 0.5)":"rgba(0, 150, 0, 0.5)",label:[n.capacityMeshNodeId,e.hasCrossings?`crossings: ${e.numSameLayerCrossings}`:"no crossings"].join(`
`)})}return t}};function q8(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved}}var Bno=class extends yr{constructor(t,e={}){super(),this.srj=t,this.opts=e,this.srj=t,this.opts={...e},this.viaDiameter=om(t).padDiameter,this.minTraceWidth=t.minTraceWidth;const n=this.opts;if(this.effort=n.effort??1,this.MAX_ITERATIONS=1e8*this.effort,n.capacityDepth===void 0){const o=t.bounds.maxX-t.bounds.minX,i=t.bounds.maxY-t.bounds.minY,r=Math.max(o,i),s=n.targetMinCapacity??.5;n.capacityDepth=$Q(r,s)}this.connMap=Jm(t),this.colorMap=Jf(t,this.connMap),this.cacheProvider=n.cacheProvider===void 0?tB():n.cacheProvider===null?null:n.cacheProvider,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={}}srj;opts;getSolverName(){return"AssignableAutoroutingPipeline3"}netToPointPairsSolver;traceKeepoutSolver;nodeSolver;nodeTargetMerger;edgeSolver;relateNodesToOffBoardConnections;colorMap;highDensityRouteSolver;simpleHighDensityRouteSolver;highDensitySolver;highDensityStitchSolver;singleLayerNodeMerger;offboardPathFragmentSolver;strawSolver;deadEndSolver;traceSimplificationSolver;traceWidthSolver;availableSegmentPointSolver;portPointPathingSolver;multiSectionPortPointOptimizer;viaDiameter;minTraceWidth;effort;startTimeOfPhase;endTimeOfPhase;timeSpentOnPhase;activeSubSolver=null;connMap;srjWithPointPairs;capacityNodes=null;capacityEdges=null;cacheProvider=null;pipelineDef=[q8("netToPointPairsSolver",J7e,t=>[t.srj,t.colorMap,JQ(t.srj)],{onSolved:t=>{t.srjWithPointPairs=t.netToPointPairsSolver?.getNewSimpleRouteJson(),t.colorMap=Jf(t.srjWithPointPairs,this.connMap),t.connMap=Jm(t.srjWithPointPairs)}}),q8("nodeSolver",qF,t=>[{simpleRouteJson:t.srjWithPointPairs,maxGapFillPasses:4}],{onSolved:t=>{t.capacityNodes=t.nodeSolver?.getOutput().meshNodes??[]}}),q8("relateNodesToOffBoardConnections",g1t,t=>[{capacityMeshNodes:t.capacityNodes,srj:t.srj}],{onSolved:t=>{t.capacityNodes=t.relateNodesToOffBoardConnections?.getOutput().capacityNodes}}),q8("edgeSolver",WQ,t=>[t.capacityNodes],{onSolved:t=>{t.capacityEdges=t.edgeSolver?.edges}}),q8("availableSegmentPointSolver",kD,t=>[{nodes:t.capacityNodes,edges:t.capacityEdges||[],traceWidth:t.minTraceWidth,colorMap:t.colorMap,shouldReturnCrampedPortPoints:!1}]),q8("portPointPathingSolver",z7e,t=>{const e=t.capacityNodes.map(i=>({capacityMeshNodeId:i.capacityMeshNodeId,center:i.center,width:i.width,height:i.height,portPoints:[],availableZ:i.availableZ,_containsTarget:i._containsTarget,_containsObstacle:i._containsObstacle,_offBoardConnectionId:i._offBoardConnectionId,_offBoardConnectedCapacityMeshNodeIds:i._offBoardConnectedCapacityMeshNodeIds})),n=new Map(e.map(i=>[i.capacityMeshNodeId,i])),o=t.availableSegmentPointSolver;for(const i of o.sharedEdgeSegments)for(const r of i.portPoints){const[s,a]=r.nodeIds,A={portPointId:r.segmentPortPointId,x:r.x,y:r.y,z:r.availableZ[0]??0,connectionNodeIds:[s,a],distToCentermostPortOnZ:r.distToCentermostPortOnZ,connectsToOffBoardNode:i.nodeIds.some(l=>n.get(l)?._offBoardConnectionId)},c=n.get(s);c&&c.portPoints.push(A)}return[{simpleRouteJson:t.srjWithPointPairs,inputNodes:e,capacityMeshNodes:t.capacityNodes,colorMap:t.colorMap,numShuffleSeeds:10*t.effort,hyperParameters:{JUMPER_PF_FN_ENABLED:!0,NODE_PF_FACTOR:100,MAX_RIPS:100*t.effort,RIPPING_ENABLED:!0,MAX_RIPPING_PF_THRESHOLD:.9,MIN_RIPPING_PF_THRESHOLD:.1,RANDOM_RIP_FRACTION:.05,NODE_PF_MAX_PENALTY:1e3,STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR:0,CENTER_OFFSET_DIST_PENALTY_FACTOR:0,FORCE_CENTER_FIRST:!0}}]},{onSolved:t=>{const e=t.portPointPathingSolver;e&&d1t({connMap:t.connMap,connectionsWithResults:e.connectionsWithResults,inputNodes:e.inputNodes,obstacles:t.srj.obstacles})}}),q8("highDensitySolver",Eno,t=>[{nodePortPoints:t.multiSectionPortPointOptimizer?.getNodesWithPortPoints()??t.portPointPathingSolver?.getNodesWithPortPoints()??[],colorMap:t.colorMap,viaDiameter:t.viaDiameter,traceWidth:t.minTraceWidth,obstacleMargin:t.srj.defaultObstacleMargin??.15,connMap:t.connMap,capacityMeshNodes:t.capacityNodes??[],capacityMeshEdges:t.capacityEdges??[],availableJumperTypes:t.srj.availableJumperTypes}]),q8("highDensityStitchSolver",reo,t=>[{connections:t.srjWithPointPairs.connections,hdRoutes:t.highDensitySolver.routes,connectionPathResults:t.multiSectionPortPointOptimizer?.connectionResults??t.portPointPathingSolver?.connectionsWithResults??[],colorMap:t.colorMap,layerCount:t.srj.layerCount,defaultViaDiameter:t.viaDiameter}]),q8("traceKeepoutSolver",u1t,t=>[{hdRoutes:t.traceSimplificationSolver?.simplifiedHdRoutes??t.highDensityStitchSolver?.mergedHdRoutes??[],obstacles:t.srj.obstacles,jumpers:t.highDensitySolver?.getOutputJumpers()??[],connMap:t.connMap,colorMap:t.colorMap,srj:t.srj}])];getConstructorParams(){return[this.srj,this.opts]}currentPipelineStepIndex=0;_step(){const t=this.pipelineDef[this.currentPipelineStepIndex];if(!t)return void(this.solved=!0);if(this.activeSubSolver)return this.activeSubSolver.step(),void(this.activeSubSolver.solved?(this.endTimeOfPhase[t.solverName]=performance.now(),this.timeSpentOnPhase[t.solverName]=this.endTimeOfPhase[t.solverName]-this.startTimeOfPhase[t.solverName],t.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null));const e=t.getConstructorParams(this);this.activeSubSolver=new t.solverClass(...e),this[t.solverName]=this.activeSubSolver,this.timeSpentOnPhase[t.solverName]=0,this.startTimeOfPhase[t.solverName]=performance.now()}solveUntilPhase(t){for(;this.getCurrentPhase()!==t;)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();const t=this.netToPointPairsSolver?.visualize(),e=this.nodeSolver?.visualize(),n=this.nodeTargetMerger?.visualize(),o=this.singleLayerNodeMerger?.visualize(),i=this.strawSolver?.visualize(),r=this.edgeSolver?.visualize(),s=this.traceKeepoutSolver?.visualize(),a=this.deadEndSolver?.visualize(),A=this.availableSegmentPointSolver?.visualize(),c=this.offboardPathFragmentSolver?.visualize(),l=this.portPointPathingSolver?.visualize(),u=this.multiSectionPortPointOptimizer?.visualize(),g=this.highDensityRouteSolver?.visualize(),h=this.highDensitySolver?.visualize(),d=this.simpleHighDensityRouteSolver?.visualize(),p=this.highDensityStitchSolver?.visualize(),m=this.traceSimplificationSolver?.visualize(),_=this.traceWidthSolver?.visualize(),f=this.srj.outline,I=[];if(I.push({points:[{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.minY??-50},{x:this.srj.bounds?.maxX??50,y:this.srj.bounds?.minY??-50},{x:this.srj.bounds?.maxX??50,y:this.srj.bounds?.maxY??50},{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.maxY??50},{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.minY??-50}],strokeColor:"rgba(255,0,0,0.25)"}),f&&f.length>=2){const E=f.map(B=>({x:B.x,y:B.y}));E.push({...E[0]}),I.push({points:E,strokeColor:"rgba(0, 136, 255, 0.95)"})}const C=z8(this.srj),y={points:[...this.srj.connections.flatMap(E=>E.pointsToConnect.map(B=>({...B,layer:J8(B,this.srj.layerCount),label:`${E.name} ${B.pcb_port_id??""}`})))],rects:[...(this.srj.obstacles??[]).filter(E=>!E.isCopperPour).map(E=>({...E,fill:E.layers?.includes("top")?"rgba(255,0,0,0.25)":E.layers?.includes("bottom")?"rgba(0,0,255,0.25)":"rgba(255,0,0,0.25)",layer:r7(E,this.srj.layerCount),label:C(E)}))],lines:I},x=[y,t,e,n,o,i,r,a,A,c,l,u,g?Il(y,g):null,h?Il(y,h):null,d?Il(y,d):null,p,m,s,_,this.solved?Il({lines:I},mx(this.getOutputSimpleRouteJson())):null].filter(Boolean);return Il(...x)}preview(){const t=this.highDensitySolver?.routes??this.simpleHighDensityRouteSolver?.routes??this.highDensityRouteSolver?.routes;if(t){const e=[];for(let n=t.length-1;n>=0;n--){const o=t[n];if(e.push({points:o.route.map(i=>({x:i.x,y:i.y})),strokeColor:this.colorMap[o.connectionName]}),e.length>200)break}return{lines:e}}if(this.portPointPathingSolver){const e=[];for(const n of this.portPointPathingSolver.connectionsWithResults)n.path&&e.push({points:n.path.map(o=>({x:o.point.x,y:o.point.y})),strokeColor:this.colorMap[n.connection.name]});return{lines:e}}return this.netToPointPairsSolver?this.netToPointPairsSolver?.visualize():{}}_getOutputHdRoutes(){return this.traceWidthSolver?.hdRoutesWithWidths??this.traceKeepoutSolver?.redrawnHdRoutes??this.traceSimplificationSolver?.simplifiedHdRoutes??this.highDensityStitchSolver?.mergedHdRoutes??this.highDensitySolver?.routes??this.simpleHighDensityRouteSolver?.routes??this.highDensityRouteSolver?.routes}getConnectedOffboardObstacles(){const t={},e=new Set(this.srj.connections.flatMap(n=>n.__rootConnectionNames??[n.name]));for(const[n,o]of this.srj.obstacles.entries()){if(!o.offBoardConnectsTo?.length)continue;const i=o.obstacleId??`__obs${n}`;o.obstacleId=i;const r=this.connMap.getNetConnectedToId(i);if(!r)continue;const s=this.connMap.getIdsConnectedToNet(r).find(a=>e.has(a));s&&(t[i]=s)}return t}getOutputSimplifiedPcbTraces(){if(!this.solved||!this.highDensityRouteSolver&&!this.simpleHighDensityRouteSolver&&!this.highDensitySolver)throw new Error("Cannot get output before solving is complete");const t=[],e=this._getOutputHdRoutes();for(const n of this.netToPointPairsSolver?.newConnections??[]){const o=n.__netConnectionName??this.srj.connections.find(r=>r.name===n.name)?.__netConnectionName,i=e.filter(r=>r.connectionName===n.name);for(let r=0;r<i.length;r++){const s=i[r],a={type:"pcb_trace",pcb_trace_id:`${n.name}_${r}`,connection_name:o??n.__rootConnectionNames?.[0]??n.name,route:nB(s,this.srj.layerCount)};t.push(a)}}return t}getOutputJumpers(){return this.highDensitySolver?this.highDensitySolver.getOutputJumpers():[]}getOutputSimpleRouteJson(){const t=this.getOutputJumpers();return{...this.srj,traces:this.getOutputSimplifiedPcbTraces(),jumpers:t.length>0?t:void 0}}},XIt=t=>{const{candidates:e,mapOfCapacityMeshNodeIdToRef:n}=t;let o=!0;for(const i of e){let r=!1;i.port.nodeIds.forEach(s=>{const a=n.get(s);if(!a)throw new Error(`Could not find capacity mesh node for id ${s}`);a._containsObstacle&&(r=!0)}),r||(o=!1)}return o},ZIt=t=>t.depth+1e3*t.countOfCrampedPortPointsInPath,eCt=class extends zA{constructor(t){if(super(),this.input=t,this.input.depthLimit<1)throw new Error("Depth limit must be at least 1");this._setup()}input;queue=[];resultExploredPortPoints=[];currentExploredPortPoints=null;visitedExploredPortPoints=new Map;getSolverName(){return"singleTargetNecessaryCrampedPortPointSolver"}_setup(){const t=this.input.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(this.input.target.capacityMeshNodeId)??[];for(const e of t){if(this.input.shouldIgnoreCrampedPortPoints&&e.cramped)continue;const n={port:e,depth:1,parent:null,countOfCrampedPortPointsInPath:e.cramped?1:0},o=this.visitedExploredPortPoints.get(e);(!o||this.getCandidateCost(n)<this.getCandidateCost(o))&&(this.visitedExploredPortPoints.set(e,n),this.queue.push(n))}}_step(){if(this.queue.length===0)return this.currentExploredPortPoints=null,void(this.solved=!0);for(;this.queue.length>0;){if(this.currentExploredPortPoints=this.queue.shift(),this.visitedExploredPortPoints.get(this.currentExploredPortPoints.port)!==this.currentExploredPortPoints)continue;if(this.currentExploredPortPoints.depth===this.input.depthLimit){this.resultExploredPortPoints.push(this.currentExploredPortPoints);continue}const t=this.currentExploredPortPoints.port.nodeIds.map(e=>{const n=this.input.mapOfCapacityMeshNodeIdToRef.get(e);if(!n)throw new Error(`Could not find capacity mesh node for id ${e}`);return n}).flatMap(e=>this.input.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(e.capacityMeshNodeId)??[]);for(const e of t){if(this.input.shouldIgnoreCrampedPortPoints&&e.cramped)continue;const n={port:e,depth:this.currentExploredPortPoints.depth+1,parent:this.currentExploredPortPoints,countOfCrampedPortPointsInPath:this.currentExploredPortPoints.countOfCrampedPortPointsInPath+(e.cramped?1:0)},o=this.visitedExploredPortPoints.get(e);o&&this.getCandidateCost(o)<=this.getCandidateCost(n)||(this.visitedExploredPortPoints.set(e,n),this.queue.push(n))}}this.solved=!0}getCandidateCost(t){return t.depth+1e3*t.countOfCrampedPortPointsInPath}getOutput(){return this.resultExploredPortPoints}visualize(){const t={points:[],rects:[]};for(const e of this.visitedExploredPortPoints.keys())t.points.push({...e,color:e.cramped?"blue":"green"});return t}},lJ=class extends zA{constructor(t){super(),this.input=t,this._setup()}input;unprocessedTargets=[];targetNode=[];currentTarget;crampedPortPointsToKeep=new Set;candidatesAtDepth=[];isRunningCrampedPass=!1;filteredOutput;activeSubSolver=null;nodeMap=new Map;mapOfCapacityMeshNodeIdToSegmentPortPoints=new Map;getSolverName(){return"multiTargetNecessaryCrampedPortPointSolver"}_setup(){this.targetNode=this.input.capacityMeshNodes.filter(t=>t._containsObstacle),this.targetNode=this.targetNode.filter(t=>{for(const e of this.input.simpleRouteJson.connections)for(const n of e.pointsToConnect)if(o7(n,t)<=0)return!0;return!1}),this.unprocessedTargets=[...this.targetNode],this.unprocessedTargets.sort((t,e)=>t.center.x-e.center.x);for(const t of this.input.capacityMeshNodes)this.nodeMap.set(t.capacityMeshNodeId,t);for(const t of this.input.sharedEdgeSegments)for(const e of t.portPoints){const n=e.nodeIds;for(const o of n){if(!this.nodeMap.get(o))throw new Error(`Could not find capacity mesh node for id ${o}`);const i=this.mapOfCapacityMeshNodeIdToSegmentPortPoints.get(o)||[];this.mapOfCapacityMeshNodeIdToSegmentPortPoints.set(o,[...i,e])}}}_step(){if(this.activeSubSolver){if(this.activeSubSolver._step(),!this.activeSubSolver.solved)return;if(this.activeSubSolver.failed)return this.failed=!0,void(this.error=this.activeSubSolver.error);if(this.candidatesAtDepth=this.activeSubSolver.getOutput(),this.activeSubSolver=null,!this.currentTarget)return this.failed=!0,void(this.error="Missing current capacity mesh node while finishing BFS");if(!this.isRunningCrampedPass)return XIt({candidates:this.candidatesAtDepth,mapOfCapacityMeshNodeIdToRef:this.nodeMap})||this.candidatesAtDepth.length===0?(this.isRunningCrampedPass=!0,void(this.activeSubSolver=new eCt({target:this.currentTarget,depthLimit:3,shouldIgnoreCrampedPortPoints:!1,mapOfCapacityMeshNodeIdToSegmentPortPoints:this.mapOfCapacityMeshNodeIdToSegmentPortPoints,mapOfCapacityMeshNodeIdToRef:this.nodeMap}))):void(this.currentTarget=void 0);let t=this.candidatesAtDepth.filter(e=>{const n=e.port;return n.nodeIds.map(o=>{const i=this.nodeMap.get(o);if(!i)throw this.failed=!0,this.error=`Could not find capacity mesh node for id ${o}`,new Error(`Could not find capacity mesh node for id ${o}`);return i}).every(o=>!o._containsObstacle)&&n.cramped});if(XIt({candidates:t,mapOfCapacityMeshNodeIdToRef:this.nodeMap})&&(this.error=`All candidates are blocked by obstacles even after including cramped port points for capacity mesh node ${this.currentTarget.capacityMeshNodeId}`),this.candidatesAtDepth=[...t].sort((e,n)=>{const o=ZIt(e)-ZIt(n);return o!==0?o:this.getCandidateExitCapacity(n)-this.getCandidateExitCapacity(e)}),this.candidatesAtDepth.length===0)this.error=`No candidates found for capacity mesh node ${this.currentTarget.capacityMeshNodeId} even after including cramped port points`;else{const e=new Map;for(const o of this.candidatesAtDepth){if(!o.parent)throw new Error(`Missing parent for cramped escape candidate ${o.port.segmentPortPointId}`);const i=`${o.parent.port.segmentPortPointId}->${o.port.segmentPortPointId}`;if(!e.has(i)&&(e.set(i,o),e.size===5))break}const n=[...e.values()];for(const o of n)this.keepCandidatePath(o)}return this.isRunningCrampedPass=!1,void(this.currentTarget=void 0)}if(!this.currentTarget)return this.currentTarget=this.unprocessedTargets.shift(),this.currentTarget?(this.isRunningCrampedPass=!1,this.candidatesAtDepth=[],void(this.activeSubSolver=new eCt({target:this.currentTarget,depthLimit:2,shouldIgnoreCrampedPortPoints:!0,mapOfCapacityMeshNodeIdToSegmentPortPoints:this.mapOfCapacityMeshNodeIdToSegmentPortPoints,mapOfCapacityMeshNodeIdToRef:this.nodeMap}))):void(this.solved=!0)}getOutput(){return this.filteredOutput||(this.filteredOutput=this.input.sharedEdgeSegments.map(t=>({...t,portPoints:t.portPoints.flatMap(e=>!e.cramped||this.crampedPortPointsToKeep.has(e)?[e]:this.isMultilayerEscapePort(e)?[{...e,tinyHypergraphPortPenalty:1e3}]:[])}))),this.filteredOutput}getCandidateExitCapacity(t){if(!t.parent)throw new Error(`Missing parent for cramped escape candidate ${t.port.segmentPortPointId}`);const e=new Set(t.parent.port.nodeIds),n=t.port.nodeIds.filter(o=>!e.has(o)).map(o=>{const i=this.nodeMap.get(o);if(!i)throw new Error(`Could not find capacity mesh node for id ${o}`);return i});if(n.length===0)throw new Error(`Could not find exit node for cramped escape candidate ${t.port.segmentPortPointId}`);return Math.max(0,...n.map(o=>o.width*o.height*o.availableZ.length))}keepCandidatePath(t){this.crampedPortPointsToKeep.add(t.port);let e=t.parent;for(;e;)this.crampedPortPointsToKeep.add(e.port),e=e.parent}isMultilayerEscapePort(t){return t.nodeIds.some(e=>(this.nodeMap.get(e)?.availableZ.length??0)>1)}visualize(){const t={rects:[],points:[]};for(const e of this.targetNode)t.rects.push({...e,fill:this.currentTarget?.capacityMeshNodeId===e.capacityMeshNodeId?"rgba(255, 0, 0, 0.5)":"rgba(255, 0, 0, 0.2)"});for(const e of this.candidatesAtDepth)t.points.push({...e.port,color:e.port.cramped?"blue":"green"});for(const e of this.crampedPortPointsToKeep)t.points.push({...e,color:"blue"});return this.activeSubSolver?MD(t,this.activeSubSolver.visualize()):t}},IL=t=>`${t.x.toFixed(4)},${t.y.toFixed(4)}`,tCt=t=>t.netIsAssignable===!0&&(t.layers?.length??0)>1,bno=(t,e)=>t.connectedTo?.find(n=>n.startsWith("pcb_via"))??t.obstacleId??`assignable_via_${e}`,Sno=t=>[...new Set(t.obstacle.layers.map(e=>Kr(e,t.layerCount)))].sort((e,n)=>e-n),Qno=t=>IL(t.center),nCt=t=>new Set(t.filter(tCt).map(Qno));function k5(t,e){if(t==null)throw new Error(e)}function z6e(t,e){const n=[];for(const o of t)e.includes(o)&&n.push(o);return n}function oCt(t){return o7(t.point,t.region.d)<=.001&&z6e(("layers"in t.point?t.point.layers:[t.point.layer]).map(e=>Kr(e,t.layerCount)),t.region.d.availableZ).length>0}function iCt({graph:t,point:e,layerCount:n}){const o=t.regions.filter(r=>oCt({point:e,region:r,layerCount:n})),i=(function({point:r,layerCount:s}){const a=("layers"in r?r.layers:[r.layer]).map(A=>Kr(A,s));return[...new Set(a)]})({point:e,layerCount:n});return o.find(r=>(function({region:s,pointZLayers:a}){return s.ports.some(A=>a.includes(A.d.z)&&z6e(a,A.region1.d.availableZ).length>0&&z6e(a,A.region2.d.availableZ).length>0)})({region:r,pointZLayers:i}))??o[0]}var rCt=(t,e)=>{const n=t.getNetConnectedToId(e);if(!n)throw new Error(`Could not resolve net ID for connection "${e}"`);return n},vno=t=>{const e=t.graph.regions.filter(i=>i.d.availableZ.includes(t.z)&&!i.d._assignableVia).map(i=>({region:i,distance:o7(t.point,i.d)})).sort((i,r)=>i.distance-r.distance||i.region.d.width*i.region.d.height-r.region.d.width*r.region.d.height),n=e[0]?.distance;if(n===void 0)return[];const o=Math.max(n+1e-6,t.viaRadius+.15);return e.filter(i=>i.distance<=o).slice(0,4).map(i=>i.region)};function uJ(t){const e={ports:[],regions:[]},n=[];for(const o of t.capacityMeshNodes){const i=o._connectedTo?.map(r=>rCt(t.connectivityMap,r));e.regions.push({regionId:o.capacityMeshNodeId,d:i?{...o,_connectedTo:[...new Set(i)]}:o,ports:[]})}for(const o of t.segmentPortPoints){const[i,r]=o.nodeIds,s=e.regions.find(A=>A.regionId===i),a=e.regions.find(A=>A.regionId===r);k5(s,`Could not find region with id ${i} for segment port point ${o.segmentPortPointId}`),k5(a,`Could not find region with id ${r} for segment port point ${o.segmentPortPointId}`);for(const A of o.availableZ){const c=o._preloadedTracePortAssignments?.filter(g=>g.z===A),l={portId:`${o.segmentPortPointId}::${A}`,x:o.x,y:o.y,z:A,distToCentermostPortOnZ:o.distToCentermostPortOnZ,cramped:o.cramped,regions:[s,a],tinyHypergraphPortPenalty:o.tinyHypergraphPortPenalty,_preloadedFixedNetIds:c&&c.length>0?[...new Set(c.map(g=>g.fixedNetId))].sort():void 0,_preloadedTracePortAssignments:c},u={portId:o.segmentPortPointId,d:l,region1:s,region2:a};e.ports.push(u),s.ports.push(u),a.ports.push(u)}}(o=>{for(const[i,r]of o.assignableViaObstacles.entries()){if(!tCt(r))continue;const s=Sno({obstacle:r,layerCount:o.layerCount});if(s.length<2)continue;const a=`assignable-via:${bno(r,i)}`,A=Math.min(r.width,r.height)/2,c={regionId:a,d:{capacityMeshNodeId:a,center:{...r.center},width:r.width,height:r.height,layer:`z${s.join(",")}`,availableZ:s,_containsObstacle:!1,_completelyInsideObstacle:!1,_containsTarget:!1,_assignableVia:!0,_assignedViaObstacle:r},ports:[]},l=[];for(const u of s)for(const g of vno({graph:o.graph,point:r.center,z:u,viaRadius:A})){const h={portId:`${a}:port:${g.regionId}:z${u}`,x:r.center.x,y:r.center.y,z:u,distToCentermostPortOnZ:0,cramped:!1,regions:[g,c]},d={portId:h.portId,d:h,region1:g,region2:c};l.push(d),g.ports.push(d)}if(new Set(l.map(u=>u.d.z)).size<2)for(const u of l)u.region1.ports=u.region1.ports.filter(g=>g!==u);else c.ports.push(...l),o.graph.regions.push(c),o.graph.ports.push(...l)}})({graph:e,assignableViaObstacles:t.assignableViaObstacles??[],layerCount:t.layerCount});for(const o of t.simpleRouteJsonConnections){const[i,r]=o.pointsToConnect,s=iCt({graph:e,point:i,layerCount:t.layerCount}),a=iCt({graph:e,point:r,layerCount:t.layerCount});k5(s,`Could not find start region for connection "${o.name}"`),k5(a,`Could not find end region for connection "${o.name}"`),n.push({connectionId:o.name,mutuallyConnectedNetworkId:rCt(t.connectivityMap,o.name),startRegion:s,endRegion:a,simpleRouteConnection:o})}return{graph:e,connections:n}}function wno(t,e){const n={lines:[],points:[]};if(!t)return n;let o=t.shift();if(!o)return n;const i=[];n.points.push({...o.port.d,color:"rgb(255, 50, 50)",label:`g: ${o.g}
h: ${o.h}
f: ${o.f}
ripRequired: ${o.ripRequired}`});do i.push({x:o.port.d.x,y:o.port.d.y,z:o.port.d.z}),o=o.parent;while(o);i.reverse();const r=i[0]?.z??0;i.unshift({x:e.x,y:e.y,z:r});for(let s=0;s<i.length-1;s++){const a=i[s],A=i[s+1];let c;c=a.z===A.z?a.z===0?void 0:"10 5":"3 3 10",n.lines.push({points:[{x:a.x,y:a.y},{x:A.x,y:A.y}],strokeColor:"rgba(255, 250, 50, 1)",strokeWidth:.01,strokeDash:c})}for(const s of t)n.points.push({...s.port.d,color:"rgb(0, 64, 255)",label:`${s.port.portId}
g: ${s.g}
h: ${s.h}
f: ${s.f}
ripRequired: ${s.ripRequired}`});return n}function Pno(t,e){const n={lines:[],points:[]};for(const o of t){const i=e[o.connection.connectionId]??"rgba(255, 50, 50, 1)",r=[{x:o.connection.startRegion.d.center.x,y:o.connection.startRegion.d.center.y,z:o.connection.startRegion.d?.availableZ?.[0]??0}];for(const s of o.path)r.push({x:s.port.d.x,y:s.port.d.y,z:s.port.d.z});r.push({x:o.connection.endRegion.d.center.x,y:o.connection.endRegion.d.center.y,z:o.connection.endRegion.d?.availableZ?.[0]??0});for(let s=0;s<r.length-1;s++){const a=r[s],A=r[s+1];let c;c=a.z===A.z?a.z===0?void 0:"10 5":"3 3 10";const l={points:[{x:a.x,y:a.y},{x:A.x,y:A.y}],strokeColor:i,strokeWidth:.01,strokeDash:c};n.lines.push(l)}}return n}function Mno(t,e){const n={lines:[],points:[]};for(const o of t){const i=o.startRegion.d.center,r=o.endRegion.d.center,s=(i.x+r.x)/2,a=(i.y+r.y)/2,A=e[o.connectionId]??"rgba(255, 50, 150, 0.8)";n.points.push({x:s,y:a,color:A,label:o.connectionId}),n.lines.push({points:[i,r],strokeColor:A,strokeWidth:.1,strokeDash:(o.startRegion.d?.availableZ?.[0]??0)===0?void 0:"10 5"})}return n}function Dno(t){const e={rects:[],points:[]};for(const n of t.regions)e.rects.push({center:n.d.center,width:n.d.width,height:n.d.height,fill:"rgba(200, 200, 200, 0.5)",label:n.regionId});for(const n of t.ports)e.points.push({x:n.d.x,y:n.d.y,color:"rgba(4, 90, 20, 0.3)",label:n.portId});return e}var sCt=class extends D1t{constructor(e){super({inputConnections:e.connections,inputGraph:e.graph,inputSolvedRoutes:e.inputSolvedRoutes,greedyMultiplier:e.weights.GREEDY_MULTIPLIER,ripCost:e.weights.RIPPING_PF_COST,rippingEnabled:e.flags.RIPPING_ENABLED}),this.params=e,this.regionMemoryPfMap=e.opts?.regionMemoryPfMap??new Map,this.baseRegionFailureCostMap=new Map,this.regionRipCountMap=new Map,this.totalRipCount=0,e.weights.MAX_ITERATIONS_PER_PATH>0&&(this.MAX_ITERATIONS=e.weights.MAX_ITERATIONS_PER_PATH*e.effort)}params;regionMemoryPfMap;baseRegionFailureCostMap;regionRipCountMap;totalRipCount;estimateCostToEnd(e){const n=this.currentEndRegion;return k5(n,"Current end region is undefined"),no(e.d,n.d.center)}computeH(e){const n=e,o=this.computeDistanceTraveled(n);if(this.params.weights.RANDOM_WALK_DISTANCE>0&&o<this.params.weights.RANDOM_WALK_DISTANCE)return 0;const i=this.estimateCostToEnd(e.port),r=(e.port.d.distToCentermostPortOnZ-this.params.weights.CENTER_OFFSET_FOCUS_SHIFT)*this.params.weights.CENTER_OFFSET_DIST_PENALTY_FACTOR,s=e.nextRegion?.regionId??e.lastRegion?.regionId,a=s?this.regionMemoryPfMap.get(s)??0:0;return i+r+this.computeMemoryPfPenalty(a)+this.computeDeviation(e)*this.params.weights.STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR}computeIncreasedRegionCostIfPortsAreUsed(e,n,o){const i=this.currentConnection;k5(i,"Current connection is undefined");const r=this.getBaseRegionFailureCost(e),s=this.computeRegionPfWithAdditionalSegment(e,n,o,i.connectionId,i.mutuallyConnectedNetworkId);if(s>=this.NODE_MAX_PF)return this.params.weights.NODE_PF_MAX_PENALTY;const a=this.pfToFailureCost(s),A=Math.max(0,a-r);return Math.min(this.params.weights.NODE_PF_MAX_PENALTY,A*this.params.weights.NODE_PF_FACTOR)}computeG(e){const n=e;let o=super.computeG(e);return n.lastPort&&n.lastPort.d.z!==n.port.d.z&&(o+=this.params.weights.LAYER_CHANGE_COST),n.nextRegion!==this.currentEndRegion?o:o+this.computeEndRegionCloseCost(n)}getPortUsagePenalty(e){const n=e.assignment;if(!n)return 0;const o=this.currentConnection?.mutuallyConnectedNetworkId;return n.connection.mutuallyConnectedNetworkId===o?0:.5*Math.max(1,this.params.weights.NODE_PF_FACTOR)+this.params.weights.BASE_CANDIDATE_COST}getRipsRequiredForPortUsage(e,n,o){const i=e.assignments??[];return i.length===0?[]:i.filter(r=>r.connection.mutuallyConnectedNetworkId!==this.currentConnection?.mutuallyConnectedNetworkId&&r.regionPort1!==n&&r.regionPort2!==n&&r.regionPort1!==o&&r.regionPort2!==o&&Uh(r.regionPort1.d,r.regionPort2.d,n.d,o.d))}selectCandidatesForEnteringRegion(e){const n=this.currentConnection?.startRegion,o=this.currentConnection?.endRegion;k5(n,"Current connection or start region is undefined"),k5(o,"Current connection or end region is undefined");const i=e.filter(a=>{const A=a.nextRegion;return!A?.d._containsObstacle||A===n||A===o});let r=this.params.flags.FORCE_CENTER_FIRST?this.getCenterFirstEnteringRegionCandidates(i):i;const s=-this.params.weights.MIN_ALLOWED_BOARD_SCORE;if(s>0){const a=r.filter(A=>A.g+A.h<=s);a.length>0&&(r=a)}return r}routeSolvedHook(e){this.baseRegionFailureCostMap.clear();const n=new Set;for(const r of e.path){const s=r.lastRegion;s&&n.add(s)}for(const r of n){const s=this.computeRegionPfFromAssignments(r);this.regionMemoryPfMap.set(r.regionId,s)}if(!e.requiredRip||this.unprocessedConnections.length<2)return;const[o,...i]=this.unprocessedConnections;this.unprocessedConnections=[...i,o]}computeRoutesToRip(e){const n=super.computePortOverlapRoutes(e),o=new Set(n),i=new Map;e.path.map(c=>{if(!c.lastPort||!c.lastRegion)return;const l=this.getRipsRequiredForPortUsage(c.lastRegion,c.lastPort,c.port);if(l.length===0)return null;const u=i.get(c.lastRegion)??new Set;for(const g of l)u.add(g.solvedRoute);i.set(c.lastRegion,u)});const r=e.path.flatMap(c=>c.lastRegion?[c.lastRegion]:[]),s=Array.from(new Set([...i.keys(),...r])),a=this.params.weights.SHUFFLE_SEED+this.iterations+this.solvedRoutes.length+this.totalRipCount,A=D5(s,a);for(const c of A){if(this.totalRipCount>=this.params.weights.MAX_RIPS)break;const l=this.getRegionRippingPfThreshold(c.regionId);let u=this.computeRegionPf({region:c,newlySolvedRoute:e,routesToRip:o});if(this.regionMemoryPfMap.set(c.regionId,u),u<=l)continue;const g=new Set;let h=0;for(;u>l&&!(this.totalRipCount>=this.params.weights.MAX_RIPS);){if(!c.assignments||c.assignments.length===0)throw new Error("We are trying to rip a region with no assignments, this should not happen");const d=c.assignments.map(m=>{const _=m.solvedRoute;return m.connection.connectionId===e.connection.connectionId?null:o.has(_)?void 0:_}).filter(m=>!!m);if(d.length===0)break;const p=D5(d,a+h+g.size)[0];if(!p)break;g.add(p.connection),o.add(p),this.totalRipCount++,h++,this.regionRipCountMap.set(c.regionId,(this.regionRipCountMap.get(c.regionId)??0)+1),u=this.computeRegionPf({region:c,newlySolvedRoute:e,routesToRip:o}),this.regionMemoryPfMap.set(c.regionId,u)}}if(o.size>n.size){if(this.totalRipCount>=this.params.weights.MAX_RIPS)return o;const c=this.solvedRoutes.filter(h=>!o.has(h)&&h.connection.connectionId!==e.connection.connectionId);if(c.length===0)return o;const l=Math.max(1,Math.floor(this.params.weights.RANDOM_RIP_FRACTION*c.length)),u=D5(c,a);let g=0;for(const h of u){if(g>=l||this.totalRipCount>=this.params.weights.MAX_RIPS)break;o.has(h)||(o.add(h),g++,this.totalRipCount++)}}return o}computeDeviation(e){const n=this.currentConnection?.startRegion.d.center,o=this.currentConnection?.endRegion.d.center;return k5(n,"Current connection or start region is undefined"),k5(o,"Current connection or end region is undefined"),wc(e.port.d,n,o)}computeDistanceTraveled(e){let n=0,o=e;for(;o?.parent;)n+=no(o.parent.port.d,o.port.d),o=o.parent;return n}computeMemoryPfPenalty(e){const n=Math.min(Math.max(e,0),.999999),o=Math.min(this.params.weights.NODE_PF_MAX_PENALTY,-Math.log(1-n));return o*this.params.weights.MEMORY_PF_FACTOR+o*this.params.weights.NODE_PF_FACTOR*.01}computeEndRegionCloseCost(e){const n=this.currentConnection,o=this.currentEndRegion;k5(n,"Current connection is undefined"),k5(o,"Current end region is undefined");const i=n.endRegion.d.center,r={portId:`end-target:${n.connectionId}`,region1:o,region2:o,d:{portId:`end-target:${n.connectionId}`,x:i.x,y:i.y,z:e.port.d.z,distToCentermostPortOnZ:0,regions:[o,o]}};return this.computeIncreasedRegionCostIfPortsAreUsed(o,e.port,r)}getCenterFirstEnteringRegionCandidates(e){const n=new Map;for(const i of e){const r=i.port.d.z,s=n.get(r)??[];s.push(i),n.set(r,s)}const o=[];for(const i of n.values()){const r=i.sort((c,l)=>c.port.d.distToCentermostPortOnZ-l.port.d.distToCentermostPortOnZ)[0];if(!r)continue;if(this.isPortAvailableForCurrentNet(r.port)){o.push(r);continue}const s=i.sort((c,l)=>c.port.d.x!==l.port.d.x?c.port.d.x-l.port.d.x:c.port.d.y-l.port.d.y),a=[];let A=[];for(const c of s)this.isPortAvailableForCurrentNet(c.port)?A.push(c):A.length>0&&(a.push(A),A=[]);A.length>0&&a.push(A);for(const c of a)o.push(c[Math.floor(c.length/2)])}return o}isPortAvailableForCurrentNet(e){const n=e.assignment;if(!n)return!0;const o=this.currentConnection?.mutuallyConnectedNetworkId;return n.connection.mutuallyConnectedNetworkId===o}computeRegionPfFromAssignments(e){const n=this.getRegionAssignedPortPoints(e),o={...e.d,portPoints:n},i=Wm(o),r=e.d;return wy(r,i.numSameLayerCrossings,i.numEntryExitLayerChanges,i.numTransitionPairCrossings)}clampPf(e){return Math.min(Math.max(e,0),.999999)}get NODE_MAX_PF(){return Math.min(.99999,1-Math.exp(-this.params.weights.NODE_PF_MAX_PENALTY))}pfToFailureCost(e){const n=this.clampPf(e);return n>=this.NODE_MAX_PF?this.params.weights.NODE_PF_MAX_PENALTY:-Math.log(1-n)}getBaseRegionFailureCost(e){const n=this.baseRegionFailureCostMap.get(e.regionId);if(n!=null)return n;const o=this.computeRegionPfFromAssignments(e),i=this.pfToFailureCost(o);return this.baseRegionFailureCostMap.set(e.regionId,i),i}getRegionAssignedPortPoints(e){return(e.assignments??[]).flatMap(n=>{const o=n.regionPort1.d,i=n.regionPort2.d,r=n.connection.connectionId,s=n.connection.simpleRouteConnection?.__rootConnectionNames?.[0];return[{x:o.x,y:o.y,z:o.z,connectionName:r,rootConnectionName:s},{x:i.x,y:i.y,z:i.z,connectionName:r,rootConnectionName:s}]})}computeRegionPfWithAdditionalSegment(e,n,o,i,r){const s=this.getRegionAssignedPortPoints(e),a=[{x:n.d.x,y:n.d.y,z:n.d.z,connectionName:i,rootConnectionName:r},{x:o.d.x,y:o.d.y,z:o.d.z,connectionName:i,rootConnectionName:r}],A={...e.d,portPoints:[...s,...a]},c=Wm(A);return wy(e.d,c.numSameLayerCrossings,c.numEntryExitLayerChanges,c.numTransitionPairCrossings)}getRegionRippingPfThreshold(e){const n=this.regionRipCountMap.get(e)??0,o=Math.max(1,Math.floor(this.params.weights.MAX_RIPS/10)),i=Math.min(1,n/o);return(this.params.weights.START_RIPPING_PF_THRESHOLD||.3)*(1-i)+(this.params.weights.END_RIPPING_PF_THRESHOLD||1)*i}computeRegionPf({region:e,newlySolvedRoute:n,routesToRip:o}){const i=[...(e.assignments??[]).filter(A=>!o.has(A.solvedRoute)).flatMap(A=>{const c=A.regionPort1,l=A.regionPort2,u=A.connection.connectionId,g=A.connection.simpleRouteConnection?.__rootConnectionNames?.[0];return[{x:c.d.x,y:c.d.y,z:c.d.z,connectionName:u,rootConnectionName:g},{x:l.d.x,y:l.d.y,z:l.d.z,connectionName:u,rootConnectionName:g}]}),...n.path.flatMap(A=>{if(!A.lastPort||A.lastRegion!==e)return[];const c=A.lastPort,l=A.port;return[{x:c.d.x,y:c.d.y,z:c.d.z,connectionName:n.connection.connectionId,rootConnectionName:n.connection.simpleRouteConnection?.__rootConnectionNames?.[0]},{x:l.d.x,y:l.d.y,z:l.d.z,connectionName:n.connection.connectionId,rootConnectionName:n.connection.simpleRouteConnection?.__rootConnectionNames?.[0]}]})],r={capacityMeshNodeId:e.d.capacityMeshNodeId,center:e.d.center,width:e.d.width,height:e.d.height,portPoints:i,availableZ:e.d.availableZ},s=Wm(r),a=e.d;return wy(a,s.numSameLayerCrossings,s.numEntryExitLayerChanges,s.numTransitionPairCrossings)}computeNodePf(e){const n=this.getOutput().nodesWithPortPoints.find(r=>r.capacityMeshNodeId===e.capacityMeshNodeId),o=this.params.graph.regions.find(r=>r.d.capacityMeshNodeId===e.capacityMeshNodeId);if(!n||!o)return null;const i=Wm(n);return wy(o.d,i.numSameLayerCrossings,i.numEntryExitLayerChanges,i.numTransitionPairCrossings)}getOutput(){new Map(this.params.graph.regions.map(r=>[r.regionId,r]));const e=new Set;for(const r of this.params.connections)e.add(r.startRegion.regionId),e.add(r.endRegion.regionId);const n=new Map;for(const r of this.solvedRoutes){const s=r.path;if(s.length===0)continue;const a=s[0]?.port,A=s[s.length-1]?.port;if(!a||!A)continue;const c=r.connection.connectionId,l=r.connection,u=l.simpleRouteConnection?.__rootConnectionNames?.[0],g=r.connection.startRegion.regionId,h=r.connection.endRegion.regionId,d=n.get(g)??[];d.push({portPointId:a.d.portId,x:a.d.x,y:a.d.y,z:a.d.z,connectionName:c,rootConnectionName:u}),n.set(g,d);const p=n.get(h)??[];p.push({portPointId:A.d.portId,x:A.d.x,y:A.d.y,z:A.d.z,connectionName:c,rootConnectionName:u}),n.set(h,p)}const o=[],i=[];for(const r of this.params.graph.regions){const s=(r.assignments??[]).flatMap(l=>{const u=l.connection.connectionId,g=l.connection.simpleRouteConnection?.__rootConnectionNames?.[0];return[{portPointId:l.regionPort1.d.portId,x:l.regionPort1.d.x,y:l.regionPort1.d.y,z:l.regionPort1.d.z,connectionName:u,rootConnectionName:g,nextPortPointId:l.regionPort2.d.portId},{portPointId:l.regionPort2.d.portId,x:l.regionPort2.d.x,y:l.regionPort2.d.y,z:l.regionPort2.d.z,connectionName:u,rootConnectionName:g,prevPortPointId:l.regionPort1.d.portId}]}),a=[];if(r.d._containsObstacle&&e.has(r.regionId)){const l=n.get(r.regionId)??[],u=[];for(const h of l)s.some(d=>d.connectionName===h.connectionName&&d.rootConnectionName===h.rootConnectionName&&d.portPointId===h.portPointId)||u.push(h);s.push(...u);const g=new Map;for(const h of s){const d=`${h.connectionName}::${h.rootConnectionName??""}`,p=g.get(d)??[];p.push(h),g.set(d,p)}for(const[h,d]of g.entries()){const[p,m=""]=h.split("::"),_=d[0];if(!_)continue;const f={portPointId:`center:${r.regionId}:${p}:${m}`,x:r.d.center.x,y:r.d.center.y,z:_.z,connectionName:p,rootConnectionName:m||void 0};if(d.length>=2){const I=d[d.length-1];_.portPointId&&(_.nextPortPointId=f.portPointId,f.prevPortPointId=_.portPointId),I.portPointId&&(I.prevPortPointId=f.portPointId,f.nextPortPointId=I.portPointId)}a.push(f)}}const A=[...s,...a];A.length>0&&o.push({capacityMeshNodeId:r.d.capacityMeshNodeId,center:r.d.center,width:r.d.width,height:r.d.height,portPoints:A,availableZ:r.d.availableZ});const c=r.ports.map(l=>{const u=l.d,g=l.d.regions.some(h=>!!h.d._offBoardConnectionId);return{portPointId:l.d.portId,x:l.d.x,y:l.d.y,z:l.d.z,prevPortPointId:u.prevPortPointId,nextPortPointId:u.nextPortPointId,connectionNodeIds:l.d.regions.map(h=>h.regionId),distToCentermostPortOnZ:l.d.distToCentermostPortOnZ,connectsToOffBoardNode:g}});i.push({capacityMeshNodeId:r.d.capacityMeshNodeId,center:r.d.center,width:r.d.width,height:r.d.height,portPoints:c,availableZ:r.d.availableZ,_containsObstacle:r.d._containsObstacle,_containsTarget:r.d._containsTarget,_offBoardConnectionId:r.d._offBoardConnectionId,_offBoardConnectedCapacityMeshNodeIds:r.d._offBoardConnectedCapacityMeshNodeIds})}return{nodesWithPortPoints:o,inputNodeWithPortPoints:i}}visualize(){return(function(e){let n={};return n=e.reduce((o,i)=>o&&i?MD(o,i):{},n),n||{}})([Dno(this.params.graph),this.visualizePfOverlay(),Mno(this.params.connections,this.params.colorMap??{}),wno(this.candidateQueue.peekMany(100),this.currentConnection?.startRegion.d.center),Pno(this.solvedRoutes,this.params.colorMap??{})])}visualizePfOverlay(){const e=this.getOutput(),n=e?.inputNodeWithPortPoints??[],o=new Map((e?.nodesWithPortPoints??[]).map(r=>[r.capacityMeshNodeId,r])),i={rects:[]};for(const r of n){const s=this.computeNodePf(r),a=s??0,A=o.get(r.capacityMeshNodeId),c=A?Wm(A):{numSameLayerCrossings:0,numEntryExitLayerChanges:0,numTransitionPairCrossings:0},l=Math.min(255,Math.floor(512*a)),u=Math.max(0,255-Math.floor(512*a));let g=`rgba(${l}, ${u}, ${u}, ${a<.001?"0.1":"0.3"})`;r._containsObstacle&&(g="rgba(255, 0, 0, 0.3)"),r._offBoardConnectedCapacityMeshNodeIds?.length&&(g="rgba(255, 165, 0, 0.3)"),i.rects.push({center:r.center,width:r.width-.2,height:r.height-.2,layer:`z${r?.availableZ?.join(",")}`,fill:g,label:`${r.capacityMeshNodeId}
pf: ${s===null?"n/a":s.toFixed(3)}
xSame: ${c.numSameLayerCrossings}, xLC: ${c.numEntryExitLayerChanges}, xTransition: ${c.numTransitionPairCrossings}`})}return i}},Nno=t=>{if(!t.assignments||t.assignments.length===0)return t.d?.assignment?0:1;const e=t.assignments.flatMap(i=>{const r=i.regionPort1.d,s=i.regionPort2.d,a=i.connection.connectionId,A=i.connection,c=A.simpleRouteConnection?.__rootConnectionNames?.[0];return[{x:r.x,y:r.y,z:r.z,connectionName:a,rootConnectionName:c},{x:s.x,y:s.y,z:s.z,connectionName:a,rootConnectionName:c}]}),n={...t.d,portPoints:e},o=Wm(n);return wy(t.d,o.numSameLayerCrossings,o.numEntryExitLayerChanges,o.numTransitionPairCrossings)};function F5(t,e,n,o={}){return{solverName:t,solverClass:e,getConstructorParams:n,onSolved:o.onSolved}}var Rno=class extends yr{constructor(e,n={}){super(),this.srj=e,this.opts=n,this.srj=e,this.opts={...n},this.viaDiameter=om(e).padDiameter,this.minTraceWidth=e.minTraceWidth;const o=this.opts;if(this.effort=o.effort??1,this.MAX_ITERATIONS=1e8*this.effort,o.capacityDepth===void 0){const i=e.bounds.maxX-e.bounds.minX,r=e.bounds.maxY-e.bounds.minY,s=Math.max(i,r),a=o.targetMinCapacity??.5;o.capacityDepth=$Q(s,a)}this.connMap=Jm(e),this.colorMap=Jf(e,this.connMap),this.cacheProvider=o.cacheProvider===void 0?tB():o.cacheProvider===null?null:o.cacheProvider,this.startTimeOfPhase={},this.endTimeOfPhase={},this.timeSpentOnPhase={}}srj;opts;netToPointPairsSolver;nodeSolver;nodeTargetMerger;edgeSolver;colorMap;highDensityRouteSolver;highDensityStitchSolver;singleLayerNodeMerger;strawSolver;deadEndSolver;traceSimplificationSolver;availableSegmentPointSolver;portPointPathingSolver;multiSectionPortPointOptimizer;uniformPortDistributionSolver;traceWidthSolver;necessaryCrampedPortPointSolver;hyperGraphSectionOptimizer;viaDiameter;minTraceWidth;effort;startTimeOfPhase;endTimeOfPhase;timeSpentOnPhase;activeSubSolver=null;connMap;srjWithPointPairs;capacityNodes=null;capacityEdges=null;cacheProvider=null;pipelineDef=[F5("netToPointPairsSolver",rL,e=>[e.srj,e.colorMap,JQ(e.srj)],{onSolved:e=>{e.srjWithPointPairs=e.netToPointPairsSolver?.getNewSimpleRouteJson(),e.colorMap=Jf(e.srjWithPointPairs,this.connMap),e.connMap=Jm(e.srjWithPointPairs)}}),F5("nodeSolver",qF,e=>[{simpleRouteJson:e.srjWithPointPairs,maxGapFillPasses:4}],{onSolved:e=>{e.capacityNodes=e.nodeSolver?.getOutput().meshNodes??[]}}),F5("edgeSolver",WQ,e=>[e.capacityNodes],{onSolved:e=>{e.capacityEdges=e.edgeSolver?.edges}}),F5("availableSegmentPointSolver",kD,e=>[{nodes:e.capacityNodes,edges:e.capacityEdges||[],traceWidth:e.minTraceWidth,colorMap:e.colorMap,shouldReturnCrampedPortPoints:!0}]),F5("necessaryCrampedPortPointSolver",lJ,e=>[{capacityMeshNodes:e.capacityNodes,sharedEdgeSegments:e.availableSegmentPointSolver.getOutput(),simpleRouteJson:e.srjWithPointPairs}]),F5("portPointPathingSolver",sCt,e=>{const n=e.necessaryCrampedPortPointSolver?.getOutput()??e.availableSegmentPointSolver.getOutput(),{graph:o,connections:i}=uJ({capacityMeshNodes:e.capacityNodes,layerCount:e.srj.layerCount,connectivityMap:e.connMap,segmentPortPoints:n.flatMap(r=>r.portPoints),simpleRouteJsonConnections:e.srjWithPointPairs.connections});return[{graph:o,connections:i,layerCount:e.srj.layerCount,effort:e.effort,flags:{FORCE_CENTER_FIRST:!0,RIPPING_ENABLED:!0},weights:{SHUFFLE_SEED:0,MEMORY_PF_FACTOR:4,CENTER_OFFSET_DIST_PENALTY_FACTOR:0,CENTER_OFFSET_FOCUS_SHIFT:0,NODE_PF_FACTOR:0,LAYER_CHANGE_COST:0,RIPPING_PF_COST:0,NODE_PF_MAX_PENALTY:100,BASE_CANDIDATE_COST:.6,MAX_ITERATIONS_PER_PATH:0,RANDOM_WALK_DISTANCE:0,START_RIPPING_PF_THRESHOLD:.3,END_RIPPING_PF_THRESHOLD:1,MAX_RIPS:1e3,RANDOM_RIP_FRACTION:.3,STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR:4,GREEDY_MULTIPLIER:.7,MIN_ALLOWED_BOARD_SCORE:-1e4}}]}),F5("hyperGraphSectionOptimizer",Oeo,e=>{const n=e.portPointPathingSolver;return[{hyperGraphSolver:n,inputSolvedRoutes:n.solvedRoutes,expansionHopsFromCentralRegion:1,createHyperGraphSolver:o=>new sCt({graph:o.inputGraph,connections:o.inputConnections,inputSolvedRoutes:o.inputSolvedRoutes,layerCount:e.srj.layerCount,effort:e.effort,flags:{FORCE_CENTER_FIRST:!0,RIPPING_ENABLED:!0},weights:{SHUFFLE_SEED:0,MEMORY_PF_FACTOR:4,CENTER_OFFSET_DIST_PENALTY_FACTOR:0,CENTER_OFFSET_FOCUS_SHIFT:0,NODE_PF_FACTOR:0,LAYER_CHANGE_COST:0,RIPPING_PF_COST:0,NODE_PF_MAX_PENALTY:100,BASE_CANDIDATE_COST:.6,MAX_ITERATIONS_PER_PATH:0,RANDOM_WALK_DISTANCE:0,START_RIPPING_PF_THRESHOLD:.3,END_RIPPING_PF_THRESHOLD:1,MAX_RIPS:1e3,RANDOM_RIP_FRACTION:.3,STRAIGHT_LINE_DEVIATION_PENALTY_FACTOR:4,GREEDY_MULTIPLIER:.7,MIN_ALLOWED_BOARD_SCORE:-1e4}}),regionCost:Nno,effort:e.effort,ACCEPTABLE_REGION_COST:.1,MAX_ATTEMPTS_PER_REGION:Math.max(3,3*e.effort),MAX_ATTEMPTS_PER_SECTION:Math.max(50,50*e.effort),FRACTION_TO_REPLACE:1,alwaysRipConflicts:!0}]}),F5("uniformPortDistributionSolver",kz,e=>[{nodeWithPortPoints:e.portPointPathingSolver?.getOutput().nodesWithPortPoints??[],inputNodesWithPortPoints:e.portPointPathingSolver?.getOutput().inputNodeWithPortPoints??[],minTraceWidth:e.minTraceWidth,obstacles:e.srj.obstacles,layerCount:e.srj.layerCount}]),F5("highDensityRouteSolver",HD,e=>[{nodePortPoints:e.uniformPortDistributionSolver?.getOutput()??[],nodePfById:new Map((e.portPointPathingSolver?.getOutput().inputNodeWithPortPoints??[]).map(n=>[n.capacityMeshNodeId,e.portPointPathingSolver?.computeNodePf(n)??null])),colorMap:e.colorMap,connMap:e.connMap,viaDiameter:e.viaDiameter,traceWidth:e.minTraceWidth}]),F5("highDensityStitchSolver",j7e,e=>[{connections:e.srjWithPointPairs.connections,hdRoutes:e.highDensityRouteSolver.routes,colorMap:e.colorMap,layerCount:e.srj.layerCount,defaultViaDiameter:e.viaDiameter}]),F5("traceSimplificationSolver",j8,e=>[{hdRoutes:e.highDensityStitchSolver.mergedHdRoutes,obstacles:e.srj.obstacles,connMap:e.connMap,colorMap:e.colorMap,outline:e.srj.outline,defaultViaDiameter:e.viaDiameter,layerCount:e.srj.layerCount,iterations:2}]),F5("traceWidthSolver",aL,e=>[{hdRoutes:e.traceSimplificationSolver.simplifiedHdRoutes,obstacles:e.srj.obstacles,connMap:e.connMap,colorMap:e.colorMap,minTraceWidth:e.minTraceWidth,connection:e.srj.connections,layerCount:e.srj.layerCount}])];getConstructorParams(){return[this.srj,this.opts]}currentPipelineStepIndex=0;_step(){const e=this.pipelineDef[this.currentPipelineStepIndex];if(!e)return void(this.solved=!0);if(this.activeSubSolver)return this.activeSubSolver.step(),void(this.activeSubSolver.solved?(this.endTimeOfPhase[e.solverName]=performance.now(),this.timeSpentOnPhase[e.solverName]=this.endTimeOfPhase[e.solverName]-this.startTimeOfPhase[e.solverName],e.onSolved?.(this),this.activeSubSolver=null,this.currentPipelineStepIndex++):this.activeSubSolver.failed&&(this.error=this.activeSubSolver?.error,this.failed=!0,this.activeSubSolver=null));const n=e.getConstructorParams(this);this.activeSubSolver=new e.solverClass(...n),this[e.solverName]=this.activeSubSolver,this.timeSpentOnPhase[e.solverName]=0,this.startTimeOfPhase[e.solverName]=performance.now()}solveUntilPhase(e){for(;this.getCurrentPhase()!==e;)this.step()}getCurrentPhase(){return this.pipelineDef[this.currentPipelineStepIndex]?.solverName??"none"}visualize(){if(!this.solved&&this.activeSubSolver)return this.activeSubSolver.visualize();const e=this.netToPointPairsSolver?.visualize(),n=this.nodeSolver?.visualize(),o=this.nodeTargetMerger?.visualize(),i=this.singleLayerNodeMerger?.visualize(),r=this.strawSolver?.visualize(),s=this.edgeSolver?.visualize(),a=this.deadEndSolver?.visualize(),A=this.availableSegmentPointSolver?.visualize(),c=this.portPointPathingSolver?.visualize(),l=this.multiSectionPortPointOptimizer?.visualize(),u=this.uniformPortDistributionSolver?.visualize(),g=this.highDensityRouteSolver?.visualize(),h=this.highDensityStitchSolver?.visualize(),d=this.traceSimplificationSolver?.visualize(),p=this.necessaryCrampedPortPointSolver?.visualize(),m=this.highDensityRouteSolver?.visualize(),_=this.srj.outline,f=[];if(f.push({points:[{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.minY??-50},{x:this.srj.bounds?.maxX??50,y:this.srj.bounds?.minY??-50},{x:this.srj.bounds?.maxX??50,y:this.srj.bounds?.maxY??50},{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.maxY??50},{x:this.srj.bounds?.minX??-50,y:this.srj.bounds?.minY??-50}],strokeColor:"rgba(255,0,0,0.25)"}),_&&_.length>=2){const x=_.map(E=>({x:E.x,y:E.y}));x.push({...x[0]}),f.push({points:x,strokeColor:"rgba(0, 136, 255, 0.95)"})}const I=z8(this.srj),C={points:[...this.srj.connections.flatMap(x=>x.pointsToConnect.map(E=>({...E,layer:J8(E,this.srj.layerCount),label:`${x.name} ${E.pcb_port_id??""}`})))],rects:[...(this.srj.obstacles??[]).filter(x=>!x.isCopperPour).map(x=>({...x,fill:x.layers?.includes("top")?"rgba(255,0,0,0.25)":x.layers?.includes("bottom")?"rgba(0,0,255,0.25)":"rgba(255,0,0,0.25)",layer:r7(x,this.srj.layerCount),label:I(x)}))],lines:f},y=[C,e,n,o,i,r,s,a,A,p,c,m,l,u,g?Il(C,g):null,h,d,this.solved?Il({lines:f},mx(this.getOutputSimpleRouteJson())):null].filter(Boolean);return Il(...y)}preview(){if(this.highDensityRouteSolver){const e=[];for(let n=this.highDensityRouteSolver.routes.length-1;n>=0;n--){const o=this.highDensityRouteSolver.routes[n];if(e.push({points:o.route.map(i=>({x:i.x,y:i.y})),strokeColor:this.colorMap[o.connectionName]}),e.length>200)break}return{lines:e}}return this.netToPointPairsSolver?this.netToPointPairsSolver.visualize():{}}_getOutputHdRoutes(){return this.traceWidthSolver?.getHdRoutesWithWidths()??this.traceSimplificationSolver?.simplifiedHdRoutes??this.highDensityStitchSolver.mergedHdRoutes}getOutputSimplifiedPcbTraces(){if(!this.solved||!this.highDensityRouteSolver)throw new Error("Cannot get output before solving is complete");const e=[],n=this._getOutputHdRoutes();for(const o of this.netToPointPairsSolver?.newConnections??[]){const i=o.__netConnectionName??this.srj.connections.find(s=>s.name===o.name)?.__netConnectionName,r=n.filter(s=>s.connectionName===o.name);for(let s=0;s<r.length;s++){const a=r[s],A={type:"pcb_trace",pcb_trace_id:`${o.name}_${s}`,connection_name:i??o.__rootConnectionNames?.[0]??o.name,route:nB(a,this.srj.layerCount)};e.push(A)}}return e}getOutputSimpleRouteJson(){return{...this.srj,traces:this.getOutputSimplifiedPcbTraces()}}},Tno=class{MAX_ITERATIONS=1e3;solved=!1;failed=!1;iterations=0;progress=0;error=null;activeSubSolver;failedSubSolvers;timeToSolve;stats={};pendingEffects;cacheHit;cacheKey;cacheToSolveSpaceTransform;getSolverName(){return this.constructor.name}step(){if(!this.solved&&!this.failed){this.iterations++;try{this._step()}catch(e){throw this.error=`${this.getSolverName()} error: ${e}`,console.error(this.error),this.failed=!0,e}!this.solved&&this.iterations>this.MAX_ITERATIONS&&this.tryFinalAcceptance(),!this.solved&&this.iterations>this.MAX_ITERATIONS&&(this.error=`${this.getSolverName()} ran out of iterations (MAX_ITERATIONS=${this.MAX_ITERATIONS})`,this.failed=!0),"computeProgress"in this&&(this.progress=this.computeProgress())}}_step(){}getConstructorParams(){throw new Error("getConstructorParams not implemented")}solve(){const e=Date.now();for(;!this.solved&&!this.failed;)this.step();const n=Date.now();this.timeToSolve=n-e}visualize(){return{lines:[],points:[],rects:[],circles:[]}}tryFinalAcceptance(){}preview(){return{lines:[],points:[],rects:[],circles:[]}}},kno=(t,e)=>{const n=l=>l===" "||l===`
`||l==="\r"||l==="	",o=l=>{let u=0,g=l.length;for(;u<g&&n(l[u]);)u+=1;for(;g>u&&n(l[g-1]);)g-=1;return l.slice(u,g)},i=l=>{const u=[];let g=0,h=0;for(let d=0;d<l.length;d+=1){const p=l[d];p!=="("?p!==")"?p===","&&h===0&&(u.push(o(l.slice(g,d))),g=d+1):h>0&&(h-=1):h+=1}return u.push(o(l.slice(g))),u},r=l=>{return`${u=l,Math.min(1,Math.max(0,u))}`;var u},s=(l=>{const u=o(l);if(!u.startsWith("#"))return null;const g=u.slice(1);if(g.length!==3&&g.length!==6)return null;for(const h of g){const d=h.toLowerCase();if(!(d>="0"&&d<="9")&&!(d>="a"&&d<="f"))return null}if(g.length===3){const[h,d,p]=g;return{r:Number.parseInt(h+h,16),g:Number.parseInt(d+d,16),b:Number.parseInt(p+p,16)}}return{r:Number.parseInt(g.slice(0,2),16),g:Number.parseInt(g.slice(2,4),16),b:Number.parseInt(g.slice(4,6),16)}})(e);if(s)return`rgba(${s.r}, ${s.g}, ${s.b}, ${r(1-t)})`;const a=(l=>{const u=o(l),g=u.indexOf("(");return g<=0||u[u.length-1]!==")"?null:{name:o(u.slice(0,g)).toLowerCase(),args:i(u.slice(g+1,-1))}})(e);if(!a)return e;const{name:A,args:c}=a;if(A==="hsl"||A==="rgb")return c.length!==3?e:`${A}a(${c[0]}, ${c[1]}, ${c[2]}, ${r(1-t)})`;if(A==="hsla"||A==="rgba"){if(c.length!==4)return e;const l=(u=>{const g=o(u);if(!g)return null;const h=Number.parseFloat(g);return Number.isFinite(h)?h:null})(c[3]);return l===null?e:`${A}(${c[0]}, ${c[1]}, ${c[2]}, ${r(l-t)})`}return e},Fno=(t,e)=>{try{return kno(e,t)}catch(n){return console.error(n),t}},aCt=t=>t.rootConnectionName??t.connectionName,gJ=t=>{const e=[];for(let n=0;n<t.route.length-1;n+=1){const o=t.route[n],i=t.route[n+1];if(!o||!i||o.z===i.z||Math.abs(o.x-i.x)>1e-6||Math.abs(o.y-i.y)>1e-6)continue;const r={x:Math.round(1e3*o.x)/1e3,y:Math.round(1e3*o.y)/1e3},s=e.at(-1);s&&s.x===r.x&&s.y===r.y||e.push(r)}return e},CL=(t,e,n=.001)=>Math.abs(t.x-e.x)<=n&&Math.abs(t.y-e.y)<=n,J6e=(t,e)=>({minX:t.center.x-t.width/2+e,maxX:t.center.x+t.width/2-e,minY:t.center.y-t.height/2+e,maxY:t.center.y+t.height/2-e}),W6e=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),dJ=(t,e)=>t.x*e.x+t.y*e.y,ACt=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}),X8=t=>{const e=[];for(let n=0;n<t.length;n+=1){const o=t[n];if(o)for(let i=0;i<o.route.length-1;i+=1){const r=o.route[i],s=o.route[i+1];r&&s&&(r.z!==s.z||CL(r,s)||e.push({routeIndex:n,rootConnectionName:aCt(o),startIndex:i,endIndex:i+1,start:r,end:s,z:r.z,traceRadius:(o.traceThickness??.1)/2}))}}return e},hJ=(t,e,n=1e-6)=>{const o=e.end.x-e.start.x,i=e.end.y-e.start.y,r=o*o+i*i;if(r<=n)return{x:e.start.x,y:e.start.y,t:0};const s=((t.x-e.start.x)*o+(t.y-e.start.y)*i)/r,a=(A=s,Math.max(0,Math.min(A,1)));var A;return{x:e.start.x+o*a,y:e.start.y+i*a,t:a}},av=(t,e,n=1e-6)=>{const o=W6e(t.end,t.start),i=W6e(e.end,e.start),r=W6e(t.start,e.start),s=dJ(o,o),a=dJ(o,i),A=dJ(i,i),c=dJ(o,r),l=dJ(i,r),u=s*A-a*a,g=n;let h,d,p=u,m=u;u<=g?(h=0,p=1,d=l,m=A):(h=a*l-A*c,d=s*l-a*c,h<0?(h=0,d=l,m=A):h>p&&(h=p,d=l+a,m=A)),d<0?(d=0,-c<0?h=0:-c>s?h=p:(h=-c,p=s)):d>m&&(d=m,-c+a<0?h=0:-c+a>s?h=p:(h=-c+a,p=s));const _=Math.abs(h)<=g?0:h/p,f=Math.abs(d)<=g?0:d/m,I=ACt(t.start,t.end,_),C=ACt(e.start,e.end,f),y=hJ(t.start,e,n),x=hJ(t.end,e,n),E=hJ(e.start,t,n),B=hJ(e.end,t,n);return[{leftT:_,rightT:f,leftPoint:I,rightPoint:C},{leftT:0,rightT:y.t,leftPoint:t.start,rightPoint:y},{leftT:1,rightT:x.t,leftPoint:t.end,rightPoint:x},{leftT:E.t,rightT:0,leftPoint:E,rightPoint:e.start},{leftT:B.t,rightT:1,leftPoint:B,rightPoint:e.end}].sort((S,Q)=>Math.hypot(S.leftPoint.x-S.rightPoint.x,S.leftPoint.y-S.rightPoint.y)-Math.hypot(Q.leftPoint.x-Q.rightPoint.x,Q.leftPoint.y-Q.rightPoint.y))},h7=1e-6,pJ=t=>{const e=[];for(const n of t){const o=e[n.routeIndex]??[];o[n.startIndex]=n,e[n.routeIndex]=o}return e},cCt=(t,e)=>t<e?[t,e]:[e,t],Oae=(t,e)=>t.some(([n,o])=>n===e[0]&&o===e[1]),lCt=(t,e,n)=>{let o,i=Number.POSITIVE_INFINITY;for(const r of t){if(r.routeIndex!==e.routeIndex||r.z!==e.z||r.endIndex!==e.startIndex&&r.startIndex!==e.endIndex)continue;const[s]=av(r,n);if(!s)continue;const a=Math.hypot(s.leftPoint.x-s.rightPoint.x,s.leftPoint.y-s.rightPoint.y);a>=i||(i=a,o=r)}return o},uCt=(t,e)=>{const n=X8(e),o=X8(t),i=pJ(o),r=[];for(let s=0;s<n.length;s+=1){const a=n[s];if(a)for(let A=s+1;A<n.length;A+=1){const c=n[A];if(!c||a.z!==c.z||a.rootConnectionName===c.rootConnectionName||Math.max(a.start.x,a.end.x)<Math.min(c.start.x,c.end.x)||Math.max(c.start.x,c.end.x)<Math.min(a.start.x,a.end.x)||Math.max(a.start.y,a.end.y)<Math.min(c.start.y,c.end.y)||Math.max(c.start.y,c.end.y)<Math.min(a.start.y,a.end.y))continue;const[l]=av(a,c);if(!l||Math.hypot(l.leftPoint.x-l.rightPoint.x,l.leftPoint.y-l.rightPoint.y)>h7||l.leftT<=h7||l.leftT>=.999999||l.rightT<=h7||l.rightT>=.999999)continue;const u=i[a.routeIndex]?.[a.startIndex],g=i[c.routeIndex]?.[c.startIndex];if(!u||!g)continue;const[h]=av(u,g);if(!h||Math.hypot(h.leftPoint.x-h.rightPoint.x,h.leftPoint.y-h.rightPoint.y)<=h7)continue;const d=lCt(o,u,g),p=lCt(o,g,u),m=d?[u,d]:[u],_=p?[g,p]:[g];for(const f of m)for(const I of _){const C={leftRouteIndex:a.routeIndex,leftStartPointIndex:f.startIndex,rightRouteIndex:c.routeIndex,rightStartPointIndex:I.startIndex};r.some(y=>y.leftRouteIndex===C.leftRouteIndex&&y.leftStartPointIndex===C.leftStartPointIndex&&y.rightRouteIndex===C.rightRouteIndex&&y.rightStartPointIndex===C.rightStartPointIndex)||r.push(C)}}}return r},j6e=t=>{const e=X8(t),n=[];for(let o=0;o<e.length;o+=1){const i=e[o];if(i)for(let r=o+1;r<e.length;r+=1){const s=e[r];if(!s||i.z!==s.z||i.rootConnectionName===s.rootConnectionName)continue;const[a]=av(i,s);if(a&&Math.hypot(a.leftPoint.x-a.rightPoint.x,a.leftPoint.y-a.rightPoint.y)+h7<i.traceRadius+s.traceRadius){const A=cCt(i.routeIndex,s.routeIndex);Oae(n,A)||n.push(A)}}}return n},$6e=(t,e)=>e<=1||e>=t-2,gCt=(t,e)=>e.some(n=>$6e(t,n)),Gae=.2,q6e=.4,Lno=.65+.05,Yae=.03,dCt=1e3,Wu=1e-6,X6e=.015,hCt=t=>Math.round(t*dCt)/dCt,Z6e=(t,e)=>({x:t.x-e.x,y:t.y-e.y}),pCt=(t,e)=>({x:t.x*e,y:t.y*e}),mCt=(t,e)=>t.x*e.x+t.y*e.y,Hno=(t,e,n)=>({x:t.x+(e.x-t.x)*n,y:t.y+(e.y-t.y)*n}),$D=t=>Math.max(0,Math.min(t,1)),yL=(t,e,n)=>Math.max(e,Math.min(t,n)),_Ct=(t,e)=>{const n=(o=>Math.hypot(o.x,o.y))(t);return n<=e||n<=Wu?t:pCt(t,e/n)},fCt=(t,e=0)=>({minX:t.center.x-t.width/2-e,maxX:t.center.x+t.width/2+e,minY:t.center.y-t.height/2-e,maxY:t.center.y+t.height/2+e}),Ono=(t,e,n=0)=>{const o=fCt(e,n);return t.x>=o.minX&&t.x<=o.maxX&&t.y>=o.minY&&t.y<=o.maxY},Gno=(t,e,n)=>{if(t.regionId){const s=e.findIndex(a=>a.capacityMeshNodeId===t.regionId);if(s!==-1)return s}const o=[...t.route.map(({x:s,y:a})=>({x:s,y:a})),...t.vias.map(({x:s,y:a})=>({x:s,y:a}))];let i=-1,r=Number.POSITIVE_INFINITY;for(let s=0;s<e.length;s++){const a=e[s];if(!a||!o.every(c=>Ono(c,a,n)))continue;const A=a.width*a.height;A<r&&(r=A,i=s)}return i},ICt=(t,e,n,o)=>{const i=((r,s,a)=>{const A=Math.min(Math.abs(r.originalX-a.minX),Math.abs(a.maxX-r.originalX)),c=Math.min(Math.abs(r.originalY-a.minY),Math.abs(a.maxY-r.originalY));return Math.abs(A-c)<=Wu?Math.abs(s.x-r.x)>=Math.abs(s.y-r.y)?"y":"x":A<c?"y":"x"})(t,e,n);return _Ct(i==="x"?{x:1.1*(t.x-e.x)*o,y:0}:{x:0,y:1.1*(t.y-e.y)*o},.06*o)},xL=(t,e,n,o,i=3.5,r=.2,s=.4)=>{const a=Math.max(t,0);if(a>=s)return 0;const A=a/r;if(A<1){const u=1-A;return e*u**3*(1+u*i)}const c=(a-r)/Math.max(s-r,Wu),l=e*n*Math.exp(-c*o);return l<1e-5?0:l},Yno=(t,e)=>{const n=t.boundaryPadding>0?.001:0,o=e.minX+t.boundaryPadding+n,i=e.maxX-t.boundaryPadding-n,r=e.minY+t.boundaryPadding+n,s=e.maxY-t.boundaryPadding-n;t.x=yL(t.x,o,i),t.y=yL(t.y,r,s)},e8e=(t,e)=>{for(const n of t)for(const o of n.nodes)Yno(o,e)},CCt=t=>t.kind==="via"?.4:.25,Uno=t=>(t.kind,.5),yCt=t=>t.kind==="via"?12:3.5,Kno=t=>t.kind==="via"?.18:.06,Vno=t=>t.kind==="via"?1.35:1.05,zno=(t,e)=>t.kind==="via"?3*e:e,t8e=(t,e,n,o)=>{const i=2*e;t[i]=(t[i]??0)+n,t[i+1]=(t[i+1]??0)+o},qD=(t,e,n,o,i,r)=>{if(t.fixed||t8e(o,t.node.forceIndex,e,n),!t.fixed&&i&&r!==void 0){const s=2*r;i[s]=(i[s]??0)+e,i[s+1]=(i[s+1]??0)+n}},xCt=(t,e,n,o,i=.5)=>{const{startNode:r,endNode:s}=t,a=1-$D(i),A=$D(i),c=r.fixed?0:a,l=s.fixed?0:A,u=c+l;if(!(u<=Wu)){if(!r.fixed&&c>0){const g=c/u;t8e(o,r.forceIndex,e*g,n*g)}if(!s.fixed&&l>0){const g=l/u;t8e(o,s.forceIndex,e*g,n*g)}}},Jno=(t,e,n,o,i)=>{if(e.fixed)return{x:0,y:0};const{minX:r,maxX:s,minY:a,maxY:A}=t,c=(d=>d.kind==="via"?.65:Gae)(e),l=(d=>d.kind==="via"?Lno:q6e)(e),u=(d=>d.kind==="via"?.015:.08)(e),g=(d=>d.kind==="via"?80:20)(e),h=yCt(e);return{x:xL(n-r,Yae,u,g,h,c,l)*i-xL(s-n,Yae,u,g,h,c,l)*i,y:xL(o-a,Yae,u,g,h,c,l)*i-xL(A-o,Yae,u,g,h,c,l)*i}},Wno=t=>{if(t.length===0)return null;const e=new X4(t.length);for(const n of t){const{startNode:o,endNode:i}=n;e.add(Math.min(o.x,i.x),Math.min(o.y,i.y),Math.max(o.x,i.x),Math.max(o.y,i.y))}return e.finish(),{index:e,segments:t}},ECt=t=>{const e=new Map,n=new Map;for(const o of t){const i=n.get(o.z)??[];i.push(o),n.set(o.z,i)}for(const[o,i]of n){const r=Wno(i);r&&e.set(o,r)}return{byLayer:e}},BCt=(t,e,n,o,i)=>{const r=a=>({candidateIndexes:a.index.search(n-i,o-i,n+i,o+i),segments:a.segments});if(e.kind==="point"){const a=t.byLayer.get(e.z);return a?[r(a)]:[]}const s=[];for(const a of t.byLayer.values())s.push(r(a));return s},jno=t=>{const e=[];for(let n=0;n<t.length;n+=1){const o=t[n];if(!o)continue;const i=new Set;for(let r=0;r<o.route.length-1;r+=1){const s=o.route[r],a=o.route[r+1];if(!s||!a||s.z===a.z||!CL(s,a))continue;const A=[r,r+1];for(let u=r-1;u>=0;u-=1){const g=o.route[u];if(!g||!CL(g,s))break;A.push(u)}for(let u=r+2;u<o.route.length;u+=1){const g=o.route[u];if(!g||!CL(g,s))break;A.push(u)}const c=[...new Set(A)].sort((u,g)=>u-g);let l=!1;for(const u of c)if(i.has(u)){l=!0;break}if(!l){for(const u of c)i.add(u);e.push({routeIndex:n,rootConnectionName:aCt(o),pointIndexes:c,x:s.x,y:s.y,radius:(o.viaDiameter??.3)/2,movable:!gCt(o.route.length,c)})}}}return e},n8e=t=>{const{routes:e,via:n,dx:o,dy:i,node:r}=t;if(!n.movable)return!1;n.x+=o,n.y+=i,((a,A)=>{const c=J6e(A,a.radius+Wu);a.x=yL(a.x,c.minX,c.maxX),a.y=yL(a.y,c.minY,c.maxY)})(n,r);const s=e[n.routeIndex];if(!s)return!1;for(const a of n.pointIndexes){const A=s.route[a];A&&(A.x=n.x,A.y=n.y)}return!0},$no=t=>{const{routes:e,node:n,vias:o}=t;let i=!1;for(let r=0;r<o.length;r+=1){const s=o[r];if(s)for(let a=r+1;a<o.length;a+=1){const A=o[a];if(!A)continue;const c=s.radius+A.radius+.1+X6e,l=s.x-A.x,u=s.y-A.y,g=Math.hypot(l,u),h=c-g;if(h<=0)continue;const d=1.61803398875*(97*r+13*a),p=g>Wu?l/g:Math.cos(d),m=g>Wu?u/g:Math.sin(d),_=Number(s.movable)+Number(A.movable);if(_===0)continue;const f=Math.min(.04,h/_);i=n8e({routes:e,via:s,dx:p*f,dy:m*f,node:n})||i,i=n8e({routes:e,via:A,dx:-p*f,dy:-m*f,node:n})||i}}return i},qno=t=>{const{routes:e,node:n,vias:o,segments:i}=t;let r=!1;for(let s=0;s<o.length;s+=1){const a=o[s];if(a?.movable)for(const A of i){if(a.rootConnectionName===A.rootConnectionName)continue;const c=hJ(a,A),l=a.x-c.x,u=a.y-c.y,g=Math.hypot(l,u),h=a.radius+A.traceRadius+.1+X6e-g;if(h<=0)continue;const d=A.end.x-A.start.x,p=A.end.y-A.start.y,m=Math.hypot(d,p),_=s%2==0?1:-1,f=g>Wu?l/g:m>Wu?-p/m*_:1,I=g>Wu?u/g:m>Wu?d/m*_:0,C=Math.min(.04,h);r=n8e({routes:e,via:a,dx:f*C,dy:I*C,node:n})||r}}return r},bCt=t=>{const{routes:e,routeIndex:n,pointIndex:o,dx:i,dy:r,node:s}=t,a=e[n];if(!a||o<=0||o>=a.route.length-1)return!1;const A=((u,g,h=.001)=>{const d=u[g];if(!d)return[];const p=[g];for(let m=g-1;m>=0;m-=1){const _=u[m];if(!_||!CL(_,d,h))break;p.push(m)}for(let m=g+1;m<u.length;m+=1){const _=u[m];if(!_||!CL(_,d,h))break;p.push(m)}return[...new Set(p)]})(a.route,o);if(gCt(a.route.length,A))return!1;const c=J6e(s,Wu);let l=!1;for(const u of A){const g=a.route[u];g&&(g.x=yL(g.x+i,c.minX,c.maxX),g.y=yL(g.y+r,c.minY,c.maxY),l=!0)}return l},o8e=t=>{const{routes:e,segment:n,dx:o,dy:i,node:r,t:s}=t,a=1-$D(s),A=$D(s),c=bCt({routes:e,routeIndex:n.routeIndex,pointIndex:n.startIndex,dx:o*a,dy:i*a,node:r}),l=bCt({routes:e,routeIndex:n.routeIndex,pointIndex:n.endIndex,dx:o*A,dy:i*A,node:r});return c||l},SCt=t=>{const{routes:e,node:n,segments:o,movableRouteIndexes:i}=t;let r=!1;for(let s=0;s<o.length;s+=1){const a=o[s];if(a)for(let A=s+1;A<o.length;A+=1){const c=o[A];if(!c||a.z!==c.z||a.rootConnectionName===c.rootConnectionName)continue;const l=a.traceRadius+c.traceRadius+.1+X6e;if(Math.max(a.start.x,a.end.x)+l<=Math.min(c.start.x,c.end.x)||Math.max(c.start.x,c.end.x)+l<=Math.min(a.start.x,a.end.x)||Math.max(a.start.y,a.end.y)+l<=Math.min(c.start.y,c.end.y)||Math.max(c.start.y,c.end.y)+l<=Math.min(a.start.y,a.end.y))continue;const[u]=av(a,c);if(!u)continue;const g=u.leftPoint.x-u.rightPoint.x,h=u.leftPoint.y-u.rightPoint.y,d=Math.hypot(g,h),p=l-d;if(p<=0)continue;const m=!i||i.has(a.routeIndex),_=!i||i.has(c.routeIndex),f=Number(m)+Number(_);if(f===0)continue;const I=a.end.x-a.start.x,C=a.end.y-a.start.y,y=Math.hypot(I,C),x=(s+A)%2==0?1:-1,E=d>Wu?g/d:y>Wu?-C/y*x:1,B=d>Wu?h/d:y>Wu?I/y*x:0,S=Math.min(.025,p/f);m&&(r=o8e({routes:e,segment:a,dx:E*S,dy:B*S,node:n,t:u.leftT})||r),_&&(r=o8e({routes:e,segment:c,dx:-E*S,dy:-B*S,node:n,t:u.rightT})||r)}}return r},QCt=(t,e)=>{for(let n=0;n<10;n+=1){const o=jno(e),i=X8(e),r=$no({routes:e,node:t,vias:o}),s=qno({routes:e,node:t,vias:o,segments:i}),a=SCt({routes:e,node:t,segments:i});if(!r&&!s&&!a)break}for(const n of e)n.vias=gJ(n);return e},Xno=(t,e,n)=>{for(let o=0;o<10&&SCt({routes:e,node:t,segments:X8(e),movableRouteIndexes:n});o+=1);for(const o of n){const i=e[o];i&&(i.vias=gJ(i))}return e},vCt=(t,e,n,o,i,r=3,s=.02)=>{for(let a=0;a<r;a+=1){i.fill(0);const A=ECt(o);for(let c=0;c<n.length;c+=1){const l=n[c];if(!l||l.kind!=="via")continue;const u=l.node;for(let g=c+1;g<n.length;g+=1){const h=n[g];if(!h||h.kind!=="via"||l.rootConnectionName===h.rootConnectionName)continue;const d=h.node,p=u.x-d.x,m=u.y-d.y;if(Math.abs(p)>=Gae||Math.abs(m)>=Gae)continue;const _=Math.hypot(p,m),f=Gae-_;if(f<=0)continue;let I=0,C=0;if(_>Wu){const B=1/_;I=p*B,C=m*B}else{const B=1.61803398875*(1009*a+97*c+13*g);I=Math.cos(B),C=Math.sin(B)}const y=Math.min(s,.9*f),x=I*y,E=C*y;qD(l,x,E,i),qD(h,-x,-E,i)}}for(let c=0;c<n.length;c+=1){const l=n[c];if(!l)continue;const u=l.node,g=CCt(l),h=BCt(A,l,u.x,u.y,g);for(const d of h)for(const p of d.candidateIndexes){const m=d.segments[p];if(!m||l.rootConnectionName===m.rootConnectionName)continue;const{startNode:_,endNode:f}=m,I=f.x-_.x,C=f.y-_.y,y=I*I+C*C;if(y<=Wu)continue;const x=u.x-_.x,E=u.y-_.y,B=$D((x*I+E*C)/y),S=_.x+I*B,Q=_.y+C*B,w=u.x-S,M=u.y-Q,k=Math.hypot(w,M),R=g-k;if(R<=0)continue;const F=1009*a+97*c+13*m.obstacleIndex;let O=0,U=0;if(k>Wu){const j=1/k;O=w*j,U=M*j}else{const j=-C,J=I,oe=Math.hypot(j,J);if(oe>Wu){const ie=(F%2==0?1:-1)/oe;O=j*ie,U=J*ie}else{const ie=1.61803398875*F;O=Math.cos(ie),U=Math.sin(ie)}}const Y=Math.min(zno(l,s),R*Vno(l)),W=O*Y,te=U*Y;qD(l,W,te,i),xCt(m,-W,-te,i,B)}}for(let c=0;c<e.length;c+=1){const l=e[c];if(l)for(let u=0;u<l.nodes.length;u+=1){const g=l.nodes[u];if(!g||g.fixed)continue;const h=2*g.forceIndex;let d=i[h]??0,p=i[h+1]??0;const m=Math.hypot(d,p);if(m>s&&m>Wu){const _=s/m;d*=_,p*=_}g.x+=d,g.y+=p}}e8e(e,t)}},wCt=(t,e,n,o)=>{const{mutableRoutes:i,totalNodeCount:r}=(h=>{let d=0;return{mutableRoutes:h.map(p=>{const m=[],_=new Int32Array(p.route.length);_.fill(-1);for(let f=0;f<p.route.length;f+=1){const I=p.route[f];if(!I)continue;const C=p.route[f-1],y=m.at(-1),x=m.length-1;y&&C&&C.x===I.x&&C.y===I.y?(C.z!==I.z&&(y.boundaryPadding=Math.max(y.boundaryPadding,p.viaDiameter/2)),y.pointIndexes.push(f),y.fixed||=$6e(p.route.length,f),_[f]=x):(m.push({x:I.x,y:I.y,originalX:I.x,originalY:I.y,boundaryPadding:0,pointIndexes:[f],fixed:$6e(p.route.length,f),forceIndex:d}),_[f]=m.length-1,d+=1)}return{route:p,rootConnectionName:p.rootConnectionName??p.connectionName,nodes:m,pointNodeIndexes:_}}),totalNodeCount:d}})(e),s=(h=>{const d=[];for(let p=0;p<h.length;p+=1){const m=h[p];if(m)for(let _=0;_<m.nodes.length;_+=1){const f=m.nodes[_],I=f?.pointIndexes[0],C=I===void 0?void 0:m.route.route[I];f&&C&&(f.pointIndexes.length>1?d.push({kind:"via",routeIndex:p,rootConnectionName:m.rootConnectionName,node:f,fixed:f.fixed}):d.push({kind:"point",routeIndex:p,rootConnectionName:m.rootConnectionName,node:f,z:C.z,fixed:f.fixed}))}}return d})(i),a=(h=>{const d=[];for(let p=0;p<h.length;p+=1){const m=h[p];if(m)for(let _=0;_<m.nodes.length-1;_+=1){const f=m.nodes[_],I=m.nodes[_+1],C=f?.pointIndexes[0],y=C===void 0?void 0:m.route.route[C];f&&I&&y&&d.push({obstacleIndex:d.length,rootConnectionName:m.rootConnectionName,z:y.z,startNode:f,endNode:I})}}return d})(i),A=new Float64Array(2*r),c=new Float64Array(2*r),l=o?.includeForceVectors??!0;e8e(i,t);let u=[];for(let h=0;h<n;h+=1){const d=n<=1?0:h/Math.max(n-1,1),p=.25+.75*(1-d),m=1-d,_=l&&h===n-1,f=_?new Float64Array(2*s.length):void 0;A.fill(0);for(let C=0;C<s.length;C+=1){const y=s[C];if(!y||y.kind!=="via")continue;const x=y.node;for(let E=C+1;E<s.length;E+=1){const B=s[E];if(!B||B.kind!=="via"||y.rootConnectionName===B.rootConnectionName)continue;const S=B.node,Q=x.x-S.x,w=x.y-S.y;if(Math.abs(Q)>=q6e||Math.abs(w)>=q6e)continue;const M=Math.hypot(Q,w);let k=0,R=0;if(M>Wu){const Y=1/M;k=Q*Y,R=w*Y}else{const Y=1.61803398875*(97*C+13*E);k=Math.cos(Y),R=Math.sin(Y)}const F=xL(M,.034,.08,18)*p;if(F<=0)continue;const O=k*F,U=R*F;qD(y,O,U,A,f,C),qD(B,-O,-U,A,f,E)}}const I=ECt(a);for(let C=0;C<s.length;C+=1){const y=s[C];if(!y)continue;const x=y.node,E=Uno(y),B=BCt(I,y,x.x,x.y,E);for(const S of B)for(const Q of S.candidateIndexes){const w=S.segments[Q];if(!w||y.rootConnectionName===w.rootConnectionName)continue;const{startNode:M,endNode:k}=w,R=k.x-M.x,F=k.y-M.y,O=R*R+F*F;if(O<=Wu)continue;const U=x.x-M.x,Y=x.y-M.y,W=$D((U*R+Y*F)/O),te=M.x+R*W,j=M.y+F*W,J=x.x-te,oe=x.y-j,ie=Math.hypot(J,oe),ne=97*C+13*w.obstacleIndex;let le=0,ge=0;if(ie>Wu){const pe=1/ie;le=J*pe,ge=oe*pe}else{const pe=-F,ye=R,Me=Math.hypot(pe,ye);if(Me>Wu){const ve=(ne%2==0?1:-1)/Me;le=pe*ve,ge=ye*ve}else{const ve=1.61803398875*ne;le=Math.cos(ve),ge=Math.sin(ve)}}const _e=xL(ie,Kno(y),.08,18,yCt(y),CCt(y),E)*p;if(_e<=0)continue;const ue=le*_e,fe=ge*_e;qD(y,ue,fe,A,f,C),xCt(w,-ue,-fe,A,W)}}_&&(u=new Array(s.length));for(let C=0;C<s.length;C+=1){const y=s[C];if(!y)continue;const x=y.node,E=Jno(t,y,x.x,x.y,p);if(qD(y,E.x,E.y,A,f,C),_&&f){const B=2*C;u[C]={kind:y.kind,routeIndex:y.routeIndex,rootConnectionName:y.rootConnectionName,x:x.x,y:x.y,dx:f[B]??0,dy:f[B+1]??0}}}for(let C=0;C<i.length;C+=1){const y=i[C];if(!y)continue;const x=y.nodes.length-2;for(let E=0;E<y.nodes.length;E+=1){const B=y.nodes[E];if(!B||B.fixed)continue;const S=2*B.forceIndex;let Q=(A[S]??0)+.14*(B.originalX-B.x),w=(A[S+1]??0)+.14*(B.originalY-B.y),M=0,k=0,R=0,F=0;const O=y.nodes[E-1],U=y.nodes[E+1];if(O||U){let J=0,oe=0,ie=0;if(O&&(J+=O.x,oe+=O.y,ie+=1),U&&(J+=U.x,oe+=U.y,ie+=1),ie>0){const ne=1/ie;Q+=.22*(J*ne-B.x),w+=.22*(oe*ne-B.y)}}if(O&&U&&m>0){const J=Z6e(U,O),oe=mCt(J,J);if(oe>Wu){const ie=$D(mCt(Z6e(B,O),J)/oe),ne=Hno(O,U,ie),le=_Ct(pCt(Z6e(ne,B),.55*m),.02*m);M=le.x,k=le.y}}if(m>0){if(E===1&&O?.fixed){const J=ICt(O,B,t,m);R+=J.x,F+=J.y}if(E===x&&U?.fixed){const J=ICt(U,B,t,m);R+=J.x,F+=J.y}}let Y=.85*Q*p,W=.85*w*p;const te=Math.hypot(Y,W),j=.012*p;if(te>j&&te>Wu){const J=j/te;Y*=J,W*=J}B.x+=Y+M+R,B.y+=W+k+F}}e8e(i,t),vCt(t,i,s,a,c,3,.02)}return vCt(t,i,s,a,c,8,.03),{routes:(h=>h.map(({route:d,nodes:p,pointNodeIndexes:m})=>{const _=d.route.map((I,C)=>{const y=m[C]??-1,x=y>=0?p[y]:void 0;return x?{...I,x:hCt(x.x),y:hCt(x.y)}:I}),f={...d,route:_,vias:[]};return f.vias=gJ(f),f}))(i),forceVectors:u,stepsCompleted:n}},mJ=class extends Tno{sampleEntries;originalHdRoutes;originalNodeWithPortPoints;colorMap;totalStepsPerNode;nodeAssignmentMargin;improvedRoutesByIndex=new Map;activeSampleIndex=0;latestVisualization={};constructor(e){super(),this.originalHdRoutes=e.hdRoutes,this.originalNodeWithPortPoints=e.nodeWithPortPoints,this.colorMap=e.colorMap??{},this.totalStepsPerNode=e.totalStepsPerNode??60,this.nodeAssignmentMargin=e.nodeAssignmentMargin??.2;const n=new Map;for(let o=0;o<e.hdRoutes.length;o++){const i=Gno(e.hdRoutes[o],e.nodeWithPortPoints,this.nodeAssignmentMargin);if(i===-1)continue;const r=n.get(i)??[];r.push(o),n.set(i,r)}this.sampleEntries=Array.from(n.entries()).map(([o,i])=>({node:e.nodeWithPortPoints[o],routeIndexes:i})),this.MAX_ITERATIONS=Math.max(10*this.sampleEntries.length,1e3),this.stats={nodeAssignmentMargin:this.nodeAssignmentMargin,sampleCount:this.sampleEntries.length,improvedNodeCount:0,improvedRouteCount:0,totalStepsPerNode:this.totalStepsPerNode}}getSolverName(){return"HighDensityForceImproveSolver"}getConstructorParams(){return[{nodeWithPortPoints:this.originalNodeWithPortPoints,hdRoutes:this.originalHdRoutes,totalStepsPerNode:this.totalStepsPerNode,nodeAssignmentMargin:this.nodeAssignmentMargin,colorMap:this.colorMap}]}_step(){const e=this.sampleEntries[this.activeSampleIndex];if(!e)return void(this.solved=!0);const n=fCt(e.node),o=e.routeIndexes.map(a=>this.originalHdRoutes[a]),i=wCt(n,o,this.totalStepsPerNode,{includeForceVectors:!0});QCt(e.node,i.routes);const r=uCt(o,i.routes);let s=r.length===0?i:wCt(n,((a,A)=>{const{routes:c,node:l,selectors:u}=a,g=structuredClone(c),h=X8(c),d=pJ(h),p=u.flatMap(m=>{const _=d[m.leftRouteIndex]?.[m.leftStartPointIndex],f=d[m.rightRouteIndex]?.[m.rightStartPointIndex];if(!_||!f)return[];const[I]=av(_,f);if(!I)return[];const C=I.leftPoint.x-I.rightPoint.x,y=I.leftPoint.y-I.rightPoint.y,x=Math.hypot(C,y);return x<=h7?[]:[{selector:m,directionX:C/x,directionY:y/x,requiredDistance:_.traceRadius+f.traceRadius+.015}]});for(let m=0;m<3;m+=1){const _=X8(g),f=pJ(_);for(const I of p){const C=f[I.selector.leftRouteIndex]?.[I.selector.leftStartPointIndex],y=f[I.selector.rightRouteIndex]?.[I.selector.rightStartPointIndex];if(!C||!y)continue;const[x]=av(C,y);if(!x)continue;const E=(x.leftPoint.x-x.rightPoint.x)*I.directionX+(x.leftPoint.y-x.rightPoint.y)*I.directionY,B=I.requiredDistance-E;if(B<=0)continue;const S=Math.min(.025,B/2);A({routes:g,segment:C,dx:I.directionX*S,dy:I.directionY*S,node:l,t:x.leftT}),A({routes:g,segment:y,dx:-I.directionX*S,dy:-I.directionY*S,node:l,t:x.rightT})}}for(const m of g)m.vias=gJ(m);return g})({routes:o,node:e.node,selectors:r},o8e),this.totalStepsPerNode,{includeForceVectors:!0});if(s!==i){QCt(e.node,s.routes);const a=uCt(o,s.routes);if(a.length>0){const A=((c,l)=>{const{originalRoutes:u,guardedRoutes:g,node:h,crossingSelectors:d,protectedSelectors:p}=c,m=pJ(X8(u)),_=pJ(X8(g)),f=j6e(g),I=p.map(({leftRouteIndex:y,rightRouteIndex:x})=>cCt(y,x)),C=J6e(h,h7);for(const y of d){const x=_[y.leftRouteIndex]?.[y.leftStartPointIndex],E=_[y.rightRouteIndex]?.[y.rightStartPointIndex];if(!x||!E)continue;const[B]=av(x,E);if(!(!B||Math.hypot(B.leftPoint.x-B.rightPoint.x,B.leftPoint.y-B.rightPoint.y)>h7||B.leftT<=h7||B.leftT>=.999999||B.rightT<=h7||B.rightT>=.999999))for(const S of["right","left"]){const Q=S==="left"?y.leftRouteIndex:y.rightRouteIndex,w=S==="left"?y.leftStartPointIndex:y.rightStartPointIndex,M=S==="left"?y.rightRouteIndex:y.leftRouteIndex,k=S==="left"?y.rightStartPointIndex:y.leftStartPointIndex,R=u[Q],F=g[Q],O=m[M]?.[k],U=_[M]?.[k];if(!(R&&F&&O&&U))continue;const Y=R.route[w]?.z,W=[];for(let te=w-2;te<=w+3;te+=1){const j=R.route[te];!j||te<=0||te>=R.route.length-1||j.z!==Y||[R.route[te-1],R.route[te+1]].some(J=>J&&J.z!==j.z)||W.push(te)}if(W.length!==0)for(const[te,j]of[[O.start,U.start],[O.end,U.end]])for(const J of[1.51,1.25,1.75,2]){const oe=[...g],ie=structuredClone(F);oe[Q]=ie;let ne=!0;for(const ue of W){const fe=R.route[ue],pe=ie.route[ue];if(!fe||!pe)continue;const ye=j.x+(fe.x-te.x)*J,Me=j.y+(fe.y-te.y)*J;if(ye<=C.minX||ye>=C.maxX||Me<=C.minY||Me>=C.maxY){ne=!1;break}pe.x=ye,pe.y=Me}if(!ne)continue;ie.vias=gJ(ie);let le=oe,ge=j6e(le);const _e=new Set;for(const[ue,fe]of ge)Oae(f,[ue,fe])||(ue===Q&&fe!==Q?_e.add(fe):fe===Q&&ue!==Q&&_e.add(ue));if(_e.size>0){const ue=l(h,structuredClone(oe),_e),fe=j6e(ue);I.every(pe=>!Oae(fe,pe))&&fe.length<ge.length&&(le=ue,ge=fe)}if(I.every(ue=>!Oae(ge,ue))&&ge.length<f.length)return le}}}})({originalRoutes:o,guardedRoutes:s.routes,node:e.node,crossingSelectors:a,protectedSelectors:[...r,...a]},Xno);A&&(s={...s,routes:A})}}for(let a=0;a<e.routeIndexes.length;a++)this.improvedRoutesByIndex.set(e.routeIndexes[a],s.routes[a]);this.latestVisualization=PCt({node:e.node,routes:s.routes,forceVectors:s.forceVectors,colorMap:this.colorMap}),this.activeSampleIndex+=1,this.stats={nodeAssignmentMargin:this.nodeAssignmentMargin,sampleCount:this.sampleEntries.length,improvedNodeCount:this.activeSampleIndex,improvedRouteCount:this.improvedRoutesByIndex.size,totalStepsPerNode:this.totalStepsPerNode},this.activeSampleIndex>=this.sampleEntries.length&&(this.solved=!0)}getOutput(){return this.originalHdRoutes.map((e,n)=>this.improvedRoutesByIndex.get(n)??e)}visualize(){return this.solved?PCt({routes:this.getOutput(),colorMap:this.colorMap}):this.latestVisualization}},PCt=t=>{const e=[],n=[],o=[];t.node&&o.push({center:t.node.center,width:t.node.width,height:t.node.height,stroke:"rgba(14,165,233,0.7)",fill:"rgba(14,165,233,0.04)",label:t.node.capacityMeshNodeId});for(const i of t.routes){const r=t.colorMap?.[i.connectionName]??"#0ea5e9";for(let s=0;s<i.route.length-1;s++){const a=i.route[s],A=i.route[s+1];a.z===A.z&&e.push({points:[{x:a.x,y:a.y},{x:A.x,y:A.y}],strokeColor:a.z===0?r:Fno(r,.5),strokeWidth:i.traceThickness,layer:`z${a.z}`,strokeDash:a.z!==0?[.1,.3]:void 0})}for(const s of i.vias)n.push({center:{x:s.x,y:s.y},radius:i.viaDiameter/2,stroke:r,fill:"rgba(14,165,233,0.12)"})}for(const i of t.forceVectors??[])e.push({points:[{x:i.x,y:i.y},{x:i.x+5*i.dx,y:i.y+5*i.dy}],strokeColor:"rgba(244,63,94,0.85)",strokeWidth:.06,strokeDash:[.08,.08]});return{lines:e,circles:n,rects:o}},_J=.005,i8e=1e-6,Uae=(t,e)=>({minX:t.minX-e,minY:t.minY-e,maxX:t.maxX+e,maxY:t.maxY+e}),MCt=t=>Uae({minX:Math.min(t.start.x,t.end.x),minY:Math.min(t.start.y,t.end.y),maxX:Math.max(t.start.x,t.end.x),maxY:Math.max(t.start.y,t.end.y)},t.width/2),Kae=t=>{const e=t.diameter/2;return{minX:t.x-e,minY:t.y-e,maxX:t.x+e,maxY:t.y+e}},r8e=t=>({minX:t.x-t.width/2,minY:t.y-t.height/2,maxX:t.x+t.width/2,maxY:t.y+t.height/2}),DCt=(t,e)=>`${t}:${e}`,s8e=class{constructor(e){this.cellSize=e}cellSize;cells=new Map;insert(e,n){const o=Math.floor(n.minX/this.cellSize),i=Math.floor(n.maxX/this.cellSize),r=Math.floor(n.minY/this.cellSize),s=Math.floor(n.maxY/this.cellSize);for(let a=o;a<=i;a+=1)for(let A=r;A<=s;A+=1){const c=DCt(a,A),l=this.cells.get(c);l?l.push(e):this.cells.set(c,[e])}}query(e){const n=Math.floor(e.minX/this.cellSize),o=Math.floor(e.maxX/this.cellSize),i=Math.floor(e.minY/this.cellSize),r=Math.floor(e.maxY/this.cellSize),s=new Set;for(let a=n;a<=o;a+=1)for(let A=i;A<=r;A+=1){const c=this.cells.get(DCt(a,A));if(c)for(const l of c)s.add(l)}return[...s]}},Zno=(t,e)=>{const n=DD(t.start,t.end,e.start,e.end);if(n)return n;const o=[{left:t.start,right:z_(t.start,e.start,e.end)},{left:t.end,right:z_(t.end,e.start,e.end)},{left:z_(e.start,t.start,t.end),right:e.start},{left:z_(e.end,t.start,t.end),right:e.end}];let i={left:t.start,right:e.start},r=Number.POSITIVE_INFINITY;for(const s of o){const a=Math.hypot(s.left.x-s.right.x,s.left.y-s.right.y);a<r&&(i=s,r=a)}return{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}},NCt=(t,e)=>{const n=z_(e,t.start,t.end);return{x:(n.x+e.x)/2,y:(n.y+e.y)/2}},eoo=(t,e)=>{const n=z_({x:(e.minX+e.maxX)/2,y:(e.minY+e.maxY)/2},t.start,t.end),o=Math.max(e.minX,Math.min(e.maxX,n.x)),i=Math.max(e.minY,Math.min(e.maxY,n.y));return{x:(n.x+o)/2,y:(n.y+i)/2}},too=t=>{const e=new Set;for(const n of t.route)n.route_type==="wire"&&(n.start_pcb_port_id&&e.add(n.start_pcb_port_id),n.end_pcb_port_id&&e.add(n.end_pcb_port_id));return[...e]},a8e=(t,e,n)=>n<0?`PCB trace ${t} overlaps with ${e} (accidental contact)`:`PCB trace ${t} is too close to ${e} (gap: ${n.toFixed(3)}mm)`,fJ=class{constructor(e,n={}){if(this.srj=e,this.traceClearance=n.traceClearance??.1,this.viaClearance=Math.max(n.viaClearance??.1,.1),this.viaToPadClearance=n.viaToPadClearance??this.srj.minViaEdgeToPadEdgeClearance??.1,this.connMap=n.connMap,this.includeTraceViaOwnerMetadata=n.includeTraceViaOwnerMetadata??!1,this.cellSize=n.spatialCellSize??this.getDefaultSpatialCellSize(),!Number.isFinite(this.traceClearance)||this.traceClearance<0)throw new Error("traceClearance must be a non-negative finite number");if(!Number.isFinite(this.viaClearance))throw new Error("viaClearance must be a finite number");if(!Number.isFinite(this.viaToPadClearance)||this.viaToPadClearance<0)throw new Error("viaToPadClearance must be a non-negative finite number");if(!Number.isFinite(this.cellSize)||this.cellSize<=0)throw new Error("spatialCellSize must be a positive finite number");this.compileConnectionAliases(),this.obstacles=this.compileStaticObstacles(),this.indexStaticObstacles()}srj;traceClearance;viaClearance;viaToPadClearance;cellSize;connMap;includeTraceViaOwnerMetadata;canonicalNetByAlias=new Map;connMapNetByCanonicalNet=new Map;obstacles;obstacleIndexesByLayer=new Map;lastRunStats={traceCount:0,segmentCount:0,viaCount:0,obstacleCount:0,broadPhaseCandidateCount:0,exactCheckCount:0};getDefaultSpatialCellSize(){const e=Math.max(0,this.srj.bounds.maxX-this.srj.bounds.minX),n=Math.max(0,this.srj.bounds.maxY-this.srj.bounds.minY);return Math.max(.25,Math.max(e,n)/64,(this.srj.minViaDiameter??.3)+Math.max(this.traceClearance,this.viaToPadClearance))}compileConnectionAliases(){const e=new Map;for(const n of this.srj.connections){const o=n.netConnectionName??n.rootConnectionName??n.name,i=[n.name,n.rootConnectionName,n.netConnectionName,...n.mergedConnectionNames??[],...n.pointsToConnect.flatMap(r=>[r.pointId,r.pcb_port_id])];for(const r of i){if(!r)continue;this.canonicalNetByAlias.set(r,o);const s=this.connMap?.getNetConnectedToId(r);if(!s)continue;let a=e.get(o);a||(a=new Set,e.set(o,a)),a.add(s)}this.canonicalNetByAlias.set(o,o)}for(const[n,o]of e)o.size===1&&this.connMapNetByCanonicalNet.set(n,o.values().next().value)}resolveNetId(e){const n=this.connMap?.getNetConnectedToId(e);if(n)return n;const o=this.canonicalNetByAlias.get(e);return o?this.connMapNetByCanonicalNet.get(o)??o:e}areConnected(e,n){return e===n||!!this.connMap?.areIdsConnected(e,n)||this.resolveNetId(e)===this.resolveNetId(n)}compileStaticObstacles(){const e=[],n=new Set,o=new Set;for(const i of this.srj.obstacles){if(i.layers.length===0)continue;const r=i.connectedTo.find(h=>h.startsWith("pcb_smtpad_")),s=i.connectedTo.find(h=>h.startsWith("pcb_plated_hole_")),a=i.connectedTo.find(h=>h.startsWith("pcb_port_"));if(!r&&!s&&!a)continue;const A=i.layers.length>1,c=A?"pcb_plated_hole":"pcb_smtpad",l=A?s??`pcb_plated_hole_${i.center.x.toFixed(3)}_${i.center.y.toFixed(3)}`:r??`pcb_smtpad_${i.center.x.toFixed(3)}_${i.center.y.toFixed(3)}`,u=A?o:n;if(u.has(l))continue;u.add(l);const g=A&&Math.abs(i.width-i.height)<.001;e.push({kind:"obstacle",obstacleType:c,obstacleId:l,connectedTo:i.connectedTo,x:i.center.x,y:i.center.y,width:i.width,height:i.height,...g?{radius:Math.max(i.width,i.height)/2}:{},layers:i.layers,...a?{pcbPortId:a}:{}})}return e}indexStaticObstacles(){for(const e of this.obstacles){const n=Uae(r8e(e),Math.max(this.traceClearance,this.viaToPadClearance));for(const o of e.layers){let i=this.obstacleIndexesByLayer.get(o);i||(i=new s8e(this.cellSize),this.obstacleIndexesByLayer.set(o,i)),i.insert(e,n)}}}collectDynamicGeometry(e){const n=[],o=[],i=new Set;for(const r of e){const s=this.resolveNetId(r.connection_name),a=too(r);for(let A=0;A<r.route.length-1;A+=1){const c=r.route[A],l=r.route[A+1];c?.route_type==="wire"&&l?.route_type==="wire"&&c.layer===l.layer&&(Math.abs(c.x-l.x)<=i8e&&Math.abs(c.y-l.y)<=i8e||n.push({kind:"trace_segment",order:n.length,traceId:r.pcb_trace_id,netId:s,start:{x:c.x,y:c.y},end:{x:l.x,y:l.y},width:noo(c,l),layer:c.layer,pcbPortIds:a}))}for(const A of r.route){if(A.route_type!=="via")continue;const c=`${A.x},${A.y},${A.from_layer},${A.to_layer}`;i.has(c)||(i.add(c),o.push({kind:"via",order:o.length,viaId:`via_${o.length}`,traceId:r.pcb_trace_id,netId:s,x:A.x,y:A.y,diameter:A.via_diameter??this.srj.minViaDiameter??.3,layers:[A.from_layer,A.to_layer]}))}}return{segments:n,vias:o}}buildDynamicIndexes(e,n){const o=new Map,i=(r,s,a)=>{let A=o.get(r);A||(A=new s8e(this.cellSize),o.set(r,A)),A.insert(s,Uae(a,this.traceClearance))};for(const r of e)i(r.layer,r,MCt(r));for(const r of n)for(const s of r.layers)i(s,r,Kae(r));return o}obstacleSharesNet(e,n){return n.connectedTo.some(o=>this.areConnected(e,o))}checkTracePair(e,n){if(this.areConnected(e.netId,n.netId))return;this.lastRunStats.exactCheckCount+=1;const o=M5(e.start,e.end,n.start,n.end)-e.width/2-n.width/2;if(o>this.traceClearance-_J)return;const i=`overlap_${e.traceId}_${n.traceId}`;return{type:"pcb_trace_error",error_type:"pcb_trace_error",message:a8e(e.traceId,`PCB trace ${n.traceId}`,o),pcb_trace_id:e.traceId,source_trace_id:"",pcb_trace_error_id:i,minimum_clearance:this.traceClearance,actual_clearance:o,pcb_component_ids:[],pcb_port_ids:[...new Set([...e.pcbPortIds,...n.pcbPortIds])],center:Zno(e,n)}}checkTraceVia(e,n){if(this.areConnected(e.netId,n.netId))return;this.lastRunStats.exactCheckCount+=1;const o=Nz(e.start,e.end,{x:n.x,y:n.y,radius:n.diameter/2})-e.width/2;if(o>this.traceClearance-_J)return;const i=`overlap_${e.traceId}_${n.viaId}`;return{type:"pcb_trace_error",error_type:"pcb_trace_error",message:a8e(e.traceId,`pcb_via "${n.viaId}"`,o),pcb_trace_id:e.traceId,...this.includeTraceViaOwnerMetadata?{pcb_trace_ids:[e.traceId,n.traceId],pcb_via_id:n.viaId,pcb_via_ids:[n.viaId]}:{},source_trace_id:"",pcb_trace_error_id:i,minimum_clearance:this.traceClearance,actual_clearance:o,pcb_component_ids:[],pcb_port_ids:e.pcbPortIds,center:NCt(e,n)}}checkTraceObstacle(e,n){if(this.obstacleSharesNet(e.netId,n))return;this.lastRunStats.exactCheckCount+=1;const o=r8e(n),i=(n.radius===void 0?Dz(e.start,e.end,o):Nz(e.start,e.end,{x:n.x,y:n.y,radius:n.radius}))-e.width/2;if(i+_J>=this.traceClearance)return;const r=`overlap_${e.traceId}_${n.obstacleId}`;return{type:"pcb_trace_error",error_type:"pcb_trace_error",message:a8e(e.traceId,`${n.obstacleType} "${n.obstacleId}"`,i),pcb_trace_id:e.traceId,source_trace_id:"",pcb_trace_error_id:r,minimum_clearance:this.traceClearance,actual_clearance:i,pcb_component_ids:[],pcb_port_ids:[...new Set([...e.pcbPortIds,...n.pcbPortId?[n.pcbPortId]:[]])],center:n.radius===void 0?eoo(e,o):NCt(e,n)}}checkViaObstacle(e,n){if(this.obstacleSharesNet(e.netId,n))return;this.lastRunStats.exactCheckCount+=1;const o=r8e(n),i=(n.radius===void 0?Math.hypot(Math.max(o.minX-e.x,0,e.x-o.maxX),Math.max(o.minY-e.y,0,e.y-o.maxY)):Math.hypot(e.x-n.x,e.y-n.y)-n.radius)-e.diameter/2;if(i+_J>=this.viaToPadClearance)return;const r=`via_pad_clearance_${e.viaId}_${n.obstacleId}`,s={x:(e.x+n.x)/2,y:(e.y+n.y)/2};return{type:"pcb_pad_pad_clearance_error",error_type:"pcb_pad_pad_clearance_error",pcb_pad_pad_clearance_error_id:r,message:`pcb_via "${e.viaId}" and ${n.obstacleType} "${n.obstacleId}" are too close (gap: ${i.toFixed(3)}mm)`,pcb_trace_id:e.traceId,pcb_pad_ids:[e.viaId,n.obstacleId],pcb_via_ids:[e.viaId],minimum_clearance:this.viaToPadClearance,actual_clearance:i,center:s}}checkViaPairs(e){if(e.length<2)return[];const n=[],o=new s8e(this.cellSize);for(const i of e)o.insert(i,Uae(Kae(i),this.viaClearance));for(const i of e)for(const r of o.query(Kae(i))){if(this.lastRunStats.broadPhaseCandidateCount+=1,r.order<=i.order)continue;this.lastRunStats.exactCheckCount+=1;const s=Math.hypot(i.x-r.x,i.y-r.y);if(s<=i8e)continue;const a=s-i.diameter/2-r.diameter/2;if(a+_J>=this.viaClearance)continue;const A=this.areConnected(i.netId,r.netId),c=[i.viaId,r.viaId].sort().join("_"),l={x:(i.x+r.x)/2,y:(i.y+r.y)/2};n.push({type:"pcb_via_clearance_error",error_type:"pcb_via_clearance_error",pcb_error_id:`${A?"same_net":"different_net"}_vias_close_${c}`,message:`Vias ${i.viaId} and ${r.viaId}${A?"":" from different nets"} are too close together (gap: ${a.toFixed(3)}mm)`,pcb_via_ids:[i.viaId,r.viaId],...this.includeTraceViaOwnerMetadata?{pcb_trace_ids:[i.traceId,r.traceId]}:{},pcb_via_pair_net_relation:A?"same_net":"different_net",minimum_clearance:this.viaClearance,actual_clearance:a,pcb_center:l,center:l})}return n}evaluate(e){return this.evaluateInternal(e,!0)}evaluateLegacy(e){return this.evaluateInternal(e,!1)}evaluateInternal(e,n){const{segments:o,vias:i}=this.collectDynamicGeometry(e),r=this.buildDynamicIndexes(o,i),s=[],a=[];this.lastRunStats={traceCount:e.length,segmentCount:o.length,viaCount:i.length,obstacleCount:this.obstacles.length,broadPhaseCandidateCount:0,exactCheckCount:0};for(const g of o){const h=MCt(g),d=r.get(g.layer)?.query(h)??[],p=this.obstacleIndexesByLayer.get(g.layer)?.query(h)??[];for(const m of d){if(this.lastRunStats.broadPhaseCandidateCount+=1,m.kind==="trace_segment"&&m.order<=g.order)continue;const _=m.kind==="trace_segment"?this.checkTracePair(g,m):this.checkTraceVia(g,m);_&&s.push(_)}for(const m of p){this.lastRunStats.broadPhaseCandidateCount+=1;const _=this.checkTraceObstacle(g,m);_&&s.push(_)}}const A=this.checkViaPairs(i);if(n)for(const g of i){const h=new Set;for(const d of g.layers){const p=this.obstacleIndexesByLayer.get(d)?.query(Kae(g))??[];for(const m of p){if(h.has(m))continue;h.add(m),this.lastRunStats.broadPhaseCandidateCount+=1;const _=this.checkViaObstacle(g,m);_&&a.push(_)}}}const c=new Map;for(const g of s){const h=String(g.pcb_trace_error_id),d=c.get(h),p=Number(g.actual_clearance);if(!d){c.set(h,{...g,first_contact_center:g.center,first_contact_message:g.message,first_actual_clearance:p,worst_contact_center:g.center,worst_contact_message:g.message,worst_actual_clearance:p});continue}const m=Number(d.worst_actual_clearance);(p<m||!Number.isFinite(m))&&(d.worst_contact_center=g.center,d.worst_contact_message=g.message,d.worst_actual_clearance=p)}const l=[...c.values()].map(g=>({...g,center:typeof g.worst_contact_center=="object"?g.worst_contact_center:g.center,message:typeof g.worst_contact_message=="string"?g.worst_contact_message:g.message,actual_clearance:typeof g.worst_actual_clearance=="number"?g.worst_actual_clearance:g.actual_clearance}));l.push(...a),l.push(...A);const u=l.filter(g=>g.center);return{errors:l,errorsWithCenters:u,locationAwareErrors:u}}},noo=(t,e)=>t.width??e.width??.1,ooo=[1,1.75,-1],ioo=[1,1.75,-1],roo=8/3,Dr=1e-6,bA=.001,IJ=.14,CJ=.035,My=.015,A8e=t=>t.minTraceToPadEdgeClearance??.16,c8e=t=>t.minViaEdgeToPadEdgeClearance??.1,RCt=t=>Math.max(48,Math.round(48*Math.max(1,t))),soo=t=>t>=2?ooo:ioo,aoo=class{netMap;idToNetMap;constructor(e){this.netMap=e,this.idToNetMap={};for(const[n,o]of Object.entries(e))for(const i of o)this.idToNetMap[i]=n}addConnections(e){for(const n of e){const o=new Set;for(const r of n){const s=this.idToNetMap[r];s&&o.add(s)}let i;if(o.size===0)i=`connectivity_net${Object.keys(this.netMap).length}`,this.netMap[i]=[];else if(o.size===1)i=o.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;else{i=o.values().next().value??`connectivity_net${Object.keys(this.netMap).length}`;for(const r of o)if(r!==i){this.netMap[i].push(...this.netMap[r]),this.netMap[r]=this.netMap[i];for(const s of this.netMap[i])this.idToNetMap[s]=i}}for(const r of n)this.netMap[i].includes(r)||this.netMap[i].push(r),this.idToNetMap[r]=i}}getIdsConnectedToNet(e){return this.netMap[e]||[]}getNetConnectedToId(e){return this.idToNetMap[e]}areIdsConnected(e,n){if(e===n)return!0;const o=this.getNetConnectedToId(e);if(!o)return!1;const i=this.getNetConnectedToId(n);return!!i&&(o===i||i===e||i===e)}areAllIdsConnected(e){const n=this.getNetConnectedToId(e[0]);for(const o of e){const i=this.getNetConnectedToId(o);if(i===void 0||i!==n)return!1}return!0}},l8e=t=>{const e=[];for(const o of t)if(o.type==="source_trace")e.push([o.source_trace_id,...o.connected_source_port_ids??[],...o.connected_source_net_ids??[]].filter(Boolean));else if(o.type==="pcb_port"){const{pcb_port_id:i,source_port_id:r}=o;r&&i&&e.push([r,i])}else if(o.type==="pcb_smtpad"){const{pcb_smtpad_id:i,pcb_port_id:r}=o;r&&i&&e.push([i,r])}else if(o.type==="pcb_plated_hole"){const{pcb_plated_hole_id:i,pcb_port_id:r}=o;r&&i&&e.push([i,r])}else if(o.type==="pcb_trace"){const{pcb_trace_id:i,source_trace_id:r}=o,s=Array.isArray(o.route)?o.route.filter(a=>a&&a.route_type==="wire"):[];if(r&&i&&e.push([i,r]),Array.isArray(s)){const a=s.find(c=>c?.start_pcb_port_id)?.start_pcb_port_id,A=s.find(c=>c?.end_pcb_port_id)?.end_pcb_port_id;a&&i&&A&&e.push([a,i,A])}}else if(o.type==="pcb_via"){const{pcb_via_id:i,pcb_trace_id:r}=o;r&&i&&e.push([i,r])}else if(o.type==="source_component"&&o.internally_connected_source_port_ids)for(const i of o.internally_connected_source_port_ids)e.push(i);const n=(function(o){const i=new Map;let r=0;function s(a){for(const[,c]of i)if(c.has(a))return c;const A=new Set;return i.set("connectivity_net"+r++,A),A}for(const a of o){let A=null;for(const c of a){if(A){if(!A.has(c)){const l=s(c);if(l!==A){for(const u of l)A.add(u);i.delete(Array.from(i.entries()).find(([,u])=>u===l)[0])}}}else A=s(c);A.add(c)}}return Object.fromEntries(Array.from(i.entries()).map(([a,A])=>[a,Array.from(A)]))})(e);return new aoo(n)},Vae={};e_t(Vae,{all_layers:()=>LJ,any_circuit_element:()=>B3t,any_soup_element:()=>aAe,any_source_component:()=>vyt,asset:()=>y8e,base_circuit_json_error:()=>Wl,battery_capacity:()=>nyt,brep_shape:()=>$8e,cadModelDefaultDirectionMap:()=>zio,cad_component:()=>i3t,cad_model_axis_directions:()=>o3t,cad_model_formats:()=>Vio,capacitance:()=>I8e,circuit_json_footprint_load_error:()=>Pxt,current:()=>vL,distance:()=>ao,duration_ms:()=>wL,experiment_type:()=>u3t,external_footprint_load_error:()=>wxt,frequency:()=>tN,getZodPrefixedIdWithDefault:()=>So,inductance:()=>eyt,kicadAt:()=>nAe,kicadEffects:()=>oyt,kicadFont:()=>x8e,kicadFootprintAttributes:()=>ryt,kicadFootprintMetadata:()=>Ayt,kicadFootprintModel:()=>ayt,kicadFootprintPad:()=>syt,kicadFootprintProperties:()=>iyt,kicadProperty:()=>FJ,kicadSymbolEffects:()=>uyt,kicadSymbolMetadata:()=>dyt,kicadSymbolPinNames:()=>lyt,kicadSymbolPinNumbers:()=>cyt,kicadSymbolProperties:()=>gyt,kicadSymbolProperty:()=>uv,layer_ref:()=>WA,layer_string:()=>W8e,length:()=>Di,manufacturing_drc_properties:()=>x2t,ms:()=>J_,ninePointAnchor:()=>ob,parseAndConvertSiUnit:()=>L5,pcbRenderLayer:()=>Iio,pcb_autorouting_error:()=>Dxt,pcb_board:()=>$2t,pcb_breakout_point:()=>Fxt,pcb_component:()=>E2t,pcb_component_invalid_layer_error:()=>Jxt,pcb_component_not_on_board_edge_error:()=>zxt,pcb_component_outside_board_error:()=>Vxt,pcb_connector_not_in_accessible_orientation_warning:()=>Txt,pcb_copper_pour:()=>Kxt,pcb_copper_pour_brep:()=>Yxt,pcb_copper_pour_polygon:()=>Uxt,pcb_copper_pour_rect:()=>Gxt,pcb_copper_text:()=>ixt,pcb_courtyard_circle:()=>t3t,pcb_courtyard_outline:()=>Zxt,pcb_courtyard_overlap_error:()=>yxt,pcb_courtyard_pill:()=>n3t,pcb_courtyard_polygon:()=>e3t,pcb_courtyard_rect:()=>Xxt,pcb_cutout:()=>Qxt,pcb_cutout_circle:()=>Bxt,pcb_cutout_path:()=>Sxt,pcb_cutout_polygon:()=>bxt,pcb_cutout_rect:()=>Ext,pcb_fabrication_note_dimension:()=>hxt,pcb_fabrication_note_path:()=>gxt,pcb_fabrication_note_rect:()=>dxt,pcb_fabrication_note_text:()=>uxt,pcb_footprint_overlap_error:()=>Cxt,pcb_ground_plane:()=>Lxt,pcb_ground_plane_region:()=>Hxt,pcb_group:()=>Mxt,pcb_hole:()=>P2t,pcb_hole_circle_or_square_shape:()=>bio,pcb_hole_circle_shape:()=>Eio,pcb_hole_oval_shape:()=>Sio,pcb_hole_pill_shape:()=>Qio,pcb_hole_rect_shape:()=>Bio,pcb_hole_rotated_pill_shape:()=>vio,pcb_keepout:()=>xxt,pcb_manual_edit_conflict_warning:()=>Nxt,pcb_missing_footprint_error:()=>vxt,pcb_net:()=>W2t,pcb_note_dimension:()=>Ixt,pcb_note_line:()=>fxt,pcb_note_path:()=>_xt,pcb_note_rect:()=>mxt,pcb_note_text:()=>pxt,pcb_pad_pad_clearance_error:()=>$xt,pcb_pad_trace_clearance_error:()=>qxt,pcb_panel:()=>q2t,pcb_panelization_placement_error:()=>Z2t,pcb_placement_error:()=>X2t,pcb_plated_hole:()=>M2t,pcb_port:()=>D2t,pcb_port_not_connected_error:()=>J2t,pcb_port_not_matched_error:()=>z2t,pcb_route_hint:()=>C2t,pcb_route_hints:()=>xio,pcb_silkscreen_circle:()=>sxt,pcb_silkscreen_graphic:()=>cxt,pcb_silkscreen_graphic_brep:()=>Axt,pcb_silkscreen_line:()=>txt,pcb_silkscreen_oval:()=>axt,pcb_silkscreen_path:()=>nxt,pcb_silkscreen_pill:()=>lxt,pcb_silkscreen_rect:()=>rxt,pcb_silkscreen_text:()=>oxt,pcb_smtpad:()=>R2t,pcb_smtpad_pill:()=>N2t,pcb_solder_paste:()=>T2t,pcb_text:()=>k2t,pcb_thermal_spoke:()=>Oxt,pcb_trace:()=>G2t,pcb_trace_error:()=>K2t,pcb_trace_hint:()=>ext,pcb_trace_missing_error:()=>V2t,pcb_trace_route_point:()=>O2t,pcb_trace_route_point_through_pad:()=>H2t,pcb_trace_route_point_via:()=>L2t,pcb_trace_route_point_wire:()=>F2t,pcb_trace_too_long_warning:()=>U2t,pcb_trace_warning:()=>Y2t,pcb_via:()=>j2t,pcb_via_clearance_error:()=>Wxt,pcb_via_trace_clearance_error:()=>jxt,point:()=>_r,point3:()=>nb,point_with_bulge:()=>I2t,port_arrangement:()=>$yt,position:()=>_io,position3:()=>fio,resistance:()=>tAe,ring:()=>j8e,rotation:()=>im,route_hint_point:()=>y2t,schematic_arc:()=>n2t,schematic_box:()=>Vyt,schematic_circle:()=>t2t,schematic_component:()=>qyt,schematic_component_port_arrangement_by_sides:()=>jyt,schematic_component_port_arrangement_by_size:()=>Wyt,schematic_debug_line:()=>l2t,schematic_debug_object:()=>g2t,schematic_debug_object_base:()=>rAe,schematic_debug_point:()=>u2t,schematic_debug_rect:()=>c2t,schematic_error:()=>a2t,schematic_group:()=>p2t,schematic_layout_error:()=>A2t,schematic_line:()=>Zyt,schematic_manual_edit_conflict_warning:()=>h2t,schematic_net_label:()=>s2t,schematic_path:()=>zyt,schematic_pin_styles:()=>Jyt,schematic_port:()=>r2t,schematic_rect:()=>e2t,schematic_sheet:()=>f2t,schematic_symbol:()=>Xyt,schematic_table:()=>m2t,schematic_table_cell:()=>_2t,schematic_text:()=>i2t,schematic_trace:()=>o2t,schematic_voltage_probe:()=>d2t,simulation_ac_current_source:()=>c3t,simulation_ac_voltage_source:()=>s3t,simulation_current_probe:()=>f3t,simulation_current_source:()=>l3t,simulation_dc_current_source:()=>A3t,simulation_dc_voltage_source:()=>r3t,simulation_experiment:()=>d3t,simulation_op_amp:()=>C3t,simulation_oscilloscope_trace:()=>E3t,simulation_spice_subcircuit:()=>y3t,simulation_switch:()=>m3t,simulation_transient_current_graph:()=>p3t,simulation_transient_voltage_graph:()=>h3t,simulation_unknown_experiment_error:()=>I3t,simulation_voltage_probe:()=>_3t,simulation_voltage_source:()=>a3t,size:()=>C8e,source_ambiguous_port_reference:()=>Tyt,source_board:()=>Ryt,source_component_base:()=>vu,source_component_internal_connection:()=>Pyt,source_component_misconfigured_error:()=>J8e,source_component_pins_underspecified_warning:()=>Gyt,source_failed_to_create_component_error:()=>Eyt,source_group:()=>Dyt,source_i2c_misconfigured_error:()=>z8e,source_interconnect:()=>Syt,source_invalid_component_property_error:()=>G8e,source_manually_placed_via:()=>Fyt,source_missing_manufacturer_part_number_warning:()=>K8e,source_missing_property_error:()=>xyt,source_net:()=>Nyt,source_no_ground_pin_defined_warning:()=>Oyt,source_no_power_pin_defined_warning:()=>Hyt,source_part_not_found_warning:()=>Kyt,source_pcb_ground_plane:()=>kyt,source_pin_attributes:()=>Iyt,source_pin_missing_trace_warning:()=>U8e,source_pin_must_be_connected_error:()=>Yyt,source_port:()=>wyt,source_project_metadata:()=>O8e,source_property_ignored_warning:()=>Byt,source_refdes_convention_warning:()=>V8e,source_simple_ammeter:()=>fyt,source_simple_battery:()=>v8e,source_simple_capacitor:()=>E8e,source_simple_chip:()=>S8e,source_simple_connector:()=>yyt,source_simple_crystal:()=>Cyt,source_simple_current_source:()=>myt,source_simple_diode:()=>iAe,source_simple_fiducial:()=>hyt,source_simple_fuse:()=>_yt,source_simple_ground:()=>pyt,source_simple_inductor:()=>w8e,source_simple_led:()=>b8e,source_simple_mosfet:()=>F8e,source_simple_op_amp:()=>L8e,source_simple_pin_header:()=>D8e,source_simple_pinout:()=>N8e,source_simple_potentiometer:()=>M8e,source_simple_power_source:()=>Q8e,source_simple_push_button:()=>P8e,source_simple_resistor:()=>B8e,source_simple_resonator:()=>R8e,source_simple_switch:()=>H8e,source_simple_test_point:()=>k8e,source_simple_transistor:()=>T8e,source_simple_voltage_probe:()=>byt,source_simple_voltage_source:()=>Qyt,source_trace:()=>Myt,source_trace_not_connected_error:()=>Y8e,source_unnamed_trace_warning:()=>Lyt,spice_simulation_options:()=>g3t,supplier_footprint_mismatch_warning:()=>kxt,supplier_name:()=>oAe,time:()=>mio,timestamp:()=>tyt,unknown_error_finding_part:()=>Uyt,visible_layer:()=>W_,voltage:()=>tb,wave_shape:()=>X8e});var zae=t=>{const e=Math.round(1e3*t)/1e3;return`${Number(e.toFixed(3))}mm`},TCt=new Map([["T",1e12],["G",1e9],["M",1e6],["K",1e3],["k",1e3],["",1],["m",.001],["µ",1e-6],["μ",1e-6],["u",1e-6],["n",1e-9],["p",1e-12],["f",1e-15]]),Aoo=[...TCt.keys()];function kCt(t){return TCt.get(t)}var FCt={Hz:{baseUnit:"Hz",variants:{MHz:1e6,kHz:1e3,Hz:1}},g:{baseUnit:"g",variants:{kg:1e3,g:1}},Ω:{baseUnit:"Ω",variants:{mΩ:.001,mohm:.001,mOhm:.001,milliohm:.001,Ω:1,ohm:1,Ohm:1,kΩ:1e3,KΩ:1e3,kohm:1e3,kOhm:1e3,KOhm:1e3,Kohm:1e3,MΩ:1e6,Mohm:1e6,MOhm:1e6,megohm:1e6,Megohm:1e6,GΩ:1e9,Gohm:1e9,GOhm:1e9,TΩ:1e12,Tohm:1e12,TOhm:1e12}},V:{baseUnit:"V",variants:{mV:.001,V:1,kV:1e3,KV:1e3,MV:1e6,GV:1e9,TV:1e12}},A:{baseUnit:"A",variants:{µA:1e-6,μA:1e-6,mA:.001,ma:.001,A:1,kA:1e3,MA:1e6}},F:{baseUnit:"F",variants:{pF:1e-12,nF:1e-9,µF:1e-6,μF:1e-6,uF:1e-6,mF:.001,F:1,kF:1e3,KF:1e3,MF:1e6}},H:{baseUnit:"H",variants:{pH:1e-12,nH:1e-9,µH:1e-6,μH:1e-6,uH:1e-6,mH:.001,H:1,kH:1e3,KH:1e3,MH:1e6}},ml:{baseUnit:"ml",variants:{ml:1,mL:1,l:1e3,L:1e3}},deg:{baseUnit:"deg",variants:{rad:180/Math.PI}},ms:{baseUnit:"ms",variants:{fs:1e-12,ps:1e-9,ns:1e-6,us:.001,µs:.001,μs:.001,ms:1,s:1e3}},mm:{baseUnit:"mm",variants:{nm:1e-6,µm:.001,μm:.001,um:.001,mm:1,cm:10,dm:100,m:1e3,km:1e6,in:25.4,ft:304.8,IN:25.4,FT:304.8,yd:914.4,mi:1609344,mil:.0254}}},u8e=new Set;for(const[t,e]of Object.entries(FCt)){u8e.add(t);for(const n of Object.keys(e.variants))u8e.add(n)}function L5(t,e){if(t==null)return{parsedUnit:null,unitOfValue:null,value:null};if(typeof t=="string"&&t.match(/^-?[\d.]+$/))return{value:Number.parseFloat(t),parsedUnit:null,unitOfValue:null};if(typeof t=="number")return{value:t,parsedUnit:null,unitOfValue:null};if(typeof t=="object"&&"x"in t&&"y"in t){const c=L5(t.x,e),l=L5(t.x,e),u=L5(t.y,e);return l.value===null||u.value===null?{parsedUnit:null,unitOfValue:null,value:null}:{parsedUnit:c.parsedUnit,unitOfValue:c.unitOfValue,value:{x:l.value,y:u.value}}}const n=t.toString().split("").reverse().join(""),o=n.match(/[^\d\s]+/)?.[0];if(!o)throw new Error(`Could not determine unit: "${t}"`);const i=o.split("").reverse().join(""),r=t.slice(0,-i.length),s=kCt(i);if(e&&s!=null)return{parsedUnit:null,unitOfValue:e,value:Number.parseFloat(r)*s};if(s!=null&&!u8e.has(i))return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(r)*s};const{baseUnit:a,conversionFactor:A}=(function(c){for(const l of Object.values(FCt)){if(c in l.variants)return{baseUnit:l.baseUnit,conversionFactor:l.variants[c]};for(const[u,g]of Object.entries(l.variants)){if(!c.endsWith(u))continue;const h=kCt(c.slice(0,-u.length));if(h!=null)return{baseUnit:l.baseUnit,conversionFactor:h*g}}}return{baseUnit:c,conversionFactor:1}})(i);return{parsedUnit:i,unitOfValue:a,value:A*Number.parseFloat(r)}}var Cl,Ix,g8e;Aoo.filter(t=>t!=="").sort((t,e)=>e.length-t.length).map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");var N={};e_t(N,{BRAND:()=>Doo,DIRTY:()=>jae,EMPTY_PATH:()=>uoo,INVALID:()=>ea,NEVER:()=>pio,OK:()=>Dy,ParseStatus:()=>Cx,Schema:()=>JA,ZodAny:()=>bL,ZodArray:()=>eN,ZodBigInt:()=>EJ,ZodBoolean:()=>BJ,ZodBranded:()=>_8e,ZodCatch:()=>TJ,ZodDate:()=>bJ,ZodDefault:()=>RJ,ZodDiscriminatedUnion:()=>KCt,ZodEffects:()=>rB,ZodEnum:()=>DJ,ZodError:()=>iB,ZodFirstPartyTypeKind:()=>aa,ZodFunction:()=>zCt,ZodIntersection:()=>wJ,ZodIssueCode:()=>hi,ZodLazy:()=>PJ,ZodLiteral:()=>MJ,ZodMap:()=>Xae,ZodNaN:()=>eAe,ZodNativeEnum:()=>NJ,ZodNever:()=>eb,ZodNull:()=>QJ,ZodNullable:()=>lv,ZodNumber:()=>xJ,ZodObject:()=>H5,ZodOptional:()=>m7,ZodParsedType:()=>xr,ZodPipeline:()=>f8e,ZodPromise:()=>QL,ZodReadonly:()=>kJ,ZodRecord:()=>VCt,ZodSchema:()=>JA,ZodSet:()=>Zae,ZodString:()=>BL,ZodSymbol:()=>$ae,ZodTransformer:()=>rB,ZodTuple:()=>cv,ZodType:()=>JA,ZodUndefined:()=>SJ,ZodUnion:()=>vJ,ZodUnknown:()=>ZD,ZodVoid:()=>qae,addIssueToContext:()=>nr,any:()=>Goo,array:()=>Voo,bigint:()=>koo,boolean:()=>XCt,coerce:()=>hio,custom:()=>jCt,date:()=>Foo,datetimeRegex:()=>UCt,defaultErrorMap:()=>EL,discriminatedUnion:()=>joo,effect:()=>ZCt,enum:()=>iio,function:()=>tio,getErrorMap:()=>Jae,getParsedType:()=>Z8,instanceof:()=>Roo,intersection:()=>$oo,isAborted:()=>d8e,isAsync:()=>yJ,isDirty:()=>h8e,isValid:()=>XD,late:()=>Noo,lazy:()=>nio,literal:()=>oio,makeIssue:()=>Wae,map:()=>Zoo,nan:()=>Too,nativeEnum:()=>rio,never:()=>Uoo,null:()=>Ooo,nullable:()=>Aio,number:()=>qCt,object:()=>zoo,objectUtil:()=>g8e,oboolean:()=>dio,onumber:()=>gio,optional:()=>aio,ostring:()=>uio,pipeline:()=>lio,preprocess:()=>cio,promise:()=>sio,quotelessJson:()=>coo,record:()=>Xoo,set:()=>eio,setErrorMap:()=>loo,strictObject:()=>Joo,string:()=>$Ct,symbol:()=>Loo,transformer:()=>ZCt,tuple:()=>qoo,undefined:()=>Hoo,union:()=>Woo,unknown:()=>Yoo,util:()=>Cl,void:()=>Koo}),(Ix=Cl||(Cl={})).assertEqual=t=>{},Ix.assertIs=function(t){},Ix.assertNever=function(t){throw new Error},Ix.arrayToEnum=t=>{const e={};for(const n of t)e[n]=n;return e},Ix.getValidEnumValues=t=>{const e=Ix.objectKeys(t).filter(o=>typeof t[t[o]]!="number"),n={};for(const o of e)n[o]=t[o];return Ix.objectValues(n)},Ix.objectValues=t=>Ix.objectKeys(t).map(function(e){return t[e]}),Ix.objectKeys=typeof Object.keys=="function"?t=>Object.keys(t):t=>{const e=[];for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.push(n);return e},Ix.find=(t,e)=>{for(const n of t)if(e(n))return n},Ix.isInteger=typeof Number.isInteger=="function"?t=>Number.isInteger(t):t=>typeof t=="number"&&Number.isFinite(t)&&Math.floor(t)===t,Ix.joinValues=function(t,e=" | "){return t.map(n=>typeof n=="string"?`'${n}'`:n).join(e)},Ix.jsonStringifyReplacer=(t,e)=>typeof e=="bigint"?e.toString():e,(g8e||(g8e={})).mergeShapes=(t,e)=>({...t,...e});var xr=Cl.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Z8=t=>{switch(typeof t){case"undefined":return xr.undefined;case"string":return xr.string;case"number":return Number.isNaN(t)?xr.nan:xr.number;case"boolean":return xr.boolean;case"function":return xr.function;case"bigint":return xr.bigint;case"symbol":return xr.symbol;case"object":return Array.isArray(t)?xr.array:t===null?xr.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?xr.promise:typeof Map<"u"&&t instanceof Map?xr.map:typeof Set<"u"&&t instanceof Set?xr.set:typeof Date<"u"&&t instanceof Date?xr.date:xr.object;default:return xr.unknown}},hi=Cl.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),coo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),iB=class s5n extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=o=>{this.issues=[...this.issues,o]},this.addIssues=(o=[])=>{this.issues=[...this.issues,...o]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(r){return r.message},o={_errors:[]},i=r=>{for(const s of r.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)o._errors.push(n(s));else{let a=o,A=0;for(;A<s.path.length;){const c=s.path[A];A===s.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(s))):a[c]=a[c]||{_errors:[]},a=a[c],A++}}};return i(this),o}static assert(e){if(!(e instanceof s5n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Cl.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},o=[];for(const i of this.issues)if(i.path.length>0){const r=i.path[0];n[r]=n[r]||[],n[r].push(e(i))}else o.push(e(i));return{formErrors:o,fieldErrors:n}}get formErrors(){return this.flatten()}};iB.create=t=>new iB(t);var EL=(t,e)=>{let n;switch(t.code){case hi.invalid_type:n=t.received===xr.undefined?"Required":`Expected ${t.expected}, received ${t.received}`;break;case hi.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,Cl.jsonStringifyReplacer)}`;break;case hi.unrecognized_keys:n=`Unrecognized key(s) in object: ${Cl.joinValues(t.keys,", ")}`;break;case hi.invalid_union:n="Invalid input";break;case hi.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Cl.joinValues(t.options)}`;break;case hi.invalid_enum_value:n=`Invalid enum value. Expected ${Cl.joinValues(t.options)}, received '${t.received}'`;break;case hi.invalid_arguments:n="Invalid function arguments";break;case hi.invalid_return_type:n="Invalid function return type";break;case hi.invalid_date:n="Invalid date";break;case hi.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:Cl.assertNever(t.validation):n=t.validation!=="regex"?`Invalid ${t.validation}`:"Invalid";break;case hi.too_small:n=t.type==="array"?`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"||t.type==="bigint"?`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:"Invalid input";break;case hi.too_big:n=t.type==="array"?`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:"Invalid input";break;case hi.custom:n="Invalid input";break;case hi.invalid_intersection_types:n="Intersection results could not be merged";break;case hi.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case hi.not_finite:n="Number must be finite";break;default:n=e.defaultError,Cl.assertNever(t)}return{message:n}},LCt=EL;function loo(t){LCt=t}function Jae(){return LCt}var Wae=t=>{const{data:e,path:n,errorMaps:o,issueData:i}=t,r=[...n,...i.path||[]],s={...i,path:r};if(i.message!==void 0)return{...i,path:r,message:i.message};let a="";const A=o.filter(c=>!!c).slice().reverse();for(const c of A)a=c(s,{data:e,defaultError:a}).message;return{...i,path:r,message:a}},uoo=[];function nr(t,e){const n=Jae(),o=Wae({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===EL?void 0:EL].filter(i=>!!i)});t.common.issues.push(o)}var rs,HCt,Cx=class a5n{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const o=[];for(const i of n){if(i.status==="aborted")return ea;i.status==="dirty"&&e.dirty(),o.push(i.value)}return{status:e.value,value:o}}static async mergeObjectAsync(e,n){const o=[];for(const i of n){const r=await i.key,s=await i.value;o.push({key:r,value:s})}return a5n.mergeObjectSync(e,o)}static mergeObjectSync(e,n){const o={};for(const i of n){const{key:r,value:s}=i;if(r.status==="aborted"||s.status==="aborted")return ea;r.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),r.value==="__proto__"||s.value===void 0&&!i.alwaysSet||(o[r.value]=s.value)}return{status:e.value,value:o}}},ea=Object.freeze({status:"aborted"}),jae=t=>({status:"dirty",value:t}),Dy=t=>({status:"valid",value:t}),d8e=t=>t.status==="aborted",h8e=t=>t.status==="dirty",XD=t=>t.status==="valid",yJ=t=>typeof Promise<"u"&&t instanceof Promise;(HCt=rs||(rs={})).errToObj=t=>typeof t=="string"?{message:t}:t||{},HCt.toString=t=>typeof t=="string"?t:t?.message;var p7=class{constructor(e,n,o,i){this._cachedPath=[],this.parent=e,this.data=n,this._path=o,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},OCt=(t,e)=>{if(XD(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new iB(t.common.issues);return this._error=n,this._error}}};function SA(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:o,description:i}=t;if(e&&(n||o))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(r,s)=>{const{message:a}=t;return r.code==="invalid_enum_value"?{message:a??s.defaultError}:s.data===void 0?{message:a??o??s.defaultError}:r.code!=="invalid_type"?{message:s.defaultError}:{message:a??n??s.defaultError}},description:i}}var p8e,JA=class{get description(){return this._def.description}_getType(e){return Z8(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Z8(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Cx,ctx:{common:e.parent.common,data:e.data,parsedType:Z8(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(yJ(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const o=this.safeParse(e,n);if(o.success)return o.data;throw o.error}safeParse(e,n){const o={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Z8(e)},i=this._parseSync({data:e,path:o.path,parent:o});return OCt(o,i)}"~validate"(e){const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Z8(e)};if(!this["~standard"].async)try{const o=this._parseSync({data:e,path:[],parent:n});return XD(o)?{value:o.value}:{issues:n.common.issues}}catch(o){o?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(o=>XD(o)?{value:o.value}:{issues:n.common.issues})}async parseAsync(e,n){const o=await this.safeParseAsync(e,n);if(o.success)return o.data;throw o.error}async safeParseAsync(e,n){const o={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Z8(e)},i=this._parse({data:e,path:o.path,parent:o}),r=await(yJ(i)?i:Promise.resolve(i));return OCt(o,r)}refine(e,n){const o=i=>typeof n=="string"||n===void 0?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,r)=>{const s=e(i),a=()=>r.addIssue({code:hi.custom,...o(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(A=>!!A||(a(),!1)):!!s||(a(),!1)})}refinement(e,n){return this._refinement((o,i)=>!!e(o)||(i.addIssue(typeof n=="function"?n(o,i):n),!1))}_refinement(e){return new rB({schema:this,typeName:aa.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return m7.create(this,this._def)}nullable(){return lv.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return eN.create(this)}promise(){return QL.create(this,this._def)}or(e){return vJ.create([this,e],this._def)}and(e){return wJ.create(this,e,this._def)}transform(e){return new rB({...SA(this._def),schema:this,typeName:aa.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new RJ({...SA(this._def),innerType:this,defaultValue:n,typeName:aa.ZodDefault})}brand(){return new _8e({typeName:aa.ZodBranded,type:this,...SA(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new TJ({...SA(this._def),innerType:this,catchValue:n,typeName:aa.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return f8e.create(this,e)}readonly(){return kJ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},goo=/^c[^\s-]{8,}$/i,doo=/^[0-9a-z]+$/,hoo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,poo=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,moo=/^[a-z0-9_-]{21}$/i,_oo=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,foo=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ioo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Coo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,yoo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,xoo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Eoo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Boo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,boo=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,GCt="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Soo=new RegExp(`^${GCt}$`);function YCt(t){let e="[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t.precision?"+":"?"}`}function Qoo(t){return new RegExp(`^${YCt(t)}$`)}function UCt(t){let e=`${GCt}T${YCt(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function voo(t,e){return!(e!=="v4"&&e||!Coo.test(t))||!(e!=="v6"&&e||!xoo.test(t))}function woo(t,e){if(!_oo.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const o=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(o));return typeof i=="object"&&i!==null&&(!("typ"in i)||i?.typ==="JWT")&&!!i.alg&&(!e||i.alg===e)}catch{return!1}}function Poo(t,e){return!(e!=="v4"&&e||!yoo.test(t))||!(e!=="v6"&&e||!Eoo.test(t))}var BL=class jte extends JA{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==xr.string){const i=this._getOrReturnCtx(e);return nr(i,{code:hi.invalid_type,expected:xr.string,received:i.parsedType}),ea}const n=new Cx;let o;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const r=e.data.length>i.value,s=e.data.length<i.value;(r||s)&&(o=this._getOrReturnCtx(e,o),r?nr(o,{code:hi.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):s&&nr(o,{code:hi.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Ioo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"email",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")p8e||(p8e=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),p8e.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"emoji",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")poo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"uuid",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")moo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"nanoid",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")goo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"cuid",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")doo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"cuid2",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")hoo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"ulid",code:hi.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),nr(o,{validation:"url",code:hi.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"regex",code:hi.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?UCt(i).test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?Soo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?Qoo(i).test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?foo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"duration",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?voo(e.data,i.version)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"ip",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?woo(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"jwt",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?Poo(e.data,i.version)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"cidr",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Boo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"base64",code:hi.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?boo.test(e.data)||(o=this._getOrReturnCtx(e,o),nr(o,{validation:"base64url",code:hi.invalid_string,message:i.message}),n.dirty()):Cl.assertNever(i);return{status:n.value,value:e.data}}_regex(e,n,o){return this.refinement(i=>e.test(i),{validation:n,code:hi.invalid_string,...rs.errToObj(o)})}_addCheck(e){return new jte({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...rs.errToObj(e)})}url(e){return this._addCheck({kind:"url",...rs.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...rs.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...rs.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...rs.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...rs.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...rs.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...rs.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...rs.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...rs.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...rs.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...rs.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...rs.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...rs.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:e?.precision===void 0?null:e?.precision,...rs.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...rs.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...rs.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...rs.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...rs.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...rs.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...rs.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...rs.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...rs.errToObj(n)})}nonempty(e){return this.min(1,rs.errToObj(e))}trim(){return new jte({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new jte({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new jte({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};function Moo(t,e){const n=(t.toString().split(".")[1]||"").length,o=(e.toString().split(".")[1]||"").length,i=n>o?n:o;return Number.parseInt(t.toFixed(i).replace(".",""))%Number.parseInt(e.toFixed(i).replace(".",""))/10**i}BL.create=t=>new BL({checks:[],typeName:aa.ZodString,coerce:t?.coerce??!1,...SA(t)});var xJ=class hit extends JA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==xr.number){const i=this._getOrReturnCtx(e);return nr(i,{code:hi.invalid_type,expected:xr.number,received:i.parsedType}),ea}let n;const o=new Cx;for(const i of this._def.checks)i.kind==="int"?Cl.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?Moo(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.not_finite,message:i.message}),o.dirty()):Cl.assertNever(i);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,rs.toString(n))}gt(e,n){return this.setLimit("min",e,!1,rs.toString(n))}lte(e,n){return this.setLimit("max",e,!0,rs.toString(n))}lt(e,n){return this.setLimit("max",e,!1,rs.toString(n))}setLimit(e,n,o,i){return new hit({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:o,message:rs.toString(i)}]})}_addCheck(e){return new hit({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:rs.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:rs.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:rs.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:rs.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:rs.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:rs.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:rs.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:rs.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:rs.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&Cl.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const o of this._def.checks){if(o.kind==="finite"||o.kind==="int"||o.kind==="multipleOf")return!0;o.kind==="min"?(n===null||o.value>n)&&(n=o.value):o.kind==="max"&&(e===null||o.value<e)&&(e=o.value)}return Number.isFinite(n)&&Number.isFinite(e)}};xJ.create=t=>new xJ({checks:[],typeName:aa.ZodNumber,coerce:t?.coerce||!1,...SA(t)});var EJ=class pit extends JA{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==xr.bigint)return this._getInvalidInput(e);let n;const o=new Cx;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),nr(n,{code:hi.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):Cl.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return nr(n,{code:hi.invalid_type,expected:xr.bigint,received:n.parsedType}),ea}gte(e,n){return this.setLimit("min",e,!0,rs.toString(n))}gt(e,n){return this.setLimit("min",e,!1,rs.toString(n))}lte(e,n){return this.setLimit("max",e,!0,rs.toString(n))}lt(e,n){return this.setLimit("max",e,!1,rs.toString(n))}setLimit(e,n,o,i){return new pit({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:o,message:rs.toString(i)}]})}_addCheck(e){return new pit({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:rs.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:rs.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:rs.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:rs.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:rs.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};EJ.create=t=>new EJ({checks:[],typeName:aa.ZodBigInt,coerce:t?.coerce??!1,...SA(t)});var BJ=class extends JA{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==xr.boolean){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.boolean,received:e.parsedType}),ea}return Dy(t.data)}};BJ.create=t=>new BJ({typeName:aa.ZodBoolean,coerce:t?.coerce||!1,...SA(t)});var bJ=class A5n extends JA{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==xr.date){const i=this._getOrReturnCtx(e);return nr(i,{code:hi.invalid_type,expected:xr.date,received:i.parsedType}),ea}if(Number.isNaN(e.data.getTime()))return nr(this._getOrReturnCtx(e),{code:hi.invalid_date}),ea;const n=new Cx;let o;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),nr(o,{code:hi.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):Cl.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new A5n({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:rs.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:rs.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};bJ.create=t=>new bJ({checks:[],coerce:t?.coerce||!1,typeName:aa.ZodDate,...SA(t)});var $ae=class extends JA{_parse(t){if(this._getType(t)!==xr.symbol){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.symbol,received:e.parsedType}),ea}return Dy(t.data)}};$ae.create=t=>new $ae({typeName:aa.ZodSymbol,...SA(t)});var SJ=class extends JA{_parse(t){if(this._getType(t)!==xr.undefined){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.undefined,received:e.parsedType}),ea}return Dy(t.data)}};SJ.create=t=>new SJ({typeName:aa.ZodUndefined,...SA(t)});var QJ=class extends JA{_parse(t){if(this._getType(t)!==xr.null){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.null,received:e.parsedType}),ea}return Dy(t.data)}};QJ.create=t=>new QJ({typeName:aa.ZodNull,...SA(t)});var bL=class extends JA{constructor(){super(...arguments),this._any=!0}_parse(t){return Dy(t.data)}};bL.create=t=>new bL({typeName:aa.ZodAny,...SA(t)});var ZD=class extends JA{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Dy(t.data)}};ZD.create=t=>new ZD({typeName:aa.ZodUnknown,...SA(t)});var eb=class extends JA{_parse(t){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.never,received:e.parsedType}),ea}};eb.create=t=>new eb({typeName:aa.ZodNever,...SA(t)});var qae=class extends JA{_parse(t){if(this._getType(t)!==xr.undefined){const e=this._getOrReturnCtx(t);return nr(e,{code:hi.invalid_type,expected:xr.void,received:e.parsedType}),ea}return Dy(t.data)}};qae.create=t=>new qae({typeName:aa.ZodVoid,...SA(t)});var eN=class Vye extends JA{_parse(e){const{ctx:n,status:o}=this._processInputParams(e),i=this._def;if(n.parsedType!==xr.array)return nr(n,{code:hi.invalid_type,expected:xr.array,received:n.parsedType}),ea;if(i.exactLength!==null){const s=n.data.length>i.exactLength.value,a=n.data.length<i.exactLength.value;(s||a)&&(nr(n,{code:s?hi.too_big:hi.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),o.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(nr(n,{code:hi.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),o.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(nr(n,{code:hi.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),o.dirty()),n.common.async)return Promise.all([...n.data].map((s,a)=>i.type._parseAsync(new p7(n,s,n.path,a)))).then(s=>Cx.mergeArray(o,s));const r=[...n.data].map((s,a)=>i.type._parseSync(new p7(n,s,n.path,a)));return Cx.mergeArray(o,r)}get element(){return this._def.type}min(e,n){return new Vye({...this._def,minLength:{value:e,message:rs.toString(n)}})}max(e,n){return new Vye({...this._def,maxLength:{value:e,message:rs.toString(n)}})}length(e,n){return new Vye({...this._def,exactLength:{value:e,message:rs.toString(n)}})}nonempty(e){return this.min(1,e)}};function SL(t){if(t instanceof H5){const e={};for(const n in t.shape){const o=t.shape[n];e[n]=m7.create(SL(o))}return new H5({...t._def,shape:()=>e})}return t instanceof eN?new eN({...t._def,type:SL(t.element)}):t instanceof m7?m7.create(SL(t.unwrap())):t instanceof lv?lv.create(SL(t.unwrap())):t instanceof cv?cv.create(t.items.map(e=>SL(e))):t}eN.create=(t,e)=>new eN({type:t,minLength:null,maxLength:null,exactLength:null,typeName:aa.ZodArray,...SA(e)});var H5=class v9 extends JA{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=Cl.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==xr.object){const A=this._getOrReturnCtx(e);return nr(A,{code:hi.invalid_type,expected:xr.object,received:A.parsedType}),ea}const{status:n,ctx:o}=this._processInputParams(e),{shape:i,keys:r}=this._getCached(),s=[];if(!(this._def.catchall instanceof eb&&this._def.unknownKeys==="strip"))for(const A in o.data)r.includes(A)||s.push(A);const a=[];for(const A of r){const c=i[A],l=o.data[A];a.push({key:{status:"valid",value:A},value:c._parse(new p7(o,l,o.path,A)),alwaysSet:A in o.data})}if(this._def.catchall instanceof eb){const A=this._def.unknownKeys;if(A==="passthrough")for(const c of s)a.push({key:{status:"valid",value:c},value:{status:"valid",value:o.data[c]}});else if(A==="strict")s.length>0&&(nr(o,{code:hi.unrecognized_keys,keys:s}),n.dirty());else if(A!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const A=this._def.catchall;for(const c of s){const l=o.data[c];a.push({key:{status:"valid",value:c},value:A._parse(new p7(o,l,o.path,c)),alwaysSet:c in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const A=[];for(const c of a){const l=await c.key,u=await c.value;A.push({key:l,value:u,alwaysSet:c.alwaysSet})}return A}).then(A=>Cx.mergeObjectSync(n,A)):Cx.mergeObjectSync(n,a)}get shape(){return this._def.shape()}strict(e){return rs.errToObj,new v9({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,o)=>{const i=this._def.errorMap?.(n,o).message??o.defaultError;return n.code==="unrecognized_keys"?{message:rs.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new v9({...this._def,unknownKeys:"strip"})}passthrough(){return new v9({...this._def,unknownKeys:"passthrough"})}extend(e){return new v9({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new v9({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:aa.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new v9({...this._def,catchall:e})}pick(e){const n={};for(const o of Cl.objectKeys(e))e[o]&&this.shape[o]&&(n[o]=this.shape[o]);return new v9({...this._def,shape:()=>n})}omit(e){const n={};for(const o of Cl.objectKeys(this.shape))e[o]||(n[o]=this.shape[o]);return new v9({...this._def,shape:()=>n})}deepPartial(){return SL(this)}partial(e){const n={};for(const o of Cl.objectKeys(this.shape)){const i=this.shape[o];e&&!e[o]?n[o]=i:n[o]=i.optional()}return new v9({...this._def,shape:()=>n})}required(e){const n={};for(const o of Cl.objectKeys(this.shape))if(e&&!e[o])n[o]=this.shape[o];else{let i=this.shape[o];for(;i instanceof m7;)i=i._def.innerType;n[o]=i}return new v9({...this._def,shape:()=>n})}keyof(){return JCt(Cl.objectKeys(this.shape))}};H5.create=(t,e)=>new H5({shape:()=>t,unknownKeys:"strip",catchall:eb.create(),typeName:aa.ZodObject,...SA(e)}),H5.strictCreate=(t,e)=>new H5({shape:()=>t,unknownKeys:"strict",catchall:eb.create(),typeName:aa.ZodObject,...SA(e)}),H5.lazycreate=(t,e)=>new H5({shape:t,unknownKeys:"strip",catchall:eb.create(),typeName:aa.ZodObject,...SA(e)});var vJ=class extends JA{_parse(t){const{ctx:e}=this._processInputParams(t),n=this._def.options;if(e.common.async)return Promise.all(n.map(async o=>{const i={...e,common:{...e.common,issues:[]},parent:null};return{result:await o._parseAsync({data:e.data,path:e.path,parent:i}),ctx:i}})).then(function(o){for(const r of o)if(r.result.status==="valid")return r.result;for(const r of o)if(r.result.status==="dirty")return e.common.issues.push(...r.ctx.common.issues),r.result;const i=o.map(r=>new iB(r.ctx.common.issues));return nr(e,{code:hi.invalid_union,unionErrors:i}),ea});{let o;const i=[];for(const s of n){const a={...e,common:{...e.common,issues:[]},parent:null},A=s._parseSync({data:e.data,path:e.path,parent:a});if(A.status==="valid")return A;A.status!=="dirty"||o||(o={result:A,ctx:a}),a.common.issues.length&&i.push(a.common.issues)}if(o)return e.common.issues.push(...o.ctx.common.issues),o.result;const r=i.map(s=>new iB(s));return nr(e,{code:hi.invalid_union,unionErrors:r}),ea}}get options(){return this._def.options}};vJ.create=(t,e)=>new vJ({options:t,typeName:aa.ZodUnion,...SA(e)});var Av=t=>t instanceof PJ?Av(t.schema):t instanceof rB?Av(t.innerType()):t instanceof MJ?[t.value]:t instanceof DJ?t.options:t instanceof NJ?Cl.objectValues(t.enum):t instanceof RJ?Av(t._def.innerType):t instanceof SJ?[void 0]:t instanceof QJ?[null]:t instanceof m7?[void 0,...Av(t.unwrap())]:t instanceof lv?[null,...Av(t.unwrap())]:t instanceof _8e||t instanceof kJ?Av(t.unwrap()):t instanceof TJ?Av(t._def.innerType):[],KCt=class c5n extends JA{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==xr.object)return nr(n,{code:hi.invalid_type,expected:xr.object,received:n.parsedType}),ea;const o=this.discriminator,i=n.data[o],r=this.optionsMap.get(i);return r?n.common.async?r._parseAsync({data:n.data,path:n.path,parent:n}):r._parseSync({data:n.data,path:n.path,parent:n}):(nr(n,{code:hi.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[o]}),ea)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,o){const i=new Map;for(const r of n){const s=Av(r.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const a of s){if(i.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);i.set(a,r)}}return new c5n({typeName:aa.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:i,...SA(o)})}};function m8e(t,e){const n=Z8(t),o=Z8(e);if(t===e)return{valid:!0,data:t};if(n===xr.object&&o===xr.object){const i=Cl.objectKeys(e),r=Cl.objectKeys(t).filter(a=>i.indexOf(a)!==-1),s={...t,...e};for(const a of r){const A=m8e(t[a],e[a]);if(!A.valid)return{valid:!1};s[a]=A.data}return{valid:!0,data:s}}if(n===xr.array&&o===xr.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let r=0;r<t.length;r++){const s=m8e(t[r],e[r]);if(!s.valid)return{valid:!1};i.push(s.data)}return{valid:!0,data:i}}return n===xr.date&&o===xr.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var wJ=class extends JA{_parse(t){const{status:e,ctx:n}=this._processInputParams(t),o=(i,r)=>{if(d8e(i)||d8e(r))return ea;const s=m8e(i.value,r.value);return s.valid?((h8e(i)||h8e(r))&&e.dirty(),{status:e.value,value:s.data}):(nr(n,{code:hi.invalid_intersection_types}),ea)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,r])=>o(i,r)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};wJ.create=(t,e,n)=>new wJ({left:t,right:e,typeName:aa.ZodIntersection,...SA(n)});var cv=class l5n extends JA{_parse(e){const{status:n,ctx:o}=this._processInputParams(e);if(o.parsedType!==xr.array)return nr(o,{code:hi.invalid_type,expected:xr.array,received:o.parsedType}),ea;if(o.data.length<this._def.items.length)return nr(o,{code:hi.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ea;!this._def.rest&&o.data.length>this._def.items.length&&(nr(o,{code:hi.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...o.data].map((r,s)=>{const a=this._def.items[s]||this._def.rest;return a?a._parse(new p7(o,r,o.path,s)):null}).filter(r=>!!r);return o.common.async?Promise.all(i).then(r=>Cx.mergeArray(n,r)):Cx.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new l5n({...this._def,rest:e})}};cv.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new cv({items:t,typeName:aa.ZodTuple,rest:null,...SA(e)})};var VCt=class u5n extends JA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:o}=this._processInputParams(e);if(o.parsedType!==xr.object)return nr(o,{code:hi.invalid_type,expected:xr.object,received:o.parsedType}),ea;const i=[],r=this._def.keyType,s=this._def.valueType;for(const a in o.data)i.push({key:r._parse(new p7(o,a,o.path,a)),value:s._parse(new p7(o,o.data[a],o.path,a)),alwaysSet:a in o.data});return o.common.async?Cx.mergeObjectAsync(n,i):Cx.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(e,n,o){return new u5n(n instanceof JA?{keyType:e,valueType:n,typeName:aa.ZodRecord,...SA(o)}:{keyType:BL.create(),valueType:e,typeName:aa.ZodRecord,...SA(n)})}},Xae=class extends JA{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:n}=this._processInputParams(t);if(n.parsedType!==xr.map)return nr(n,{code:hi.invalid_type,expected:xr.map,received:n.parsedType}),ea;const o=this._def.keyType,i=this._def.valueType,r=[...n.data.entries()].map(([s,a],A)=>({key:o._parse(new p7(n,s,n.path,[A,"key"])),value:i._parse(new p7(n,a,n.path,[A,"value"]))}));if(n.common.async){const s=new Map;return Promise.resolve().then(async()=>{for(const a of r){const A=await a.key,c=await a.value;if(A.status==="aborted"||c.status==="aborted")return ea;A.status!=="dirty"&&c.status!=="dirty"||e.dirty(),s.set(A.value,c.value)}return{status:e.value,value:s}})}{const s=new Map;for(const a of r){const A=a.key,c=a.value;if(A.status==="aborted"||c.status==="aborted")return ea;A.status!=="dirty"&&c.status!=="dirty"||e.dirty(),s.set(A.value,c.value)}return{status:e.value,value:s}}}};Xae.create=(t,e,n)=>new Xae({valueType:e,keyType:t,typeName:aa.ZodMap,...SA(n)});var Zae=class mit extends JA{_parse(e){const{status:n,ctx:o}=this._processInputParams(e);if(o.parsedType!==xr.set)return nr(o,{code:hi.invalid_type,expected:xr.set,received:o.parsedType}),ea;const i=this._def;i.minSize!==null&&o.data.size<i.minSize.value&&(nr(o,{code:hi.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&o.data.size>i.maxSize.value&&(nr(o,{code:hi.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const r=this._def.valueType;function s(A){const c=new Set;for(const l of A){if(l.status==="aborted")return ea;l.status==="dirty"&&n.dirty(),c.add(l.value)}return{status:n.value,value:c}}const a=[...o.data.values()].map((A,c)=>r._parse(new p7(o,A,o.path,c)));return o.common.async?Promise.all(a).then(A=>s(A)):s(a)}min(e,n){return new mit({...this._def,minSize:{value:e,message:rs.toString(n)}})}max(e,n){return new mit({...this._def,maxSize:{value:e,message:rs.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Zae.create=(t,e)=>new Zae({valueType:t,minSize:null,maxSize:null,typeName:aa.ZodSet,...SA(e)});var zCt=class zye extends JA{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==xr.function)return nr(n,{code:hi.invalid_type,expected:xr.function,received:n.parsedType}),ea;function o(a,A){return Wae({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Jae(),EL].filter(c=>!!c),issueData:{code:hi.invalid_arguments,argumentsError:A}})}function i(a,A){return Wae({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Jae(),EL].filter(c=>!!c),issueData:{code:hi.invalid_return_type,returnTypeError:A}})}const r={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof QL){const a=this;return Dy(async function(...A){const c=new iB([]),l=await a._def.args.parseAsync(A,r).catch(g=>{throw c.addIssue(o(A,g)),c}),u=await Reflect.apply(s,this,l);return await a._def.returns._def.type.parseAsync(u,r).catch(g=>{throw c.addIssue(i(u,g)),c})})}{const a=this;return Dy(function(...A){const c=a._def.args.safeParse(A,r);if(!c.success)throw new iB([o(A,c.error)]);const l=Reflect.apply(s,this,c.data),u=a._def.returns.safeParse(l,r);if(!u.success)throw new iB([i(l,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new zye({...this._def,args:cv.create(e).rest(ZD.create())})}returns(e){return new zye({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,o){return new zye({args:e||cv.create([]).rest(ZD.create()),returns:n||ZD.create(),typeName:aa.ZodFunction,...SA(o)})}},PJ=class extends JA{get schema(){return this._def.getter()}_parse(t){const{ctx:e}=this._processInputParams(t);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}};PJ.create=(t,e)=>new PJ({getter:t,typeName:aa.ZodLazy,...SA(e)});var MJ=class extends JA{_parse(t){if(t.data!==this._def.value){const e=this._getOrReturnCtx(t);return nr(e,{received:e.data,code:hi.invalid_literal,expected:this._def.value}),ea}return{status:"valid",value:t.data}}get value(){return this._def.value}};function JCt(t,e){return new DJ({values:t,typeName:aa.ZodEnum,...SA(e)})}MJ.create=(t,e)=>new MJ({value:t,typeName:aa.ZodLiteral,...SA(e)});var DJ=class _it extends JA{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),o=this._def.values;return nr(n,{expected:Cl.joinValues(o),received:n.parsedType,code:hi.invalid_type}),ea}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),o=this._def.values;return nr(n,{received:n.data,code:hi.invalid_enum_value,options:o}),ea}return Dy(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return _it.create(e,{...this._def,...n})}exclude(e,n=this._def){return _it.create(this.options.filter(o=>!e.includes(o)),{...this._def,...n})}};DJ.create=JCt;var NJ=class extends JA{_parse(t){const e=Cl.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==xr.string&&n.parsedType!==xr.number){const o=Cl.objectValues(e);return nr(n,{expected:Cl.joinValues(o),received:n.parsedType,code:hi.invalid_type}),ea}if(this._cache||(this._cache=new Set(Cl.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Cl.objectValues(e);return nr(n,{received:n.data,code:hi.invalid_enum_value,options:o}),ea}return Dy(t.data)}get enum(){return this._def.values}};NJ.create=(t,e)=>new NJ({values:t,typeName:aa.ZodNativeEnum,...SA(e)});var QL=class extends JA{unwrap(){return this._def.type}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==xr.promise&&e.common.async===!1)return nr(e,{code:hi.invalid_type,expected:xr.promise,received:e.parsedType}),ea;const n=e.parsedType===xr.promise?e.data:Promise.resolve(e.data);return Dy(n.then(o=>this._def.type.parseAsync(o,{path:e.path,errorMap:e.common.contextualErrorMap})))}};QL.create=(t,e)=>new QL({type:t,typeName:aa.ZodPromise,...SA(e)});var rB=class extends JA{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===aa.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:e,ctx:n}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:r=>{nr(n,r),r.fatal?e.abort():e.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const r=o.transform(n.data,i);if(n.common.async)return Promise.resolve(r).then(async s=>{if(e.value==="aborted")return ea;const a=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return a.status==="aborted"?ea:a.status==="dirty"||e.value==="dirty"?jae(a.value):a});{if(e.value==="aborted")return ea;const s=this._def.schema._parseSync({data:r,path:n.path,parent:n});return s.status==="aborted"?ea:s.status==="dirty"||e.value==="dirty"?jae(s.value):s}}if(o.type==="refinement"){const r=s=>{const a=o.refinement(s,i);if(n.common.async)return Promise.resolve(a);if(a instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){const s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?ea:(s.status==="dirty"&&e.dirty(),r(s.value),{status:e.value,value:s.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?ea:(s.status==="dirty"&&e.dirty(),r(s.value).then(()=>({status:e.value,value:s.value}))))}if(o.type==="transform"){if(n.common.async===!1){const r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!XD(r))return ea;const s=o.transform(r.value,i);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:s}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(r=>XD(r)?Promise.resolve(o.transform(r.value,i)).then(s=>({status:e.value,value:s})):ea)}Cl.assertNever(o)}};rB.create=(t,e,n)=>new rB({schema:t,typeName:aa.ZodEffects,effect:e,...SA(n)}),rB.createWithPreprocess=(t,e,n)=>new rB({schema:e,effect:{type:"preprocess",transform:t},typeName:aa.ZodEffects,...SA(n)});var m7=class extends JA{_parse(t){return this._getType(t)===xr.undefined?Dy(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};m7.create=(t,e)=>new m7({innerType:t,typeName:aa.ZodOptional,...SA(e)});var lv=class extends JA{_parse(t){return this._getType(t)===xr.null?Dy(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};lv.create=(t,e)=>new lv({innerType:t,typeName:aa.ZodNullable,...SA(e)});var RJ=class extends JA{_parse(t){const{ctx:e}=this._processInputParams(t);let n=e.data;return e.parsedType===xr.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:e.path,parent:e})}removeDefault(){return this._def.innerType}};RJ.create=(t,e)=>new RJ({innerType:t,typeName:aa.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...SA(e)});var TJ=class extends JA{_parse(e){const{ctx:n}=this._processInputParams(e),o={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:o.data,path:o.path,parent:{...o}});return yJ(i)?i.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new iB(o.common.issues)},input:o.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new iB(o.common.issues)},input:o.data})}}removeCatch(){return this._def.innerType}};TJ.create=(t,e)=>new TJ({innerType:t,typeName:aa.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...SA(e)});var eAe=class extends JA{_parse(e){if(this._getType(e)!==xr.nan){const n=this._getOrReturnCtx(e);return nr(n,{code:hi.invalid_type,expected:xr.nan,received:n.parsedType}),ea}return{status:"valid",value:e.data}}};eAe.create=t=>new eAe({typeName:aa.ZodNaN,...SA(t)});var Doo=Symbol("zod_brand"),_8e=class extends JA{_parse(e){const{ctx:n}=this._processInputParams(e),o=n.data;return this._def.type._parse({data:o,path:n.path,parent:n})}unwrap(){return this._def.type}},f8e=class g5n extends JA{_parse(e){const{status:n,ctx:o}=this._processInputParams(e);if(o.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:o.data,path:o.path,parent:o});return i.status==="aborted"?ea:i.status==="dirty"?(n.dirty(),jae(i.value)):this._def.out._parseAsync({data:i.value,path:o.path,parent:o})})();{const i=this._def.in._parseSync({data:o.data,path:o.path,parent:o});return i.status==="aborted"?ea:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:o.path,parent:o})}}static create(e,n){return new g5n({in:e,out:n,typeName:aa.ZodPipeline})}},kJ=class extends JA{_parse(e){const n=this._def.innerType._parse(e),o=i=>(XD(i)&&(i.value=Object.freeze(i.value)),i);return yJ(n)?n.then(i=>o(i)):o(n)}unwrap(){return this._def.innerType}};function WCt(t,e){const n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function jCt(t,e={},n){return t?bL.create().superRefine((o,i)=>{const r=t(o);if(r instanceof Promise)return r.then(s=>{if(!s){const a=WCt(e,o),A=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:A})}});if(!r){const s=WCt(e,o),a=s.fatal??n??!0;i.addIssue({code:"custom",...s,fatal:a})}}):bL.create()}kJ.create=(t,e)=>new kJ({innerType:t,typeName:aa.ZodReadonly,...SA(e)});var aa,Yc,Noo={object:H5.lazycreate};(Yc=aa||(aa={})).ZodString="ZodString",Yc.ZodNumber="ZodNumber",Yc.ZodNaN="ZodNaN",Yc.ZodBigInt="ZodBigInt",Yc.ZodBoolean="ZodBoolean",Yc.ZodDate="ZodDate",Yc.ZodSymbol="ZodSymbol",Yc.ZodUndefined="ZodUndefined",Yc.ZodNull="ZodNull",Yc.ZodAny="ZodAny",Yc.ZodUnknown="ZodUnknown",Yc.ZodNever="ZodNever",Yc.ZodVoid="ZodVoid",Yc.ZodArray="ZodArray",Yc.ZodObject="ZodObject",Yc.ZodUnion="ZodUnion",Yc.ZodDiscriminatedUnion="ZodDiscriminatedUnion",Yc.ZodIntersection="ZodIntersection",Yc.ZodTuple="ZodTuple",Yc.ZodRecord="ZodRecord",Yc.ZodMap="ZodMap",Yc.ZodSet="ZodSet",Yc.ZodFunction="ZodFunction",Yc.ZodLazy="ZodLazy",Yc.ZodLiteral="ZodLiteral",Yc.ZodEnum="ZodEnum",Yc.ZodEffects="ZodEffects",Yc.ZodNativeEnum="ZodNativeEnum",Yc.ZodOptional="ZodOptional",Yc.ZodNullable="ZodNullable",Yc.ZodDefault="ZodDefault",Yc.ZodCatch="ZodCatch",Yc.ZodPromise="ZodPromise",Yc.ZodBranded="ZodBranded",Yc.ZodPipeline="ZodPipeline",Yc.ZodReadonly="ZodReadonly";var Roo=(t,e={message:`Input not instance of ${t.name}`})=>jCt(n=>n instanceof t,e),$Ct=BL.create,qCt=xJ.create,Too=eAe.create,koo=EJ.create,XCt=BJ.create,Foo=bJ.create,Loo=$ae.create,Hoo=SJ.create,Ooo=QJ.create,Goo=bL.create,Yoo=ZD.create,Uoo=eb.create,Koo=qae.create,Voo=eN.create,zoo=H5.create,Joo=H5.strictCreate,Woo=vJ.create,joo=KCt.create,$oo=wJ.create,qoo=cv.create,Xoo=VCt.create,Zoo=Xae.create,eio=Zae.create,tio=zCt.create,nio=PJ.create,oio=MJ.create,iio=DJ.create,rio=NJ.create,sio=QL.create,ZCt=rB.create,aio=m7.create,Aio=lv.create,cio=rB.createWithPreprocess,lio=f8e.create,uio=()=>$Ct().optional(),gio=()=>qCt().optional(),dio=()=>XCt().optional(),hio={string:t=>BL.create({...t,coerce:!0}),number:t=>xJ.create({...t,coerce:!0}),boolean:t=>BJ.create({...t,coerce:!0}),bigint:t=>EJ.create({...t,coerce:!0}),date:t=>bJ.create({...t,coerce:!0})},pio=ea,tAe=N.string().or(N.number()).transform(t=>L5(t,"Ω").value),I8e=N.string().or(N.number()).transform(t=>L5(t,"F").value).transform(t=>Number.parseFloat(t.toPrecision(12))),eyt=N.string().or(N.number()).transform(t=>L5(t,"H").value),tb=N.string().or(N.number()).transform(t=>L5(t,"V").value),Di=N.string().or(N.number()).transform(t=>L5(t).value),tN=N.string().or(N.number()).transform(t=>L5(t,"Hz").value),ao=Di,vL=N.string().or(N.number()).transform(t=>L5(t,"A").value),wL=N.string().or(N.number()).transform(t=>L5(t).value),mio=wL,J_=wL,tyt=N.string().datetime(),im=N.string().or(N.number()).transform(t=>typeof t=="number"?t:t.endsWith("deg")?Number.parseFloat(t.split("deg")[0]):t.endsWith("rad")?180*Number.parseFloat(t.split("rad")[0])/Math.PI:Number.parseFloat(t)),nyt=N.number().or(N.string().endsWith("mAh")).transform(t=>{if(typeof t=="string"){const e=t.replace("mAh",""),n=Number.parseFloat(e);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return t}).describe("Battery capacity in mAh"),_r=N.object({x:ao,y:ao}),_io=_r,nb=N.object({x:ao,y:ao,z:ao}),fio=nb,C8e=N.object({width:N.number(),height:N.number()}),So=t=>N.string().optional().default(()=>`${t}_${(e=>{const n="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:e},()=>n[Math.floor(62*Math.random())]).join("")})(10)}`),ob=N.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Iio=N.enum(["top_silkscreen","bottom_silkscreen","top_copper","bottom_copper","top_soldermask","bottom_soldermask","top_fabrication_note","bottom_fabrication_note","top_user_note","bottom_user_note","top_courtyard","bottom_courtyard","inner1_copper","inner2_copper","inner3_copper","inner4_copper","inner5_copper","inner6_copper","inner7_copper","inner8_copper","edge_cuts","drill"]),y8e=N.object({project_relative_path:N.string(),url:N.string(),mimetype:N.string()}),nAe=_r.extend({rotation:im.optional()}),x8e=N.object({size:_r.optional(),thickness:ao.optional()}),oyt=N.object({font:x8e.optional()}),FJ=N.object({value:N.string(),at:nAe.optional(),layer:N.string().optional(),uuid:N.string().optional(),hide:N.boolean().optional(),effects:oyt.optional()}),iyt=N.object({Reference:FJ.optional(),Value:FJ.optional(),Datasheet:FJ.optional(),Description:FJ.optional()}),ryt=N.object({through_hole:N.boolean().optional(),smd:N.boolean().optional(),exclude_from_pos_files:N.boolean().optional(),exclude_from_bom:N.boolean().optional()}),syt=N.object({name:N.string(),type:N.string(),shape:N.string().optional(),at:nAe.optional(),size:_r.optional(),drill:ao.optional(),layers:N.array(N.string()).optional(),removeUnusedLayers:N.boolean().optional(),uuid:N.string().optional()}),ayt=N.object({path:N.string(),offset:nb.optional(),scale:nb.optional(),rotate:nb.optional()}),Ayt=N.object({footprintName:N.string().optional(),version:N.union([N.number(),N.string()]).optional(),generator:N.string().optional(),generatorVersion:N.union([N.number(),N.string()]).optional(),layer:N.string().optional(),properties:iyt.optional(),attributes:ryt.optional(),pads:N.array(syt).optional(),embeddedFonts:N.boolean().optional(),model:ayt.optional()}),cyt=N.object({hide:N.boolean().optional()}),lyt=N.object({offset:ao.optional(),hide:N.boolean().optional()}),uyt=N.object({font:x8e.optional(),justify:N.union([N.string(),N.array(N.string())]).optional(),hide:N.boolean().optional()}),uv=N.object({value:N.string(),id:N.union([N.number(),N.string()]).optional(),at:nAe.optional(),effects:uyt.optional()}),gyt=N.object({Reference:uv.optional(),Value:uv.optional(),Footprint:uv.optional(),Datasheet:uv.optional(),Description:uv.optional(),ki_keywords:uv.optional(),ki_fp_filters:uv.optional()}),dyt=N.object({symbolName:N.string().optional(),extends:N.string().optional(),pinNumbers:cyt.optional(),pinNames:lyt.optional(),excludeFromSim:N.boolean().optional(),inBom:N.boolean().optional(),onBoard:N.boolean().optional(),properties:gyt.optional(),embeddedFonts:N.boolean().optional()}),Wl=N.object({error_type:N.string(),message:N.string(),is_fatal:N.boolean().optional()}),oAe=N.enum(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]),vu=N.object({type:N.literal("source_component"),ftype:N.string().optional(),source_component_id:N.string(),name:N.string(),manufacturer_part_number:N.string().optional(),supplier_part_numbers:N.record(oAe,N.array(N.string())).optional(),display_value:N.string().optional(),display_name:N.string().optional(),are_pins_interchangeable:N.boolean().optional(),internally_connected_source_port_ids:N.array(N.array(N.string())).optional(),source_group_id:N.string().optional(),subcircuit_id:N.string().optional()}),E8e=vu.extend({ftype:N.literal("simple_capacitor"),capacitance:I8e,max_voltage_rating:tb.optional(),display_capacitance:N.string().optional(),max_decoupling_trace_length:ao.optional()}),B8e=vu.extend({ftype:N.literal("simple_resistor"),resistance:tAe,display_resistance:N.string().optional()}),iAe=vu.extend({ftype:N.literal("simple_diode")}),hyt=vu.extend({ftype:N.literal("simple_fiducial")}),b8e=iAe.extend({ftype:N.literal("simple_led"),color:N.string().optional(),wavelength:N.string().optional()}),pyt=vu.extend({ftype:N.literal("simple_ground")}),S8e=vu.extend({ftype:N.literal("simple_chip")}),Q8e=vu.extend({ftype:N.literal("simple_power_source"),voltage:tb}),myt=vu.extend({ftype:N.literal("simple_current_source"),current:vL,frequency:tN.optional(),peak_to_peak_current:vL.optional(),wave_shape:N.enum(["sine","square","triangle","sawtooth","dc"]).optional().default("dc"),phase:N.number().optional(),duty_cycle:N.number().min(0).max(1).optional()}),_yt=vu.extend({ftype:N.literal("simple_fuse"),current_rating_amps:N.number().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:N.number().describe("Voltage rating in volts, e.g. ±5V would be 5")}),fyt=vu.extend({ftype:N.literal("simple_ammeter")}),Iyt=N.object({must_be_connected:N.boolean().optional(),provides_power:N.boolean().optional(),requires_power:N.boolean().optional(),provides_ground:N.boolean().optional(),requires_ground:N.boolean().optional(),provides_voltage:N.union([N.string(),N.number()]).optional(),requires_voltage:N.union([N.string(),N.number()]).optional(),do_not_connect:N.boolean().optional(),include_in_board_pinout:N.boolean().optional(),can_use_internal_pullup:N.boolean().optional(),is_using_internal_pullup:N.boolean().optional(),needs_external_pullup:N.boolean().optional(),can_use_internal_pulldown:N.boolean().optional(),is_using_internal_pulldown:N.boolean().optional(),needs_external_pulldown:N.boolean().optional(),can_use_open_drain:N.boolean().optional(),is_using_open_drain:N.boolean().optional(),can_use_push_pull:N.boolean().optional(),is_using_push_pull:N.boolean().optional(),should_have_decoupling_capacitor:N.boolean().optional(),recommended_decoupling_capacitor_capacitance:N.union([N.string(),N.number()]).optional(),is_configured_for_i2c_sda:N.boolean().optional(),is_configured_for_i2c_scl:N.boolean().optional(),is_configured_for_spi_mosi:N.boolean().optional(),is_configured_for_spi_miso:N.boolean().optional(),is_configured_for_spi_sck:N.boolean().optional(),is_configured_for_spi_cs:N.boolean().optional(),is_configured_for_uart_tx:N.boolean().optional(),is_configured_for_uart_rx:N.boolean().optional(),supports_i2c_sda:N.boolean().optional(),supports_i2c_scl:N.boolean().optional(),supports_spi_mosi:N.boolean().optional(),supports_spi_miso:N.boolean().optional(),supports_spi_sck:N.boolean().optional(),supports_spi_cs:N.boolean().optional(),supports_uart_tx:N.boolean().optional(),supports_uart_rx:N.boolean().optional()}),v8e=vu.extend({ftype:N.literal("simple_battery"),capacity:nyt}),w8e=vu.extend({ftype:N.literal("simple_inductor"),inductance:eyt,display_inductance:N.string().optional(),max_current_rating:N.number().optional()}),P8e=vu.extend({ftype:N.literal("simple_push_button")}),M8e=vu.extend({ftype:N.literal("simple_potentiometer"),max_resistance:tAe,display_max_resistance:N.string().optional()}),Cyt=vu.extend({ftype:N.literal("simple_crystal"),frequency:N.number().describe("Frequency in Hz"),load_capacitance:N.number().optional().describe("Load capacitance in pF"),pin_variant:N.enum(["two_pin","four_pin"]).optional()}),D8e=vu.extend({ftype:N.literal("simple_pin_header"),pin_count:N.number(),gender:N.enum(["male","female"]).optional().default("male")}),yyt=vu.extend({ftype:N.literal("simple_connector"),standard:N.enum(["usb_c","m2"]).optional()}),N8e=vu.extend({ftype:N.literal("simple_pinout")}),R8e=vu.extend({ftype:N.literal("simple_resonator"),load_capacitance:I8e,equivalent_series_resistance:tAe.optional(),frequency:tN}),T8e=vu.extend({ftype:N.literal("simple_transistor"),transistor_type:N.enum(["npn","pnp"])}),k8e=vu.extend({ftype:N.literal("simple_test_point"),footprint_variant:N.enum(["pad","through_hole"]).optional(),pad_shape:N.enum(["rect","circle"]).optional(),pad_diameter:N.union([N.number(),N.string()]).optional(),hole_diameter:N.union([N.number(),N.string()]).optional(),width:N.union([N.number(),N.string()]).optional(),height:N.union([N.number(),N.string()]).optional()}),F8e=vu.extend({ftype:N.literal("simple_mosfet"),channel_type:N.enum(["n","p"]),mosfet_mode:N.enum(["enhancement","depletion"])}),L8e=vu.extend({ftype:N.literal("simple_op_amp")}),H8e=vu.extend({ftype:N.literal("simple_switch")}),O8e=N.object({type:N.literal("source_project_metadata"),name:N.string().optional(),software_used_string:N.string().optional(),project_url:N.string().optional(),source_filesystem_md5_hash:N.string().optional(),created_at:tyt.optional()}),xyt=Wl.extend({type:N.literal("source_missing_property_error"),source_missing_property_error_id:So("source_missing_property_error"),source_component_id:N.string(),property_name:N.string(),subcircuit_id:N.string().optional(),error_type:N.literal("source_missing_property_error").default("source_missing_property_error")}).describe("The source code is missing a property"),Eyt=Wl.extend({type:N.literal("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:So("source_failed_to_create_component_error"),error_type:N.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:N.string().optional(),subcircuit_id:N.string().optional(),parent_source_component_id:N.string().optional(),pcb_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),schematic_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional()}).describe("Error emitted when a component fails to be constructed"),G8e=Wl.extend({type:N.literal("source_invalid_component_property_error"),source_invalid_component_property_error_id:So("source_invalid_component_property_error"),source_component_id:N.string(),property_name:N.string(),property_value:N.unknown().optional(),expected_format:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal("source_invalid_component_property_error").default("source_invalid_component_property_error")}).describe("The source component property is invalid"),Y8e=Wl.extend({type:N.literal("source_trace_not_connected_error"),source_trace_not_connected_error_id:So("source_trace_not_connected_error"),error_type:N.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"),subcircuit_id:N.string().optional(),source_group_id:N.string().optional(),source_trace_id:N.string().optional(),connected_source_port_ids:N.array(N.string()).optional(),selectors_not_found:N.array(N.string()).optional()}).describe("Occurs when a source trace selector does not match any ports"),Byt=N.object({type:N.literal("source_property_ignored_warning"),source_property_ignored_warning_id:So("source_property_ignored_warning"),source_component_id:N.string(),property_name:N.string(),subcircuit_id:N.string().optional(),error_type:N.literal("source_property_ignored_warning").default("source_property_ignored_warning"),message:N.string()}).describe("The source property was ignored"),U8e=N.object({type:N.literal("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:So("source_pin_missing_trace_warning"),warning_type:N.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:N.string(),source_component_id:N.string(),source_port_id:N.string(),subcircuit_id:N.string().optional()}).describe("Warning emitted when a source component pin is missing a trace connection"),K8e=N.object({type:N.literal("source_missing_manufacturer_part_number_warning"),source_missing_manufacturer_part_number_warning_id:So("source_missing_manufacturer_part_number_warning"),warning_type:N.literal("source_missing_manufacturer_part_number_warning").default("source_missing_manufacturer_part_number_warning"),message:N.string(),source_component_id:N.string(),standard:N.string(),subcircuit_id:N.string().optional()}).describe("Warning emitted when a standard connector is missing manufacturer part number"),V8e=N.object({type:N.literal("source_refdes_convention_warning"),source_refdes_convention_warning_id:So("source_refdes_convention_warning"),warning_type:N.literal("source_refdes_convention_warning").default("source_refdes_convention_warning"),message:N.string(),source_component_id:N.string(),refdes:N.string(),source_component_ftype:N.string(),expected_prefixes:N.array(N.string()),actual_prefix:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Warning emitted when a source component reference designator does not match the component type convention"),byt=vu.extend({ftype:N.literal("simple_voltage_probe")}),Syt=vu.extend({ftype:N.literal("interconnect")}),z8e=Wl.extend({type:N.literal("source_i2c_misconfigured_error"),source_i2c_misconfigured_error_id:So("source_i2c_misconfigured_error"),error_type:N.literal("source_i2c_misconfigured_error").default("source_i2c_misconfigured_error"),source_port_ids:N.array(N.string())}).describe("Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net"),J8e=Wl.extend({type:N.literal("source_component_misconfigured_error"),source_component_misconfigured_error_id:So("source_component_misconfigured_error"),error_type:N.literal("source_component_misconfigured_error").default("source_component_misconfigured_error"),source_component_ids:N.array(N.string()),source_port_ids:N.array(N.string()).optional()}).describe("Error emitted when one or more source components have an invalid or conflicting configuration"),Qyt=vu.extend({ftype:N.literal("simple_voltage_source"),voltage:tb,frequency:tN.optional(),peak_to_peak_voltage:tb.optional(),wave_shape:N.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:im.optional(),duty_cycle:N.number().optional().describe("Duty cycle as a fraction (0 to 1)"),pulse_delay:J_.optional(),rise_time:J_.optional(),fall_time:J_.optional(),pulse_width:J_.optional(),period:J_.optional()}),vyt=N.union([B8e,E8e,iAe,hyt,b8e,pyt,S8e,Q8e,myt,fyt,v8e,w8e,P8e,M8e,Cyt,D8e,yyt,N8e,R8e,H8e,T8e,k8e,F8e,L8e,_yt,byt,Syt,Qyt,O8e,xyt,G8e,Eyt,Y8e,Byt,U8e,K8e,V8e,z8e,J8e]),wyt=N.object({type:N.literal("source_port"),pin_number:N.number().optional(),port_hints:N.array(N.string()).optional(),name:N.string(),source_port_id:N.string(),source_component_id:N.string().optional(),source_group_id:N.string().optional(),most_frequently_referenced_by_name:N.string().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}).merge(Iyt),Pyt=N.object({type:N.literal("source_component_internal_connection"),source_component_internal_connection_id:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}),Myt=N.object({type:N.literal("source_trace"),source_trace_id:N.string(),connected_source_port_ids:N.array(N.string()),connected_source_net_ids:N.array(N.string()),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),max_length:N.number().optional(),name:N.string().optional(),min_trace_thickness:N.number().optional(),display_name:N.string().optional()}),Dyt=N.object({type:N.literal("source_group"),source_group_id:N.string(),subcircuit_id:N.string().optional(),parent_subcircuit_id:N.string().optional(),parent_source_group_id:N.string().optional(),is_subcircuit:N.boolean().optional(),show_as_schematic_box:N.boolean().optional(),name:N.string().optional(),was_automatically_named:N.boolean().optional()}),Nyt=N.object({type:N.literal("source_net"),source_net_id:N.string(),name:N.string(),member_source_group_ids:N.array(N.string()),is_power:N.boolean().optional(),is_ground:N.boolean().optional(),is_digital_signal:N.boolean().optional(),is_analog_signal:N.boolean().optional(),is_positive_voltage_source:N.boolean().optional(),trace_width:N.number().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}),Ryt=N.object({type:N.literal("source_board"),source_board_id:N.string(),source_group_id:N.string(),title:N.string().optional()}).describe("Defines a board in the source domain"),Tyt=Wl.extend({type:N.literal("source_ambiguous_port_reference"),source_ambiguous_port_reference_id:So("source_ambiguous_port_reference"),error_type:N.literal("source_ambiguous_port_reference").default("source_ambiguous_port_reference"),source_port_id:N.string().optional(),source_component_id:N.string().optional()}).describe("Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous"),kyt=N.object({type:N.literal("source_pcb_ground_plane"),source_pcb_ground_plane_id:N.string(),source_group_id:N.string(),source_net_id:N.string(),subcircuit_id:N.string().optional()}).describe("Defines a ground plane in the source domain"),LJ=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6","inner7","inner8"],W8e=N.enum(LJ),WA=W8e.or(N.object({name:W8e})).transform(t=>typeof t=="string"?t:t.name),W_=N.enum(["top","bottom"]),Fyt=N.object({type:N.literal("source_manually_placed_via"),source_manually_placed_via_id:N.string(),source_group_id:N.string(),source_net_id:N.string(),subcircuit_id:N.string().optional(),source_trace_id:N.string().optional()}).describe("Defines a via that is manually placed in the source domain"),Lyt=N.object({type:N.literal("source_unnamed_trace_warning"),source_unnamed_trace_warning_id:So("source_unnamed_trace_warning"),warning_type:N.literal("source_unnamed_trace_warning").default("source_unnamed_trace_warning"),message:N.string(),source_trace_id:N.string(),subcircuit_id:N.string().optional()}).describe("Warning emitted when a source trace is missing a name"),Hyt=N.object({type:N.literal("source_no_power_pin_defined_warning"),source_no_power_pin_defined_warning_id:So("source_no_power_pin_defined_warning"),warning_type:N.literal("source_no_power_pin_defined_warning").default("source_no_power_pin_defined_warning"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Warning emitted when a chip has no source ports with requires_power=true"),Oyt=N.object({type:N.literal("source_no_ground_pin_defined_warning"),source_no_ground_pin_defined_warning_id:So("source_no_ground_pin_defined_warning"),warning_type:N.literal("source_no_ground_pin_defined_warning").default("source_no_ground_pin_defined_warning"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Warning emitted when a chip has no source ports marked as ground pins"),Gyt=N.object({type:N.literal("source_component_pins_underspecified_warning"),source_component_pins_underspecified_warning_id:So("source_component_pins_underspecified_warning"),warning_type:N.literal("source_component_pins_underspecified_warning").default("source_component_pins_underspecified_warning"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Warning emitted when all ports on a source component are underspecified"),Yyt=Wl.extend({type:N.literal("source_pin_must_be_connected_error"),source_pin_must_be_connected_error_id:So("source_pin_must_be_connected_error"),error_type:N.literal("source_pin_must_be_connected_error").default("source_pin_must_be_connected_error"),source_component_id:N.string(),source_port_id:N.string(),subcircuit_id:N.string().optional()}).describe("Error emitted when a pin with mustBeConnected attribute is not connected to any trace"),Uyt=Wl.extend({type:N.literal("unknown_error_finding_part"),unknown_error_finding_part_id:So("unknown_error_finding_part"),error_type:N.literal("unknown_error_finding_part").default("unknown_error_finding_part"),source_component_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when an unexpected error occurs while finding a part"),Kyt=N.object({type:N.literal("source_part_not_found_warning"),source_part_not_found_warning_id:So("source_part_not_found_warning"),warning_type:N.literal("source_part_not_found_warning").default("source_part_not_found_warning"),message:N.string(),source_component_id:N.string().optional(),subcircuit_id:N.string().optional(),supplier_name:oAe.optional(),manufacturer_part_number:N.string().optional(),supplier_part_number:N.string().optional(),part_name:N.string().optional()}).describe("Warning emitted when a requested part can not be found"),Vyt=N.object({type:N.literal("schematic_box"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),width:ao,height:ao,is_dashed:N.boolean().default(!1),x:ao,y:ao,subcircuit_id:N.string().optional()}).describe("Draws a box on the schematic"),zyt=N.object({type:N.literal("schematic_path"),schematic_path_id:So("schematic_path"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),fill_color:N.string().optional(),is_filled:N.boolean().optional(),is_dashed:N.boolean().default(!1),stroke_width:ao.nullable().optional(),stroke_color:N.string().optional(),dash_length:ao.optional(),dash_gap:ao.optional(),points:N.array(_r),subcircuit_id:N.string().optional()}),Jyt=N.record(N.object({left_margin:Di.optional(),right_margin:Di.optional(),top_margin:Di.optional(),bottom_margin:Di.optional()})),Wyt=N.object({left_size:N.number(),right_size:N.number(),top_size:N.number().optional(),bottom_size:N.number().optional()}),jyt=N.object({left_side:N.object({pins:N.array(N.number()),direction:N.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:N.object({pins:N.array(N.number()),direction:N.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:N.object({pins:N.array(N.number()),direction:N.enum(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:N.object({pins:N.array(N.number()),direction:N.enum(["left-to-right","right-to-left"]).optional()}).optional()}),$yt=N.union([Wyt,jyt]),qyt=N.object({type:N.literal("schematic_component"),size:C8e,center:_r,source_component_id:N.string().optional(),schematic_component_id:N.string(),schematic_sheet_id:N.string().optional(),schematic_symbol_id:N.string().optional(),pin_spacing:Di.optional(),pin_styles:Jyt.optional(),box_width:Di.optional(),symbol_name:N.string().optional(),port_arrangement:$yt.optional(),port_labels:N.record(N.string()).optional(),symbol_display_value:N.string().optional(),subcircuit_id:N.string().optional(),schematic_group_id:N.string().optional(),is_schematic_group:N.boolean().optional(),source_group_id:N.string().optional(),is_box_with_pins:N.boolean().optional().default(!0)}),Cio=N.object({kicad_symbol:dyt.optional()}).catchall(N.unknown()),Xyt=N.object({type:N.literal("schematic_symbol"),schematic_symbol_id:N.string(),name:N.string().optional(),metadata:Cio.optional()}).describe("Defines a named schematic symbol that can be referenced by components."),Zyt=N.object({type:N.literal("schematic_line"),schematic_line_id:So("schematic_line"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),x1:ao,y1:ao,x2:ao,y2:ao,stroke_width:ao.nullable().optional(),color:N.string().default("#000000"),is_dashed:N.boolean().default(!1),dash_length:ao.optional(),dash_gap:ao.optional(),subcircuit_id:N.string().optional()}).describe("Draws a styled line on the schematic"),e2t=N.object({type:N.literal("schematic_rect"),schematic_rect_id:So("schematic_rect"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:_r,width:ao,height:ao,rotation:im.default(0),stroke_width:ao.nullable().optional(),color:N.string().default("#000000"),is_filled:N.boolean().default(!1),fill_color:N.string().optional(),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe("Draws a styled rectangle on the schematic"),t2t=N.object({type:N.literal("schematic_circle"),schematic_circle_id:So("schematic_circle"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:_r,radius:ao,stroke_width:ao.nullable().optional(),color:N.string().default("#000000"),is_filled:N.boolean().default(!1),fill_color:N.string().optional(),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe("Draws a styled circle on the schematic"),n2t=N.object({type:N.literal("schematic_arc"),schematic_arc_id:So("schematic_arc"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:_r,radius:ao,start_angle_degrees:im,end_angle_degrees:im,direction:N.enum(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:ao.nullable().optional(),color:N.string().default("#000000"),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe("Draws a styled arc on the schematic"),o2t=N.object({type:N.literal("schematic_trace"),schematic_trace_id:N.string(),schematic_sheet_id:N.string().optional(),source_trace_id:N.string().optional(),junctions:N.array(N.object({x:N.number(),y:N.number()})),edges:N.array(N.object({from:N.object({x:N.number(),y:N.number()}),to:N.object({x:N.number(),y:N.number()}),is_crossing:N.boolean().optional(),from_schematic_port_id:N.string().optional(),to_schematic_port_id:N.string().optional()})),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}),yio=N.enum(["center","left","right","top","bottom"]),i2t=N.object({type:N.literal("schematic_text"),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),schematic_text_id:N.string(),text:N.string(),font_size:N.number().default(.18),position:N.object({x:ao,y:ao}),rotation:N.number().default(0),anchor:N.union([yio.describe("legacy"),ob]).default("center"),color:N.string().default("#000000"),subcircuit_id:N.string().optional()}),r2t=N.object({type:N.literal("schematic_port"),schematic_port_id:N.string(),source_port_id:N.string(),schematic_sheet_id:N.string().optional(),schematic_component_id:N.string().optional(),center:_r,facing_direction:N.enum(["up","down","left","right"]).optional(),distance_from_component_edge:N.number().optional(),side_of_component:N.enum(["top","bottom","left","right"]).optional(),true_ccw_index:N.number().optional(),pin_number:N.number().optional(),display_pin_label:N.string().optional(),subcircuit_id:N.string().optional(),is_connected:N.boolean().optional(),has_input_arrow:N.boolean().optional(),has_output_arrow:N.boolean().optional(),is_drawn_with_inversion_circle:N.boolean().optional()}).describe("Defines a port on a schematic component"),s2t=N.object({type:N.literal("schematic_net_label"),schematic_net_label_id:So("schematic_net_label"),schematic_sheet_id:N.string().optional(),schematic_trace_id:N.string().optional(),source_trace_id:N.string().optional(),source_net_id:N.string(),center:_r,anchor_position:_r.optional(),anchor_side:N.enum(["top","bottom","left","right"]),text:N.string(),symbol_name:N.string().optional(),is_movable:N.boolean().optional(),subcircuit_id:N.string().optional()}),a2t=Wl.extend({type:N.literal("schematic_error"),schematic_error_id:N.string(),error_type:N.literal("schematic_port_not_found").default("schematic_port_not_found"),subcircuit_id:N.string().optional()}).describe("Defines a schematic error on the schematic"),A2t=Wl.extend({type:N.literal("schematic_layout_error"),schematic_layout_error_id:So("schematic_layout_error"),error_type:N.literal("schematic_layout_error").default("schematic_layout_error"),source_group_id:N.string(),schematic_group_id:N.string(),subcircuit_id:N.string().optional()}).describe("Error emitted when schematic layout fails for a group"),rAe=N.object({type:N.literal("schematic_debug_object"),label:N.string().optional(),subcircuit_id:N.string().optional()}),c2t=rAe.extend({shape:N.literal("rect"),center:_r,size:C8e}),l2t=rAe.extend({shape:N.literal("line"),start:_r,end:_r}),u2t=rAe.extend({shape:N.literal("point"),center:_r}),g2t=N.discriminatedUnion("shape",[c2t,l2t,u2t]),d2t=N.object({type:N.literal("schematic_voltage_probe"),schematic_voltage_probe_id:N.string(),schematic_sheet_id:N.string().optional(),source_component_id:N.string().optional(),name:N.string().optional(),position:_r,schematic_trace_id:N.string(),voltage:tb.optional(),subcircuit_id:N.string().optional(),color:N.string().optional(),label_alignment:ob.optional()}).describe("Defines a voltage probe measurement point on a schematic trace"),h2t=N.object({type:N.literal("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:So("schematic_manual_edit_conflict_warning"),warning_type:N.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:N.string(),schematic_component_id:N.string(),schematic_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_component_id:N.string()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates"),p2t=N.object({type:N.literal("schematic_group"),schematic_group_id:So("schematic_group"),schematic_sheet_id:N.string().optional(),source_group_id:N.string(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),width:Di,height:Di,center:_r,schematic_component_ids:N.array(N.string()),show_as_schematic_box:N.boolean().optional(),name:N.string().optional(),description:N.string().optional()}).describe("Defines a group of components on the schematic"),m2t=N.object({type:N.literal("schematic_table"),schematic_table_id:So("schematic_table"),schematic_sheet_id:N.string().optional(),anchor_position:_r,column_widths:N.array(ao),row_heights:N.array(ao),cell_padding:ao.optional(),border_width:ao.optional(),subcircuit_id:N.string().optional(),schematic_component_id:N.string().optional(),anchor:ob.optional()}).describe("Defines a table on the schematic"),_2t=N.object({type:N.literal("schematic_table_cell"),schematic_table_cell_id:So("schematic_table_cell"),schematic_sheet_id:N.string().optional(),schematic_table_id:N.string(),start_row_index:N.number(),end_row_index:N.number(),start_column_index:N.number(),end_column_index:N.number(),text:N.string().optional(),center:_r,width:ao,height:ao,horizontal_align:N.enum(["left","center","right"]).optional(),vertical_align:N.enum(["top","middle","bottom"]).optional(),font_size:ao.optional(),subcircuit_id:N.string().optional()}).describe("Defines a cell within a schematic_table"),f2t=N.object({type:N.literal("schematic_sheet"),schematic_sheet_id:So("schematic_sheet"),name:N.string().optional(),sheet_index:N.number().optional(),subcircuit_id:N.string().optional(),outline_color:N.string().optional()}).describe("Defines a schematic sheet or page that components can be placed on"),I2t=N.object({x:ao,y:ao,bulge:N.number().optional()}),j8e=N.object({vertices:N.array(I2t)}),$8e=N.object({outer_ring:j8e,inner_rings:N.array(j8e).default([])}),C2t=N.object({x:ao,y:ao,via:N.boolean().optional(),via_to_layer:WA.optional()}),xio=N.array(C2t),y2t=N.object({x:ao,y:ao,via:N.boolean().optional(),to_layer:WA.optional(),trace_width:ao.optional()}),x2t=N.object({min_trace_width:Di.optional(),min_board_edge_clearance:Di.optional(),min_via_hole_edge_to_via_hole_edge_clearance:Di.optional(),min_plated_hole_drill_edge_to_drill_edge_clearance:Di.optional(),min_trace_to_pad_edge_clearance:Di.optional(),min_pad_edge_to_pad_edge_clearance:Di.optional(),min_same_net_trace_edge_to_trace_edge_clearance:Di.optional(),min_different_net_trace_edge_to_trace_edge_clearance:Di.optional(),min_via_edge_to_pad_edge_clearance:Di.optional(),min_via_hole_diameter:Di.optional(),min_via_pad_diameter:Di.optional()}),E2t=N.object({type:N.literal("pcb_component"),pcb_component_id:So("pcb_component"),source_component_id:N.string(),center:_r,layer:WA,rotation:im,display_offset_x:N.string().optional().describe("How to display the x offset for this part, usually corresponding with how the user specified it"),display_offset_y:N.string().optional().describe("How to display the y offset for this part, usually corresponding with how the user specified it"),width:Di,height:Di,do_not_place:N.boolean().optional(),is_allowed_to_be_off_board:N.boolean().optional(),subcircuit_id:N.string().optional(),pcb_group_id:N.string().optional(),position_mode:N.enum(["packed","relative_to_group_anchor","relative_to_another_component","none"]).optional(),anchor_position:_r.optional(),anchor_alignment:ob.optional(),positioned_relative_to_pcb_group_id:N.string().optional(),positioned_relative_to_pcb_board_id:N.string().optional(),cable_insertion_center:_r.optional(),insertion_direction:N.enum(["from_above","from_left","from_right","from_front","from_back"]).optional(),metadata:N.object({kicad_footprint:Ayt.optional()}).optional(),obstructs_within_bounds:N.boolean().default(!0).describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath")}).describe("Defines a component on the PCB"),B2t=N.object({type:N.literal("pcb_hole"),pcb_hole_id:So("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("circle"),hole_diameter:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Eio=B2t.describe("Defines a circular hole on the PCB"),b2t=N.object({type:N.literal("pcb_hole"),pcb_hole_id:So("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("rect"),hole_width:N.number(),hole_height:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Bio=b2t.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square."),S2t=N.object({type:N.literal("pcb_hole"),pcb_hole_id:So("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.enum(["circle","square"]),hole_diameter:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),bio=S2t.describe("Defines a circular or square hole on the PCB"),Q2t=N.object({type:N.literal("pcb_hole"),pcb_hole_id:So("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("oval"),hole_width:N.number(),hole_height:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Sio=Q2t.describe("Defines an oval hole on the PCB"),v2t=N.object({type:N.literal("pcb_hole"),pcb_hole_id:So("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("pill"),hole_width:N.number(),hole_height:N.number(),x:ao,y:ao,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Qio=v2t.describe("Defines a pill-shaped hole on the PCB"),w2t=N.object({type:N.literal("pcb_hole"),pcb_hole_id:So("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("rotated_pill"),hole_width:N.number(),hole_height:N.number(),x:ao,y:ao,ccw_rotation:im,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),vio=w2t.describe("Defines a rotated pill-shaped hole on the PCB"),P2t=S2t.or(Q2t).or(v2t).or(w2t).or(B2t).or(b2t),wio=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("circle"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),outer_diameter:N.number(),hole_diameter:N.number(),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So("pcb_plated_hole"),soldermask_margin:N.number().optional()}),Pio=N.object({type:N.literal("pcb_plated_hole"),shape:N.enum(["oval","pill"]),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),outer_width:N.number(),outer_height:N.number(),hole_width:N.number(),hole_height:N.number(),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,ccw_rotation:im,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So("pcb_plated_hole"),soldermask_margin:N.number().optional()}),Mio=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("circular_hole_with_rect_pad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal("circle"),pad_shape:N.literal("rect"),hole_diameter:N.number(),rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),hole_offset_x:ao.default(0),hole_offset_y:ao.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So("pcb_plated_hole"),soldermask_margin:N.number().optional(),rect_ccw_rotation:im.optional()}),Dio=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("pill_hole_with_rect_pad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal("pill"),pad_shape:N.literal("rect"),hole_width:N.number(),hole_height:N.number(),rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),hole_offset_x:ao.default(0),hole_offset_y:ao.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So("pcb_plated_hole"),soldermask_margin:N.number().optional()}),Nio=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("rotated_pill_hole_with_rect_pad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal("rotated_pill"),pad_shape:N.literal("rect"),hole_width:N.number(),hole_height:N.number(),hole_ccw_rotation:im,rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),rect_ccw_rotation:im,hole_offset_x:ao.default(0),hole_offset_y:ao.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So("pcb_plated_hole"),soldermask_margin:N.number().optional()}),Rio=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("hole_with_polygon_pad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.enum(["circle","oval","pill","rotated_pill"]),hole_diameter:N.number().optional(),hole_width:N.number().optional(),hole_height:N.number().optional(),pad_outline:N.array(N.object({x:ao,y:ao})).min(3),hole_offset_x:ao.default(0),hole_offset_y:ao.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ao,y:ao,layers:N.array(WA),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:So("pcb_plated_hole"),soldermask_margin:N.number().optional(),ccw_rotation:im.optional()}),M2t=N.union([wio,Pio,Mio,Dio,Nio,Rio]),D2t=N.object({type:N.literal("pcb_port"),pcb_port_id:So("pcb_port"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_port_id:N.string(),pcb_component_id:N.string().optional(),x:ao,y:ao,layers:N.array(WA),is_board_pinout:N.boolean().optional()}).describe("Defines a port on the PCB"),Tio=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("circle"),pcb_smtpad_id:So("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,radius:N.number(),layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),kio=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("rect"),pcb_smtpad_id:So("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),rect_border_radius:N.number().optional(),corner_radius:N.number().optional(),layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional(),soldermask_margin_left:N.number().optional(),soldermask_margin_top:N.number().optional(),soldermask_margin_right:N.number().optional(),soldermask_margin_bottom:N.number().optional()}),Fio=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("rotated_rect"),pcb_smtpad_id:So("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),rect_border_radius:N.number().optional(),corner_radius:N.number().optional(),ccw_rotation:im,layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional(),soldermask_margin_left:N.number().optional(),soldermask_margin_top:N.number().optional(),soldermask_margin_right:N.number().optional(),soldermask_margin_bottom:N.number().optional()}),N2t=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("pill"),pcb_smtpad_id:So("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),radius:N.number(),layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Lio=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("rotated_pill"),pcb_smtpad_id:So("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),radius:N.number(),ccw_rotation:im,layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Hio=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("polygon"),pcb_smtpad_id:So("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),points:N.array(_r),layer:WA,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),R2t=N.discriminatedUnion("shape",[Tio,kio,Fio,Lio,N2t,Hio]).describe("Defines an SMT pad on the PCB"),Oio=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("circle"),pcb_solder_paste_id:So("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,radius:N.number(),layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Gio=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("rect"),pcb_solder_paste_id:So("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Yio=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("pill"),pcb_solder_paste_id:So("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),radius:N.number(),layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Uio=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("rotated_rect"),pcb_solder_paste_id:So("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),ccw_rotation:ao,layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Kio=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("oval"),pcb_solder_paste_id:So("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ao,y:ao,width:N.number(),height:N.number(),layer:WA,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),T2t=N.union([Oio,Gio,Yio,Uio,Kio]).describe("Defines solderpaste on the PCB"),k2t=N.object({type:N.literal("pcb_text"),pcb_text_id:So("pcb_text"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),text:N.string(),center:_r,layer:WA,width:Di,height:Di,lines:N.number(),align:N.enum(["bottom-left"])}).describe("Defines text on the PCB"),F2t=N.object({route_type:N.literal("wire"),x:ao,y:ao,width:ao,copper_pour_id:N.string().optional(),is_inside_copper_pour:N.boolean().optional(),start_pcb_port_id:N.string().optional(),end_pcb_port_id:N.string().optional(),layer:WA}),L2t=N.object({route_type:N.literal("via"),x:ao,y:ao,copper_pour_id:N.string().optional(),is_inside_copper_pour:N.boolean().optional(),hole_diameter:ao.optional(),outer_diameter:ao.optional(),from_layer:WA,to_layer:WA}),H2t=N.object({route_type:N.literal("through_pad"),start:_r,end:_r,width:ao,start_layer:WA,end_layer:WA,pcb_smtpad_id:N.string().optional(),pcb_plated_hole_id:N.string().optional()}),O2t=N.union([F2t,L2t,H2t]),G2t=N.object({type:N.literal("pcb_trace"),source_trace_id:N.string().optional(),pcb_component_id:N.string().optional(),pcb_trace_id:So("pcb_trace"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),route_thickness_mode:N.enum(["constant","interpolated"]).default("constant").optional(),route_order_index:N.number().optional(),should_round_corners:N.boolean().optional(),trace_length:N.number().optional(),highlight_color:N.string().optional(),route:N.array(O2t)}).describe("Defines a trace on the PCB"),Y2t=N.object({type:N.literal("pcb_trace_warning"),pcb_trace_warning_id:So("pcb_trace_warning"),warning_type:N.literal("pcb_trace_warning").default("pcb_trace_warning"),message:N.string(),center:_r.optional(),pcb_trace_id:N.string(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines a trace warning on the PCB"),U2t=N.object({type:N.literal("pcb_trace_too_long_warning"),pcb_trace_too_long_warning_id:So("pcb_trace_too_long_warning"),warning_type:N.literal("pcb_trace_too_long_warning").default("pcb_trace_too_long_warning"),message:N.string(),pcb_trace_id:N.string(),source_net_id:N.string().optional(),source_trace_id:N.string().optional(),actual_trace_length:ao,maximum_trace_length:ao,subcircuit_id:N.string().optional()}).describe("Warning emitted when a PCB trace is longer than its maximum allowed length"),K2t=Wl.extend({type:N.literal("pcb_trace_error"),pcb_trace_error_id:So("pcb_trace_error"),error_type:N.literal("pcb_trace_error").default("pcb_trace_error"),center:_r.optional(),pcb_trace_id:N.string(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines a trace error on the PCB"),V2t=Wl.extend({type:N.literal("pcb_trace_missing_error"),pcb_trace_missing_error_id:So("pcb_trace_missing_error"),error_type:N.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"),center:_r.optional(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace"),z2t=Wl.extend({type:N.literal("pcb_port_not_matched_error"),pcb_error_id:So("pcb_error"),error_type:N.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),pcb_component_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines a trace error on the PCB where a port is not matched"),J2t=Wl.extend({type:N.literal("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:So("pcb_port_not_connected_error"),error_type:N.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),pcb_port_ids:N.array(N.string()),pcb_component_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines an error when a pcb port is not connected to any trace"),W2t=N.object({type:N.literal("pcb_net"),pcb_net_id:So("pcb_net"),source_net_id:N.string().optional(),highlight_color:N.string().optional()}).describe("Defines a net on the PCB"),j2t=N.object({type:N.literal("pcb_via"),pcb_via_id:So("pcb_via"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),x:ao,y:ao,outer_diameter:ao.default("0.6mm"),hole_diameter:ao.default("0.25mm"),from_layer:WA.optional(),to_layer:WA.optional(),layers:N.array(WA),pcb_trace_id:N.string().optional(),net_is_assignable:N.boolean().optional(),net_assigned:N.boolean().optional(),is_tented:N.boolean().optional()}).describe("Defines a via on the PCB"),$2t=N.object({type:N.literal("pcb_board"),pcb_board_id:So("pcb_board"),pcb_panel_id:N.string().optional(),carrier_pcb_board_id:N.string().optional(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),is_mounted_to_carrier_board:N.boolean().optional(),width:Di.optional(),height:Di.optional(),center:_r,display_offset_x:N.string().optional().describe("How to display the x offset for this board, usually corresponding with how the user specified it"),display_offset_y:N.string().optional().describe("How to display the y offset for this board, usually corresponding with how the user specified it"),thickness:Di.optional().default(1.4),num_layers:N.number().optional().default(4),outline:N.array(_r).optional(),shape:N.enum(["rect","polygon"]).optional(),material:N.enum(["fr4","fr1"]).default("fr4"),solder_mask_color:N.string().optional(),silkscreen_color:N.string().optional(),anchor_position:_r.optional(),anchor_alignment:ob.optional(),position_mode:N.enum(["relative_to_panel_anchor","none"]).optional()}).merge(x2t).describe("Defines the board outline of the PCB"),q2t=N.object({type:N.literal("pcb_panel"),pcb_panel_id:So("pcb_panel"),width:Di,height:Di,center:_r,thickness:Di.optional().default(1.4),covered_with_solder_mask:N.boolean().optional().default(!0)}).describe("Defines a PCB panel that can contain multiple boards"),X2t=Wl.extend({type:N.literal("pcb_placement_error"),pcb_placement_error_id:So("pcb_placement_error"),error_type:N.literal("pcb_placement_error").default("pcb_placement_error"),subcircuit_id:N.string().optional()}).describe("Defines a placement error on the PCB"),Z2t=Wl.extend({type:N.literal("pcb_panelization_placement_error"),pcb_panelization_placement_error_id:So("pcb_panelization_placement_error"),error_type:N.literal("pcb_panelization_placement_error").default("pcb_panelization_placement_error"),pcb_panel_id:N.string().optional(),pcb_board_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Defines a panelization placement error on the PCB"),ext=N.object({type:N.literal("pcb_trace_hint"),pcb_trace_hint_id:So("pcb_trace_hint"),pcb_port_id:N.string(),pcb_component_id:N.string(),route:N.array(y2t),subcircuit_id:N.string().optional()}).describe("A hint that can be used during generation of a PCB trace"),txt=N.object({type:N.literal("pcb_silkscreen_line"),pcb_silkscreen_line_id:So("pcb_silkscreen_line"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),stroke_width:ao.default("0.1mm"),x1:ao,y1:ao,x2:ao,y2:ao,layer:W_}).describe("Defines a silkscreen line on the PCB"),nxt=N.object({type:N.literal("pcb_silkscreen_path"),pcb_silkscreen_path_id:So("pcb_silkscreen_path"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,route:N.array(_r),stroke_width:Di}).describe("Defines a silkscreen path on the PCB"),oxt=N.object({type:N.literal("pcb_silkscreen_text"),pcb_silkscreen_text_id:So("pcb_silkscreen_text"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:ao.default("0.2mm"),pcb_component_id:N.string(),text:N.string(),is_knockout:N.boolean().default(!1).optional(),knockout_padding:N.object({left:Di,top:Di,bottom:Di,right:Di}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:N.number().optional(),layer:WA,is_mirrored:N.boolean().default(!1).optional(),anchor_position:_r.default({x:0,y:0}),anchor_alignment:ob.default("center")}).describe("Defines silkscreen text on the PCB"),ixt=N.object({type:N.literal("pcb_copper_text"),pcb_copper_text_id:So("pcb_copper_text"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:ao.default("0.2mm"),pcb_component_id:N.string(),text:N.string(),is_knockout:N.boolean().default(!1).optional(),knockout_padding:N.object({left:Di,top:Di,bottom:Di,right:Di}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:N.number().optional(),layer:WA,is_mirrored:N.boolean().default(!1).optional(),anchor_position:_r.default({x:0,y:0}),anchor_alignment:ob.default("center")}).describe("Defines copper text on the PCB"),rxt=N.object({type:N.literal("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:So("pcb_silkscreen_rect"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,layer:WA,stroke_width:Di.default("1mm"),corner_radius:Di.optional(),is_filled:N.boolean().default(!0).optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),ccw_rotation:N.number().optional()}).describe("Defines a silkscreen rect on the PCB"),sxt=N.object({type:N.literal("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:So("pcb_silkscreen_circle"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,radius:Di,layer:W_,stroke_width:Di.default("1mm"),is_filled:N.boolean().optional()}).describe("Defines a silkscreen circle on the PCB"),axt=N.object({type:N.literal("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:So("pcb_silkscreen_oval"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,radius_x:ao,radius_y:ao,layer:W_,ccw_rotation:im.optional()}).describe("Defines a silkscreen oval on the PCB"),Axt=N.object({type:N.literal("pcb_silkscreen_graphic"),pcb_silkscreen_graphic_id:So("pcb_silkscreen_graphic"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,image_asset:y8e.optional()}).extend({shape:N.literal("brep"),brep_shape:$8e}).describe("Defines a BRep silkscreen graphic on the PCB"),cxt=N.discriminatedUnion("shape",[Axt]).describe("Defines a silkscreen graphic on the PCB"),lxt=N.object({type:N.literal("pcb_silkscreen_pill"),pcb_silkscreen_pill_id:So("pcb_silkscreen_pill"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,layer:WA,ccw_rotation:N.number().optional()}).describe("Defines a silkscreen pill on the PCB"),uxt=N.object({type:N.literal("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:So("pcb_fabrication_note_text"),subcircuit_id:N.string().optional(),pcb_group_id:N.string().optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:ao.default("1mm"),pcb_component_id:N.string(),text:N.string(),ccw_rotation:N.number().optional(),layer:W_,anchor_position:_r.default({x:0,y:0}),anchor_alignment:N.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:N.string().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators"),gxt=N.object({type:N.literal("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:So("pcb_fabrication_note_path"),pcb_component_id:N.string(),subcircuit_id:N.string().optional(),layer:WA,route:N.array(_r),stroke_width:Di,color:N.string().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers"),dxt=N.object({type:N.literal("pcb_fabrication_note_rect"),pcb_fabrication_note_rect_id:So("pcb_fabrication_note_rect"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,layer:W_,stroke_width:Di.default("0.1mm"),corner_radius:Di.optional(),is_filled:N.boolean().optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),color:N.string().optional()}).describe("Defines a fabrication note rectangle on the PCB"),hxt=N.object({type:N.literal("pcb_fabrication_note_dimension"),pcb_fabrication_note_dimension_id:So("pcb_fabrication_note_dimension"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,from:_r,to:_r,text:N.string().optional(),text_ccw_rotation:N.number().optional(),offset:Di.optional(),offset_distance:Di.optional(),offset_direction:N.object({x:N.number(),y:N.number()}).optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:Di.default("1mm"),color:N.string().optional(),arrow_size:Di.default("1mm")}).describe("Defines a measurement annotation within PCB fabrication notes"),pxt=N.object({type:N.literal("pcb_note_text"),pcb_note_text_id:So("pcb_note_text"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:ao.default("1mm"),text:N.string().optional(),anchor_position:_r.default({x:0,y:0}),anchor_alignment:N.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),layer:W_.default("top"),is_mirrored_from_top_view:N.boolean().optional(),color:N.string().optional()}).describe("Defines a documentation note in text on the PCB"),mxt=N.object({type:N.literal("pcb_note_rect"),pcb_note_rect_id:So("pcb_note_rect"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),center:_r,width:Di,height:Di,layer:W_.default("top"),stroke_width:Di.default("0.1mm"),corner_radius:Di.optional(),is_filled:N.boolean().optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),color:N.string().optional()}).describe("Defines a rectangular documentation note on the PCB"),_xt=N.object({type:N.literal("pcb_note_path"),pcb_note_path_id:So("pcb_note_path"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),route:N.array(_r),layer:W_.default("top"),stroke_width:Di.default("0.1mm"),color:N.string().optional()}).describe("Defines a polyline documentation note on the PCB"),fxt=N.object({type:N.literal("pcb_note_line"),pcb_note_line_id:So("pcb_note_line"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),x1:ao,y1:ao,x2:ao,y2:ao,layer:W_.default("top"),stroke_width:ao.default("0.1mm"),color:N.string().optional(),is_dashed:N.boolean().optional()}).describe("Defines a straight documentation note line on the PCB"),Ixt=N.object({type:N.literal("pcb_note_dimension"),pcb_note_dimension_id:So("pcb_note_dimension"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),from:_r,to:_r,text:N.string().optional(),text_ccw_rotation:N.number().optional(),offset_distance:Di.optional(),offset_direction:N.object({x:N.number(),y:N.number()}).optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:Di.default("1mm"),layer:W_.default("top"),color:N.string().optional(),arrow_size:Di.default("1mm")}).describe("Defines a measurement annotation within PCB documentation notes"),Cxt=Wl.extend({type:N.literal("pcb_footprint_overlap_error"),pcb_error_id:So("pcb_error"),error_type:N.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),pcb_smtpad_ids:N.array(N.string()).optional(),pcb_plated_hole_ids:N.array(N.string()).optional(),pcb_hole_ids:N.array(N.string()).optional(),pcb_keepout_ids:N.array(N.string()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element"),yxt=Wl.extend({type:N.literal("pcb_courtyard_overlap_error"),pcb_error_id:So("pcb_error"),error_type:N.literal("pcb_courtyard_overlap_error").default("pcb_courtyard_overlap_error"),pcb_component_ids:N.tuple([N.string(),N.string()])}).describe("Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another"),xxt=N.object({type:N.literal("pcb_keepout"),shape:N.literal("rect"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:ao,height:ao,pcb_keepout_id:N.string(),layers:N.array(N.string()),description:N.string().optional()}).or(N.object({type:N.literal("pcb_keepout"),shape:N.literal("circle"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,radius:ao,pcb_keepout_id:N.string(),layers:N.array(N.string()),description:N.string().optional()})),sAe=N.object({type:N.literal("pcb_cutout"),pcb_cutout_id:So("pcb_cutout"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_board_id:N.string().optional(),pcb_panel_id:N.string().optional()}),Ext=sAe.extend({shape:N.literal("rect"),center:_r,width:Di,height:Di,rotation:im.optional(),corner_radius:Di.optional()}),Bxt=sAe.extend({shape:N.literal("circle"),center:_r,radius:Di}),bxt=sAe.extend({shape:N.literal("polygon"),points:N.array(_r)}),Sxt=sAe.extend({shape:N.literal("path"),route:N.array(_r),slot_width:Di,slot_length:Di.optional(),space_between_slots:Di.optional(),slot_corner_radius:Di.optional()}),Qxt=N.discriminatedUnion("shape",[Ext,Bxt,bxt,Sxt]).describe("Defines a cutout on the PCB, removing board material."),vxt=Wl.extend({type:N.literal("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:So("pcb_missing_footprint_error"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:N.string()}).describe("Defines a missing footprint error on the PCB"),wxt=Wl.extend({type:N.literal("external_footprint_load_error"),external_footprint_load_error_id:So("external_footprint_load_error"),pcb_component_id:N.string(),source_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),footprinter_string:N.string().optional(),error_type:N.literal("external_footprint_load_error").default("external_footprint_load_error")}).describe("Defines an error when an external footprint fails to load"),Pxt=Wl.extend({type:N.literal("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:So("circuit_json_footprint_load_error"),pcb_component_id:N.string(),source_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),circuit_json:N.array(N.any()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load"),Mxt=N.object({type:N.literal("pcb_group"),pcb_group_id:So("pcb_group"),source_group_id:N.string(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),width:Di.optional(),height:Di.optional(),center:_r,display_offset_x:N.string().optional().describe("How to display the x offset for this group, usually corresponding with how the user specified it"),display_offset_y:N.string().optional().describe("How to display the y offset for this group, usually corresponding with how the user specified it"),outline:N.array(_r).optional(),anchor_position:_r.optional(),anchor_alignment:ob.default("center"),position_mode:N.enum(["packed","relative_to_group_anchor","none"]).optional(),positioned_relative_to_pcb_group_id:N.string().optional(),positioned_relative_to_pcb_board_id:N.string().optional(),pcb_component_ids:N.array(N.string()),child_layout_mode:N.enum(["packed","none"]).optional(),name:N.string().optional(),description:N.string().optional(),layout_mode:N.string().optional(),autorouter_configuration:N.object({trace_clearance:Di}).optional(),autorouter_used_string:N.string().optional()}).describe("Defines a group of components on the PCB"),Dxt=Wl.extend({type:N.literal("pcb_autorouting_error"),pcb_error_id:So("pcb_autorouting_error"),error_type:N.literal("pcb_autorouting_error").default("pcb_autorouting_error"),subcircuit_id:N.string().optional()}).describe("The autorouting has failed to route a portion of the board"),Nxt=N.object({type:N.literal("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:So("pcb_manual_edit_conflict_warning"),warning_type:N.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:N.string(),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_component_id:N.string()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates"),Rxt=N.enum(["x-","x+","y+","y-"]),Txt=N.object({type:N.literal("pcb_connector_not_in_accessible_orientation_warning"),pcb_connector_not_in_accessible_orientation_warning_id:So("pcb_connector_not_in_accessible_orientation_warning"),warning_type:N.literal("pcb_connector_not_in_accessible_orientation_warning").default("pcb_connector_not_in_accessible_orientation_warning"),message:N.string(),pcb_component_id:N.string(),source_component_id:N.string().optional(),pcb_board_id:N.string().optional(),facing_direction:Rxt,recommended_facing_direction:Rxt,subcircuit_id:N.string().optional()}).describe("Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction"),kxt=N.object({type:N.literal("supplier_footprint_mismatch_warning"),supplier_footprint_mismatch_warning_id:So("supplier_footprint_mismatch_warning"),warning_type:N.literal("supplier_footprint_mismatch_warning").default("supplier_footprint_mismatch_warning"),message:N.string(),source_component_id:N.string(),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),supplier_name:oAe.optional(),supplier_part_number:N.string().optional(),supplier_footprint_url:N.string().optional(),footprint_copper_intersection_over_union:N.number()}).describe("Warning emitted when a supplier part footprint does not match the expected footprint"),Fxt=N.object({type:N.literal("pcb_breakout_point"),pcb_breakout_point_id:So("pcb_breakout_point"),pcb_group_id:N.string(),subcircuit_id:N.string().optional(),source_trace_id:N.string().optional(),source_port_id:N.string().optional(),source_net_id:N.string().optional(),x:ao,y:ao}).describe("Defines a routing target within a pcb_group for a source_trace or source_net"),Lxt=N.object({type:N.literal("pcb_ground_plane"),pcb_ground_plane_id:So("pcb_ground_plane"),source_pcb_ground_plane_id:N.string(),source_net_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Defines a ground plane on the PCB"),Hxt=N.object({type:N.literal("pcb_ground_plane_region"),pcb_ground_plane_region_id:So("pcb_ground_plane_region"),pcb_ground_plane_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:WA,points:N.array(_r)}).describe("Defines a polygon region of a ground plane"),Oxt=N.object({type:N.literal("pcb_thermal_spoke"),pcb_thermal_spoke_id:So("pcb_thermal_spoke"),pcb_ground_plane_id:N.string(),shape:N.string(),spoke_count:N.number(),spoke_thickness:ao,spoke_inner_diameter:ao,spoke_outer_diameter:ao,pcb_plated_hole_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Pattern for connecting a ground plane to a plated hole"),q8e=N.object({type:N.literal("pcb_copper_pour"),pcb_copper_pour_id:So("pcb_copper_pour"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:WA,source_net_id:N.string().optional(),covered_with_solder_mask:N.boolean().optional().default(!0)}),Gxt=q8e.extend({shape:N.literal("rect"),center:_r,width:Di,height:Di,rotation:im.optional()}),Yxt=q8e.extend({shape:N.literal("brep"),brep_shape:$8e}),Uxt=q8e.extend({shape:N.literal("polygon"),points:N.array(_r)}),Kxt=N.discriminatedUnion("shape",[Gxt,Yxt,Uxt]).describe("Defines a copper pour on the PCB."),Vxt=Wl.extend({type:N.literal("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:So("pcb_component_outside_board_error"),error_type:N.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),pcb_component_id:N.string(),pcb_board_id:N.string(),component_center:_r,component_bounds:N.object({min_x:N.number(),max_x:N.number(),min_y:N.number(),max_y:N.number()}),subcircuit_id:N.string().optional(),source_component_id:N.string().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries"),zxt=Wl.extend({type:N.literal("pcb_component_not_on_board_edge_error"),pcb_component_not_on_board_edge_error_id:So("pcb_component_not_on_board_edge_error"),error_type:N.literal("pcb_component_not_on_board_edge_error").default("pcb_component_not_on_board_edge_error"),pcb_component_id:N.string(),pcb_board_id:N.string(),component_center:_r,pad_to_nearest_board_edge_distance:N.number(),source_component_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when a component that must be placed on the board edge is centered away from the edge"),Jxt=Wl.extend({type:N.literal("pcb_component_invalid_layer_error"),pcb_component_invalid_layer_error_id:So("pcb_component_invalid_layer_error"),error_type:N.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"),pcb_component_id:N.string().optional(),source_component_id:N.string(),layer:WA,subcircuit_id:N.string().optional()}).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)"),Wxt=Wl.extend({type:N.literal("pcb_via_clearance_error"),pcb_error_id:So("pcb_error"),error_type:N.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"),pcb_via_ids:N.array(N.string()).min(2),minimum_clearance:ao.optional(),actual_clearance:ao.optional(),pcb_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when vias are closer than the allowed clearance"),jxt=Wl.extend({type:N.literal("pcb_via_trace_clearance_error"),pcb_via_trace_clearance_error_id:So("pcb_via_trace_clearance_error"),error_type:N.literal("pcb_via_trace_clearance_error").default("pcb_via_trace_clearance_error"),pcb_via_id:N.string(),pcb_trace_id:N.string(),minimum_clearance:ao.optional(),actual_clearance:ao.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when a via and trace are closer than the allowed clearance"),$xt=Wl.extend({type:N.literal("pcb_pad_pad_clearance_error"),pcb_pad_pad_clearance_error_id:So("pcb_pad_pad_clearance_error"),error_type:N.literal("pcb_pad_pad_clearance_error").default("pcb_pad_pad_clearance_error"),pcb_pad_ids:N.array(N.string()).min(2),minimum_clearance:ao.optional(),actual_clearance:ao.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when pads are closer than the allowed clearance"),qxt=Wl.extend({type:N.literal("pcb_pad_trace_clearance_error"),pcb_pad_trace_clearance_error_id:So("pcb_pad_trace_clearance_error"),error_type:N.literal("pcb_pad_trace_clearance_error").default("pcb_pad_trace_clearance_error"),pcb_pad_id:N.string(),pcb_trace_id:N.string(),minimum_clearance:ao.optional(),actual_clearance:ao.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when a pad and trace are closer than allowed clearance"),Xxt=N.object({type:N.literal("pcb_courtyard_rect"),pcb_courtyard_rect_id:So("pcb_courtyard_rect"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,layer:W_,ccw_rotation:im.optional(),color:N.string().optional()}).describe("Defines a courtyard rectangle on the PCB"),Zxt=N.object({type:N.literal("pcb_courtyard_outline"),pcb_courtyard_outline_id:So("pcb_courtyard_outline"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,outline:N.array(_r).min(2)}).describe("Defines a courtyard outline on the PCB"),e3t=N.object({type:N.literal("pcb_courtyard_polygon"),pcb_courtyard_polygon_id:So("pcb_courtyard_polygon"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:W_,points:N.array(_r).min(3),color:N.string().optional()}).describe("Defines a courtyard polygon on the PCB"),t3t=N.object({type:N.literal("pcb_courtyard_circle"),pcb_courtyard_circle_id:So("pcb_courtyard_circle"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,radius:Di,layer:W_,color:N.string().optional()}).describe("Defines a courtyard circle on the PCB"),n3t=N.object({type:N.literal("pcb_courtyard_pill"),pcb_courtyard_pill_id:So("pcb_courtyard_pill"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:_r,width:Di,height:Di,radius:Di,layer:W_,color:N.string().optional()}).describe("Defines a courtyard pill on the PCB"),Vio=["obj","stl","3mf","gltf","glb","step","wrl"],o3t=["x+","x-","y+","y-","z+","z-"],zio={obj:"z+",stl:"z+","3mf":"z+",gltf:"y+",glb:"y+",step:"z+",wrl:"y+"},i3t=N.object({type:N.literal("cad_component"),cad_component_id:N.string(),pcb_component_id:N.string(),source_component_id:N.string(),position:nb,rotation:nb.optional(),size:nb.optional(),layer:WA.optional(),subcircuit_id:N.string().optional(),footprinter_string:N.string().optional(),model_obj_url:N.string().optional(),model_stl_url:N.string().optional(),model_3mf_url:N.string().optional(),model_gltf_url:N.string().optional(),model_glb_url:N.string().optional(),model_step_url:N.string().optional(),model_wrl_url:N.string().optional(),model_asset:y8e.optional(),model_unit_to_mm_scale_factor:N.number().optional(),model_board_normal_direction:N.enum(o3t).optional().describe(`The direction in the model's coordinate space that is considered "up" or "coming out of the board surface"`),model_origin_position:nb.optional(),model_origin_alignment:N.enum(["unknown","center","center_of_component_on_board_surface","bottom_center_of_component"]).optional(),model_object_fit:N.enum(["contain_within_bounds","fill_bounds"]).optional().default("contain_within_bounds"),model_jscad:N.any().optional(),show_as_translucent_model:N.boolean().optional(),show_as_bounding_box:N.boolean().optional(),anchor_alignment:N.enum(["center","center_of_component_on_board_surface"]).optional().default("center")}).describe("Defines a component on the PCB"),X8e=N.enum(["sinewave","square","triangle","sawtooth"]),Jio=N.union([N.string(),N.number()]).transform(t=>typeof t=="string"?t.endsWith("%")?parseFloat(t.slice(0,-1))/100:parseFloat(t):t).pipe(N.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),r3t=N.object({type:N.literal("simulation_voltage_source"),simulation_voltage_source_id:So("simulation_voltage_source"),is_dc_source:N.literal(!0).optional().default(!0),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),voltage:tb}).describe("Defines a DC voltage source for simulation"),s3t=N.object({type:N.literal("simulation_voltage_source"),simulation_voltage_source_id:So("simulation_voltage_source"),is_dc_source:N.literal(!1),terminal1_source_port_id:N.string().optional(),terminal2_source_port_id:N.string().optional(),terminal1_source_net_id:N.string().optional(),terminal2_source_net_id:N.string().optional(),voltage:tb.optional(),frequency:tN.optional(),peak_to_peak_voltage:tb.optional(),wave_shape:X8e.optional(),phase:im.optional(),duty_cycle:Jio.optional(),pulse_delay:J_.optional(),rise_time:J_.optional(),fall_time:J_.optional(),pulse_width:J_.optional(),period:J_.optional()}).describe("Defines an AC voltage source for simulation"),a3t=N.union([r3t,s3t]).describe("Defines a voltage source for simulation"),Wio=N.union([N.string(),N.number()]).transform(t=>typeof t=="string"?t.endsWith("%")?parseFloat(t.slice(0,-1))/100:parseFloat(t):t).pipe(N.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),A3t=N.object({type:N.literal("simulation_current_source"),simulation_current_source_id:So("simulation_current_source"),is_dc_source:N.literal(!0).optional().default(!0),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),current:vL}).describe("Defines a DC current source for simulation"),c3t=N.object({type:N.literal("simulation_current_source"),simulation_current_source_id:So("simulation_current_source"),is_dc_source:N.literal(!1),terminal1_source_port_id:N.string().optional(),terminal2_source_port_id:N.string().optional(),terminal1_source_net_id:N.string().optional(),terminal2_source_net_id:N.string().optional(),current:vL.optional(),frequency:tN.optional(),peak_to_peak_current:vL.optional(),wave_shape:X8e.optional(),phase:im.optional(),duty_cycle:Wio.optional()}).describe("Defines an AC current source for simulation"),l3t=N.union([A3t,c3t]).describe("Defines a current source for simulation"),u3t=N.union([N.literal("spice_dc_sweep"),N.literal("spice_dc_operating_point"),N.literal("spice_transient_analysis"),N.literal("spice_ac_analysis")]),g3t=N.object({method:N.enum(["trap","gear"]).optional(),reltol:N.union([N.number(),N.string()]).optional(),abstol:N.union([N.number(),N.string()]).optional(),vntol:N.union([N.number(),N.string()]).optional()}).describe("SPICE solver options for a simulation experiment"),d3t=N.object({type:N.literal("simulation_experiment"),simulation_experiment_id:So("simulation_experiment"),name:N.string(),experiment_type:u3t,time_per_step:wL.optional(),start_time_ms:J_.optional(),end_time_ms:J_.optional(),spice_options:g3t.optional()}).describe("Defines a simulation experiment configuration"),h3t=N.object({type:N.literal("simulation_transient_voltage_graph"),simulation_transient_voltage_graph_id:So("simulation_transient_voltage_graph"),simulation_experiment_id:N.string(),timestamps_ms:N.array(N.number()).optional(),voltage_levels:N.array(N.number()),source_component_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),time_per_step:wL,start_time_ms:J_,end_time_ms:J_,name:N.string().optional(),color:N.string().optional()}).describe("Stores voltage measurements over time for a simulation"),p3t=N.object({type:N.literal("simulation_transient_current_graph"),simulation_transient_current_graph_id:So("simulation_transient_current_graph"),simulation_experiment_id:N.string(),timestamps_ms:N.array(N.number()).optional(),current_levels:N.array(N.number()),source_component_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),time_per_step:wL,start_time_ms:J_,end_time_ms:J_,name:N.string().optional(),color:N.string().optional()}).describe("Stores current measurements over time for a simulation"),m3t=N.object({type:N.literal("simulation_switch"),simulation_switch_id:So("simulation_switch"),source_component_id:N.string().optional(),closes_at:J_.optional(),opens_at:J_.optional(),starts_closed:N.boolean().optional(),switching_frequency:tN.optional()}).describe("Defines a switch for simulation timing control"),_3t=N.object({type:N.literal("simulation_voltage_probe"),simulation_voltage_probe_id:So("simulation_voltage_probe"),source_component_id:N.string().optional(),name:N.string().optional(),signal_input_source_port_id:N.string().optional(),signal_input_source_net_id:N.string().optional(),reference_input_source_port_id:N.string().optional(),reference_input_source_net_id:N.string().optional(),subcircuit_id:N.string().optional(),color:N.string().optional()}).describe("Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.").superRefine((t,e)=>{if(t.reference_input_source_port_id||t.reference_input_source_net_id){const n=!!t.signal_input_source_port_id||!!t.reference_input_source_port_id,o=!!t.signal_input_source_net_id||!!t.reference_input_source_net_id;n&&o?e.addIssue({code:N.ZodIssueCode.custom,message:"Cannot mix port and net connections in a differential probe."}):n?t.signal_input_source_port_id&&t.reference_input_source_port_id||e.addIssue({code:N.ZodIssueCode.custom,message:"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id."}):o&&(t.signal_input_source_net_id&&t.reference_input_source_net_id||e.addIssue({code:N.ZodIssueCode.custom,message:"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id."}))}else!!t.signal_input_source_port_id==!!t.signal_input_source_net_id&&e.addIssue({code:N.ZodIssueCode.custom,message:"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id."})}),f3t=N.object({type:N.literal("simulation_current_probe"),simulation_current_probe_id:So("simulation_current_probe"),source_component_id:N.string().optional(),name:N.string().optional(),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),subcircuit_id:N.string().optional(),color:N.string().optional()}).describe("Defines a current probe for simulation. It measures current flowing from the positive endpoint to the negative endpoint.").superRefine((t,e)=>{const n=!!t.positive_source_port_id,o=!!t.negative_source_port_id,i=!!t.positive_source_net_id,r=!!t.negative_source_net_id,s=n||o,a=i||r;s&&a?e.addIssue({code:N.ZodIssueCode.custom,message:"Cannot mix port and net connections in a current probe."}):s?n&&o||e.addIssue({code:N.ZodIssueCode.custom,message:"Current probe using source ports requires both positive_source_port_id and negative_source_port_id."}):a?i&&r||e.addIssue({code:N.ZodIssueCode.custom,message:"Current probe using source nets requires both positive_source_net_id and negative_source_net_id."}):e.addIssue({code:N.ZodIssueCode.custom,message:"A current probe must have either positive/negative source port ids or positive/negative source net ids."})}),I3t=Wl.extend({type:N.literal("simulation_unknown_experiment_error"),simulation_unknown_experiment_error_id:So("simulation_unknown_experiment_error"),error_type:N.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"),simulation_experiment_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("An unknown error occurred during the simulation experiment."),C3t=N.object({type:N.literal("simulation_op_amp"),simulation_op_amp_id:So("simulation_op_amp"),source_component_id:N.string().optional(),inverting_input_source_port_id:N.string(),non_inverting_input_source_port_id:N.string(),output_source_port_id:N.string(),positive_supply_source_port_id:N.string(),negative_supply_source_port_id:N.string()}).describe("Defines a simple ideal operational amplifier for simulation"),y3t=N.object({type:N.literal("simulation_spice_subcircuit"),simulation_spice_subcircuit_id:So("simulation_spice_subcircuit"),source_component_id:N.string(),spice_pin_to_source_port_map:N.record(N.string(),N.string()),subcircuit_source:N.string()}).describe("Defines a custom SPICE subcircuit model for simulation"),x3t=t=>t!==void 0,E3t=N.object({type:N.literal("simulation_oscilloscope_trace"),simulation_oscilloscope_trace_id:So("simulation_oscilloscope_trace"),simulation_transient_voltage_graph_id:N.string().optional(),simulation_transient_current_graph_id:N.string().optional(),simulation_voltage_probe_id:N.string().optional(),simulation_current_probe_id:N.string().optional(),display_name:N.string().optional(),color:N.string().optional(),display_center_value:N.number().optional(),display_center_offset_divs:N.number().optional(),volts_per_div:N.number().positive().optional(),amps_per_div:N.number().positive().optional()}).describe("Defines how a simulation measurement is rendered as an oscilloscope-style trace.").superRefine((t,e)=>{const n=[t.simulation_transient_voltage_graph_id,t.simulation_voltage_probe_id].filter(x3t).length,o=[t.simulation_transient_current_graph_id,t.simulation_current_probe_id].filter(x3t).length;n+o!==1&&e.addIssue({code:N.ZodIssueCode.custom,message:"An oscilloscope trace must reference exactly one voltage graph, current graph, voltage probe, or current probe."}),n>0&&t.amps_per_div!==void 0&&e.addIssue({code:N.ZodIssueCode.custom,message:"Voltage oscilloscope traces must use volts_per_div, not amps_per_div."}),o>0&&t.volts_per_div!==void 0&&e.addIssue({code:N.ZodIssueCode.custom,message:"Current oscilloscope traces must use amps_per_div, not volts_per_div."})}),B3t=N.union([Myt,wyt,Pyt,vyt,Nyt,Dyt,S8e,E8e,iAe,b8e,B8e,Q8e,v8e,w8e,D8e,N8e,R8e,H8e,T8e,k8e,F8e,L8e,M8e,P8e,kyt,Fyt,Ryt,O8e,G8e,Y8e,U8e,Lyt,K8e,V8e,Hyt,Oyt,Gyt,Yyt,Uyt,Kyt,z8e,J8e,Tyt,E2t,P2t,vxt,wxt,Pxt,Nxt,Txt,kxt,M2t,xxt,D2t,W2t,k2t,G2t,Y2t,U2t,j2t,R2t,T2t,$2t,q2t,Mxt,ext,txt,nxt,oxt,lxt,ixt,rxt,sxt,axt,cxt,K2t,V2t,X2t,Z2t,z2t,J2t,Wxt,jxt,$xt,qxt,gxt,uxt,dxt,hxt,pxt,mxt,_xt,fxt,Ixt,Dxt,Cxt,yxt,Fxt,Qxt,Lxt,Hxt,Oxt,Kxt,Vxt,zxt,Jxt,Xxt,Zxt,e3t,t3t,n3t,Vyt,i2t,Zyt,e2t,t2t,n2t,qyt,Xyt,r2t,o2t,zyt,a2t,A2t,s2t,g2t,d2t,h2t,p2t,f2t,m2t,_2t,i3t,a3t,l3t,d3t,h3t,p3t,m3t,_3t,f3t,E3t,I3t,C3t,y3t]),aAe=B3t;function b3t(t,e,n){if(!e||!n)return;let o=t.get(e);o||(o=new Set,t.set(e,o)),o.add(n);let i=t.get(n);i||(i=new Set,t.set(n,i)),i.add(e)}var yx=(t,e={})=>{const n=t;let o=n._internal_store;if(!o){o={counts:{},editCount:0},n._internal_store=o;for(const r of n){const s=r.type,a=r[`${s}_id`];if(!a)continue;const A=Number.parseInt(a.split("_").pop());Number.isNaN(A)||(o.counts[s]=Math.max(o.counts[s]??0,A))}}const i=new Proxy({},{get:(r,s)=>{if(s==="toArray")return()=>(n.editCount=o.editCount,n);if(s==="editCount")return o.editCount;if(s==="subtree")return A=>yx((function(c,l){if(!l.subcircuit_id&&!l.source_group_id)return[...c];let u=l;if(l.subcircuit_id){const m=new Set([l.subcircuit_id]),_=new Map,f=new Map;for(const C of c)if(C.type==="source_group"){const y=C.source_group_id,x=C.subcircuit_id;x&&f.set(y,x);const E=C.parent_source_group_id;E&&(_.has(E)||_.set(E,[]),_.get(E).push(y))}let I;for(const[C,y]of f)if(y===l.subcircuit_id){I=C;break}if(I){const C=y=>{const x=_.get(y)||[];for(const E of x){const B=f.get(E);B&&m.add(B),C(E)}};C(I),u={...l,subcircuit_ids:Array.from(m)}}}const g=new Map;for(const m of c){const _=m[`${m.type}_id`];typeof _=="string"&&g.set(_,m)}const h=new Map;for(const m of c){const _=Object.entries(m);for(const[f,I]of _)if(f!=="parent_source_group_id"){if(f.endsWith("_id")&&typeof I=="string")b3t(h,m,g.get(I));else if(f.endsWith("_ids")&&Array.isArray(I))for(const C of I)typeof C=="string"&&b3t(h,m,g.get(C))}}const d=[],p=new Set;for(const m of c){let _=!1;(u.subcircuit_id&&"subcircuit_id"in m&&m.subcircuit_id===u.subcircuit_id||u.subcircuit_ids&&"subcircuit_id"in m&&m.subcircuit_id&&u.subcircuit_ids.includes(m.subcircuit_id)||u.source_group_id&&"source_group_id"in m&&m.source_group_id===u.source_group_id||u.source_group_id&&"member_source_group_ids"in m&&Array.isArray(m.member_source_group_ids)&&m.member_source_group_ids.includes(u.source_group_id))&&(_=!0),_&&(d.push(m),p.add(m))}for(;d.length>0;){const m=d.shift(),_=h.get(m);if(_)for(const f of _)p.has(f)||(p.add(f),d.push(f))}return c.filter(m=>p.has(m))})(n,A),e);if(s==="insert")return A=>{const c=A.type;if(!c)throw new Error("insert requires an element with a type");o.counts[c]??=-1,o.counts[c]++;const l=o.counts[c],u={...A,type:c,[`${c}_id`]:`${c}_${l}`};return e.validateInserts&&(Vae[c]??aAe).parse(u),n.push(u),o.editCount++,u};if(s==="insertAll")return A=>A.map(c=>i.insert(c));const a=s;return{get:A=>n.find(c=>c.type===a&&c[`${a}_id`]===A),getUsing:A=>{const c=Object.keys(A);if(c.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");const l=c[0],u=l.replace("_id",""),g=n.find(h=>h.type===u&&h[l]===A[l]);return g?n.find(h=>h.type===a&&h[`${a}_id`]===g[`${a}_id`]):null},getWhere:A=>{const c=Object.keys(A);return n.find(l=>l.type===a&&c.every(u=>l[u]===A[u]))},list:A=>{const c=A?Object.keys(A):[];return n.filter(l=>l.type===a&&c.every(u=>l[u]===A[u]))},insert:A=>{o.counts[a]??=-1,o.counts[a]++;const c=o.counts[a],l={type:a,[`${a}_id`]:`${a}_${c}`,...A};return e.validateInserts&&(Vae[a]??aAe).parse(l),n.push(l),o.editCount++,l},delete:A=>{const c=n.find(l=>l[`${a}_id`]===A);c&&(n.splice(n.indexOf(c),1),o.editCount++)},update:(A,c)=>{const l=n.find(u=>u.type===a&&u[`${a}_id`]===A);return l?(Object.assign(l,c),o.editCount++,l):null},select:A=>{if(a==="source_component")return n.find(c=>c.type==="source_component"&&c.name===A.replace(/\./g,""));if(a==="pcb_port"||a==="source_port"||a==="schematic_port"){const[c,l]=A.replace(/\./g,"").split(/[\s\>]+/),u=n.find(h=>h.type==="source_component"&&h.name===c);if(!u)return null;const g=n.find(h=>h.type==="source_port"&&h.source_component_id===u.source_component_id&&(h.name===l||(h.port_hints??[]).includes(l)));if(!g)return null;if(a==="source_port")return g;if(a==="pcb_port")return n.find(h=>h.type==="pcb_port"&&h.source_port_id===g.source_port_id);if(a==="schematic_port")return n.find(h=>h.type==="schematic_port"&&h.source_port_id===g.source_port_id)}}}}});return i};yx.unparsed=yx;var nI=yx;function Z8e(t){const e=t.type;return`${e}:${t[`${e}_id`]}`}var S3t=(t,e={})=>{let n=t._internal_store_indexed;if(!n){n={counts:{},editCount:0,indexes:{}};for(const r of t){const s=r.type,a=r[`${s}_id`];if(!a)continue;const A=Number.parseInt(a.split("_").pop()||"");Number.isNaN(A)||(n.counts[s]=Math.max(n.counts[s]??0,A))}const o=e.indexConfig||{},i=n.indexes;if(o.byId&&(i.byId=new Map),o.byType&&(i.byType=new Map),o.byRelation&&(i.byRelation=new Map),o.bySubcircuit&&(i.bySubcircuit=new Map),o.byCustomField&&o.byCustomField.length>0){i.byCustomField=new Map;for(const r of o.byCustomField)i.byCustomField.set(r,new Map)}for(const r of t){if(o.byId){const s=Z8e(r);i.byId.set(s,r)}if(o.byType){const s=i.byType.get(r.type)||[];s.push(r),i.byType.set(r.type,s)}if(o.byRelation){const s=Object.entries(r);for(const[a,A]of s)if(a.endsWith("_id")&&a!==`${r.type}_id`&&typeof A=="string"){const c=i.byRelation.get(a)||new Map,l=c.get(A)||[];l.push(r),c.set(A,l),i.byRelation.set(a,c)}}if(o.bySubcircuit&&"subcircuit_id"in r){const s=r.subcircuit_id;if(s&&typeof s=="string"){const a=i.bySubcircuit.get(s)||[];a.push(r),i.bySubcircuit.set(s,a)}}if(o.byCustomField&&i.byCustomField){for(const s of o.byCustomField)if(s in r){const a=r[s];if(a!==void 0&&(typeof a=="string"||typeof a=="number")){const A=String(a),c=i.byCustomField.get(s),l=c.get(A)||[];l.push(r),c.set(A,l)}}}}t._internal_store_indexed=n}return new Proxy({},{get:(o,i)=>{if(i==="toArray")return()=>(t.editCount=n.editCount,t);if(i==="editCount")return n.editCount;const r=i;return{get:s=>{const a=e.indexConfig||{};return a.byId&&n.indexes.byId?n.indexes.byId.get(`${r}:${s}`)||null:a.byType&&n.indexes.byType?(n.indexes.byType.get(r)||[]).find(A=>A[`${r}_id`]===s)||null:t.find(A=>A.type===r&&A[`${r}_id`]===s)||null},getUsing:s=>{const a=e.indexConfig||{},A=Object.keys(s);if(A.length!==1)throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");const c=A[0],l=c.replace("_id","");if(a.byRelation&&n.indexes.byRelation){const g=n.indexes.byRelation.get(c);if(g){const h=(g.get(s[c])||[]).find(p=>p.type===l);if(!h)return null;const d=h[`${r}_id`];return a.byId&&n.indexes.byId?n.indexes.byId.get(`${r}:${d}`)||null:a.byType&&n.indexes.byType?(n.indexes.byType.get(r)||[]).find(p=>p[`${r}_id`]===d)||null:t.find(p=>p.type===r&&p[`${r}_id`]===d)||null}}const u=t.find(g=>g.type===l&&g[c]===s[c]);return u&&t.find(g=>g.type===r&&g[`${r}_id`]===u[`${r}_id`])||null},getWhere:s=>{const a=e.indexConfig||{},A=Object.keys(s);if(A.length===1&&a.byCustomField&&n.indexes.byCustomField){const c=A[0],l=n.indexes.byCustomField.get(c);if(l){const u=String(s[c]);return(l.get(u)||[]).find(g=>g.type===r)||null}}if("subcircuit_id"in s&&a.bySubcircuit&&n.indexes.bySubcircuit){const c=s.subcircuit_id;return(n.indexes.bySubcircuit.get(c)||[]).find(l=>l.type===r&&A.every(u=>l[u]===s[u]))||null}return a.byType&&n.indexes.byType?(n.indexes.byType.get(r)||[]).find(c=>A.every(l=>c[l]===s[l]))||null:t.find(c=>c.type===r&&A.every(l=>c[l]===s[l]))||null},list:s=>{const a=e.indexConfig||{},A=s?Object.keys(s):[];if(A.length===0&&a.byType&&n.indexes.byType)return n.indexes.byType.get(r)||[];if(A.length===1&&A[0]==="subcircuit_id"&&a.bySubcircuit&&n.indexes.bySubcircuit){const l=s.subcircuit_id;return(n.indexes.bySubcircuit.get(l)||[]).filter(u=>u.type===r)}let c;return c=a.byType&&n.indexes.byType?n.indexes.byType.get(r)||[]:t.filter(l=>l.type===r),A.length>0?c.filter(l=>A.every(u=>l[u]===s[u])):c},insert:s=>{n.counts[r]??=-1,n.counts[r]++;const a=n.counts[r],A={type:r,[`${r}_id`]:`${r}_${a}`,...s};e.validateInserts&&(Vae[r]??aAe).parse(A),t.push(A),n.editCount++;const c=e.indexConfig||{};if(c.byId&&n.indexes.byId){const l=Z8e(A);n.indexes.byId.set(l,A)}if(c.byType&&n.indexes.byType){const l=n.indexes.byType.get(r)||[];l.push(A),n.indexes.byType.set(r,l)}if(c.byRelation&&n.indexes.byRelation){const l=Object.entries(A);for(const[u,g]of l)if(u.endsWith("_id")&&u!==`${A.type}_id`&&typeof g=="string"){const h=n.indexes.byRelation.get(u)||new Map,d=h.get(g)||[];d.push(A),h.set(g,d),n.indexes.byRelation.set(u,h)}}if(c.bySubcircuit&&n.indexes.bySubcircuit&&"subcircuit_id"in A){const l=A.subcircuit_id;if(l&&typeof l=="string"){const u=n.indexes.bySubcircuit.get(l)||[];u.push(A),n.indexes.bySubcircuit.set(l,u)}}if(c.byCustomField&&n.indexes.byCustomField){for(const l of c.byCustomField)if(l in A){const u=A[l];if(u!==void 0&&(typeof u=="string"||typeof u=="number")){const g=String(u),h=n.indexes.byCustomField.get(l),d=h.get(g)||[];d.push(A),h.set(g,d)}}}return A},delete:s=>{const a=e.indexConfig||{};let A;if(a.byId&&n.indexes.byId?A=n.indexes.byId.get(`${r}:${s}`):a.byType&&n.indexes.byType?A=(n.indexes.byType.get(r)||[]).find(u=>u[`${r}_id`]===s):A=t.find(l=>l[`${r}_id`]===s),!A)return;const c=t.indexOf(A);if(c>=0&&(t.splice(c,1),n.editCount++),a.byId&&n.indexes.byId){const l=Z8e(A);n.indexes.byId.delete(l)}if(a.byType&&n.indexes.byType){const l=(n.indexes.byType.get(r)||[]).filter(u=>u[`${r}_id`]!==s);n.indexes.byType.set(r,l)}if(a.byRelation&&n.indexes.byRelation)for(const[l,u]of n.indexes.byRelation.entries())for(const[g,h]of u.entries()){const d=h.filter(p=>p!==A);d.length===0?u.delete(g):u.set(g,d)}if(a.bySubcircuit&&n.indexes.bySubcircuit&&"subcircuit_id"in A){const l=A.subcircuit_id;if(l){const u=(n.indexes.bySubcircuit.get(l)||[]).filter(g=>g!==A);u.length===0?n.indexes.bySubcircuit.delete(l):n.indexes.bySubcircuit.set(l,u)}}if(a.byCustomField&&n.indexes.byCustomField)for(const l of n.indexes.byCustomField.values())for(const[u,g]of l.entries()){const h=g.filter(d=>d!==A);h.length===0?l.delete(u):l.set(u,h)}},update:(s,a)=>{const A=e.indexConfig||{};let c;if(A.byId&&n.indexes.byId?c=n.indexes.byId.get(`${r}:${s}`):A.byType&&n.indexes.byType?c=(n.indexes.byType.get(r)||[]).find(u=>u[`${r}_id`]===s):c=t.find(l=>l.type===r&&l[`${r}_id`]===s),!c)return null;if(A.byRelation&&n.indexes.byRelation){const l=Object.entries(c);for(const[u,g]of l)if(u.endsWith("_id")&&u!==`${c.type}_id`&&typeof g=="string"&&u in a&&a[u]!==g){const h=n.indexes.byRelation.get(u);if(h){const d=(h.get(g)||[]).filter(p=>p!==c);d.length===0?h.delete(g):h.set(g,d)}}}if(A.bySubcircuit&&n.indexes.bySubcircuit&&"subcircuit_id"in c&&"subcircuit_id"in a){const l=c.subcircuit_id;if(l!==a.subcircuit_id){const u=(n.indexes.bySubcircuit.get(l)||[]).filter(g=>g!==c);u.length===0?n.indexes.bySubcircuit.delete(l):n.indexes.bySubcircuit.set(l,u)}}if(A.byCustomField&&n.indexes.byCustomField){for(const l of A.byCustomField)if(l in c&&l in a&&c[l]!==a[l]){const u=n.indexes.byCustomField.get(l);if(u){const g=String(c[l]),h=(u.get(g)||[]).filter(d=>d!==c);h.length===0?u.delete(g):u.set(g,h)}}}if(Object.assign(c,a),n.editCount++,A.byRelation&&n.indexes.byRelation){const l=Object.entries(c);for(const[u,g]of l)if(u.endsWith("_id")&&u!==`${c.type}_id`&&typeof g=="string"&&u in a){const h=n.indexes.byRelation.get(u)||new Map,d=h.get(g)||[];d.includes(c)||(d.push(c),h.set(g,d),n.indexes.byRelation.set(u,h))}}if(A.bySubcircuit&&n.indexes.bySubcircuit&&"subcircuit_id"in c&&"subcircuit_id"in a){const l=c.subcircuit_id;if(l&&typeof l=="string"){const u=n.indexes.bySubcircuit.get(l)||[];u.includes(c)||(u.push(c),n.indexes.bySubcircuit.set(l,u))}}if(A.byCustomField&&n.indexes.byCustomField){for(const l of A.byCustomField)if(l in c&&l in a){const u=c[l];if(u!==void 0&&(typeof u=="string"||typeof u=="number")){const g=String(u),h=n.indexes.byCustomField.get(l),d=h.get(g)||[];d.includes(c)||(d.push(c),h.set(g,d))}}}return c},select:s=>{if(r==="source_component")return t.find(a=>a.type==="source_component"&&a.name===s.replace(/\./g,""))||null;if(r==="pcb_port"||r==="source_port"||r==="schematic_port"){const[a,A]=s.replace(/\./g,"").split(/[\s\>]+/),c=t.find(u=>u.type==="source_component"&&u.name===a);if(!c)return null;const l=t.find(u=>u.type==="source_port"&&u.source_component_id===c.source_component_id&&(u.name===A||(u.port_hints??[]).includes(A)));if(!l)return null;if(r==="source_port")return l;if(r==="pcb_port")return t.find(u=>u.type==="pcb_port"&&u.source_port_id===l.source_port_id)||null;if(r==="schematic_port")return t.find(u=>u.type==="schematic_port"&&u.source_port_id===l.source_port_id)||null}return null}}}})};S3t.unparsed=S3t;var Q3t=t=>t[`${t.type}_id`];function ebe(t,e){const n=yx(t).pcb_trace.get(e);if(!n)return`trace[${e}]`;const o=n.route.flatMap(i=>[i.start_pcb_port_id,i.end_pcb_port_id]).filter(Boolean);return o.length===0?`trace[${e}]`:`trace[${o.map(i=>{const r=(function(s){const a=yx(t).pcb_port.get(s);if(!a)return null;const A=a.pcb_component_id?yx(t).pcb_component.get(a.pcb_component_id):void 0;if(!A)return null;const c=yx(t).source_component.get(A.source_component_id);if(!c)return null;const l=yx(t).source_port.get(a.source_port_id),u=l?.port_hints?l.port_hints[1]:"";return{componentName:c.name,portHint:u}})(i);return r?`.${r.componentName} > port.${r.portHint}`:`port[${i}]`}).join(", ")}]`}var tbe=(t,e)=>{const n=yx(t).pcb_port.get(e);if(!n)return`pcb_port[#${e}]`;const o=n.pcb_component_id?yx(t).pcb_component.get(n.pcb_component_id):void 0;if(!o)return`pcb_port[#${e}]`;const i=yx(t).source_component.get(o.source_component_id);if(!i)return`pcb_port[#${e}]`;const r=yx(t).source_port.get(n.source_port_id);if(!r)return`pcb_port[#${e}]`;let s;return s=r?.port_hints&&r.port_hints.length>0||r.port_hints&&r.port_hints.length>0?r.port_hints[0]:e,`pcb_port[.${i.name} > .${s}]`},Ny=(t,e)=>{if(typeof e=="string"){const n=((o,i)=>o.find(r=>Q3t(r)===i)??null)(t,e);return Ny(t,n)}switch(e.type){case"pcb_port":return tbe(t,e.pcb_port_id);case"pcb_smtpad":return(function(n,o){const i=yx(n).pcb_smtpad.get(o);return i&&i.pcb_port_id?tbe(n,i.pcb_port_id):`smtpad[${o}]`})(t,e.pcb_smtpad_id);case"pcb_trace":return ebe(t,e.pcb_trace_id);case"source_component":return`source_component[${e.name}]`;default:return`${e.type}[#${Q3t(e)}]`}},v3t=(t,e)=>({minX:Math.min(t.minX,e.minX),minY:Math.min(t.minY,e.minY),maxX:Math.max(t.maxX,e.maxX),maxY:Math.max(t.maxY,e.maxY)}),AAe=(t,e,n)=>{const o=n/2;return{minX:t-o,minY:e-o,maxX:t+o,maxY:e+o}},jio=(t,e,n,o,i)=>{const r=n/2,s=o/2,a=i*Math.PI/180,A=Math.cos(a),c=Math.sin(a),l=[{x:-r,y:-s},{x:r,y:-s},{x:r,y:s},{x:-r,y:s}].map(u=>({x:t+u.x*A-u.y*c,y:e+u.x*c+u.y*A}));return{minX:Math.min(...l.map(u=>u.x)),minY:Math.min(...l.map(u=>u.y)),maxX:Math.max(...l.map(u=>u.x)),maxY:Math.max(...l.map(u=>u.y))}},nbe=t=>{let e=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(const r of t){if(!r.type.startsWith("pcb_"))continue;if(r.type==="pcb_smtpad"&&r.shape==="polygon"&&Array.isArray(r.points)){for(const l of r.points)e=Math.min(e,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y);continue}if(r.type==="pcb_hole"&&r.hole_shape==="circle"){const l=AAe(r.x,r.y,r.hole_diameter);e=Math.min(e,l.minX),n=Math.min(n,l.minY),o=Math.max(o,l.maxX),i=Math.max(i,l.maxY);continue}if(r.type==="pcb_plated_hole"){let l;if("outer_diameter"in r&&typeof r.outer_diameter=="number"?l=AAe(r.x,r.y,r.outer_diameter):"hole_diameter"in r&&typeof r.hole_diameter=="number"&&(l=AAe(r.x,r.y,r.hole_diameter)),"rect_pad_width"in r&&typeof r.rect_pad_width=="number"&&"rect_pad_height"in r&&typeof r.rect_pad_height=="number"){const u=jio(r.x,r.y,r.rect_pad_width,r.rect_pad_height,"rect_ccw_rotation"in r?r.rect_ccw_rotation??0:0);l=l?v3t(l,u):u}if("hole_diameter"in r&&typeof r.hole_diameter=="number"){const u=AAe(r.x+("hole_offset_x"in r?r.hole_offset_x??0:0),r.y+("hole_offset_y"in r?r.hole_offset_y??0:0),r.hole_diameter);l=l?v3t(l,u):u}if(l){e=Math.min(e,l.minX),n=Math.min(n,l.minY),o=Math.max(o,l.maxX),i=Math.max(i,l.maxY);continue}}let s,a,A,c;if("x"in r&&"y"in r&&(s=Number(r.x),a=Number(r.y)),"outer_diameter"in r&&(A=Number(r.outer_diameter),c=Number(r.outer_diameter)),"width"in r&&(A=Number(r.width)),"height"in r&&(c=Number(r.height)),"center"in r&&(s=r.center.x,a=r.center.y),s!==void 0&&a!==void 0)e=Math.min(e,s),n=Math.min(n,a),o=Math.max(o,s),i=Math.max(i,a),A!==void 0&&c!==void 0&&(e=Math.min(e,s-A/2),n=Math.min(n,a-c/2),o=Math.max(o,s+A/2),i=Math.max(i,a+c/2)),"radius"in r&&(e=Math.min(e,s-r.radius),n=Math.min(n,a-r.radius),o=Math.max(o,s+r.radius),i=Math.max(i,a+r.radius));else if(r.type==="pcb_trace")for(const l of r.route)e=Math.min(e,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y);else if(r.type==="pcb_courtyard_outline")for(const l of r.outline)e=Math.min(e,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y);else if(r.type==="pcb_courtyard_polygon")for(const l of r.points)e=Math.min(e,l.x),n=Math.min(n,l.y),o=Math.max(o,l.x),i=Math.max(i,l.y)}return{minX:e,minY:n,maxX:o,maxY:i}},gv=t=>t[`${t.type}_id`],w3t={Hz:{baseUnit:"Hz",variants:{MHz:1e6,kHz:1e3,Hz:1}},g:{baseUnit:"g",variants:{kg:1e3,g:1}},Ω:{baseUnit:"Ω",variants:{mΩ:.001,Ω:1,kΩ:1e3,KΩ:1e3,kohm:1e3,MΩ:1e6,GΩ:1e9,TΩ:1e12}},V:{baseUnit:"V",variants:{mV:.001,V:1,kV:1e3,KV:1e3,MV:1e6,GV:1e9,TV:1e12}},A:{baseUnit:"A",variants:{µA:1e-6,mA:.001,ma:.001,A:1,kA:1e3,MA:1e6}},F:{baseUnit:"F",variants:{pF:1e-12,nF:1e-9,µF:1e-6,uF:1e-6,mF:.001,F:1}},ml:{baseUnit:"ml",variants:{ml:1,mL:1,l:1e3,L:1e3}},deg:{baseUnit:"deg",variants:{rad:180/Math.PI}},ms:{baseUnit:"ms",variants:{fs:1e-12,ps:1e-9,ns:1e-6,us:.001,µs:.001,ms:1,s:1e3}},mm:{baseUnit:"mm",variants:{nm:1e-6,µm:.001,um:.001,mm:1,cm:10,dm:100,m:1e3,km:1e6,in:25.4,ft:304.8,IN:25.4,FT:304.8,yd:914.4,mi:1609344,mil:.0254}}},obe=new Set;for(const[t,e]of Object.entries(w3t)){obe.add(t);for(const n of Object.keys(e.variants))obe.add(n)}var P3t={tera:1e12,T:1e12,giga:1e9,G:1e9,mega:1e6,M:1e6,kilo:1e3,k:1e3,deci:.1,d:.1,centi:.01,c:.01,milli:.001,m:.001,micro:1e-6,u:1e-6,µ:1e-6,nano:1e-9,n:1e-9,pico:1e-12,p:1e-12};function sB(t){if(t==null)return{parsedUnit:null,unitOfValue:null,value:null};if(typeof t=="string"&&t.match(/^-?[\d\.]+$/))return{value:Number.parseFloat(t),parsedUnit:null,unitOfValue:null};if(typeof t=="number")return{value:t,parsedUnit:null,unitOfValue:null};if(typeof t=="object"&&"x"in t&&"y"in t){const{parsedUnit:a,unitOfValue:A}=sB(t.x),c=sB(t.x),l=sB(t.y);return c.value===null||l.value===null?{parsedUnit:null,unitOfValue:null,value:null}:{parsedUnit:a,unitOfValue:A,value:{x:c.value,y:l.value}}}const e=t.toString().split("").reverse().join(""),n=e.match(/[^\d\s]+/)?.[0];if(!n)throw new Error(`Could not determine unit: "${t}"`);const o=n.split("").reverse().join(""),i=t.slice(0,-o.length);if(o in P3t&&!obe.has(o)){const a=P3t[o];return{parsedUnit:null,unitOfValue:null,value:Number.parseFloat(i)*a}}const{baseUnit:r,conversionFactor:s}=(function(a){for(const[A,c]of Object.entries(w3t))if(a in c.variants)return{baseUnit:c.baseUnit,conversionFactor:c.variants[a]};return{baseUnit:a,conversionFactor:1}})(o);return{parsedUnit:o,unitOfValue:r,value:s*Number.parseFloat(i)}}var ibe=N.string().or(N.number()).transform(t=>sB(t).value),M3t=N.string().or(N.number()).transform(t=>sB(t).value).transform(t=>Number.parseFloat(t.toPrecision(12))),$io=N.string().or(N.number()).transform(t=>sB(t).value),dv=N.string().or(N.number()).transform(t=>sB(t).value),Ui=N.string().or(N.number()).transform(t=>sB(t).value),PL=N.string().or(N.number()).transform(t=>sB(t).value),ho=Ui,HJ=N.string().or(N.number()).transform(t=>sB(t).value),rbe=N.string().or(N.number()).transform(t=>sB(t).value),ML=rbe,qio=N.string().datetime(),jm=N.string().or(N.number()).transform(t=>typeof t=="number"?t:t.endsWith("deg")?Number.parseFloat(t.split("deg")[0]):t.endsWith("rad")?180*Number.parseFloat(t.split("rad")[0])/Math.PI:Number.parseFloat(t)),Xio=N.number().or(N.string().endsWith("mAh")).transform(t=>{if(typeof t=="string"){const e=t.replace("mAh",""),n=Number.parseFloat(e);if(Number.isNaN(n))throw new Error("Invalid capacity");return n}return t}).describe("Battery capacity in mAh"),Lr=N.object({x:ho,y:ho}),nN=N.object({x:ho,y:ho,z:ho}),D3t=N.object({width:N.number(),height:N.number()}),Yo=t=>N.string().optional().default(()=>`${t}_${(e=>{const n="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";return Array.from({length:e},()=>n[Math.floor(62*Math.random())]).join("")})(10)}`),hv=N.enum(["top_left","top_center","top_right","center_left","center","center_right","bottom_left","bottom_center","bottom_right"]),Zio=(N.enum(["top_silkscreen","bottom_silkscreen","top_copper","bottom_copper","top_soldermask","bottom_soldermask","top_fabrication_note","bottom_fabrication_note","top_user_note","bottom_user_note","top_courtyard","bottom_courtyard","inner1_copper","inner2_copper","inner3_copper","inner4_copper","inner5_copper","inner6_copper","edge_cuts","drill"]),N.object({project_relative_path:N.string(),url:N.string(),mimetype:N.string()})),sbe=Lr.extend({rotation:jm.optional()}),N3t=N.object({size:Lr.optional(),thickness:ho.optional()}),ero=N.object({font:N3t.optional()}),cAe=N.object({value:N.string(),at:sbe.optional(),layer:N.string().optional(),uuid:N.string().optional(),hide:N.boolean().optional(),effects:ero.optional()}),tro=N.object({Reference:cAe.optional(),Value:cAe.optional(),Datasheet:cAe.optional(),Description:cAe.optional()}),nro=N.object({through_hole:N.boolean().optional(),smd:N.boolean().optional(),exclude_from_pos_files:N.boolean().optional(),exclude_from_bom:N.boolean().optional()}),oro=N.object({name:N.string(),type:N.string(),shape:N.string().optional(),at:sbe.optional(),size:Lr.optional(),drill:ho.optional(),layers:N.array(N.string()).optional(),removeUnusedLayers:N.boolean().optional(),uuid:N.string().optional()}),iro=N.object({path:N.string(),offset:nN.optional(),scale:nN.optional(),rotate:nN.optional()}),rro=N.object({footprintName:N.string().optional(),version:N.union([N.number(),N.string()]).optional(),generator:N.string().optional(),generatorVersion:N.union([N.number(),N.string()]).optional(),layer:N.string().optional(),properties:tro.optional(),attributes:nro.optional(),pads:N.array(oro).optional(),embeddedFonts:N.boolean().optional(),model:iro.optional()}),sro=N.object({hide:N.boolean().optional()}),aro=N.object({offset:ho.optional(),hide:N.boolean().optional()}),Aro=N.object({font:N3t.optional(),justify:N.union([N.string(),N.array(N.string())]).optional(),hide:N.boolean().optional()}),oN=N.object({value:N.string(),id:N.union([N.number(),N.string()]).optional(),at:sbe.optional(),effects:Aro.optional()}),cro=N.object({Reference:oN.optional(),Value:oN.optional(),Footprint:oN.optional(),Datasheet:oN.optional(),Description:oN.optional(),ki_keywords:oN.optional(),ki_fp_filters:oN.optional()}),lro=N.object({symbolName:N.string().optional(),extends:N.string().optional(),pinNumbers:sro.optional(),pinNames:aro.optional(),excludeFromSim:N.boolean().optional(),inBom:N.boolean().optional(),onBoard:N.boolean().optional(),properties:cro.optional(),embeddedFonts:N.boolean().optional()}),N0=N.object({error_type:N.string(),message:N.string(),is_fatal:N.boolean().optional()}),R3t=N.enum(["jlcpcb","macrofab","pcbway","digikey","mouser","lcsc"]),Mg=N.object({type:N.literal("source_component"),ftype:N.string().optional(),source_component_id:N.string(),name:N.string(),manufacturer_part_number:N.string().optional(),supplier_part_numbers:N.record(R3t,N.array(N.string())).optional(),display_value:N.string().optional(),display_name:N.string().optional(),are_pins_interchangeable:N.boolean().optional(),internally_connected_source_port_ids:N.array(N.array(N.string())).optional(),source_group_id:N.string().optional(),subcircuit_id:N.string().optional()}),T3t=Mg.extend({ftype:N.literal("simple_capacitor"),capacitance:M3t,max_voltage_rating:dv.optional(),display_capacitance:N.string().optional(),max_decoupling_trace_length:ho.optional()}),k3t=Mg.extend({ftype:N.literal("simple_resistor"),resistance:ibe,display_resistance:N.string().optional()}),abe=Mg.extend({ftype:N.literal("simple_diode")}),uro=Mg.extend({ftype:N.literal("simple_fiducial")}),F3t=abe.extend({ftype:N.literal("simple_led"),color:N.string().optional(),wavelength:N.string().optional()}),gro=Mg.extend({ftype:N.literal("simple_ground")}),L3t=Mg.extend({ftype:N.literal("simple_chip")}),H3t=Mg.extend({ftype:N.literal("simple_power_source"),voltage:dv}),dro=Mg.extend({ftype:N.literal("simple_current_source"),current:HJ,frequency:PL.optional(),peak_to_peak_current:HJ.optional(),wave_shape:N.enum(["sine","square","triangle","sawtooth","dc"]).optional().default("dc"),phase:N.number().optional(),duty_cycle:N.number().min(0).max(1).optional()}),hro=N.object({must_be_connected:N.boolean().optional(),provides_power:N.boolean().optional(),requires_power:N.boolean().optional(),provides_ground:N.boolean().optional(),requires_ground:N.boolean().optional(),provides_voltage:N.union([N.string(),N.number()]).optional(),requires_voltage:N.union([N.string(),N.number()]).optional(),do_not_connect:N.boolean().optional(),include_in_board_pinout:N.boolean().optional(),can_use_internal_pullup:N.boolean().optional(),is_using_internal_pullup:N.boolean().optional(),needs_external_pullup:N.boolean().optional(),can_use_internal_pulldown:N.boolean().optional(),is_using_internal_pulldown:N.boolean().optional(),needs_external_pulldown:N.boolean().optional(),can_use_open_drain:N.boolean().optional(),is_using_open_drain:N.boolean().optional(),can_use_push_pull:N.boolean().optional(),is_using_push_pull:N.boolean().optional(),should_have_decoupling_capacitor:N.boolean().optional(),recommended_decoupling_capacitor_capacitance:N.union([N.string(),N.number()]).optional(),is_configured_for_i2c_sda:N.boolean().optional(),is_configured_for_i2c_scl:N.boolean().optional(),is_configured_for_spi_mosi:N.boolean().optional(),is_configured_for_spi_miso:N.boolean().optional(),is_configured_for_spi_sck:N.boolean().optional(),is_configured_for_spi_cs:N.boolean().optional(),is_configured_for_uart_tx:N.boolean().optional(),is_configured_for_uart_rx:N.boolean().optional(),supports_i2c_sda:N.boolean().optional(),supports_i2c_scl:N.boolean().optional(),supports_spi_mosi:N.boolean().optional(),supports_spi_miso:N.boolean().optional(),supports_spi_sck:N.boolean().optional(),supports_spi_cs:N.boolean().optional(),supports_uart_tx:N.boolean().optional(),supports_uart_rx:N.boolean().optional()}),pro=Mg.extend({ftype:N.literal("simple_fuse"),current_rating_amps:N.number().describe("Nominal current in amps the fuse is rated for"),voltage_rating_volts:N.number().describe("Voltage rating in volts, e.g. ±5V would be 5")}),O3t=Mg.extend({ftype:N.literal("simple_battery"),capacity:Xio}),G3t=Mg.extend({ftype:N.literal("simple_inductor"),inductance:$io,display_inductance:N.string().optional(),max_current_rating:N.number().optional()}),Y3t=Mg.extend({ftype:N.literal("simple_push_button")}),U3t=Mg.extend({ftype:N.literal("simple_potentiometer"),max_resistance:ibe,display_max_resistance:N.string().optional()}),mro=Mg.extend({ftype:N.literal("simple_crystal"),frequency:N.number().describe("Frequency in Hz"),load_capacitance:N.number().optional().describe("Load capacitance in pF"),pin_variant:N.enum(["two_pin","four_pin"]).optional()}),K3t=Mg.extend({ftype:N.literal("simple_pin_header"),pin_count:N.number(),gender:N.enum(["male","female"]).optional().default("male")}),_ro=Mg.extend({ftype:N.literal("simple_connector"),standard:N.enum(["usb_c","m2"]).optional()}),V3t=Mg.extend({ftype:N.literal("simple_pinout")}),z3t=Mg.extend({ftype:N.literal("simple_resonator"),load_capacitance:M3t,equivalent_series_resistance:ibe.optional(),frequency:PL}),J3t=Mg.extend({ftype:N.literal("simple_transistor"),transistor_type:N.enum(["npn","pnp"])}),W3t=Mg.extend({ftype:N.literal("simple_test_point"),footprint_variant:N.enum(["pad","through_hole"]).optional(),pad_shape:N.enum(["rect","circle"]).optional(),pad_diameter:N.union([N.number(),N.string()]).optional(),hole_diameter:N.union([N.number(),N.string()]).optional(),width:N.union([N.number(),N.string()]).optional(),height:N.union([N.number(),N.string()]).optional()}),j3t=Mg.extend({ftype:N.literal("simple_mosfet"),channel_type:N.enum(["n","p"]),mosfet_mode:N.enum(["enhancement","depletion"])}),$3t=Mg.extend({ftype:N.literal("simple_op_amp")}),q3t=Mg.extend({ftype:N.literal("simple_switch")}),X3t=N.object({type:N.literal("source_project_metadata"),name:N.string().optional(),software_used_string:N.string().optional(),project_url:N.string().optional(),created_at:qio.optional()}),fro=N0.extend({type:N.literal("source_missing_property_error"),source_missing_property_error_id:Yo("source_missing_property_error"),source_component_id:N.string(),property_name:N.string(),subcircuit_id:N.string().optional(),error_type:N.literal("source_missing_property_error").default("source_missing_property_error")}).describe("The source code is missing a property"),Iro=N0.extend({type:N.literal("source_failed_to_create_component_error"),source_failed_to_create_component_error_id:Yo("source_failed_to_create_component_error"),error_type:N.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"),component_name:N.string().optional(),subcircuit_id:N.string().optional(),parent_source_component_id:N.string().optional(),pcb_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),schematic_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional()}).describe("Error emitted when a component fails to be constructed"),Z3t=N0.extend({type:N.literal("source_invalid_component_property_error"),source_invalid_component_property_error_id:Yo("source_invalid_component_property_error"),source_component_id:N.string(),property_name:N.string(),property_value:N.unknown().optional(),expected_format:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal("source_invalid_component_property_error").default("source_invalid_component_property_error")}).describe("The source component property is invalid"),eEt=N0.extend({type:N.literal("source_trace_not_connected_error"),source_trace_not_connected_error_id:Yo("source_trace_not_connected_error"),error_type:N.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"),subcircuit_id:N.string().optional(),source_group_id:N.string().optional(),source_trace_id:N.string().optional(),connected_source_port_ids:N.array(N.string()).optional(),selectors_not_found:N.array(N.string()).optional()}).describe("Occurs when a source trace selector does not match any ports"),Cro=N.object({type:N.literal("source_property_ignored_warning"),source_property_ignored_warning_id:Yo("source_property_ignored_warning"),source_component_id:N.string(),property_name:N.string(),subcircuit_id:N.string().optional(),error_type:N.literal("source_property_ignored_warning").default("source_property_ignored_warning"),message:N.string()}).describe("The source property was ignored"),tEt=N.object({type:N.literal("source_pin_missing_trace_warning"),source_pin_missing_trace_warning_id:Yo("source_pin_missing_trace_warning"),warning_type:N.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"),message:N.string(),source_component_id:N.string(),source_port_id:N.string(),subcircuit_id:N.string().optional()}).describe("Warning emitted when a source component pin is missing a trace connection"),nEt=N.object({type:N.literal("source_missing_manufacturer_part_number_warning"),source_missing_manufacturer_part_number_warning_id:Yo("source_missing_manufacturer_part_number_warning"),warning_type:N.literal("source_missing_manufacturer_part_number_warning").default("source_missing_manufacturer_part_number_warning"),message:N.string(),source_component_id:N.string(),standard:N.string(),subcircuit_id:N.string().optional()}).describe("Warning emitted when a standard connector is missing manufacturer part number"),yro=Mg.extend({ftype:N.literal("simple_voltage_probe")}),xro=Mg.extend({ftype:N.literal("interconnect")}),oEt=N0.extend({type:N.literal("source_i2c_misconfigured_error"),source_i2c_misconfigured_error_id:Yo("source_i2c_misconfigured_error"),error_type:N.literal("source_i2c_misconfigured_error").default("source_i2c_misconfigured_error"),source_port_ids:N.array(N.string())}).describe("Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net"),Ero=Mg.extend({ftype:N.literal("simple_voltage_source"),voltage:dv,frequency:PL.optional(),peak_to_peak_voltage:dv.optional(),wave_shape:N.enum(["sinewave","square","triangle","sawtooth"]).optional(),phase:jm.optional(),duty_cycle:N.number().optional().describe("Duty cycle as a fraction (0 to 1)")}),Bro=N.union([k3t,T3t,abe,uro,F3t,gro,L3t,H3t,dro,O3t,G3t,Y3t,U3t,mro,K3t,_ro,V3t,z3t,q3t,J3t,W3t,j3t,$3t,pro,yro,xro,Ero,X3t,fro,Z3t,Iro,eEt,Cro,tEt,nEt,oEt]),bro=N.object({type:N.literal("source_port"),pin_number:N.number().optional(),port_hints:N.array(N.string()).optional(),name:N.string(),source_port_id:N.string(),source_component_id:N.string().optional(),source_group_id:N.string().optional(),most_frequently_referenced_by_name:N.string().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}).merge(hro),Sro=N.object({type:N.literal("source_component_internal_connection"),source_component_internal_connection_id:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}),Qro=N.object({type:N.literal("source_trace"),source_trace_id:N.string(),connected_source_port_ids:N.array(N.string()),connected_source_net_ids:N.array(N.string()),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),max_length:N.number().optional(),min_trace_thickness:N.number().optional(),display_name:N.string().optional()}),vro=N.object({type:N.literal("source_group"),source_group_id:N.string(),subcircuit_id:N.string().optional(),parent_subcircuit_id:N.string().optional(),parent_source_group_id:N.string().optional(),is_subcircuit:N.boolean().optional(),show_as_schematic_box:N.boolean().optional(),name:N.string().optional(),was_automatically_named:N.boolean().optional()}),wro=N.object({type:N.literal("source_net"),source_net_id:N.string(),name:N.string(),member_source_group_ids:N.array(N.string()),is_power:N.boolean().optional(),is_ground:N.boolean().optional(),is_digital_signal:N.boolean().optional(),is_analog_signal:N.boolean().optional(),is_positive_voltage_source:N.boolean().optional(),trace_width:N.number().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}),Pro=N.object({type:N.literal("source_board"),source_board_id:N.string(),source_group_id:N.string(),title:N.string().optional()}).describe("Defines a board in the source domain"),Mro=N0.extend({type:N.literal("source_ambiguous_port_reference"),source_ambiguous_port_reference_id:Yo("source_ambiguous_port_reference"),error_type:N.literal("source_ambiguous_port_reference").default("source_ambiguous_port_reference"),source_port_id:N.string().optional(),source_component_id:N.string().optional()}).describe("Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous"),Dro=N.object({type:N.literal("source_pcb_ground_plane"),source_pcb_ground_plane_id:N.string(),source_group_id:N.string(),source_net_id:N.string(),subcircuit_id:N.string().optional()}).describe("Defines a ground plane in the source domain"),lAe=["top","bottom","inner1","inner2","inner3","inner4","inner5","inner6"],iEt=N.enum(lAe),Pc=iEt.or(N.object({name:iEt})).transform(t=>typeof t=="string"?t:t.name),mC=N.enum(["top","bottom"]),Nro=N.object({type:N.literal("source_manually_placed_via"),source_manually_placed_via_id:N.string(),source_group_id:N.string(),source_net_id:N.string(),subcircuit_id:N.string().optional(),source_trace_id:N.string().optional()}).describe("Defines a via that is manually placed in the source domain"),Rro=N.object({type:N.literal("source_no_power_pin_defined_warning"),source_no_power_pin_defined_warning_id:Yo("source_no_power_pin_defined_warning"),warning_type:N.literal("source_no_power_pin_defined_warning").default("source_no_power_pin_defined_warning"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Warning emitted when a chip has no source ports with requires_power=true"),Tro=N.object({type:N.literal("source_no_ground_pin_defined_warning"),source_no_ground_pin_defined_warning_id:Yo("source_no_ground_pin_defined_warning"),warning_type:N.literal("source_no_ground_pin_defined_warning").default("source_no_ground_pin_defined_warning"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Warning emitted when a chip has no source ports marked as ground pins"),kro=N.object({type:N.literal("source_component_pins_underspecified_warning"),source_component_pins_underspecified_warning_id:Yo("source_component_pins_underspecified_warning"),warning_type:N.literal("source_component_pins_underspecified_warning").default("source_component_pins_underspecified_warning"),message:N.string(),source_component_id:N.string(),source_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Warning emitted when all ports on a source component are underspecified"),Fro=N0.extend({type:N.literal("source_pin_must_be_connected_error"),source_pin_must_be_connected_error_id:Yo("source_pin_must_be_connected_error"),error_type:N.literal("source_pin_must_be_connected_error").default("source_pin_must_be_connected_error"),source_component_id:N.string(),source_port_id:N.string(),subcircuit_id:N.string().optional()}).describe("Error emitted when a pin with mustBeConnected attribute is not connected to any trace"),Lro=N0.extend({type:N.literal("unknown_error_finding_part"),unknown_error_finding_part_id:Yo("unknown_error_finding_part"),error_type:N.literal("unknown_error_finding_part").default("unknown_error_finding_part"),source_component_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when an unexpected error occurs while finding a part"),Hro=N.object({type:N.literal("schematic_box"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),width:ho,height:ho,is_dashed:N.boolean().default(!1),x:ho,y:ho,subcircuit_id:N.string().optional()}).describe("Draws a box on the schematic"),Oro=N.object({type:N.literal("schematic_path"),schematic_path_id:Yo("schematic_path"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),fill_color:N.string().optional(),is_filled:N.boolean().optional(),stroke_width:ho.nullable().optional(),stroke_color:N.string().optional(),points:N.array(Lr),subcircuit_id:N.string().optional()}),Gro=N.record(N.object({left_margin:Ui.optional(),right_margin:Ui.optional(),top_margin:Ui.optional(),bottom_margin:Ui.optional()})),Yro=N.object({left_size:N.number(),right_size:N.number(),top_size:N.number().optional(),bottom_size:N.number().optional()}),Uro=N.object({left_side:N.object({pins:N.array(N.number()),direction:N.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),right_side:N.object({pins:N.array(N.number()),direction:N.enum(["top-to-bottom","bottom-to-top"]).optional()}).optional(),top_side:N.object({pins:N.array(N.number()),direction:N.enum(["left-to-right","right-to-left"]).optional()}).optional(),bottom_side:N.object({pins:N.array(N.number()),direction:N.enum(["left-to-right","right-to-left"]).optional()}).optional()}),Kro=N.union([Yro,Uro]),Vro=N.object({type:N.literal("schematic_component"),size:D3t,center:Lr,source_component_id:N.string().optional(),schematic_component_id:N.string(),schematic_symbol_id:N.string().optional(),pin_spacing:Ui.optional(),pin_styles:Gro.optional(),box_width:Ui.optional(),symbol_name:N.string().optional(),port_arrangement:Kro.optional(),port_labels:N.record(N.string()).optional(),symbol_display_value:N.string().optional(),subcircuit_id:N.string().optional(),schematic_group_id:N.string().optional(),is_schematic_group:N.boolean().optional(),source_group_id:N.string().optional(),is_box_with_pins:N.boolean().optional().default(!0)}),zro=N.object({kicad_symbol:lro.optional()}).catchall(N.unknown()),Jro=N.object({type:N.literal("schematic_symbol"),schematic_symbol_id:N.string(),name:N.string().optional(),metadata:zro.optional()}).describe("Defines a named schematic symbol that can be referenced by components."),Wro=N.object({type:N.literal("schematic_line"),schematic_line_id:Yo("schematic_line"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),x1:ho,y1:ho,x2:ho,y2:ho,stroke_width:ho.nullable().optional(),color:N.string().default("#000000"),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe("Draws a styled line on the schematic"),jro=N.object({type:N.literal("schematic_rect"),schematic_rect_id:Yo("schematic_rect"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:Lr,width:ho,height:ho,rotation:jm.default(0),stroke_width:ho.nullable().optional(),color:N.string().default("#000000"),is_filled:N.boolean().default(!1),fill_color:N.string().optional(),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe("Draws a styled rectangle on the schematic"),$ro=N.object({type:N.literal("schematic_circle"),schematic_circle_id:Yo("schematic_circle"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:Lr,radius:ho,stroke_width:ho.nullable().optional(),color:N.string().default("#000000"),is_filled:N.boolean().default(!1),fill_color:N.string().optional(),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe("Draws a styled circle on the schematic"),qro=N.object({type:N.literal("schematic_arc"),schematic_arc_id:Yo("schematic_arc"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),center:Lr,radius:ho,start_angle_degrees:jm,end_angle_degrees:jm,direction:N.enum(["clockwise","counterclockwise"]).default("counterclockwise"),stroke_width:ho.nullable().optional(),color:N.string().default("#000000"),is_dashed:N.boolean().default(!1),subcircuit_id:N.string().optional()}).describe("Draws a styled arc on the schematic"),Xro=N.object({type:N.literal("schematic_trace"),schematic_trace_id:N.string(),source_trace_id:N.string().optional(),junctions:N.array(N.object({x:N.number(),y:N.number()})),edges:N.array(N.object({from:N.object({x:N.number(),y:N.number()}),to:N.object({x:N.number(),y:N.number()}),is_crossing:N.boolean().optional(),from_schematic_port_id:N.string().optional(),to_schematic_port_id:N.string().optional()})),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional()}),Zro=N.enum(["center","left","right","top","bottom"]),eso=N.object({type:N.literal("schematic_text"),schematic_component_id:N.string().optional(),schematic_symbol_id:N.string().optional(),schematic_text_id:N.string(),text:N.string(),font_size:N.number().default(.18),position:N.object({x:ho,y:ho}),rotation:N.number().default(0),anchor:N.union([Zro.describe("legacy"),hv]).default("center"),color:N.string().default("#000000"),subcircuit_id:N.string().optional()}),tso=N.object({type:N.literal("schematic_port"),schematic_port_id:N.string(),source_port_id:N.string(),schematic_component_id:N.string().optional(),center:Lr,facing_direction:N.enum(["up","down","left","right"]).optional(),distance_from_component_edge:N.number().optional(),side_of_component:N.enum(["top","bottom","left","right"]).optional(),true_ccw_index:N.number().optional(),pin_number:N.number().optional(),display_pin_label:N.string().optional(),subcircuit_id:N.string().optional(),is_connected:N.boolean().optional(),has_input_arrow:N.boolean().optional(),has_output_arrow:N.boolean().optional(),is_drawn_with_inversion_circle:N.boolean().optional()}).describe("Defines a port on a schematic component"),nso=N.object({type:N.literal("schematic_net_label"),schematic_net_label_id:Yo("schematic_net_label"),schematic_trace_id:N.string().optional(),source_trace_id:N.string().optional(),source_net_id:N.string(),center:Lr,anchor_position:Lr.optional(),anchor_side:N.enum(["top","bottom","left","right"]),text:N.string(),symbol_name:N.string().optional(),is_movable:N.boolean().optional(),subcircuit_id:N.string().optional()}),oso=N0.extend({type:N.literal("schematic_error"),schematic_error_id:N.string(),error_type:N.literal("schematic_port_not_found").default("schematic_port_not_found"),subcircuit_id:N.string().optional()}).describe("Defines a schematic error on the schematic"),iso=N0.extend({type:N.literal("schematic_layout_error"),schematic_layout_error_id:Yo("schematic_layout_error"),error_type:N.literal("schematic_layout_error").default("schematic_layout_error"),source_group_id:N.string(),schematic_group_id:N.string(),subcircuit_id:N.string().optional()}).describe("Error emitted when schematic layout fails for a group"),Abe=N.object({type:N.literal("schematic_debug_object"),label:N.string().optional(),subcircuit_id:N.string().optional()}),rso=Abe.extend({shape:N.literal("rect"),center:Lr,size:D3t}),sso=Abe.extend({shape:N.literal("line"),start:Lr,end:Lr}),aso=Abe.extend({shape:N.literal("point"),center:Lr}),Aso=N.discriminatedUnion("shape",[rso,sso,aso]),cso=N.object({type:N.literal("schematic_voltage_probe"),schematic_voltage_probe_id:N.string(),source_component_id:N.string().optional(),name:N.string().optional(),position:Lr,schematic_trace_id:N.string(),voltage:dv.optional(),subcircuit_id:N.string().optional(),color:N.string().optional(),label_alignment:hv.optional()}).describe("Defines a voltage probe measurement point on a schematic trace"),lso=N.object({type:N.literal("schematic_manual_edit_conflict_warning"),schematic_manual_edit_conflict_warning_id:Yo("schematic_manual_edit_conflict_warning"),warning_type:N.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"),message:N.string(),schematic_component_id:N.string(),schematic_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_component_id:N.string()}).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates"),uso=N.object({type:N.literal("schematic_group"),schematic_group_id:Yo("schematic_group"),source_group_id:N.string(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),width:Ui,height:Ui,center:Lr,schematic_component_ids:N.array(N.string()),show_as_schematic_box:N.boolean().optional(),name:N.string().optional(),description:N.string().optional()}).describe("Defines a group of components on the schematic"),gso=N.object({type:N.literal("schematic_table"),schematic_table_id:Yo("schematic_table"),anchor_position:Lr,column_widths:N.array(ho),row_heights:N.array(ho),cell_padding:ho.optional(),border_width:ho.optional(),subcircuit_id:N.string().optional(),schematic_component_id:N.string().optional(),anchor:hv.optional()}).describe("Defines a table on the schematic"),dso=N.object({type:N.literal("schematic_table_cell"),schematic_table_cell_id:Yo("schematic_table_cell"),schematic_table_id:N.string(),start_row_index:N.number(),end_row_index:N.number(),start_column_index:N.number(),end_column_index:N.number(),text:N.string().optional(),center:Lr,width:ho,height:ho,horizontal_align:N.enum(["left","center","right"]).optional(),vertical_align:N.enum(["top","middle","bottom"]).optional(),font_size:ho.optional(),subcircuit_id:N.string().optional()}).describe("Defines a cell within a schematic_table"),hso=N.object({type:N.literal("schematic_sheet"),schematic_sheet_id:Yo("schematic_sheet"),name:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Defines a schematic sheet or page that components can be placed on"),pso=N.object({x:ho,y:ho,bulge:N.number().optional()}),rEt=N.object({vertices:N.array(pso)}),mso=N.object({outer_ring:rEt,inner_rings:N.array(rEt).default([])}),_so=N.object({x:ho,y:ho,via:N.boolean().optional(),via_to_layer:Pc.optional()}),fso=(N.array(_so),N.object({x:ho,y:ho,via:N.boolean().optional(),to_layer:Pc.optional(),trace_width:ho.optional()})),Iso=N.object({min_trace_width:Ui.optional(),min_board_edge_clearance:Ui.optional(),min_via_hole_edge_to_via_hole_edge_clearance:Ui.optional(),min_plated_hole_drill_edge_to_drill_edge_clearance:Ui.optional(),min_trace_to_pad_edge_clearance:Ui.optional(),min_pad_edge_to_pad_edge_clearance:Ui.optional(),min_same_net_trace_edge_to_trace_edge_clearance:Ui.optional(),min_different_net_trace_edge_to_trace_edge_clearance:Ui.optional(),min_via_hole_diameter:Ui.optional(),min_via_pad_diameter:Ui.optional()}),Cso=N.object({type:N.literal("pcb_component"),pcb_component_id:Yo("pcb_component"),source_component_id:N.string(),center:Lr,layer:Pc,rotation:jm,display_offset_x:N.string().optional().describe("How to display the x offset for this part, usually corresponding with how the user specified it"),display_offset_y:N.string().optional().describe("How to display the y offset for this part, usually corresponding with how the user specified it"),width:Ui,height:Ui,do_not_place:N.boolean().optional(),is_allowed_to_be_off_board:N.boolean().optional(),subcircuit_id:N.string().optional(),pcb_group_id:N.string().optional(),position_mode:N.enum(["packed","relative_to_group_anchor","relative_to_another_component","none"]).optional(),anchor_position:Lr.optional(),anchor_alignment:hv.optional(),positioned_relative_to_pcb_group_id:N.string().optional(),positioned_relative_to_pcb_board_id:N.string().optional(),cable_insertion_center:Lr.optional(),insertion_direction:N.enum(["from_above","from_left","from_right","from_front","from_back"]).optional(),metadata:N.object({kicad_footprint:rro.optional()}).optional(),obstructs_within_bounds:N.boolean().default(!0).describe("Does this component take up all the space within its bounds on a layer. This is generally true except for when separated pin headers are being represented by a single component (in which case, chips can be placed between the pin headers) or for tall modules where chips fit underneath")}).describe("Defines a component on the PCB"),sEt=N.object({type:N.literal("pcb_hole"),pcb_hole_id:Yo("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("circle"),hole_diameter:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),aEt=(sEt.describe("Defines a circular hole on the PCB"),N.object({type:N.literal("pcb_hole"),pcb_hole_id:Yo("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("rect"),hole_width:N.number(),hole_height:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),AEt=(aEt.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square."),N.object({type:N.literal("pcb_hole"),pcb_hole_id:Yo("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.enum(["circle","square"]),hole_diameter:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),cEt=(AEt.describe("Defines a circular or square hole on the PCB"),N.object({type:N.literal("pcb_hole"),pcb_hole_id:Yo("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("oval"),hole_width:N.number(),hole_height:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),lEt=(cEt.describe("Defines an oval hole on the PCB"),N.object({type:N.literal("pcb_hole"),pcb_hole_id:Yo("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("pill"),hole_width:N.number(),hole_height:N.number(),x:ho,y:ho,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),uEt=(lEt.describe("Defines a pill-shaped hole on the PCB"),N.object({type:N.literal("pcb_hole"),pcb_hole_id:Yo("pcb_hole"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_component_id:N.string().optional(),hole_shape:N.literal("rotated_pill"),hole_width:N.number(),hole_height:N.number(),x:ho,y:ho,ccw_rotation:jm,is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()})),yso=(uEt.describe("Defines a rotated pill-shaped hole on the PCB"),AEt.or(cEt).or(lEt).or(uEt).or(sEt).or(aEt)),xso=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("circle"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),outer_diameter:N.number(),hole_diameter:N.number(),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo("pcb_plated_hole"),soldermask_margin:N.number().optional()}),Eso=N.object({type:N.literal("pcb_plated_hole"),shape:N.enum(["oval","pill"]),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),outer_width:N.number(),outer_height:N.number(),hole_width:N.number(),hole_height:N.number(),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,ccw_rotation:jm,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo("pcb_plated_hole"),soldermask_margin:N.number().optional()}),Bso=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("circular_hole_with_rect_pad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal("circle"),pad_shape:N.literal("rect"),hole_diameter:N.number(),rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),hole_offset_x:ho.default(0),hole_offset_y:ho.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo("pcb_plated_hole"),soldermask_margin:N.number().optional(),rect_ccw_rotation:jm.optional()}),bso=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("pill_hole_with_rect_pad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal("pill"),pad_shape:N.literal("rect"),hole_width:N.number(),hole_height:N.number(),rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),hole_offset_x:ho.default(0),hole_offset_y:ho.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo("pcb_plated_hole"),soldermask_margin:N.number().optional()}),Sso=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("rotated_pill_hole_with_rect_pad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.literal("rotated_pill"),pad_shape:N.literal("rect"),hole_width:N.number(),hole_height:N.number(),hole_ccw_rotation:jm,rect_pad_width:N.number(),rect_pad_height:N.number(),rect_border_radius:N.number().optional(),rect_ccw_rotation:jm,hole_offset_x:ho.default(0),hole_offset_y:ho.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo("pcb_plated_hole"),soldermask_margin:N.number().optional()}),Qso=N.object({type:N.literal("pcb_plated_hole"),shape:N.literal("hole_with_polygon_pad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),hole_shape:N.enum(["circle","oval","pill","rotated_pill"]),hole_diameter:N.number().optional(),hole_width:N.number().optional(),hole_height:N.number().optional(),pad_outline:N.array(N.object({x:ho,y:ho})).min(3),hole_offset_x:ho.default(0),hole_offset_y:ho.default(0),is_covered_with_solder_mask:N.boolean().optional(),x:ho,y:ho,layers:N.array(Pc),port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),pcb_plated_hole_id:Yo("pcb_plated_hole"),soldermask_margin:N.number().optional(),ccw_rotation:jm.optional()}),vso=N.union([xso,Eso,Bso,bso,Sso,Qso]),wso=N.object({type:N.literal("pcb_port"),pcb_port_id:Yo("pcb_port"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_port_id:N.string(),pcb_component_id:N.string().optional(),x:ho,y:ho,layers:N.array(Pc),is_board_pinout:N.boolean().optional()}).describe("Defines a port on the PCB"),Pso=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("circle"),pcb_smtpad_id:Yo("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,radius:N.number(),layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Mso=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("rect"),pcb_smtpad_id:Yo("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),rect_border_radius:N.number().optional(),corner_radius:N.number().optional(),layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional(),soldermask_margin_left:N.number().optional(),soldermask_margin_top:N.number().optional(),soldermask_margin_right:N.number().optional(),soldermask_margin_bottom:N.number().optional()}),Dso=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("rotated_rect"),pcb_smtpad_id:Yo("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),rect_border_radius:N.number().optional(),corner_radius:N.number().optional(),ccw_rotation:jm,layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional(),soldermask_margin_left:N.number().optional(),soldermask_margin_top:N.number().optional(),soldermask_margin_right:N.number().optional(),soldermask_margin_bottom:N.number().optional()}),Nso=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("pill"),pcb_smtpad_id:Yo("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),radius:N.number(),layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Rso=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("rotated_pill"),pcb_smtpad_id:Yo("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),radius:N.number(),ccw_rotation:jm,layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),Tso=N.object({type:N.literal("pcb_smtpad"),shape:N.literal("polygon"),pcb_smtpad_id:Yo("pcb_smtpad"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),points:N.array(Lr),layer:Pc,port_hints:N.array(N.string()).optional(),pcb_component_id:N.string().optional(),pcb_port_id:N.string().optional(),is_covered_with_solder_mask:N.boolean().optional(),soldermask_margin:N.number().optional()}),kso=N.discriminatedUnion("shape",[Pso,Mso,Dso,Rso,Nso,Tso]).describe("Defines an SMT pad on the PCB"),Fso=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("circle"),pcb_solder_paste_id:Yo("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,radius:N.number(),layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Lso=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("rect"),pcb_solder_paste_id:Yo("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Hso=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("pill"),pcb_solder_paste_id:Yo("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),radius:N.number(),layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Oso=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("rotated_rect"),pcb_solder_paste_id:Yo("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),ccw_rotation:ho,layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Gso=N.object({type:N.literal("pcb_solder_paste"),shape:N.literal("oval"),pcb_solder_paste_id:Yo("pcb_solder_paste"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),x:ho,y:ho,width:N.number(),height:N.number(),layer:Pc,pcb_component_id:N.string().optional(),pcb_smtpad_id:N.string().optional()}),Yso=N.union([Fso,Lso,Hso,Oso,Gso]).describe("Defines solderpaste on the PCB"),Uso=N.object({type:N.literal("pcb_text"),pcb_text_id:Yo("pcb_text"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),text:N.string(),center:Lr,layer:Pc,width:Ui,height:Ui,lines:N.number(),align:N.enum(["bottom-left"])}).describe("Defines text on the PCB"),Kso=N.object({route_type:N.literal("wire"),x:ho,y:ho,width:ho,copper_pour_id:N.string().optional(),is_inside_copper_pour:N.boolean().optional(),start_pcb_port_id:N.string().optional(),end_pcb_port_id:N.string().optional(),layer:Pc}),Vso=N.object({route_type:N.literal("via"),x:ho,y:ho,copper_pour_id:N.string().optional(),is_inside_copper_pour:N.boolean().optional(),hole_diameter:ho.optional(),outer_diameter:ho.optional(),from_layer:Pc,to_layer:Pc}),zso=N.union([Kso,Vso]),Jso=N.object({type:N.literal("pcb_trace"),source_trace_id:N.string().optional(),pcb_component_id:N.string().optional(),pcb_trace_id:Yo("pcb_trace"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),route_thickness_mode:N.enum(["constant","interpolated"]).default("constant").optional(),route_order_index:N.number().optional(),should_round_corners:N.boolean().optional(),trace_length:N.number().optional(),highlight_color:N.string().optional(),route:N.array(zso)}).describe("Defines a trace on the PCB"),Wso=N.object({type:N.literal("pcb_trace_warning"),pcb_trace_warning_id:Yo("pcb_trace_warning"),warning_type:N.literal("pcb_trace_warning").default("pcb_trace_warning"),message:N.string(),center:Lr.optional(),pcb_trace_id:N.string(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines a trace warning on the PCB"),jso=N0.extend({type:N.literal("pcb_trace_error"),pcb_trace_error_id:Yo("pcb_trace_error"),error_type:N.literal("pcb_trace_error").default("pcb_trace_error"),center:Lr.optional(),pcb_trace_id:N.string(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines a trace error on the PCB"),$so=N0.extend({type:N.literal("pcb_trace_missing_error"),pcb_trace_missing_error_id:Yo("pcb_trace_missing_error"),error_type:N.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"),center:Lr.optional(),source_trace_id:N.string(),pcb_component_ids:N.array(N.string()),pcb_port_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines an error when a source trace has no corresponding PCB trace"),qso=N0.extend({type:N.literal("pcb_port_not_matched_error"),pcb_error_id:Yo("pcb_error"),error_type:N.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"),pcb_component_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines a trace error on the PCB where a port is not matched"),Xso=N0.extend({type:N.literal("pcb_port_not_connected_error"),pcb_port_not_connected_error_id:Yo("pcb_port_not_connected_error"),error_type:N.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"),pcb_port_ids:N.array(N.string()),pcb_component_ids:N.array(N.string()),subcircuit_id:N.string().optional()}).describe("Defines an error when a pcb port is not connected to any trace"),Zso=N.object({type:N.literal("pcb_net"),pcb_net_id:Yo("pcb_net"),source_net_id:N.string().optional(),highlight_color:N.string().optional()}).describe("Defines a net on the PCB"),eao=N.object({type:N.literal("pcb_via"),pcb_via_id:Yo("pcb_via"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),x:ho,y:ho,outer_diameter:ho.default("0.6mm"),hole_diameter:ho.default("0.25mm"),from_layer:Pc.optional(),to_layer:Pc.optional(),layers:N.array(Pc),pcb_trace_id:N.string().optional(),net_is_assignable:N.boolean().optional(),net_assigned:N.boolean().optional(),is_tented:N.boolean().optional()}).describe("Defines a via on the PCB"),tao=N.object({type:N.literal("pcb_board"),pcb_board_id:Yo("pcb_board"),pcb_panel_id:N.string().optional(),carrier_pcb_board_id:N.string().optional(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),is_mounted_to_carrier_board:N.boolean().optional(),width:Ui.optional(),height:Ui.optional(),center:Lr,display_offset_x:N.string().optional().describe("How to display the x offset for this board, usually corresponding with how the user specified it"),display_offset_y:N.string().optional().describe("How to display the y offset for this board, usually corresponding with how the user specified it"),thickness:Ui.optional().default(1.4),num_layers:N.number().optional().default(4),outline:N.array(Lr).optional(),shape:N.enum(["rect","polygon"]).optional(),material:N.enum(["fr4","fr1"]).default("fr4"),anchor_position:Lr.optional(),anchor_alignment:hv.optional(),position_mode:N.enum(["relative_to_panel_anchor","none"]).optional()}).merge(Iso).describe("Defines the board outline of the PCB"),nao=N.object({type:N.literal("pcb_panel"),pcb_panel_id:Yo("pcb_panel"),width:Ui,height:Ui,center:Lr,thickness:Ui.optional().default(1.4),covered_with_solder_mask:N.boolean().optional().default(!0)}).describe("Defines a PCB panel that can contain multiple boards"),oao=N0.extend({type:N.literal("pcb_placement_error"),pcb_placement_error_id:Yo("pcb_placement_error"),error_type:N.literal("pcb_placement_error").default("pcb_placement_error"),subcircuit_id:N.string().optional()}).describe("Defines a placement error on the PCB"),iao=N0.extend({type:N.literal("pcb_panelization_placement_error"),pcb_panelization_placement_error_id:Yo("pcb_panelization_placement_error"),error_type:N.literal("pcb_panelization_placement_error").default("pcb_panelization_placement_error"),pcb_panel_id:N.string().optional(),pcb_board_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Defines a panelization placement error on the PCB"),rao=N.object({type:N.literal("pcb_trace_hint"),pcb_trace_hint_id:Yo("pcb_trace_hint"),pcb_port_id:N.string(),pcb_component_id:N.string(),route:N.array(fso),subcircuit_id:N.string().optional()}).describe("A hint that can be used during generation of a PCB trace"),sao=N.object({type:N.literal("pcb_silkscreen_line"),pcb_silkscreen_line_id:Yo("pcb_silkscreen_line"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),stroke_width:ho.default("0.1mm"),x1:ho,y1:ho,x2:ho,y2:ho,layer:mC}).describe("Defines a silkscreen line on the PCB"),aao=N.object({type:N.literal("pcb_silkscreen_path"),pcb_silkscreen_path_id:Yo("pcb_silkscreen_path"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:mC,route:N.array(Lr),stroke_width:Ui}).describe("Defines a silkscreen path on the PCB"),Aao=N.object({type:N.literal("pcb_silkscreen_text"),pcb_silkscreen_text_id:Yo("pcb_silkscreen_text"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:ho.default("0.2mm"),pcb_component_id:N.string(),text:N.string(),is_knockout:N.boolean().default(!1).optional(),knockout_padding:N.object({left:Ui,top:Ui,bottom:Ui,right:Ui}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:N.number().optional(),layer:Pc,is_mirrored:N.boolean().default(!1).optional(),anchor_position:Lr.default({x:0,y:0}),anchor_alignment:hv.default("center")}).describe("Defines silkscreen text on the PCB"),cao=N.object({type:N.literal("pcb_copper_text"),pcb_copper_text_id:Yo("pcb_copper_text"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:ho.default("0.2mm"),pcb_component_id:N.string(),text:N.string(),is_knockout:N.boolean().default(!1).optional(),knockout_padding:N.object({left:Ui,top:Ui,bottom:Ui,right:Ui}).default({left:"0.2mm",top:"0.2mm",bottom:"0.2mm",right:"0.2mm"}).optional(),ccw_rotation:N.number().optional(),layer:Pc,is_mirrored:N.boolean().default(!1).optional(),anchor_position:Lr.default({x:0,y:0}),anchor_alignment:hv.default("center")}).describe("Defines copper text on the PCB"),lao=N.object({type:N.literal("pcb_silkscreen_rect"),pcb_silkscreen_rect_id:Yo("pcb_silkscreen_rect"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:Pc,stroke_width:Ui.default("1mm"),corner_radius:Ui.optional(),is_filled:N.boolean().default(!0).optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),ccw_rotation:N.number().optional()}).describe("Defines a silkscreen rect on the PCB"),uao=N.object({type:N.literal("pcb_silkscreen_circle"),pcb_silkscreen_circle_id:Yo("pcb_silkscreen_circle"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,radius:Ui,layer:mC,stroke_width:Ui.default("1mm"),is_filled:N.boolean().optional()}).describe("Defines a silkscreen circle on the PCB"),gao=N.object({type:N.literal("pcb_silkscreen_oval"),pcb_silkscreen_oval_id:Yo("pcb_silkscreen_oval"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,radius_x:ho,radius_y:ho,layer:mC,ccw_rotation:jm.optional()}).describe("Defines a silkscreen oval on the PCB"),dao=N.object({type:N.literal("pcb_silkscreen_pill"),pcb_silkscreen_pill_id:Yo("pcb_silkscreen_pill"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:Pc,ccw_rotation:N.number().optional()}).describe("Defines a silkscreen pill on the PCB"),hao=N.object({type:N.literal("pcb_fabrication_note_text"),pcb_fabrication_note_text_id:Yo("pcb_fabrication_note_text"),subcircuit_id:N.string().optional(),pcb_group_id:N.string().optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:ho.default("1mm"),pcb_component_id:N.string(),text:N.string(),layer:mC,anchor_position:Lr.default({x:0,y:0}),anchor_alignment:N.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),color:N.string().optional()}).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators"),pao=N.object({type:N.literal("pcb_fabrication_note_path"),pcb_fabrication_note_path_id:Yo("pcb_fabrication_note_path"),pcb_component_id:N.string(),subcircuit_id:N.string().optional(),layer:Pc,route:N.array(Lr),stroke_width:Ui,color:N.string().optional()}).describe("Defines a fabrication path on the PCB for fabricators or assemblers"),mao=N.object({type:N.literal("pcb_fabrication_note_rect"),pcb_fabrication_note_rect_id:Yo("pcb_fabrication_note_rect"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:mC,stroke_width:Ui.default("0.1mm"),corner_radius:Ui.optional(),is_filled:N.boolean().optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),color:N.string().optional()}).describe("Defines a fabrication note rectangle on the PCB"),_ao=N.object({type:N.literal("pcb_fabrication_note_dimension"),pcb_fabrication_note_dimension_id:Yo("pcb_fabrication_note_dimension"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:mC,from:Lr,to:Lr,text:N.string().optional(),text_ccw_rotation:N.number().optional(),offset:Ui.optional(),offset_distance:Ui.optional(),offset_direction:N.object({x:N.number(),y:N.number()}).optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:Ui.default("1mm"),color:N.string().optional(),arrow_size:Ui.default("1mm")}).describe("Defines a measurement annotation within PCB fabrication notes"),fao=N.object({type:N.literal("pcb_note_text"),pcb_note_text_id:Yo("pcb_note_text"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:ho.default("1mm"),text:N.string().optional(),anchor_position:Lr.default({x:0,y:0}),anchor_alignment:N.enum(["center","top_left","top_right","bottom_left","bottom_right"]).default("center"),layer:mC.default("top"),is_mirrored_from_top_view:N.boolean().optional(),color:N.string().optional()}).describe("Defines a documentation note in text on the PCB"),Iao=N.object({type:N.literal("pcb_note_rect"),pcb_note_rect_id:Yo("pcb_note_rect"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:mC.default("top"),stroke_width:Ui.default("0.1mm"),corner_radius:Ui.optional(),is_filled:N.boolean().optional(),has_stroke:N.boolean().optional(),is_stroke_dashed:N.boolean().optional(),color:N.string().optional()}).describe("Defines a rectangular documentation note on the PCB"),Cao=N.object({type:N.literal("pcb_note_path"),pcb_note_path_id:Yo("pcb_note_path"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),route:N.array(Lr),layer:mC.default("top"),stroke_width:Ui.default("0.1mm"),color:N.string().optional()}).describe("Defines a polyline documentation note on the PCB"),yao=N.object({type:N.literal("pcb_note_line"),pcb_note_line_id:Yo("pcb_note_line"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),text:N.string().optional(),x1:ho,y1:ho,x2:ho,y2:ho,layer:mC.default("top"),stroke_width:ho.default("0.1mm"),color:N.string().optional(),is_dashed:N.boolean().optional()}).describe("Defines a straight documentation note line on the PCB"),xao=N.object({type:N.literal("pcb_note_dimension"),pcb_note_dimension_id:Yo("pcb_note_dimension"),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),name:N.string().optional(),from:Lr,to:Lr,text:N.string().optional(),text_ccw_rotation:N.number().optional(),offset_distance:Ui.optional(),offset_direction:N.object({x:N.number(),y:N.number()}).optional(),font:N.literal("tscircuit2024").default("tscircuit2024"),font_size:Ui.default("1mm"),layer:mC.default("top"),color:N.string().optional(),arrow_size:Ui.default("1mm")}).describe("Defines a measurement annotation within PCB documentation notes"),Eao=N0.extend({type:N.literal("pcb_footprint_overlap_error"),pcb_error_id:Yo("pcb_error"),error_type:N.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"),pcb_smtpad_ids:N.array(N.string()).optional(),pcb_plated_hole_ids:N.array(N.string()).optional(),pcb_hole_ids:N.array(N.string()).optional(),pcb_keepout_ids:N.array(N.string()).optional()}).describe("Error emitted when a pcb footprint overlaps with another element"),Bao=N0.extend({type:N.literal("pcb_courtyard_overlap_error"),pcb_error_id:Yo("pcb_error"),error_type:N.literal("pcb_courtyard_overlap_error").default("pcb_courtyard_overlap_error"),pcb_component_ids:N.tuple([N.string(),N.string()])}).describe("Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another"),bao=N.object({type:N.literal("pcb_keepout"),shape:N.literal("rect"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:ho,height:ho,pcb_keepout_id:N.string(),layers:N.array(N.string()),description:N.string().optional()}).or(N.object({type:N.literal("pcb_keepout"),shape:N.literal("circle"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,radius:ho,pcb_keepout_id:N.string(),layers:N.array(N.string()),description:N.string().optional()})),uAe=N.object({type:N.literal("pcb_cutout"),pcb_cutout_id:Yo("pcb_cutout"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),pcb_board_id:N.string().optional(),pcb_panel_id:N.string().optional()}),Sao=uAe.extend({shape:N.literal("rect"),center:Lr,width:Ui,height:Ui,rotation:jm.optional(),corner_radius:Ui.optional()}),Qao=uAe.extend({shape:N.literal("circle"),center:Lr,radius:Ui}),vao=uAe.extend({shape:N.literal("polygon"),points:N.array(Lr)}),wao=uAe.extend({shape:N.literal("path"),route:N.array(Lr),slot_width:Ui,slot_length:Ui.optional(),space_between_slots:Ui.optional(),slot_corner_radius:Ui.optional()}),Pao=N.discriminatedUnion("shape",[Sao,Qao,vao,wao]).describe("Defines a cutout on the PCB, removing board material."),Mao=N0.extend({type:N.literal("pcb_missing_footprint_error"),pcb_missing_footprint_error_id:Yo("pcb_missing_footprint_error"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"),source_component_id:N.string()}).describe("Defines a missing footprint error on the PCB"),Dao=N0.extend({type:N.literal("external_footprint_load_error"),external_footprint_load_error_id:Yo("external_footprint_load_error"),pcb_component_id:N.string(),source_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),footprinter_string:N.string().optional(),error_type:N.literal("external_footprint_load_error").default("external_footprint_load_error")}).describe("Defines an error when an external footprint fails to load"),Nao=N0.extend({type:N.literal("circuit_json_footprint_load_error"),circuit_json_footprint_load_error_id:Yo("circuit_json_footprint_load_error"),pcb_component_id:N.string(),source_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),error_type:N.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"),circuit_json:N.array(N.any()).optional()}).describe("Defines an error when a circuit JSON footprint fails to load"),Rao=N.object({type:N.literal("pcb_group"),pcb_group_id:Yo("pcb_group"),source_group_id:N.string(),is_subcircuit:N.boolean().optional(),subcircuit_id:N.string().optional(),width:Ui.optional(),height:Ui.optional(),center:Lr,display_offset_x:N.string().optional().describe("How to display the x offset for this group, usually corresponding with how the user specified it"),display_offset_y:N.string().optional().describe("How to display the y offset for this group, usually corresponding with how the user specified it"),outline:N.array(Lr).optional(),anchor_position:Lr.optional(),anchor_alignment:hv.default("center"),position_mode:N.enum(["packed","relative_to_group_anchor","none"]).optional(),positioned_relative_to_pcb_group_id:N.string().optional(),positioned_relative_to_pcb_board_id:N.string().optional(),pcb_component_ids:N.array(N.string()),child_layout_mode:N.enum(["packed","none"]).optional(),name:N.string().optional(),description:N.string().optional(),layout_mode:N.string().optional(),autorouter_configuration:N.object({trace_clearance:Ui}).optional(),autorouter_used_string:N.string().optional()}).describe("Defines a group of components on the PCB"),Tao=N0.extend({type:N.literal("pcb_autorouting_error"),pcb_error_id:Yo("pcb_autorouting_error"),error_type:N.literal("pcb_autorouting_error").default("pcb_autorouting_error"),subcircuit_id:N.string().optional()}).describe("The autorouting has failed to route a portion of the board"),kao=N.object({type:N.literal("pcb_manual_edit_conflict_warning"),pcb_manual_edit_conflict_warning_id:Yo("pcb_manual_edit_conflict_warning"),warning_type:N.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"),message:N.string(),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),source_component_id:N.string()}).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates"),gEt=N.enum(["x-","x+","y+","y-"]),Fao=N.object({type:N.literal("pcb_connector_not_in_accessible_orientation_warning"),pcb_connector_not_in_accessible_orientation_warning_id:Yo("pcb_connector_not_in_accessible_orientation_warning"),warning_type:N.literal("pcb_connector_not_in_accessible_orientation_warning").default("pcb_connector_not_in_accessible_orientation_warning"),message:N.string(),pcb_component_id:N.string(),source_component_id:N.string().optional(),pcb_board_id:N.string().optional(),facing_direction:gEt,recommended_facing_direction:gEt,subcircuit_id:N.string().optional()}).describe("Warning emitted when a connector PCB component is facing inward toward the board and should be reoriented to an outward-facing direction"),Lao=N.object({type:N.literal("supplier_footprint_mismatch_warning"),supplier_footprint_mismatch_warning_id:Yo("supplier_footprint_mismatch_warning"),warning_type:N.literal("supplier_footprint_mismatch_warning").default("supplier_footprint_mismatch_warning"),message:N.string(),source_component_id:N.string(),pcb_component_id:N.string().optional(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),supplier_name:R3t.optional(),supplier_part_number:N.string().optional(),supplier_footprint_url:N.string().optional(),footprint_copper_intersection_over_union:N.number()}).describe("Warning emitted when a supplier part footprint does not match the expected footprint"),Hao=N.object({type:N.literal("pcb_breakout_point"),pcb_breakout_point_id:Yo("pcb_breakout_point"),pcb_group_id:N.string(),subcircuit_id:N.string().optional(),source_trace_id:N.string().optional(),source_port_id:N.string().optional(),source_net_id:N.string().optional(),x:ho,y:ho}).describe("Defines a routing target within a pcb_group for a source_trace or source_net"),Oao=N.object({type:N.literal("pcb_ground_plane"),pcb_ground_plane_id:Yo("pcb_ground_plane"),source_pcb_ground_plane_id:N.string(),source_net_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Defines a ground plane on the PCB"),Gao=N.object({type:N.literal("pcb_ground_plane_region"),pcb_ground_plane_region_id:Yo("pcb_ground_plane_region"),pcb_ground_plane_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:Pc,points:N.array(Lr)}).describe("Defines a polygon region of a ground plane"),Yao=N.object({type:N.literal("pcb_thermal_spoke"),pcb_thermal_spoke_id:Yo("pcb_thermal_spoke"),pcb_ground_plane_id:N.string(),shape:N.string(),spoke_count:N.number(),spoke_thickness:ho,spoke_inner_diameter:ho,spoke_outer_diameter:ho,pcb_plated_hole_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Pattern for connecting a ground plane to a plated hole"),cbe=N.object({type:N.literal("pcb_copper_pour"),pcb_copper_pour_id:Yo("pcb_copper_pour"),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:Pc,source_net_id:N.string().optional(),covered_with_solder_mask:N.boolean().optional().default(!0)}),Uao=cbe.extend({shape:N.literal("rect"),center:Lr,width:Ui,height:Ui,rotation:jm.optional()}),Kao=cbe.extend({shape:N.literal("brep"),brep_shape:mso}),Vao=cbe.extend({shape:N.literal("polygon"),points:N.array(Lr)}),zao=N.discriminatedUnion("shape",[Uao,Kao,Vao]).describe("Defines a copper pour on the PCB."),Jao=N0.extend({type:N.literal("pcb_component_outside_board_error"),pcb_component_outside_board_error_id:Yo("pcb_component_outside_board_error"),error_type:N.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"),pcb_component_id:N.string(),pcb_board_id:N.string(),component_center:Lr,component_bounds:N.object({min_x:N.number(),max_x:N.number(),min_y:N.number(),max_y:N.number()}),subcircuit_id:N.string().optional(),source_component_id:N.string().optional()}).describe("Error emitted when a PCB component is placed outside the board boundaries"),Wao=N0.extend({type:N.literal("pcb_component_not_on_board_edge_error"),pcb_component_not_on_board_edge_error_id:Yo("pcb_component_not_on_board_edge_error"),error_type:N.literal("pcb_component_not_on_board_edge_error").default("pcb_component_not_on_board_edge_error"),pcb_component_id:N.string(),pcb_board_id:N.string(),component_center:Lr,pad_to_nearest_board_edge_distance:N.number(),source_component_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when a component that must be placed on the board edge is centered away from the edge"),jao=N0.extend({type:N.literal("pcb_component_invalid_layer_error"),pcb_component_invalid_layer_error_id:Yo("pcb_component_invalid_layer_error"),error_type:N.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"),pcb_component_id:N.string().optional(),source_component_id:N.string(),layer:Pc,subcircuit_id:N.string().optional()}).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)"),$ao=N0.extend({type:N.literal("pcb_via_clearance_error"),pcb_error_id:Yo("pcb_error"),error_type:N.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"),pcb_via_ids:N.array(N.string()).min(2),minimum_clearance:ho.optional(),actual_clearance:ho.optional(),pcb_center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when vias are closer than the allowed clearance"),qao=N0.extend({type:N.literal("pcb_via_trace_clearance_error"),pcb_via_trace_clearance_error_id:Yo("pcb_via_trace_clearance_error"),error_type:N.literal("pcb_via_trace_clearance_error").default("pcb_via_trace_clearance_error"),pcb_via_id:N.string(),pcb_trace_id:N.string(),minimum_clearance:ho.optional(),actual_clearance:ho.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when a via and trace are closer than the allowed clearance"),Xao=N0.extend({type:N.literal("pcb_pad_pad_clearance_error"),pcb_pad_pad_clearance_error_id:Yo("pcb_pad_pad_clearance_error"),error_type:N.literal("pcb_pad_pad_clearance_error").default("pcb_pad_pad_clearance_error"),pcb_pad_ids:N.array(N.string()).min(2),minimum_clearance:ho.optional(),actual_clearance:ho.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when pads are closer than the allowed clearance"),Zao=N0.extend({type:N.literal("pcb_pad_trace_clearance_error"),pcb_pad_trace_clearance_error_id:Yo("pcb_pad_trace_clearance_error"),error_type:N.literal("pcb_pad_trace_clearance_error").default("pcb_pad_trace_clearance_error"),pcb_pad_id:N.string(),pcb_trace_id:N.string(),minimum_clearance:ho.optional(),actual_clearance:ho.optional(),center:N.object({x:N.number().optional(),y:N.number().optional()}).optional(),subcircuit_id:N.string().optional()}).describe("Error emitted when a pad and trace are closer than allowed clearance"),eAo=N.object({type:N.literal("pcb_courtyard_rect"),pcb_courtyard_rect_id:Yo("pcb_courtyard_rect"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,width:Ui,height:Ui,layer:mC,ccw_rotation:jm.optional(),color:N.string().optional()}).describe("Defines a courtyard rectangle on the PCB"),tAo=N.object({type:N.literal("pcb_courtyard_outline"),pcb_courtyard_outline_id:Yo("pcb_courtyard_outline"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:mC,outline:N.array(Lr).min(2)}).describe("Defines a courtyard outline on the PCB"),nAo=N.object({type:N.literal("pcb_courtyard_polygon"),pcb_courtyard_polygon_id:Yo("pcb_courtyard_polygon"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),layer:mC,points:N.array(Lr).min(3),color:N.string().optional()}).describe("Defines a courtyard polygon on the PCB"),oAo=N.object({type:N.literal("pcb_courtyard_circle"),pcb_courtyard_circle_id:Yo("pcb_courtyard_circle"),pcb_component_id:N.string(),pcb_group_id:N.string().optional(),subcircuit_id:N.string().optional(),center:Lr,radius:Ui,layer:mC,color:N.string().optional()}).describe("Defines a courtyard circle on the PCB"),iAo=N.object({type:N.literal("cad_component"),cad_component_id:N.string(),pcb_component_id:N.string(),source_component_id:N.string(),position:nN,rotation:nN.optional(),size:nN.optional(),layer:Pc.optional(),subcircuit_id:N.string().optional(),footprinter_string:N.string().optional(),model_obj_url:N.string().optional(),model_stl_url:N.string().optional(),model_3mf_url:N.string().optional(),model_gltf_url:N.string().optional(),model_glb_url:N.string().optional(),model_step_url:N.string().optional(),model_wrl_url:N.string().optional(),model_asset:Zio.optional(),model_unit_to_mm_scale_factor:N.number().optional(),model_board_normal_direction:N.enum(["x+","x-","y+","y-","z+","z-"]).optional().describe(`The direction in the model's coordinate space that is considered "up" or "coming out of the board surface"`),model_origin_position:nN.optional(),model_origin_alignment:N.enum(["unknown","center","center_of_component_on_board_surface","bottom_center_of_component"]).optional(),model_object_fit:N.enum(["contain_within_bounds","fill_bounds"]).optional().default("contain_within_bounds"),model_jscad:N.any().optional(),show_as_translucent_model:N.boolean().optional(),anchor_alignment:N.enum(["center","center_of_component_on_board_surface"]).optional().default("center")}).describe("Defines a component on the PCB"),dEt=N.enum(["sinewave","square","triangle","sawtooth"]),rAo=N.union([N.string(),N.number()]).transform(t=>typeof t=="string"?t.endsWith("%")?parseFloat(t.slice(0,-1))/100:parseFloat(t):t).pipe(N.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),sAo=N.object({type:N.literal("simulation_voltage_source"),simulation_voltage_source_id:Yo("simulation_voltage_source"),is_dc_source:N.literal(!0).optional().default(!0),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),voltage:dv}).describe("Defines a DC voltage source for simulation"),aAo=N.object({type:N.literal("simulation_voltage_source"),simulation_voltage_source_id:Yo("simulation_voltage_source"),is_dc_source:N.literal(!1),terminal1_source_port_id:N.string().optional(),terminal2_source_port_id:N.string().optional(),terminal1_source_net_id:N.string().optional(),terminal2_source_net_id:N.string().optional(),voltage:dv.optional(),frequency:PL.optional(),peak_to_peak_voltage:dv.optional(),wave_shape:dEt.optional(),phase:jm.optional(),duty_cycle:rAo.optional()}).describe("Defines an AC voltage source for simulation"),AAo=N.union([sAo,aAo]).describe("Defines a voltage source for simulation"),cAo=N.union([N.string(),N.number()]).transform(t=>typeof t=="string"?t.endsWith("%")?parseFloat(t.slice(0,-1))/100:parseFloat(t):t).pipe(N.number().min(0,"Duty cycle must be non-negative").max(1,"Duty cycle cannot be greater than 100%")),lAo=N.object({type:N.literal("simulation_current_source"),simulation_current_source_id:Yo("simulation_current_source"),is_dc_source:N.literal(!0).optional().default(!0),positive_source_port_id:N.string().optional(),negative_source_port_id:N.string().optional(),positive_source_net_id:N.string().optional(),negative_source_net_id:N.string().optional(),current:HJ}).describe("Defines a DC current source for simulation"),uAo=N.object({type:N.literal("simulation_current_source"),simulation_current_source_id:Yo("simulation_current_source"),is_dc_source:N.literal(!1),terminal1_source_port_id:N.string().optional(),terminal2_source_port_id:N.string().optional(),terminal1_source_net_id:N.string().optional(),terminal2_source_net_id:N.string().optional(),current:HJ.optional(),frequency:PL.optional(),peak_to_peak_current:HJ.optional(),wave_shape:dEt.optional(),phase:jm.optional(),duty_cycle:cAo.optional()}).describe("Defines an AC current source for simulation"),gAo=N.union([lAo,uAo]).describe("Defines a current source for simulation"),dAo=N.union([N.literal("spice_dc_sweep"),N.literal("spice_dc_operating_point"),N.literal("spice_transient_analysis"),N.literal("spice_ac_analysis")]),hAo=N.object({type:N.literal("simulation_experiment"),simulation_experiment_id:Yo("simulation_experiment"),name:N.string(),experiment_type:dAo,time_per_step:rbe.optional(),start_time_ms:ML.optional(),end_time_ms:ML.optional()}).describe("Defines a simulation experiment configuration"),pAo=N.object({type:N.literal("simulation_transient_voltage_graph"),simulation_transient_voltage_graph_id:Yo("simulation_transient_voltage_graph"),simulation_experiment_id:N.string(),timestamps_ms:N.array(N.number()).optional(),voltage_levels:N.array(N.number()),source_component_id:N.string().optional(),subcircuit_connectivity_map_key:N.string().optional(),time_per_step:rbe,start_time_ms:ML,end_time_ms:ML,name:N.string().optional(),color:N.string().optional()}).describe("Stores voltage measurements over time for a simulation"),mAo=N.object({type:N.literal("simulation_switch"),simulation_switch_id:Yo("simulation_switch"),source_component_id:N.string().optional(),closes_at:ML.optional(),opens_at:ML.optional(),starts_closed:N.boolean().optional(),switching_frequency:PL.optional()}).describe("Defines a switch for simulation timing control"),_Ao=N.object({type:N.literal("simulation_voltage_probe"),simulation_voltage_probe_id:Yo("simulation_voltage_probe"),source_component_id:N.string().optional(),name:N.string().optional(),signal_input_source_port_id:N.string().optional(),signal_input_source_net_id:N.string().optional(),reference_input_source_port_id:N.string().optional(),reference_input_source_net_id:N.string().optional(),subcircuit_id:N.string().optional(),color:N.string().optional()}).describe("Defines a voltage probe for simulation. If a reference input is not provided, it measures against ground. If a reference input is provided, it measures the differential voltage between two points.").superRefine((t,e)=>{if(t.reference_input_source_port_id||t.reference_input_source_net_id){const n=!!t.signal_input_source_port_id||!!t.reference_input_source_port_id,o=!!t.signal_input_source_net_id||!!t.reference_input_source_net_id;n&&o?e.addIssue({code:N.ZodIssueCode.custom,message:"Cannot mix port and net connections in a differential probe."}):n?t.signal_input_source_port_id&&t.reference_input_source_port_id||e.addIssue({code:N.ZodIssueCode.custom,message:"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id."}):o&&(t.signal_input_source_net_id&&t.reference_input_source_net_id||e.addIssue({code:N.ZodIssueCode.custom,message:"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id."}))}else!!t.signal_input_source_port_id==!!t.signal_input_source_net_id&&e.addIssue({code:N.ZodIssueCode.custom,message:"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id."})}),fAo=N0.extend({type:N.literal("simulation_unknown_experiment_error"),simulation_unknown_experiment_error_id:Yo("simulation_unknown_experiment_error"),error_type:N.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"),simulation_experiment_id:N.string().optional(),subcircuit_id:N.string().optional()}).describe("An unknown error occurred during the simulation experiment."),IAo=N.object({type:N.literal("simulation_op_amp"),simulation_op_amp_id:Yo("simulation_op_amp"),source_component_id:N.string().optional(),inverting_input_source_port_id:N.string(),non_inverting_input_source_port_id:N.string(),output_source_port_id:N.string(),positive_supply_source_port_id:N.string(),negative_supply_source_port_id:N.string()}).describe("Defines a simple ideal operational amplifier for simulation"),hEt=(N.union([Qro,bro,Sro,Bro,wro,vro,L3t,T3t,abe,F3t,k3t,H3t,O3t,G3t,K3t,V3t,z3t,q3t,J3t,W3t,j3t,$3t,U3t,Y3t,Dro,Nro,Pro,X3t,Z3t,eEt,tEt,nEt,Rro,Tro,kro,Fro,Lro,oEt,Mro,Cso,yso,Mao,Dao,Nao,kao,Fao,Lao,vso,bao,wso,Zso,Uso,Jso,Wso,eao,kso,Yso,tao,nao,Rao,rao,sao,aao,Aao,dao,cao,lao,uao,gao,jso,$so,oao,iao,qso,Xso,$ao,qao,Xao,Zao,pao,hao,mao,_ao,fao,Iao,Cao,yao,xao,Tao,Eao,Bao,Hao,Pao,Oao,Gao,Yao,zao,Jao,Wao,jao,eAo,tAo,nAo,oAo,Hro,eso,Wro,jro,$ro,qro,Vro,Jro,tso,Xro,Oro,oso,iso,nso,Aso,cso,lso,uso,hso,gso,dso,iAo,AAo,gAo,hAo,pAo,mAo,_Ao,fAo,IAo]),!0),OJ={CCW:-1,CW:1,NOT_ORIENTABLE:0},CAo=2*Math.PI,gAe=Object.freeze({__proto__:null,BOUNDARY:2,CCW:hEt,CONTAINS:3,CW:!1,END_VERTEX:2,INSIDE:1,INTERLACE:4,NOT_VERTEX:0,ORIENTATION:OJ,OUTSIDE:0,OVERLAP_OPPOSITE:2,OVERLAP_SAME:1,PIx2:CAo,START_VERTEX:1}),_7=1e-6;function pEt(t){_7=t}function mEt(){return _7}function lbe(t){return t<_7&&t>-_7}function iN(t,e){return t-e<_7&&t-e>-_7}function _Et(t,e){return t-e>_7}function fEt(t,e){return t-e<-_7}var Ke={Utils:Object.freeze({__proto__:null,DECIMALS:3,EQ:iN,EQ_0:lbe,GE:function(t,e){return t-e>-_7},GT:_Et,LE:function(t,e){return t-e<_7},LT:fEt,getTolerance:mEt,setTolerance:pEt}),Errors:void 0,Matrix:void 0,Planar_set:void 0,Point:void 0,Vector:void 0,Line:void 0,Circle:void 0,Segment:void 0,Arc:void 0,Box:void 0,Edge:void 0,Face:void 0,Ray:void 0,Ray_shooting:void 0,Multiline:void 0,Polygon:void 0,Distance:void 0,Inversion:void 0};for(let t in gAe)Ke[t]=gAe[t];Object.defineProperty(Ke,"DP_TOL",{get:function(){return mEt()},set:function(t){pEt(t)}});var ud=class{static get ILLEGAL_PARAMETERS(){return new ReferenceError("Illegal Parameters")}static get ZERO_DIVISION(){return new Error("Zero division")}static get UNRESOLVED_BOUNDARY_CONFLICT(){return new Error("Unresolved boundary conflict in boolean operation")}static get INFINITE_LOOP(){return new Error("Infinite loop")}static get CANNOT_COMPLETE_BOOLEAN_OPERATION(){return new Error("Cannot complete boolean operation")}static get CANNOT_INVOKE_ABSTRACT_METHOD(){return new Error("Abstract method cannot be invoked")}static get OPERATION_IS_NOT_SUPPORTED(){return new Error("Operation is not supported")}static get UNSUPPORTED_SHAPE_TYPE(){return new Error("Unsupported shape type")}};Ke.Errors=ud;var ube=class{constructor(t,e){this.first=t,this.last=e||this.first}[Symbol.iterator](){let t;return{next:()=>(t=t?t.next:this.first,{value:t,done:t===void 0})}}get size(){let t=0;for(let e of this)t++;return t}toArray(t=void 0,e=void 0){let n=[],o=t||this.first,i=e||this.last,r=o;if(r===void 0)return n;do n.push(r),r=r.next;while(r!==i.next);return n}append(t){return this.isEmpty()?this.first=t:(t.prev=this.last,this.last.next=t),this.last=t,this.last.next=void 0,this.first.prev=void 0,this}insert(t,e){if(this.isEmpty())this.first=t,this.last=t;else if(e==null)t.next=this.first,this.first.prev=t,this.first=t;else{let n=e.next;e.next=t,n&&(n.prev=t),t.prev=e,t.next=n,this.last===e&&(this.last=t)}return this.last.next=void 0,this.first.prev=void 0,this}remove(t){return t===this.first&&t===this.last?(this.first=void 0,this.last=void 0):(t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t===this.first&&(this.first=t.next),t===this.last&&(this.last=t.prev)),this}isEmpty(){return this.first===void 0}static testInfiniteLoop(t){let e=t,n=t;do{if(e!=t&&e===n)throw ud.INFINITE_LOOP;e=e.next,n=n.next.next}while(e!=t)}},IEt={stroke:"black"},yAo=class{constructor(t=IEt){for(const e in t)this[e]=t[e];this.stroke=t.stroke??IEt.stroke}toAttributesString(){return Object.keys(this).reduce((t,e)=>t+(this[e]!==void 0?this.toAttrString(e,this[e]):""),"")}toAttrString(t,e){const n=t==="className"?"class":this.convertCamelToKebabCase(t);return e===null?`${n} `:`${n}="${e.toString()}" `}convertCamelToKebabCase(t){return t.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join("-").toLowerCase()}};function rN(t){return new yAo(t).toAttributesString()}function DL(t,e){let n=[],[o,i,r]=t.standard,[s,a,A]=e.standard,c=o*a-i*s,l=r*a-i*A,u=o*A-r*s;if(!Ke.Utils.EQ_0(c)){let g,h;i===0?(g=r/o,h=u/c):a===0?(g=A/s,h=u/c):o===0?(g=l/c,h=r/i):s===0?(g=l/c,h=A/a):(g=l/c,h=u/c),n.push(new Ke.Point(g,h))}return n}function sN(t,e){let n=[],o=e.pc.projectionOn(t),i=e.pc.distanceTo(o)[0];if(Ke.Utils.EQ(i,e.r))n.push(o);else if(Ke.Utils.LT(i,e.r)){let r,s,a=Math.sqrt(e.r*e.r-i*i);r=t.norm.rotate90CCW().multiply(a),s=o.translate(r),n.push(s),r=t.norm.rotate90CW().multiply(a),s=o.translate(r),n.push(s)}return n}function NL(t,e){let n=[];for(let o of e.toSegments()){let i=GJ(o,t);for(let r of i)PEt(r,n)||n.push(r)}return n}function dAe(t,e){let n=[];if(NL(t,e.box).length===0)return n;let o=sN(t,new Ke.Circle(e.pc,e.r));for(let i of o)i.on(e)&&n.push(i);return n}function GJ(t,e){let n=[];return t.ps.on(e)&&n.push(t.ps),t.pe.on(e)&&!t.isZeroLength()&&n.push(t.pe),n.length>0||t.isZeroLength()||t.ps.leftTo(e)&&t.pe.leftTo(e)||!t.ps.leftTo(e)&&!t.pe.leftTo(e)?n:DL(new Ke.Line(t.ps,t.pe),e)}function hAe(t,e){let n=[];if(t.isZeroLength())return t.ps.on(e)&&n.push(t.ps),n;if(e.isZeroLength())return e.ps.on(t)&&n.push(e.ps),n;let o=new Ke.Line(t.ps,t.pe),i=new Ke.Line(e.ps,e.pe);if(o.incidentTo(i))t.ps.on(e)&&n.push(t.ps),t.pe.on(e)&&n.push(t.pe),!e.ps.on(t)||e.ps.equalTo(t.ps)||e.ps.equalTo(t.pe)||n.push(e.ps),!e.pe.on(t)||e.pe.equalTo(t.ps)||e.pe.equalTo(t.pe)||n.push(e.pe);else if(o.parallelTo(i)){const r=new Ke.Vector(t.ps,t.pe),s=new Ke.Vector(e.ps,e.pe),a=new Ke.Vector(t.ps,e.ps),A=r.cross(s);if(!Ke.Utils.EQ_0(A)){const c=a.cross(s)/A,l=a.cross(r)/A;Ke.Utils.GE(c,0)&&Ke.Utils.LE(c,1)&&Ke.Utils.GE(l,0)&&Ke.Utils.LE(l,1)&&n.push(CEt(t.ps.translate(r.multiply(c)),t,e))}}else{let r=DL(o,i);r.length>0&&yEt(r[0],t)&&yEt(r[0],e)&&n.push(CEt(r[0],t,e))}return n}function CEt(t,e,n){for(const o of[e.ps,e.pe,n.ps,n.pe])if(t.equalTo(o))return o;return t}function yEt(t,e){const n=e.box;return Ke.Utils.LE(t.x,n.xmax)&&Ke.Utils.GE(t.x,n.xmin)&&Ke.Utils.LE(t.y,n.ymax)&&Ke.Utils.GE(t.y,n.ymin)}function pAe(t,e){let n=[];if(t.isZeroLength()){let[i,r]=t.ps.distanceTo(e.pc);return Ke.Utils.EQ(i,e.r)&&n.push(t.ps),n}let o=sN(new Ke.Line(t.ps,t.pe),e);for(let i of o)i.on(t)&&n.push(i);return n}function RL(t,e){let n=[];if(t.isZeroLength())return t.ps.on(e)&&n.push(t.ps),n;let o=sN(new Ke.Line(t.ps,t.pe),new Ke.Circle(e.pc,e.r));for(let i of o)i.on(t)&&i.on(e)&&n.push(i);return n}function xEt(t,e){let n=[],o=new Ke.Vector(t.pc,e.pc),i=t.r,r=e.r;if(Ke.Utils.EQ_0(i)||Ke.Utils.EQ_0(r))return n;if(Ke.Utils.EQ_0(o.x)&&Ke.Utils.EQ_0(o.y)&&Ke.Utils.EQ(i,r))return n.push(t.pc.translate(-i,0)),n;let s,a=t.pc.distanceTo(e.pc)[0];if(Ke.Utils.GT(a,i+r)||Ke.Utils.LT(a,Math.abs(i-r)))return n;if(o.x/=a,o.y/=a,Ke.Utils.EQ(a,i+r)||Ke.Utils.EQ(a,Math.abs(i-r)))return s=t.pc.translate(i*o.x,i*o.y),n.push(s),n;let A=i*i/(2*a)-r*r/(2*a)+a/2,c=t.pc.translate(A*o.x,A*o.y),l=Math.sqrt(i*i-A*A);return s=c.translate(o.rotate90CCW().multiply(l)),n.push(s),s=c.translate(o.rotate90CW().multiply(l)),n.push(s),n}function EEt(t,e){let n=[];if(t.pc.equalTo(e.pc)&&Ke.Utils.EQ(t.r,e.r)){let s;return s=t.start,s.on(e)&&n.push(s),s=t.end,s.on(e)&&n.push(s),s=e.start,s.on(t)&&n.push(s),s=e.end,s.on(t)&&n.push(s),n}let o=new Ke.Circle(t.pc,t.r),i=new Ke.Circle(e.pc,e.r),r=o.intersect(i);for(let s of r)s.on(t)&&s.on(e)&&n.push(s);return n}function gbe(t,e){let n=[];if(e.pc.equalTo(t.pc)&&Ke.Utils.EQ(e.r,t.r))return n.push(t.start),n.push(t.end),n;let o=xEt(e,new Ke.Circle(t.pc,t.r));for(let i of o)i.on(t)&&n.push(i);return n}function BEt(t,e){return t.isSegment?hAe(t.shape,e):RL(e,t.shape)}function bEt(t,e){return t.isSegment?RL(t.shape,e):EEt(t.shape,e)}function SEt(t,e){return t.isSegment?GJ(t.shape,e):dAe(e,t.shape)}function xAo(t,e){return t.isSegment?pAe(t.shape,e):gbe(t.shape,e)}function dbe(t,e){let n=[];for(let o of e.edges)for(let i of BEt(o,t))n.push(i);return n}function hbe(t,e){let n=[];for(let o of e.edges)for(let i of bEt(o,t))n.push(i);return n}function YJ(t,e){let n=[];if(e.isEmpty())return n;for(let o of e.edges)for(let i of SEt(o,t))PEt(i,n)||n.push(i);return t.sortPoints(n)}function QEt(t,e){let n=[];if(e.isEmpty())return n;for(let o of e.edges)for(let i of xAo(o,t))n.push(i);return n}function vEt(t,e){return t.isSegment?BEt(e,t.shape):t.isArc?bEt(e,t.shape):t.isLine?SEt(e,t.shape):t.isRay?(n=e,o=t.shape,n.isSegment?pbe(o,n.shape):mbe(o,n.shape)):[];var n,o}function wEt(t,e){let n=[];if(e.isEmpty()||t.shape.box.not_intersect(e.box))return n;let o=e.edges.search(t.shape.box);for(let i of o)n=[...n,...vEt(t,i)];return n}function PEt(t,e){return e.some(n=>n.equalTo(t))}function pv(t){return new Ke.Line(t.start,t.norm)}function pbe(t,e){return GJ(e,pv(t)).filter(n=>t.contains(n))}function mbe(t,e){return dAe(pv(t),e).filter(n=>t.contains(n))}function MEt(t,e){return sN(pv(t),e).filter(n=>t.contains(n))}function DEt(t,e){return DL(pv(t),e).filter(n=>t.contains(n))}function NEt(t,e){return YJ(pv(t),e).filter(n=>t.contains(n))}function REt(t,e){if(t.intersect&&t.intersect instanceof Function)return t.intersect(e);throw ud.UNSUPPORTED_SHAPE_TYPE}function TL(t,e){let n=[];for(let o of e)n=[...n,...REt(t,o.shape)];return n}var aN=class $te extends ube{constructor(...e){if(super(),this.isInfinite=!1,e.length===1&&e[0]instanceof Array&&e[0].length>0){const n=e[0],o=n.length,i=s=>s instanceof Ke.Segment||s instanceof Ke.Arc||s instanceof Ke.Ray,r=s=>s instanceof Ke.Segment||s instanceof Ke.Arc;if(!(o===1&&(s=>s instanceof Ke.Segment||s instanceof Ke.Arc||s instanceof Ke.Ray||s instanceof Ke.Line)(n[0])||o>1&&i(n[0])&&i(n[o-1])&&n.slice(1,o-1).every(r)))throw Ke.Errors.ILLEGAL_PARAMETERS;this.isInfinite=n.some(s=>s instanceof Ke.Ray||s instanceof Ke.Line);for(let s of n){let a=new Ke.Edge(s);this.append(a)}this.setArcLength()}}get edges(){return[...this]}get box(){return this.edges.reduce((e,n)=>e.merge(n.box),new Ke.Box)}get vertices(){let e=this.edges.map(n=>n.start);return e.push(this.last.end),e}get length(){if(this.isEmpty())return 0;if(this.isInfinite)return Number.POSITIVE_INFINITY;let e=0;for(let n of this)e+=n.length;return e}clone(){return new $te(this.toShapes())}setArcLength(){for(let e of this)this.setOneEdgeArcLength(e)}setOneEdgeArcLength(e){e===this.first?e.arc_length=0:e.arc_length=e.prev.arc_length+e.prev.length}pointAtLength(e){if(e>this.length||e<0||this.isInfinite)return null;let n=null;for(let o of this)if(e>=o.arc_length&&(o===this.last||e<o.next.arc_length)){n=o.pointAtLength(e-o.arc_length);break}return n}addVertex(e,n){let o=n.shape.split(e);if(o[0]===null)return n.prev;if(o[1]===null)return n;let i=new Ke.Edge(o[0]),r=n.prev;return this.insert(i,r),n.shape=o[1],i}getChain(e,n){let o=[];for(let i=e;i!==n.next;i=i.next)o.push(i);return o}split(e){for(let n of e){let o=this.findEdgeByPoint(n);this.addVertex(n,o)}return this}findEdgeByPoint(e){let n;for(let o of this)if(o.shape.contains(e)){n=o;break}return n}distanceTo(e){if(e instanceof Ke.Point){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Line){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Circle){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Segment){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Arc){const[n,o]=Ke.Distance.shape2multiline(e,this);return[n,o.reverse()]}if(e instanceof Ke.Box){const[n,o]=Ke.Distance.shape2multiline(new Ke.Polygon(e),this);return[n,o.reverse()]}if(e instanceof Ke.Multiline)return Ke.Distance.multiline2multiline(this,e);throw Ke.Errors.UNSUPPORTED_SHAPE_TYPE}intersect(e){return e instanceof Ke.Multiline?(function(n,o){let i=[];for(let r of n)for(let s of o)i=[...i,...REt(r.shape,s.shape)];return i})(this,e):TL(e,this)}contains(e){if(e instanceof Ke.Point)return this.edges.some(n=>n.shape.contains(e));throw Ke.Errors.UNSUPPORTED_SHAPE_TYPE}translate(e){return new $te(this.edges.map(n=>n.shape.translate(e)))}rotate(e=0,n=new Ke.Point){return new $te(this.edges.map(o=>o.shape.rotate(e,n)))}transform(e=new Ke.Matrix){return new $te(this.edges.map(n=>n.shape.transform(e)))}toShapes(){return this.edges.map(e=>e.shape.clone())}toJSON(){return this.edges.map(e=>e.toJSON())}svgPoints(){return this.vertices.map(e=>`${e.x},${e.y}`).join(" ")}dpath(){let e=`M${this.first.start.x},${this.first.start.y}`;for(let n of this)e+=n.svg();return e}svg(e={}){let n=`
<path ${rN({fill:"none",...e})} d="`;n+=`
M${this.first.start.x},${this.first.start.y}`;for(let o of this)n+=o.svg();return n+=`" >
</path>`,n}};Ke.Multiline=aN;function kL(t,e,n){let o=n.length,i=t.shape.split(e);if(i.length===0)return;let r=0;r=i[0]===null?0:i[1]===null?t.shape.length:i[0].length;let s,a=0;iN(r,0)&&(a|=1),iN(r,t.shape.length)&&(a|=2),s=r===1/0?i[0].coord(e):2&a&&t.next&&t.next.arc_length===0?0:t.arc_length+r,n.push({id:o,pt:e,arc_length:s,edge_before:t,edge_after:void 0,face:t.face,is_vertex:a})}function UJ(t){t.int_points1_sorted=mv(t.int_points1),t.int_points2_sorted=mv(t.int_points2)}function mv(t){let e=new Map,n=0;for(let o of t)e.has(o.face)||(e.set(o.face,n),n++);for(let o of t)o.faceId=e.get(o.face);return t.slice().sort(EAo)}function EAo(t,e){return t.faceId<e.faceId?-1:t.faceId>e.faceId?1:t.arc_length<e.arc_length?-1:t.arc_length>e.arc_length?1:0}function _be(t){if(t.int_points1.length<2)return;let e,n,o,i,r=!1;for(let s=0;s<t.int_points1_sorted.length;s++)if(t.int_points1_sorted[s].id!==-1){e=t.int_points1_sorted[s],n=t.int_points2[e.id];for(let a=s+1;a<t.int_points1_sorted.length&&(o=t.int_points1_sorted[a],iN(o.arc_length,e.arc_length));a++)o.id!==-1&&(i=t.int_points2[o.id],i.id!==-1&&o.edge_before===e.edge_before&&o.edge_after===e.edge_after&&i.edge_before===n.edge_before&&i.edge_after===n.edge_after&&(o.id=-1,i.id=-1,r=!0))}n=t.int_points2_sorted[0],e=t.int_points1[n.id];for(let s=1;s<t.int_points2_sorted.length;s++){let a=t.int_points2_sorted[s];if(a.id===-1)continue;if(n.id===-1||!iN(a.arc_length,n.arc_length)){n=a,e=t.int_points1[n.id];continue}let A=t.int_points1[a.id];A.edge_before===e.edge_before&&A.edge_after===e.edge_after&&a.edge_before===n.edge_before&&a.edge_after===n.edge_after&&(A.id=-1,a.id=-1,r=!0)}r&&(t.int_points1=t.int_points1.filter(s=>s.id>=0),t.int_points2=t.int_points2.filter(s=>s.id>=0),t.int_points1.forEach((s,a)=>s.id=a),t.int_points2.forEach((s,a)=>s.id=a))}function fbe(t){for(let e of t)e.edge_before&&(e.edge_before.bvStart=void 0,e.edge_before.bvEnd=void 0,e.edge_before.bv=void 0,e.edge_before.overlap=void 0),e.edge_after&&(e.edge_after.bvStart=void 0,e.edge_after.bvEnd=void 0,e.edge_after.bv=void 0,e.edge_after.overlap=void 0);for(let e of t)e.edge_before&&(e.edge_before.bvEnd=2),e.edge_after&&(e.edge_after.bvStart=2)}function Ibe(t,e){for(let n of t)n.edge_before&&n.edge_before.setInclusion(e),n.edge_after&&n.edge_after.setInclusion(e)}function FL(t,e,n){let o,i,r=1;if(t.length===1)return 1;o=t[e];for(let s=e+1;s<t.length&&o.face===n&&(i=t[s],i.pt.equalTo(o.pt)&&i.edge_before===o.edge_before&&i.edge_after===o.edge_after);s++)r++;return r}function LL(t,e){if(e){for(let n of e){let o=n.edge_before;if(n.is_vertex=0,o.shape.start&&o.shape.start.equalTo(n.pt)&&(n.is_vertex|=1),o.shape.end&&o.shape.end.equalTo(n.pt)&&(n.is_vertex|=2),1&n.is_vertex){n.edge_before=o.prev,o.prev&&(n.is_vertex=2);continue}if(2&n.is_vertex)continue;let i=t.addVertex(n.pt,o);n.edge_before=i}for(let n of e)n.edge_before?n.edge_after=n.edge_before.next:t instanceof aN&&1&n.is_vertex&&(n.edge_after=t.first)}}function TEt(t,e,n){const o=t.edge_before,i=e.edge_after,r=n.length;o.next=n[0],n[0].prev=o,n[r-1].next=i,i.prev=n[r-1]}Ke.multiline=(...t)=>new Ke.Multiline(...t);var{INSIDE:f7,OUTSIDE:I7,BOUNDARY:$f,OVERLAP_SAME:BAo,OVERLAP_OPPOSITE:bAo}=gAe,{NOT_VERTEX:Yhr,START_VERTEX:kEt,END_VERTEX:FEt}=gAe;function Cbe(t,e){let n=e.clone().reverse(),[o]=KJ(t,n,3,!0);return o}function LEt(t,e){let[n]=KJ(t,e,2,!0);return n}function HEt(t,e){let[n,o]=KJ(t,e,2,!1),i=[];for(let s of n.faces)i=[...i,...[...s.edges].map(a=>a.shape)];let r=[];for(let s of o.faces)r=[...r,...[...s.edges].map(a=>a.shape)];return[i,r]}function ybe(t,e){let[n]=KJ(t,e,3,!1),o=[];for(let i of n.faces)o=[...o,...[...i.edges].map(r=>r.shape)];return o}function OEt(t,e){let n=t.clone(),o=e.clone(),i=GEt(n,o);return UJ(i),LL(n,i.int_points1_sorted),LL(o,i.int_points2_sorted),_be(i),UJ(i),[i.int_points1_sorted.map(r=>r.pt),i.int_points2_sorted.map(r=>r.pt)]}function SAo(t,e,n,o){let i=YEt(t,n.int_points1),r=YEt(e,n.int_points2);for(UEt(i,e),UEt(r,t),fbe(n.int_points1),fbe(n.int_points2),Ibe(n.int_points1,e),Ibe(n.int_points2,t);QAo(t,e,n.int_points1,n.int_points1_sorted,n.int_points2,n););(function(s){let a,A,c,l=s.int_points1.length;for(let u=0;u<l;u++){let g=s.int_points1_sorted[u];g.face!==a&&(A=u,a=g.face);let h,d=u,p=FL(s.int_points1_sorted,u,a);h=d+p<l&&s.int_points1_sorted[d+p].face===a?d+p:A;let m=FL(s.int_points1_sorted,h,a);c=null;for(let E=h;E<h+m;E++){let B=s.int_points1_sorted[E];if(B.face===a&&s.int_points2[B.id].face===s.int_points2[g.id].face){c=B;break}}if(c===null)continue;let _=g.edge_after,f=c.edge_before;if(_.bv!==2||f.bv!==2||_!==f)continue;let I=s.int_points2[g.id],C=s.int_points2[c.id],y=I.edge_after,x=C.edge_before;y.bv===2&&x.bv===2&&y===x||(I=s.int_points2[c.id],C=s.int_points2[g.id],y=I.edge_after,x=C.edge_before),y.bv===2&&x.bv===2&&y===x&&_.setOverlap(y)}})(n),xbe(t,o,n.int_points1_sorted,!0),xbe(e,o,n.int_points2_sorted,!1),KEt(t,i,o,!0),KEt(e,r,o,!1)}function KJ(t,e,n,o){let i=t.clone(),r=e.clone(),s=GEt(i,r);return UJ(s),LL(i,s.int_points1_sorted),LL(r,s.int_points2_sorted),_be(s),UJ(s),SAo(i,r,s,n),o&&(function(a,A,c){(function(l,u,g,h){for(let d of u.faces){for(let p of d)l.edges.add(p);h.find(p=>p.face===d)===void 0&&l.addFace(d.first,d.last)}})(a,A,0,c.int_points2),(function(l,u,g){if(g.int_points1.length!==0)for(let h=0;h<g.int_points1.length;h++){let d=g.int_points1[h],p=g.int_points2[h];if(d.edge_before!==void 0&&d.edge_after===void 0&&p.edge_before===void 0&&p.edge_after!==void 0&&(d.edge_before.next=p.edge_after,p.edge_after.prev=d.edge_before,d.edge_after=p.edge_after,p.edge_before=d.edge_before),p.edge_before!==void 0&&p.edge_after===void 0&&d.edge_before===void 0&&d.edge_after!==void 0&&(p.edge_before.next=d.edge_after,d.edge_after.prev=p.edge_before,p.edge_after=d.edge_after,d.edge_before=p.edge_before),d.edge_before!==void 0&&d.edge_after===void 0)for(let m of g.int_points1_sorted)m!==d&&m.edge_before===void 0&&m.edge_after!==void 0&&m.pt.equalTo(d.pt)&&(d.edge_before.next=m.edge_after,m.edge_after.prev=d.edge_before,d.edge_after=m.edge_after,m.edge_before=d.edge_before);if(p.edge_before!==void 0&&p.edge_after===void 0)for(let m of g.int_points2_sorted)m!==p&&m.edge_before===void 0&&m.edge_after!==void 0&&m.pt.equalTo(p.pt)&&(p.edge_before.next=m.edge_after,m.edge_after.prev=p.edge_before,p.edge_after=m.edge_after,m.edge_before=p.edge_before)}})(0,0,c),Ebe(a,c.int_points1),Ebe(A,c.int_points2),Bbe(a,c.int_points1,c.int_points2),Bbe(a,c.int_points2,c.int_points1),VEt(a),VEt(A)})(i,r,s),[i,r]}function GEt(t,e){let n={int_points1:[],int_points2:[]};for(let o of t.edges){let i=e.edges.search(o.box);for(let r of i){let s=o.shape.intersect(r.shape);for(let a of s)kL(o,a,n.int_points1),kL(r,a,n.int_points2)}}return n}function YEt(t,e){let n=[];for(let o of t.faces)e.find(i=>i.face===o)||n.push(o);return n}function UEt(t,e){for(let n of t)n.first.bv=n.first.bvStart=n.first.bvEnd=void 0,n.first.setInclusion(e)}function QAo(t,e,n,o,i,r){let s,a,A,c=o.length,l=!1;for(let u=0;u<c;u++){let g=o[u];g.face!==s&&(a=u,s=g.face);let h,d=u,p=FL(o,u,s);h=d+p<c&&o[d+p].face===s?d+p:a;let m=FL(o,h,s);A=null;for(let I=h;I<h+m;I++){let C=o[I];if(C.face===s&&i[C.id].face===i[g.id].face){A=C;break}}if(A===null)continue;let _=g.edge_after,f=A.edge_before;if(_.bv!==$f||f.bv==$f)if(_.bv==$f||f.bv!==$f){if(_.bv===$f&&f.bv===$f&&_!=f||_.bv===f7&&f.bv===I7||_.bv===I7&&f.bv===f7){let I=_.next;for(;I!=f;)I.bvStart=void 0,I.bvEnd=void 0,I.bv=void 0,I.setInclusion(e),I=I.next}if(_.bv===$f&&f.bv===$f&&_!=f){let I,C=_.next;for(;C!=f;){if(C.bv!=$f){if(I===void 0)I=C.bv;else if(C.bv!=I)throw ud.UNRESOLVED_BOUNDARY_CONFLICT}C=C.next}I!=null&&(_.bv=I,f.bv=I);continue}if(_.bv===f7&&f.bv===I7||_.bv===I7&&f.bv===f7){let I=_;for(;I!=f;){if(I.bvStart===_.bv&&I.bvEnd===f.bv){let[C,y]=I.shape.distanceTo(e);if(C<10*Ke.DP_TOL){kL(I,y.ps,n);let x=n[n.length-1];if(x.is_vertex&kEt)x.edge_after=I,x.edge_before=I.prev,I.bvStart=$f,I.bv=void 0,I.setInclusion(e);else if(x.is_vertex&FEt)x.edge_after=I.next,I.bvEnd=$f,I.bv=void 0,I.setInclusion(e);else{let S=e.addVertex(x.pt,I);x.edge_before=S,x.edge_after=S.next,S.setInclusion(e),S.next.bvStart=$f,S.next.bvEnd=void 0,S.next.bv=void 0,S.next.setInclusion(e)}let E=e.findEdgeByPoint(y.pe);kL(E,y.pe,i);let B=i[i.length-1];if(B.is_vertex&kEt)B.edge_after=E,B.edge_before=E.prev;else if(B.is_vertex&FEt)B.edge_after=E.next;else{let S=i.find(w=>w.edge_after===E),Q=e.addVertex(B.pt,E);B.edge_before=Q,B.edge_after=Q.next,S&&(S.edge_after=Q),Q.bvStart=void 0,Q.bvEnd=$f,Q.bv=void 0,Q.setInclusion(t),Q.next.bvStart=$f,Q.next.bvEnd=void 0,Q.next.bv=void 0,Q.next.setInclusion(t)}UJ(r),l=!0;break}}I=I.next}if(l)break;throw ud.UNRESOLVED_BOUNDARY_CONFLICT}}else f.bv=_.bv;else _.bv=f.bv}return l}function xbe(t,e,n,o){if(!n)return;let i,r,s,a;for(let A=0;A<n.length;A++){if(s=n[A],s.face!==i&&(r=A,i=s.face),i.isEmpty())continue;let c,l=A,u=FL(n,A,i);c=l+u<n.length&&n[l+u].face===s.face?l+u:r,a=n[c];let g=c,h=FL(n,g,i),d=s.edge_after,p=a.edge_before;if(d.bv===f7&&p.bv===f7&&e===1||d.bv===I7&&p.bv===I7&&e===2||(d.bv===I7||p.bv===I7)&&e===3&&!o||(d.bv===f7||p.bv===f7)&&e===3&&o||d.bv===$f&&p.bv===$f&&d.overlap&BAo&&o||d.bv===$f&&p.bv===$f&&d.overlap&bAo){t.removeChain(i,d,p);for(let m=l;m<l+u;m++)n[m].edge_after=void 0;for(let m=g;m<g+h;m++)n[m].edge_before=void 0}A+=u-1}}function Ebe(t,e){for(let n of e)t.faces.delete(n.face),n.face=void 0,n.edge_before&&(n.edge_before.face=void 0),n.edge_after&&(n.edge_after.face=void 0)}function Bbe(t,e,n){for(let o of e){if(o.edge_before===void 0||o.edge_after===void 0||o.face||o.edge_after.face||o.edge_before.face)continue;let i=o.edge_after,r=o.edge_before;try{ube.testInfiniteLoop(i)}catch{throw ud.CANNOT_COMPLETE_BOOLEAN_OPERATION}let s=t.addFace(i,r);for(let a of e)a.edge_before&&a.edge_after&&a.edge_before.face===s&&a.edge_after.face===s&&(a.face=s);for(let a of n)a.edge_before&&a.edge_after&&a.edge_before.face===s&&a.edge_after.face===s&&(a.face=s)}}function KEt(t,e,n,o){for(let i of e){let r=i.first.bv;(n===1&&r===f7||n===3&&r===f7&&o||n===3&&r===I7&&!o||n===2&&r===I7)&&t.deleteFace(i)}}function VEt(t){const e=[];for(const n of t.edges)n.face&&t.faces.has(n.face)||e.push(n);for(const n of e)t.edges.delete(n)}var vAo=Object.freeze({__proto__:null,BOOLEAN_INTERSECT:2,BOOLEAN_SUBTRACT:3,BOOLEAN_UNION:1,calculateIntersections:OEt,innerClip:HEt,intersect:LEt,outerClip:ybe,removeNotRelevantChains:xbe,removeOldFaces:Ebe,restoreFaces:Bbe,subtract:Cbe,unify:function(t,e){let[n]=KJ(t,e,1,!0);return n}}),wAo=RegExp("T.F..FFF.|T.F...F.."),PAo=RegExp("T........|.T.......|...T.....|....T...."),MAo=RegExp("FT.......|F..T.....|F...T...."),DAo=RegExp("T.F..F..."),NAo=RegExp("T.F..F...|.TF..F...|..FT.F...|..F.TF..."),HL=class{constructor(){this.m=new Array(9).fill(void 0)}get I2I(){return this.m[0]}set I2I(t){this.m[0]=t}get I2B(){return this.m[1]}set I2B(t){this.m[1]=t}get I2E(){return this.m[2]}set I2E(t){this.m[2]=t}get B2I(){return this.m[3]}set B2I(t){this.m[3]=t}get B2B(){return this.m[4]}set B2B(t){this.m[4]=t}get B2E(){return this.m[5]}set B2E(t){this.m[5]=t}get E2I(){return this.m[6]}set E2I(t){this.m[6]=t}get E2B(){return this.m[7]}set E2B(t){this.m[7]=t}get E2E(){return this.m[8]}set E2E(t){this.m[8]=t}toString(){return this.m.map(t=>t instanceof Array&&t.length>0?"T":t instanceof Array&&t.length===0?"F":"*").join("")}equal(){return wAo.test(this.toString())}intersect(){return PAo.test(this.toString())}touch(){return MAo.test(this.toString())}inside(){return DAo.test(this.toString())}covered(){return NAo.test(this.toString())}};function VJ(t,e){let n,o=new Ke.Ray(e),i=new Ke.Line(o.pt,o.norm);const r=new Ke.Box(o.box.xmin-Ke.DP_TOL,o.box.ymin-Ke.DP_TOL,o.box.xmax+Ke.DP_TOL,o.box.ymax+Ke.DP_TOL);if(t.box.not_intersect(r))return Ke.OUTSIDE;let s=t.edges.search(r);if(s.length===0)return Ke.OUTSIDE;for(let l of s)if(l.shape.contains(e))return Ke.BOUNDARY;let a=[...t.faces],A=[];for(let l of s)for(let u of o.intersect(l.shape)){if(u.equalTo(e))return Ke.BOUNDARY;A.push({pt:u,edge:l,face_index:a.indexOf(l.face)})}A.sort((l,u)=>fEt(l.pt.x,u.pt.x)?-1:_Et(l.pt.x,u.pt.x)?1:l.face_index<u.face_index?-1:l.face_index>u.face_index?1:l.edge.arc_length<u.edge.arc_length?-1:l.edge.arc_length>u.edge.arc_length?1:0);let c=0;for(let l=0;l<A.length;l++){let u=A[l];if(u.pt.equalTo(u.edge.shape.start)){if(l>0&&u.pt.equalTo(A[l-1].pt)&&u.face_index===A[l-1].face_index&&u.edge.prev===A[l-1].edge)continue;let g=u.edge.prev;for(;lbe(g.length);)g=g.prev;let h=g.shape.tangentInEnd(),d=u.pt.translate(h),p=u.edge.shape.tangentInStart(),m=u.pt.translate(p),_=d.leftTo(i),f=m.leftTo(i);(_&&!f||!_&&f)&&c++}else if(u.pt.equalTo(u.edge.shape.end)){if(l>0&&u.pt.equalTo(A[l-1].pt)&&u.face_index===A[l-1].face_index&&u.edge.next===A[l-1].edge)continue;let g=u.edge.next;for(;lbe(g.length);)g=g.next;let h=g.shape.tangentInStart(),d=u.pt.translate(h),p=u.edge.shape.tangentInEnd(),m=u.pt.translate(p),_=d.leftTo(i),f=m.leftTo(i);(_&&!f||!_&&f)&&c++}else if(u.edge.shape instanceof Ke.Segment)c++;else{let g=u.edge.shape.box;iN(u.pt.y,g.ymin)||iN(u.pt.y,g.ymax)||c++}}return n=c%2==1?1:0,n}function zEt(t,e){return OL(t,e).intersect()}function JEt(t,e){return OL(t,e).inside()}function WEt(t,e){return OL(t,e).covered()}function jEt(t,e){return WEt(e,t)}function OL(t,e){return t instanceof Ke.Line&&e instanceof Ke.Line?(function(n,o){let i=new HL,r=DL(n,o);return r.length===0?n.contains(o.pt)&&o.contains(n.pt)?(i.I2I=[n],i.I2E=[],i.E2I=[]):(i.I2I=[],i.I2E=[n],i.E2I=[o]):(i.I2I=r,i.I2E=n.split(r),i.E2I=o.split(r)),i})(t,e):t instanceof Ke.Line&&e instanceof Ke.Circle?(function(n,o){let i=new HL,r=sN(n,o);if(r.length===0)i.I2I=[],i.I2B=[],i.I2E=[n],i.E2I=[o];else if(r.length===1)i.I2I=[],i.I2B=r,i.I2E=n.split(r),i.E2I=[o];else{let s=new aN([n]),a=n.sortPoints(r);s.split(a);let A=s.toShapes();i.I2I=[A[1]],i.I2B=a,i.I2E=[A[0],A[2]],i.E2I=new Ke.Polygon([o.toArc()]).cutWithLine(n)}return i})(t,e):t instanceof Ke.Line&&e instanceof Ke.Box?(function(n,o){let i=new HL,r=NL(n,o);if(r.length===0)i.I2I=[],i.I2B=[],i.I2E=[n],i.E2I=[o];else if(r.length===1)i.I2I=[],i.I2B=r,i.I2E=n.split(r),i.E2I=[o];else{let s=new aN([n]),a=n.sortPoints(r);s.split(a);let A=s.toShapes();o.toSegments().some(c=>c.contains(r[0])&&c.contains(r[1]))?(i.I2I=[],i.I2B=[A[1]],i.I2E=[A[0],A[2]],i.E2I=[o]):(i.I2I=[A[1]],i.I2B=a,i.I2E=[A[0],A[2]],i.E2I=new Ke.Polygon(o.toSegments()).cutWithLine(n))}return i})(t,e):t instanceof Ke.Line&&e instanceof Ke.Polygon?(function(n,o){let i=new HL,r=YJ(n,o),s=new aN([n]),a=r.length>0?r.slice():n.sortPoints(r);return s.split(a),[...s].forEach(A=>A.setInclusion(o)),i.I2I=[...s].filter(A=>A.bv===Ke.INSIDE).map(A=>A.shape),i.I2B=[...s].slice(1).map(A=>A.bv===Ke.BOUNDARY?A.shape:A.shape.start),i.I2E=[...s].filter(A=>A.bv===Ke.OUTSIDE).map(A=>A.shape),i.E2I=o.cutWithLine(n),i})(t,e):(t instanceof Ke.Segment||t instanceof Ke.Arc)&&e instanceof Ke.Polygon?$Et(t,e):(t instanceof Ke.Segment||t instanceof Ke.Arc)&&(e instanceof Ke.Circle||e instanceof Ke.Box)?$Et(t,new Ke.Polygon(e)):t instanceof Ke.Polygon&&e instanceof Ke.Polygon?mAe(t,e):(t instanceof Ke.Circle||t instanceof Ke.Box)&&(e instanceof Ke.Circle||e instanceof Ke.Box)?mAe(new Ke.Polygon(t),new Ke.Polygon(e)):(t instanceof Ke.Circle||t instanceof Ke.Box)&&e instanceof Ke.Polygon?mAe(new Ke.Polygon(t),e):t instanceof Ke.Polygon&&(e instanceof Ke.Circle||e instanceof Ke.Box)?mAe(t,new Ke.Polygon(e)):void 0}function $Et(t,e){let n=new HL,o=(function(s,a){return s instanceof Ke.Line?YJ(s,a):s instanceof Ke.Segment?dbe(s,a):s instanceof Ke.Arc?hbe(s,a):[]})(t,e),i=o.length>0?o.slice():t.sortPoints(o),r=new aN([t]);r.split(i),[...r].forEach(s=>s.setInclusion(e)),n.I2I=[...r].filter(s=>s.bv===Ke.INSIDE).map(s=>s.shape),n.I2B=[...r].slice(1).map(s=>s.bv===Ke.BOUNDARY?s.shape:s.shape.start),n.I2E=[...r].filter(s=>s.bv===Ke.OUTSIDE).map(s=>s.shape),n.B2I=[],n.B2B=[],n.B2E=[];for(let s of[t.start,t.end])switch(VJ(e,s)){case Ke.INSIDE:n.B2I.push(s);break;case Ke.BOUNDARY:n.B2B.push(s);break;case Ke.OUTSIDE:n.B2E.push(s)}return n}function mAe(t,e){let n=new HL,[o,i]=OEt(t,e),r=LEt(t,e),s=Cbe(t,e),a=Cbe(e,t),[A,c]=HEt(t,e),l=ybe(t,e),u=ybe(e,t);return n.I2I=r.isEmpty()?[]:[r],n.I2B=c,n.I2E=s.isEmpty()?[]:[s],n.B2I=A,n.B2B=o,n.B2E=l,n.E2I=a.isEmpty()?[]:[a],n.E2B=u,n}var RAo=Object.freeze({__proto__:null,contain:function(t,e){return JEt(e,t)},cover:jEt,covered:WEt,disjoint:function(t,e){return!zEt(t,e)},equal:function(t,e){return OL(t,e).equal()},inside:JEt,intersect:zEt,relate:OL,touch:function(t,e){return OL(t,e).touch()}}),zJ=class kk{constructor(e=1,n=0,o=0,i=1,r=0,s=0){this.a=e,this.b=n,this.c=o,this.d=i,this.tx=r,this.ty=s}fromMatrix3x3(e){const[n,o,i]=e[0],[r,s,a]=e[1];return new kk(n,r,o,s,i,a)}toMatrix3x3(){return[[this.a,this.c,this.tx],[this.b,this.d,this.ty],[0,0,1]]}clone(){return new kk(this.a,this.b,this.c,this.d,this.tx,this.ty)}transform(e){return[e[0]*this.a+e[1]*this.c+this.tx,e[0]*this.b+e[1]*this.d+this.ty]}multiply(e){return new kk(this.a*e.a+this.c*e.b,this.b*e.a+this.d*e.b,this.a*e.c+this.c*e.d,this.b*e.c+this.d*e.d,this.a*e.tx+this.c*e.ty+this.tx,this.b*e.tx+this.d*e.ty+this.ty)}translate(...e){let n,o;if(e.length!=1||isNaN(e[0].x)||isNaN(e[0].y)){if(e.length!==2||typeof e[0]!="number"||typeof e[1]!="number")throw ud.ILLEGAL_PARAMETERS;n=e[0],o=e[1]}else n=e[0].x,o=e[0].y;return this.multiply(new kk(1,0,0,1,n,o))}rotate(e,n=0,o=0){let i=Math.cos(e),r=Math.sin(e);return this.translate(n,o).multiply(new kk(i,r,-r,i,0,0)).translate(-n,-o)}scale(e,n){return this.multiply(new kk(e,0,0,n,0,0))}equalTo(e){return!!Ke.Utils.EQ(this.tx,e.tx)&&!!Ke.Utils.EQ(this.ty,e.ty)&&!!Ke.Utils.EQ(this.a,e.a)&&!!Ke.Utils.EQ(this.b,e.b)&&!!Ke.Utils.EQ(this.c,e.c)&&!!Ke.Utils.EQ(this.d,e.d)}};Ke.Matrix=zJ,Ke.matrix=(...t)=>new Ke.Matrix(...t);var TAo=class{constructor(t,e){this.low=t,this.high=e}get max(){return this.clone()}less_than(t){return this.low<t.low||this.low===t.low&&this.high<t.high}equal_to(t){return this.low===t.low&&this.high===t.high}intersect(t){return!this.not_intersect(t)}not_intersect(t){return this.high<t.low||t.high<this.low}merge(t){const e=this.low===void 0?t.low:this.low<t.low?this.low:t.low,n=this.high===void 0?t.high:this.high>t.high?this.high:t.high,o=this.clone();return o.low=e,o.high=n,o}output(){return[this.low,this.high]}comparable_less_than(t,e){return t<e}},kAo=class d5n extends TAo{clone(){return new d5n(this.low,this.high)}},_v=class{constructor(t,e,n=null,o=null,i=null,r=0){if(this.left=n,this.right=o,this.parent=i,this.color=r,this.item={key:void 0,values:[]},e!==void 0&&this.item.values.push(e),t!==void 0)if(Array.isArray(t)){const[s,a]=t;if(!Number.isNaN(s)&&!Number.isNaN(a)){let A=s,c=a;A>c&&([A,c]=[c,A]),this.item.key=new kAo(A,c)}}else this.item.key=t;this.max=this.item.key?this.item.key.max:void 0}isNil(){return this.item.key===void 0&&this.item.values.length===0&&this.left===null&&this.right===null&&this.color===0}requireKey(){if(!this.item.key)throw new Error("Node key is undefined (nil/sentinel). Operation is not applicable.");return this.item.key}less_than(t){const e=this.requireKey(),n=t.requireKey();return e.less_than(n)}_value_equal(t){const e=this.item.values[0],n=t.item.values[0];return e&&n&&e.equal_to?e.equal_to(n):e===n}equal_to(t){const e=this.requireKey(),n=t.requireKey();return e.equal_to(n)}intersect(t){const e=this.requireKey(),n=t.requireKey();return e.intersect(n)}copy_data(t){this.item.key=t.item.key,this.item.values=t.item.values.slice()}update_max(){this.max=this.item.key?this.item.key.max:void 0,this.right&&this.right.max&&(this.max=this.max?this.max.merge(this.right.max):this.right.max),this.left&&this.left.max&&(this.max=this.max?this.max.merge(this.left.max):this.left.max)}not_intersect_left_subtree(t){if(!this.left)return!0;const e=this.left.max?this.left.max.high:this.left.item.key.high,n=this.requireKey(),o=t.requireKey();return n.comparable_less_than(e,o.low)}not_intersect_right_subtree(t){if(!this.right)return!0;const e=this.right.max?this.right.max.low:this.right.item.key.low,n=this.requireKey(),o=t.requireKey();return n.comparable_less_than(o.high,e)}},bbe=class h5n{constructor(){this.root=null,this.nil_node=new _v}get size(){let e=0;return this.tree_walk(this.root,n=>e+=n.item.values.length),e}get keys(){const e=[];return this.tree_walk(this.root,n=>e.push(n.item.key.output())),e}get values(){const e=[];return this.tree_walk(this.root,n=>{for(const o of n.item.values)e.push(o)}),e}get items(){const e=[];return this.tree_walk(this.root,n=>{const o=n.item.key.output();for(const i of n.item.values)e.push({key:o,value:i})}),e}isEmpty(){return this.root==null||this.root===this.nil_node}clear(){this.root=null}insert(e,n=e){if(e===void 0)return;const o=this.tree_search(this.root,new _v(e));if(o)return o.item.values.push(n),o;const i=new _v(e,n,this.nil_node,this.nil_node,null,1);return this.tree_insert(i),this.recalc_max(i),i}exist(e,n=e){const o=this.tree_search(this.root,new _v(e));return!!o&&(arguments.length<2||n===e||o.item.values.some(i=>i&&i.equal_to?i.equal_to(n):i===n))}remove(e,n=e){const o=this.tree_search(this.root,new _v(e));if(!o)return;if(arguments.length<2)return this.tree_delete(o),o;const i=o.item.values.findIndex(r=>r&&r.equal_to?r.equal_to(n):r===n);return i>=0?(o.item.va