), {});\na(A_, { BRAND: () =\u003e ub, DIRTY: () =\u003e Z_, EMPTY_PATH: () =\u003e B_, INVALID: () =\u003e G_, NEVER: () =\u003e sx, OK: () =\u003e q_, ParseStatus: () =\u003e U_, Schema: () =\u003e ry, ZodAny: () =\u003e ky, ZodArray: () =\u003e $y, ZodBigInt: () =\u003e Ey, ZodBoolean: () =\u003e Ay, ZodBranded: () =\u003e pb, ZodCatch: () =\u003e hb, ZodDate: () =\u003e Oy, ZodDefault: () =\u003e lb, ZodDiscriminatedUnion: () =\u003e Vy, ZodEffects: () =\u003e sb, ZodEnum: () =\u003e ob, ZodError: () =\u003e k_, ZodFirstPartyTypeKind: () =\u003e yb, ZodFunction: () =\u003e Qy, ZodIntersection: () =\u003e Gy, ZodIssueCode: () =\u003e D_, ZodLazy: () =\u003e tb, ZodLiteral: () =\u003e eb, ZodMap: () =\u003e Jy, ZodNaN: () =\u003e db, ZodNativeEnum: () =\u003e ib, ZodNever: () =\u003e jy, ZodNull: () =\u003e zy, ZodNullable: () =\u003e cb, ZodNumber: () =\u003e Ry, ZodObject: () =\u003e By, ZodOptional: () =\u003e ab, ZodParsedType: () =\u003e O_, ZodPipeline: () =\u003e mb, ZodPromise: () =\u003e rb, ZodReadonly: () =\u003e gb, ZodRecord: () =\u003e qy, ZodSchema: () =\u003e ry, ZodSet: () =\u003e Ky, ZodString: () =\u003e wy, ZodSymbol: () =\u003e Ly, ZodTransformer: () =\u003e sb, ZodTuple: () =\u003e Zy, ZodType: () =\u003e ry, ZodUndefined: () =\u003e Dy, ZodUnion: () =\u003e Hy, ZodUnknown: () =\u003e Fy, ZodVoid: () =\u003e Yy, addIssueToContext: () =\u003e H_, any: () =\u003e Eb, array: () =\u003e Db, bigint: () =\u003e Mb, boolean: () =\u003e Cb, coerce: () =\u003e rx, custom: () =\u003e _b, date: () =\u003e Nb, datetimeRegex: () =\u003e Py, defaultErrorMap: () =\u003e F_, discriminatedUnion: () =\u003e jb, effect: () =\u003e Jb, enum: () =\u003e Gb, function: () =\u003e Wb, getErrorMap: () =\u003e $_, getParsedType: () =\u003e L_, instanceof: () =\u003e vb, intersection: () =\u003e Yb, isAborted: () =\u003e J_, isAsync: () =\u003e ty, isDirty: () =\u003e K_, isValid: () =\u003e Q_, late: () =\u003e xb, lazy: () =\u003e Vb, literal: () =\u003e Ub, makeIssue: () =\u003e X_, map: () =\u003e Bb, nan: () =\u003e Pb, nativeEnum: () =\u003e Zb, never: () =\u003e Ob, null: () =\u003e Rb, nullable: () =\u003e Qb, number: () =\u003e Ib, object: () =\u003e zb, objectUtil: () =\u003e R_, oboolean: () =\u003e ix, onumber: () =\u003e ox, optional: () =\u003e Kb, ostring: () =\u003e nx, pipeline: () =\u003e ex, preprocess: () =\u003e tx, promise: () =\u003e qb, quotelessJson: () =\u003e z_, record: () =\u003e Xb, set: () =\u003e Hb, setErrorMap: () =\u003e Y_, strictObject: () =\u003e kb, string: () =\u003e Sb, symbol: () =\u003e wb, transformer: () =\u003e Jb, tuple: () =\u003e $b, undefined: () =\u003e Tb, union: () =\u003e Fb, unknown: () =\u003e Ab, util: () =\u003e w_, void: () =\u003e Lb }), (T_ = w_ || (w_ = {})).assertEqual = (t48) =\u003e {\n}, T_.assertIs = function(t48) {\n}, T_.assertNever = function(t48) {\n throw new Error();\n}, T_.arrayToEnum = (t48) =\u003e {\n const e2 = {};\n for (const n2 of t48) e2[n2] = n2;\n return e2;\n}, T_.getValidEnumValues = (t48) =\u003e {\n const e2 = T_.objectKeys(t48).filter((e3) =\u003e \"number\" != typeof t48[t48[e3]]), n2 = {};\n for (const o2 of e2) n2[o2] = t48[o2];\n return T_.objectValues(n2);\n}, T_.objectValues = (t48) =\u003e T_.objectKeys(t48).map(function(e2) {\n return t48[e2];\n}), T_.objectKeys = \"function\" == typeof Object.keys ? (t48) =\u003e Object.keys(t48) : (t48) =\u003e {\n const e2 = [];\n for (const n2 in t48) Object.prototype.hasOwnProperty.call(t48, n2) \u0026\u0026 e2.push(n2);\n return e2;\n}, T_.find = (t48, e2) =\u003e {\n for (const n2 of t48) if (e2(n2)) return n2;\n}, T_.isInteger = \"function\" == typeof Number.isInteger ? (t48) =\u003e Number.isInteger(t48) : (t48) =\u003e \"number\" == typeof t48 \u0026\u0026 Number.isFinite(t48) \u0026\u0026 Math.floor(t48) === t48, T_.joinValues = function(t48, e2 = \" | \") {\n return t48.map((t49) =\u003e \"string\" == typeof t49 ? `'${t49}'` : t49).join(e2);\n}, T_.jsonStringifyReplacer = (t48, e2) =\u003e \"bigint\" == typeof e2 ? e2.toString() : e2, (R_ || (R_ = {})).mergeShapes = (t48, e2) =\u003e ({ ...t48, ...e2 });\nvar O_ = w_.arrayToEnum([\"string\", \"nan\", \"number\", \"integer\", \"float\", \"boolean\", \"date\", \"bigint\", \"symbol\", \"function\", \"undefined\", \"null\", \"array\", \"object\", \"unknown\", \"promise\", \"void\", \"never\", \"map\", \"set\"]);\nvar L_ = (t48) =\u003e {\n switch (typeof t48) {\n case \"undefined\":\n return O_.undefined;\n case \"string\":\n return O_.string;\n case \"number\":\n return Number.isNaN(t48) ? O_.nan : O_.number;\n case \"boolean\":\n return O_.boolean;\n case \"function\":\n return O_.function;\n case \"bigint\":\n return O_.bigint;\n case \"symbol\":\n return O_.symbol;\n case \"object\":\n return Array.isArray(t48) ? O_.array : null === t48 ? O_.null : t48.then \u0026\u0026 \"function\" == typeof t48.then \u0026\u0026 t48.catch \u0026\u0026 \"function\" == typeof t48.catch ? O_.promise : \"undefined\" != typeof Map \u0026\u0026 t48 instanceof Map ? O_.map : \"undefined\" != typeof Set \u0026\u0026 t48 instanceof Set ? O_.set : \"undefined\" != typeof Date \u0026\u0026 t48 instanceof Date ? O_.date : O_.object;\n default:\n return O_.unknown;\n }\n};\nvar D_ = w_.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\"]);\nvar z_ = (t48) =\u003e JSON.stringify(t48, null, 2).replace(/\"([^\"]+)\":/g, \"$1:\");\nvar k_ = class t17 extends Error {\n get errors() {\n return this.issues;\n }\n constructor(t48) {\n super(), this.issues = [], this.addIssue = (t49) =\u003e {\n this.issues = [...this.issues, t49];\n }, this.addIssues = (t49 = []) =\u003e {\n this.issues = [...this.issues, ...t49];\n };\n const e2 = new.target.prototype;\n Object.setPrototypeOf ? Object.setPrototypeOf(this, e2) : this.__proto__ = e2, this.name = \"ZodError\", this.issues = t48;\n }\n format(t48) {\n const e2 = t48 || function(t49) {\n return t49.message;\n }, n2 = { _errors: [] }, o2 = (t49) =\u003e {\n for (const i2 of t49.issues) if (\"invalid_union\" === i2.code) i2.unionErrors.map(o2);\n else if (\"invalid_return_type\" === i2.code) o2(i2.returnTypeError);\n else if (\"invalid_arguments\" === i2.code) o2(i2.argumentsError);\n else if (0 === i2.path.length) n2._errors.push(e2(i2));\n else {\n let t50 = n2, o3 = 0;\n for (; o3 \u003c i2.path.length; ) {\n const n3 = i2.path[o3];\n o3 === i2.path.length - 1 ? (t50[n3] = t50[n3] || { _errors: [] }, t50[n3]._errors.push(e2(i2))) : t50[n3] = t50[n3] || { _errors: [] }, t50 = t50[n3], o3++;\n }\n }\n };\n return o2(this), n2;\n }\n static assert(e2) {\n if (!(e2 instanceof t17)) throw new Error(`Not a ZodError: ${e2}`);\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, w_.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return 0 === this.issues.length;\n }\n flatten(t48 = (t49) =\u003e t49.message) {\n const e2 = {}, n2 = [];\n for (const o2 of this.issues) if (o2.path.length \u003e 0) {\n const n3 = o2.path[0];\n e2[n3] = e2[n3] || [], e2[n3].push(t48(o2));\n } else n2.push(t48(o2));\n return { formErrors: n2, fieldErrors: e2 };\n }\n get formErrors() {\n return this.flatten();\n }\n};\nk_.create = (t48) =\u003e new k_(t48);\nvar F_ = (t48, e2) =\u003e {\n let n2;\n switch (t48.code) {\n case D_.invalid_type:\n n2 = t48.received === O_.undefined ? \"Required\" : `Expected ${t48.expected}, received ${t48.received}`;\n break;\n case D_.invalid_literal:\n n2 = `Invalid literal value, expected ${JSON.stringify(t48.expected, w_.jsonStringifyReplacer)}`;\n break;\n case D_.unrecognized_keys:\n n2 = `Unrecognized key(s) in object: ${w_.joinValues(t48.keys, \", \")}`;\n break;\n case D_.invalid_union:\n n2 = \"Invalid input\";\n break;\n case D_.invalid_union_discriminator:\n n2 = `Invalid discriminator value. Expected ${w_.joinValues(t48.options)}`;\n break;\n case D_.invalid_enum_value:\n n2 = `Invalid enum value. Expected ${w_.joinValues(t48.options)}, received '${t48.received}'`;\n break;\n case D_.invalid_arguments:\n n2 = \"Invalid function arguments\";\n break;\n case D_.invalid_return_type:\n n2 = \"Invalid function return type\";\n break;\n case D_.invalid_date:\n n2 = \"Invalid date\";\n break;\n case D_.invalid_string:\n \"object\" == typeof t48.validation ? \"includes\" in t48.validation ? (n2 = `Invalid input: must include \"${t48.validation.includes}\"`, \"number\" == typeof t48.validation.position \u0026\u0026 (n2 = `${n2} at one or more positions greater than or equal to ${t48.validation.position}`)) : \"startsWith\" in t48.validation ? n2 = `Invalid input: must start with \"${t48.validation.startsWith}\"` : \"endsWith\" in t48.validation ? n2 = `Invalid input: must end with \"${t48.validation.endsWith}\"` : w_.assertNever(t48.validation) : n2 = \"regex\" !== t48.validation ? `Invalid ${t48.validation}` : \"Invalid\";\n break;\n case D_.too_small:\n n2 = \"array\" === t48.type ? `Array must contain ${t48.exact ? \"exactly\" : t48.inclusive ? \"at least\" : \"more than\"} ${t48.minimum} element(s)` : \"string\" === t48.type ? `String must contain ${t48.exact ? \"exactly\" : t48.inclusive ? \"at least\" : \"over\"} ${t48.minimum} character(s)` : \"number\" === t48.type || \"bigint\" === t48.type ? `Number must be ${t48.exact ? \"exactly equal to \" : t48.inclusive ? \"greater than or equal to \" : \"greater than \"}${t48.minimum}` : \"date\" === t48.type ? `Date must be ${t48.exact ? \"exactly equal to \" : t48.inclusive ? \"greater than or equal to \" : \"greater than \"}${new Date(Number(t48.minimum))}` : \"Invalid input\";\n break;\n case D_.too_big:\n n2 = \"array\" === t48.type ? `Array must contain ${t48.exact ? \"exactly\" : t48.inclusive ? \"at most\" : \"less than\"} ${t48.maximum} element(s)` : \"string\" === t48.type ? `String must contain ${t48.exact ? \"exactly\" : t48.inclusive ? \"at most\" : \"under\"} ${t48.maximum} character(s)` : \"number\" === t48.type ? `Number must be ${t48.exact ? \"exactly\" : t48.inclusive ? \"less than or equal to\" : \"less than\"} ${t48.maximum}` : \"bigint\" === t48.type ? `BigInt must be ${t48.exact ? \"exactly\" : t48.inclusive ? \"less than or equal to\" : \"less than\"} ${t48.maximum}` : \"date\" === t48.type ? `Date must be ${t48.exact ? \"exactly\" : t48.inclusive ? \"smaller than or equal to\" : \"smaller than\"} ${new Date(Number(t48.maximum))}` : \"Invalid input\";\n break;\n case D_.custom:\n n2 = \"Invalid input\";\n break;\n case D_.invalid_intersection_types:\n n2 = \"Intersection results could not be merged\";\n break;\n case D_.not_multiple_of:\n n2 = `Number must be a multiple of ${t48.multipleOf}`;\n break;\n case D_.not_finite:\n n2 = \"Number must be finite\";\n break;\n default:\n n2 = e2.defaultError, w_.assertNever(t48);\n }\n return { message: n2 };\n};\nvar j_ = F_;\nfunction Y_(t48) {\n j_ = t48;\n}\nfunction $_() {\n return j_;\n}\nvar X_ = (t48) =\u003e {\n const { data: e2, path: n2, errorMaps: o2, issueData: i2 } = t48, r2 = [...n2, ...i2.path || []], s2 = { ...i2, path: r2 };\n if (void 0 !== i2.message) return { ...i2, path: r2, message: i2.message };\n let a2 = \"\";\n const c2 = o2.filter((t49) =\u003e !!t49).slice().reverse();\n for (const t49 of c2) a2 = t49(s2, { data: e2, defaultError: a2 }).message;\n return { ...i2, path: r2, message: a2 };\n};\nvar B_ = [];\nfunction H_(t48, e2) {\n const n2 = $_(), o2 = X_({ issueData: e2, data: t48.data, path: t48.path, errorMaps: [t48.common.contextualErrorMap, t48.schemaErrorMap, n2, n2 === F_ ? void 0 : F_].filter((t49) =\u003e !!t49) });\n t48.common.issues.push(o2);\n}\nvar W_;\nvar V_;\nvar U_ = class t18 {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n \"valid\" === this.value \u0026\u0026 (this.value = \"dirty\");\n }\n abort() {\n \"aborted\" !== this.value \u0026\u0026 (this.value = \"aborted\");\n }\n static mergeArray(t48, e2) {\n const n2 = [];\n for (const o2 of e2) {\n if (\"aborted\" === o2.status) return G_;\n \"dirty\" === o2.status \u0026\u0026 t48.dirty(), n2.push(o2.value);\n }\n return { status: t48.value, value: n2 };\n }\n static async mergeObjectAsync(e2, n2) {\n const o2 = [];\n for (const t48 of n2) {\n const e3 = await t48.key, n3 = await t48.value;\n o2.push({ key: e3, value: n3 });\n }\n return t18.mergeObjectSync(e2, o2);\n }\n static mergeObjectSync(t48, e2) {\n const n2 = {};\n for (const o2 of e2) {\n const { key: e3, value: i2 } = o2;\n if (\"aborted\" === e3.status) return G_;\n if (\"aborted\" === i2.status) return G_;\n \"dirty\" === e3.status \u0026\u0026 t48.dirty(), \"dirty\" === i2.status \u0026\u0026 t48.dirty(), \"__proto__\" === e3.value || void 0 === i2.value \u0026\u0026 !o2.alwaysSet || (n2[e3.value] = i2.value);\n }\n return { status: t48.value, value: n2 };\n }\n};\nvar G_ = Object.freeze({ status: \"aborted\" });\nvar Z_ = (t48) =\u003e ({ status: \"dirty\", value: t48 });\nvar q_ = (t48) =\u003e ({ status: \"valid\", value: t48 });\nvar J_ = (t48) =\u003e \"aborted\" === t48.status;\nvar K_ = (t48) =\u003e \"dirty\" === t48.status;\nvar Q_ = (t48) =\u003e \"valid\" === t48.status;\nvar ty = (t48) =\u003e \"undefined\" != typeof Promise \u0026\u0026 t48 instanceof Promise;\n(V_ = W_ || (W_ = {})).errToObj = (t48) =\u003e \"string\" == typeof t48 ? { message: t48 } : t48 || {}, V_.toString = (t48) =\u003e \"string\" == typeof t48 ? t48 : t48?.message;\nvar ey = class {\n constructor(t48, e2, n2, o2) {\n this._cachedPath = [], this.parent = t48, this.data = e2, this._path = n2, this._key = o2;\n }\n get path() {\n return this._cachedPath.length || (Array.isArray(this._key) ? this._cachedPath.push(...this._path, ...this._key) : this._cachedPath.push(...this._path, this._key)), this._cachedPath;\n }\n};\nvar ny = (t48, e2) =\u003e {\n if (Q_(e2)) return { success: true, data: e2.value };\n if (!t48.common.issues.length) throw new Error(\"Validation failed but no issues detected.\");\n return { success: false, get error() {\n if (this._error) return this._error;\n const e3 = new k_(t48.common.issues);\n return this._error = e3, this._error;\n } };\n};\nfunction oy(t48) {\n if (!t48) return {};\n const { errorMap: e2, invalid_type_error: n2, required_error: o2, description: i2 } = t48;\n if (e2 \u0026\u0026 (n2 || o2)) throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n if (e2) return { errorMap: e2, description: i2 };\n return { errorMap: (e3, i3) =\u003e {\n const { message: r2 } = t48;\n return \"invalid_enum_value\" === e3.code ? { message: r2 ?? i3.defaultError } : void 0 === i3.data ? { message: r2 ?? o2 ?? i3.defaultError } : \"invalid_type\" !== e3.code ? { message: i3.defaultError } : { message: r2 ?? n2 ?? i3.defaultError };\n }, description: i2 };\n}\nvar iy;\nvar ry = class {\n get description() {\n return this._def.description;\n }\n _getType(t48) {\n return L_(t48.data);\n }\n _getOrReturnCtx(t48, e2) {\n return e2 || { common: t48.parent.common, data: t48.data, parsedType: L_(t48.data), schemaErrorMap: this._def.errorMap, path: t48.path, parent: t48.parent };\n }\n _processInputParams(t48) {\n return { status: new U_(), ctx: { common: t48.parent.common, data: t48.data, parsedType: L_(t48.data), schemaErrorMap: this._def.errorMap, path: t48.path, parent: t48.parent } };\n }\n _parseSync(t48) {\n const e2 = this._parse(t48);\n if (ty(e2)) throw new Error(\"Synchronous parse encountered promise.\");\n return e2;\n }\n _parseAsync(t48) {\n const e2 = this._parse(t48);\n return Promise.resolve(e2);\n }\n parse(t48, e2) {\n const n2 = this.safeParse(t48, e2);\n if (n2.success) return n2.data;\n throw n2.error;\n }\n safeParse(t48, e2) {\n const n2 = { common: { issues: [], async: e2?.async ?? false, contextualErrorMap: e2?.errorMap }, path: e2?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data: t48, parsedType: L_(t48) }, o2 = this._parseSync({ data: t48, path: n2.path, parent: n2 });\n return ny(n2, o2);\n }\n \"~validate\"(t48) {\n const e2 = { common: { issues: [], async: !!this[\"~standard\"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data: t48, parsedType: L_(t48) };\n if (!this[\"~standard\"].async) try {\n const n2 = this._parseSync({ data: t48, path: [], parent: e2 });\n return Q_(n2) ? { value: n2.value } : { issues: e2.common.issues };\n } catch (t49) {\n t49?.message?.toLowerCase()?.includes(\"encountered\") \u0026\u0026 (this[\"~standard\"].async = true), e2.common = { issues: [], async: true };\n }\n return this._parseAsync({ data: t48, path: [], parent: e2 }).then((t49) =\u003e Q_(t49) ? { value: t49.value } : { issues: e2.common.issues });\n }\n async parseAsync(t48, e2) {\n const n2 = await this.safeParseAsync(t48, e2);\n if (n2.success) return n2.data;\n throw n2.error;\n }\n async safeParseAsync(t48, e2) {\n const n2 = { common: { issues: [], contextualErrorMap: e2?.errorMap, async: true }, path: e2?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data: t48, parsedType: L_(t48) }, o2 = this._parse({ data: t48, path: n2.path, parent: n2 }), i2 = await (ty(o2) ? o2 : Promise.resolve(o2));\n return ny(n2, i2);\n }\n refine(t48, e2) {\n const n2 = (t49) =\u003e \"string\" == typeof e2 || void 0 === e2 ? { message: e2 } : \"function\" == typeof e2 ? e2(t49) : e2;\n return this._refinement((e3, o2) =\u003e {\n const i2 = t48(e3), r2 = () =\u003e o2.addIssue({ code: D_.custom, ...n2(e3) });\n return \"undefined\" != typeof Promise \u0026\u0026 i2 instanceof Promise ? i2.then((t49) =\u003e !!t49 || (r2(), false)) : !!i2 || (r2(), false);\n });\n }\n refinement(t48, e2) {\n return this._refinement((n2, o2) =\u003e !!t48(n2) || (o2.addIssue(\"function\" == typeof e2 ? e2(n2, o2) : e2), false));\n }\n _refinement(t48) {\n return new sb({ schema: this, typeName: yb.ZodEffects, effect: { type: \"refinement\", refinement: t48 } });\n }\n superRefine(t48) {\n return this._refinement(t48);\n }\n constructor(t48) {\n this.spa = this.safeParseAsync, this._def = t48, 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: (t49) =\u003e this[\"~validate\"](t49) };\n }\n optional() {\n return ab.create(this, this._def);\n }\n nullable() {\n return cb.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return $y.create(this);\n }\n promise() {\n return rb.create(this, this._def);\n }\n or(t48) {\n return Hy.create([this, t48], this._def);\n }\n and(t48) {\n return Gy.create(this, t48, this._def);\n }\n transform(t48) {\n return new sb({ ...oy(this._def), schema: this, typeName: yb.ZodEffects, effect: { type: \"transform\", transform: t48 } });\n }\n default(t48) {\n const e2 = \"function\" == typeof t48 ? t48 : () =\u003e t48;\n return new lb({ ...oy(this._def), innerType: this, defaultValue: e2, typeName: yb.ZodDefault });\n }\n brand() {\n return new pb({ typeName: yb.ZodBranded, type: this, ...oy(this._def) });\n }\n catch(t48) {\n const e2 = \"function\" == typeof t48 ? t48 : () =\u003e t48;\n return new hb({ ...oy(this._def), innerType: this, catchValue: e2, typeName: yb.ZodCatch });\n }\n describe(t48) {\n return new (0, this.constructor)({ ...this._def, description: t48 });\n }\n pipe(t48) {\n return mb.create(this, t48);\n }\n readonly() {\n return gb.create(this);\n }\n isOptional() {\n return this.safeParse(void 0).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n};\nvar sy = /^c[^\\s-]{8,}$/i;\nvar ay = /^[0-9a-z]+$/;\nvar cy = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\nvar ly = /^[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;\nvar hy = /^[a-z0-9_-]{21}$/i;\nvar dy = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nvar uy = /^[-+]?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)?)??$/;\nvar py = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\nvar my = /^(?:(?: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])$/;\nvar gy = /^(?:(?: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])$/;\nvar fy = /^(([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]))$/;\nvar _y = /^(([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])$/;\nvar yy = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\nvar by = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\nvar xy = \"((\\\\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])))\";\nvar vy = new RegExp(`^${xy} design/vendor/bus-lanes-candidate.js - astra/am3352-sbc - tscircuit );\nfunction Sy(t48) {\n let e2 = \"[0-5]\\\\d\";\n t48.precision ? e2 = `${e2}\\\\.\\\\d{${t48.precision}}` : null == t48.precision \u0026\u0026 (e2 = `${e2}(\\\\.\\\\d+)?`);\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${e2})${t48.precision ? \"+\" : \"?\"}`;\n}\nfunction Iy(t48) {\n return new RegExp(`^${Sy(t48)} design/vendor/bus-lanes-candidate.js - astra/am3352-sbc - tscircuit );\n}\nfunction Py(t48) {\n let e2 = `${xy}T${Sy(t48)}`;\n const n2 = [];\n return n2.push(t48.local ? \"Z?\" : \"Z\"), t48.offset \u0026\u0026 n2.push(\"([+-]\\\\d{2}:?\\\\d{2})\"), e2 = `${e2}(${n2.join(\"|\")})`, new RegExp(`^${e2} design/vendor/bus-lanes-candidate.js - astra/am3352-sbc - tscircuit );\n}\nfunction My(t48, e2) {\n return !(\"v4\" !== e2 \u0026\u0026 e2 || !my.test(t48)) || !(\"v6\" !== e2 \u0026\u0026 e2 || !fy.test(t48));\n}\nfunction Cy(t48, e2) {\n if (!dy.test(t48)) return false;\n try {\n const [n2] = t48.split(\".\");\n if (!n2) return false;\n const o2 = n2.replace(/-/g, \"+\").replace(/_/g, \"/\").padEnd(n2.length + (4 - n2.length % 4) % 4, \"=\"), i2 = JSON.parse(atob(o2));\n return \"object\" == typeof i2 \u0026\u0026 null !== i2 \u0026\u0026 ((!(\"typ\" in i2) || \"JWT\" === i2?.typ) \u0026\u0026 (!!i2.alg \u0026\u0026 (!e2 || i2.alg === e2)));\n } catch {\n return false;\n }\n}\nfunction Ny(t48, e2) {\n return !(\"v4\" !== e2 \u0026\u0026 e2 || !gy.test(t48)) || !(\"v6\" !== e2 \u0026\u0026 e2 || !_y.test(t48));\n}\nvar wy = class t19 extends ry {\n _parse(t48) {\n this._def.coerce \u0026\u0026 (t48.data = String(t48.data));\n if (this._getType(t48) !== O_.string) {\n const e3 = this._getOrReturnCtx(t48);\n return H_(e3, { code: D_.invalid_type, expected: O_.string, received: e3.parsedType }), G_;\n }\n const e2 = new U_();\n let n2;\n for (const o2 of this._def.checks) if (\"min\" === o2.kind) t48.data.length \u003c o2.value \u0026\u0026 (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.too_small, minimum: o2.value, type: \"string\", inclusive: true, exact: false, message: o2.message }), e2.dirty());\n else if (\"max\" === o2.kind) t48.data.length \u003e o2.value \u0026\u0026 (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.too_big, maximum: o2.value, type: \"string\", inclusive: true, exact: false, message: o2.message }), e2.dirty());\n else if (\"length\" === o2.kind) {\n const i2 = t48.data.length \u003e o2.value, r2 = t48.data.length \u003c o2.value;\n (i2 || r2) \u0026\u0026 (n2 = this._getOrReturnCtx(t48, n2), i2 ? H_(n2, { code: D_.too_big, maximum: o2.value, type: \"string\", inclusive: true, exact: true, message: o2.message }) : r2 \u0026\u0026 H_(n2, { code: D_.too_small, minimum: o2.value, type: \"string\", inclusive: true, exact: true, message: o2.message }), e2.dirty());\n } else if (\"email\" === o2.kind) py.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"email\", code: D_.invalid_string, message: o2.message }), e2.dirty());\n else if (\"emoji\" === o2.kind) iy || (iy = new RegExp(\"^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$\", \"u\")), iy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"emoji\", code: D_.invalid_string, message: o2.message }), e2.dirty());\n else if (\"uuid\" === o2.kind) ly.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"uuid\", code: D_.invalid_string, message: o2.message }), e2.dirty());\n else if (\"nanoid\" === o2.kind) hy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"nanoid\", code: D_.invalid_string, message: o2.message }), e2.dirty());\n else if (\"cuid\" === o2.kind) sy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"cuid\", code: D_.invalid_string, message: o2.message }), e2.dirty());\n else if (\"cuid2\" === o2.kind) ay.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"cuid2\", code: D_.invalid_string, message: o2.message }), e2.dirty());\n else if (\"ulid\" === o2.kind) cy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"ulid\", code: D_.invalid_string, message: o2.message }), e2.dirty());\n else if (\"url\" === o2.kind) try {\n new URL(t48.data);\n } catch {\n n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"url\", code: D_.invalid_string, message: o2.message }), e2.dirty();\n }\n else if (\"regex\" === o2.kind) {\n o2.regex.lastIndex = 0;\n o2.regex.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"regex\", code: D_.invalid_string, message: o2.message }), e2.dirty());\n } else if (\"trim\" === o2.kind) t48.data = t48.data.trim();\n else if (\"includes\" === o2.kind) t48.data.includes(o2.value, o2.position) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: { includes: o2.value, position: o2.position }, message: o2.message }), e2.dirty());\n else if (\"toLowerCase\" === o2.kind) t48.data = t48.data.toLowerCase();\n else if (\"toUpperCase\" === o2.kind) t48.data = t48.data.toUpperCase();\n else if (\"startsWith\" === o2.kind) t48.data.startsWith(o2.value) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: { startsWith: o2.value }, message: o2.message }), e2.dirty());\n else if (\"endsWith\" === o2.kind) t48.data.endsWith(o2.value) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: { endsWith: o2.value }, message: o2.message }), e2.dirty());\n else if (\"datetime\" === o2.kind) {\n Py(o2).test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: \"datetime\", message: o2.message }), e2.dirty());\n } else if (\"date\" === o2.kind) {\n vy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: \"date\", message: o2.message }), e2.dirty());\n } else if (\"time\" === o2.kind) {\n Iy(o2).test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: \"time\", message: o2.message }), e2.dirty());\n } else \"duration\" === o2.kind ? uy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"duration\", code: D_.invalid_string, message: o2.message }), e2.dirty()) : \"ip\" === o2.kind ? My(t48.data, o2.version) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"ip\", code: D_.invalid_string, message: o2.message }), e2.dirty()) : \"jwt\" === o2.kind ? Cy(t48.data, o2.alg) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"jwt\", code: D_.invalid_string, message: o2.message }), e2.dirty()) : \"cidr\" === o2.kind ? Ny(t48.data, o2.version) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"cidr\", code: D_.invalid_string, message: o2.message }), e2.dirty()) : \"base64\" === o2.kind ? yy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"base64\", code: D_.invalid_string, message: o2.message }), e2.dirty()) : \"base64url\" === o2.kind ? by.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: \"base64url\", code: D_.invalid_string, message: o2.message }), e2.dirty()) : w_.assertNever(o2);\n return { status: e2.value, value: t48.data };\n }\n _regex(t48, e2, n2) {\n return this.refinement((e3) =\u003e t48.test(e3), { validation: e2, code: D_.invalid_string, ...W_.errToObj(n2) });\n }\n _addCheck(e2) {\n return new t19({ ...this._def, checks: [...this._def.checks, e2] });\n }\n email(t48) {\n return this._addCheck({ kind: \"email\", ...W_.errToObj(t48) });\n }\n url(t48) {\n return this._addCheck({ kind: \"url\", ...W_.errToObj(t48) });\n }\n emoji(t48) {\n return this._addCheck({ kind: \"emoji\", ...W_.errToObj(t48) });\n }\n uuid(t48) {\n return this._addCheck({ kind: \"uuid\", ...W_.errToObj(t48) });\n }\n nanoid(t48) {\n return this._addCheck({ kind: \"nanoid\", ...W_.errToObj(t48) });\n }\n cuid(t48) {\n return this._addCheck({ kind: \"cuid\", ...W_.errToObj(t48) });\n }\n cuid2(t48) {\n return this._addCheck({ kind: \"cuid2\", ...W_.errToObj(t48) });\n }\n ulid(t48) {\n return this._addCheck({ kind: \"ulid\", ...W_.errToObj(t48) });\n }\n base64(t48) {\n return this._addCheck({ kind: \"base64\", ...W_.errToObj(t48) });\n }\n base64url(t48) {\n return this._addCheck({ kind: \"base64url\", ...W_.errToObj(t48) });\n }\n jwt(t48) {\n return this._addCheck({ kind: \"jwt\", ...W_.errToObj(t48) });\n }\n ip(t48) {\n return this._addCheck({ kind: \"ip\", ...W_.errToObj(t48) });\n }\n cidr(t48) {\n return this._addCheck({ kind: \"cidr\", ...W_.errToObj(t48) });\n }\n datetime(t48) {\n return \"string\" == typeof t48 ? this._addCheck({ kind: \"datetime\", precision: null, offset: false, local: false, message: t48 }) : this._addCheck({ kind: \"datetime\", precision: void 0 === t48?.precision ? null : t48?.precision, offset: t48?.offset ?? false, local: t48?.local ?? false, ...W_.errToObj(t48?.message) });\n }\n date(t48) {\n return this._addCheck({ kind: \"date\", message: t48 });\n }\n time(t48) {\n return \"string\" == typeof t48 ? this._addCheck({ kind: \"time\", precision: null, message: t48 }) : this._addCheck({ kind: \"time\", precision: void 0 === t48?.precision ? null : t48?.precision, ...W_.errToObj(t48?.message) });\n }\n duration(t48) {\n return this._addCheck({ kind: \"duration\", ...W_.errToObj(t48) });\n }\n regex(t48, e2) {\n return this._addCheck({ kind: \"regex\", regex: t48, ...W_.errToObj(e2) });\n }\n includes(t48, e2) {\n return this._addCheck({ kind: \"includes\", value: t48, position: e2?.position, ...W_.errToObj(e2?.message) });\n }\n startsWith(t48, e2) {\n return this._addCheck({ kind: \"startsWith\", value: t48, ...W_.errToObj(e2) });\n }\n endsWith(t48, e2) {\n return this._addCheck({ kind: \"endsWith\", value: t48, ...W_.errToObj(e2) });\n }\n min(t48, e2) {\n return this._addCheck({ kind: \"min\", value: t48, ...W_.errToObj(e2) });\n }\n max(t48, e2) {\n return this._addCheck({ kind: \"max\", value: t48, ...W_.errToObj(e2) });\n }\n length(t48, e2) {\n return this._addCheck({ kind: \"length\", value: t48, ...W_.errToObj(e2) });\n }\n nonempty(t48) {\n return this.min(1, W_.errToObj(t48));\n }\n trim() {\n return new t19({ ...this._def, checks: [...this._def.checks, { kind: \"trim\" }] });\n }\n toLowerCase() {\n return new t19({ ...this._def, checks: [...this._def.checks, { kind: \"toLowerCase\" }] });\n }\n toUpperCase() {\n return new t19({ ...this._def, checks: [...this._def.checks, { kind: \"toUpperCase\" }] });\n }\n get isDatetime() {\n return !!this._def.checks.find((t48) =\u003e \"datetime\" === t48.kind);\n }\n get isDate() {\n return !!this._def.checks.find((t48) =\u003e \"date\" === t48.kind);\n }\n get isTime() {\n return !!this._def.checks.find((t48) =\u003e \"time\" === t48.kind);\n }\n get isDuration() {\n return !!this._def.checks.find((t48) =\u003e \"duration\" === t48.kind);\n }\n get isEmail() {\n return !!this._def.checks.find((t48) =\u003e \"email\" === t48.kind);\n }\n get isURL() {\n return !!this._def.checks.find((t48) =\u003e \"url\" === t48.kind);\n }\n get isEmoji() {\n return !!this._def.checks.find((t48) =\u003e \"emoji\" === t48.kind);\n }\n get isUUID() {\n return !!this._def.checks.find((t48) =\u003e \"uuid\" === t48.kind);\n }\n get isNANOID() {\n return !!this._def.checks.find((t48) =\u003e \"nanoid\" === t48.kind);\n }\n get isCUID() {\n return !!this._def.checks.find((t48) =\u003e \"cuid\" === t48.kind);\n }\n get isCUID2() {\n return !!this._def.checks.find((t48) =\u003e \"cuid2\" === t48.kind);\n }\n get isULID() {\n return !!this._def.checks.find((t48) =\u003e \"ulid\" === t48.kind);\n }\n get isIP() {\n return !!this._def.checks.find((t48) =\u003e \"ip\" === t48.kind);\n }\n get isCIDR() {\n return !!this._def.checks.find((t48) =\u003e \"cidr\" === t48.kind);\n }\n get isBase64() {\n return !!this._def.checks.find((t48) =\u003e \"base64\" === t48.kind);\n }\n get isBase64url() {\n return !!this._def.checks.find((t48) =\u003e \"base64url\" === t48.kind);\n }\n get minLength() {\n let t48 = null;\n for (const e2 of this._def.checks) \"min\" === e2.kind \u0026\u0026 (null === t48 || e2.value \u003e t48) \u0026\u0026 (t48 = e2.value);\n return t48;\n }\n get maxLength() {\n let t48 = null;\n for (const e2 of this._def.checks) \"max\" === e2.kind \u0026\u0026 (null === t48 || e2.value \u003c t48) \u0026\u0026 (t48 = e2.value);\n return t48;\n }\n};\nfunction Ty(t48, e2) {\n const n2 = (t48.toString().split(\".\")[1] || \"\").length, o2 = (e2.toString().split(\".\")[1] || \"\").length, i2 = n2 \u003e o2 ? n2 : o2;\n return Number.parseInt(t48.toFixed(i2).replace(\".\", \"\")) % Number.parseInt(e2.toFixed(i2).replace(\".\", \"\")) / 10 ** i2;\n}\nwy.create = (t48) =\u003e new wy({ checks: [], typeName: yb.ZodString, coerce: t48?.coerce ?? false, ...oy(t48) });\nvar Ry = class t20 extends ry {\n constructor() {\n super(...arguments), this.min = this.gte, this.max = this.lte, this.step = this.multipleOf;\n }\n _parse(t48) {\n this._def.coerce \u0026\u0026 (t48.data = Number(t48.data));\n if (this._getType(t48) !== O_.number) {\n const e3 = this._getOrReturnCtx(t48);\n return H_(e3, { code: D_.invalid_type, expected: O_.number, received: e3.parsedType }), G_;\n }\n let e2;\n const n2 = new U_();\n for (const o2 of this._def.checks) if (\"int\" === o2.kind) w_.isInteger(t48.data) || (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.invalid_type, expected: \"integer\", received: \"float\", message: o2.message }), n2.dirty());\n else if (\"min\" === o2.kind) {\n (o2.inclusive ? t48.data \u003c o2.value : t48.data \u003c= o2.value) \u0026\u0026 (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.too_small, minimum: o2.value, type: \"number\", inclusive: o2.inclusive, exact: false, message: o2.message }), n2.dirty());\n } else if (\"max\" === o2.kind) {\n (o2.inclusive ? t48.data \u003e o2.value : t48.data \u003e= o2.value) \u0026\u0026 (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.too_big, maximum: o2.value, type: \"number\", inclusive: o2.inclusive, exact: false, message: o2.message }), n2.dirty());\n } else \"multipleOf\" === o2.kind ? 0 !== Ty(t48.data, o2.value) \u0026\u0026 (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.not_multiple_of, multipleOf: o2.value, message: o2.message }), n2.dirty()) : \"finite\" === o2.kind ? Number.isFinite(t48.data) || (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.not_finite, message: o2.message }), n2.dirty()) : w_.assertNever(o2);\n return { status: n2.value, value: t48.data };\n }\n gte(t48, e2) {\n return this.setLimit(\"min\", t48, true, W_.toString(e2));\n }\n gt(t48, e2) {\n return this.setLimit(\"min\", t48, false, W_.toString(e2));\n }\n lte(t48, e2) {\n return this.setLimit(\"max\", t48, true, W_.toString(e2));\n }\n lt(t48, e2) {\n return this.setLimit(\"max\", t48, false, W_.toString(e2));\n }\n setLimit(e2, n2, o2, i2) {\n return new t20({ ...this._def, checks: [...this._def.checks, { kind: e2, value: n2, inclusive: o2, message: W_.toString(i2) }] });\n }\n _addCheck(e2) {\n return new t20({ ...this._def, checks: [...this._def.checks, e2] });\n }\n int(t48) {\n return this._addCheck({ kind: \"int\", message: W_.toString(t48) });\n }\n positive(t48) {\n return this._addCheck({ kind: \"min\", value: 0, inclusive: false, message: W_.toString(t48) });\n }\n negative(t48) {\n return this._addCheck({ kind: \"max\", value: 0, inclusive: false, message: W_.toString(t48) });\n }\n nonpositive(t48) {\n return this._addCheck({ kind: \"max\", value: 0, inclusive: true, message: W_.toString(t48) });\n }\n nonnegative(t48) {\n return this._addCheck({ kind: \"min\", value: 0, inclusive: true, message: W_.toString(t48) });\n }\n multipleOf(t48, e2) {\n return this._addCheck({ kind: \"multipleOf\", value: t48, message: W_.toString(e2) });\n }\n finite(t48) {\n return this._addCheck({ kind: \"finite\", message: W_.toString(t48) });\n }\n safe(t48) {\n return this._addCheck({ kind: \"min\", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: W_.toString(t48) })._addCheck({ kind: \"max\", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: W_.toString(t48) });\n }\n get minValue() {\n let t48 = null;\n for (const e2 of this._def.checks) \"min\" === e2.kind \u0026\u0026 (null === t48 || e2.value \u003e t48) \u0026\u0026 (t48 = e2.value);\n return t48;\n }\n get maxValue() {\n let t48 = null;\n for (const e2 of this._def.checks) \"max\" === e2.kind \u0026\u0026 (null === t48 || e2.value \u003c t48) \u0026\u0026 (t48 = e2.value);\n return t48;\n }\n get isInt() {\n return !!this._def.checks.find((t48) =\u003e \"int\" === t48.kind || \"multipleOf\" === t48.kind \u0026\u0026 w_.isInteger(t48.value));\n }\n get isFinite() {\n let t48 = null, e2 = null;\n for (const n2 of this._def.checks) {\n if (\"finite\" === n2.kind || \"int\" === n2.kind || \"multipleOf\" === n2.kind) return true;\n \"min\" === n2.kind ? (null === e2 || n2.value \u003e e2) \u0026\u0026 (e2 = n2.value) : \"max\" === n2.kind \u0026\u0026 (null === t48 || n2.value \u003c t48) \u0026\u0026 (t48 = n2.value);\n }\n return Number.isFinite(e2) \u0026\u0026 Number.isFinite(t48);\n }\n};\nRy.create = (t48) =\u003e new Ry({ checks: [], typeName: yb.ZodNumber, coerce: t48?.coerce || false, ...oy(t48) });\nvar Ey = class t21 extends ry {\n constructor() {\n super(...arguments), this.min = this.gte, this.max = this.lte;\n }\n _parse(t48) {\n if (this._def.coerce) try {\n t48.data = BigInt(t48.data);\n } catch {\n return this._getInvalidInput(t48);\n }\n if (this._getType(t48) !== O_.bigint) return this._getInvalidInput(t48);\n let e2;\n const n2 = new U_();\n for (const o2 of this._def.checks) if (\"min\" === o2.kind) {\n (o2.inclusive ? t48.data \u003c o2.value : t48.data \u003c= o2.value) \u0026\u0026 (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.too_small, type: \"bigint\", minimum: o2.value, inclusive: o2.inclusive, message: o2.message }), n2.dirty());\n } else if (\"max\" === o2.kind) {\n (o2.inclusive ? t48.data \u003e o2.value : t48.data \u003e= o2.value) \u0026\u0026 (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.too_big, type: \"bigint\", maximum: o2.value, inclusive: o2.inclusive, message: o2.message }), n2.dirty());\n } else \"multipleOf\" === o2.kind ? t48.data % o2.value !== BigInt(0) \u0026\u0026 (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.not_multiple_of, multipleOf: o2.value, message: o2.message }), n2.dirty()) : w_.assertNever(o2);\n return { status: n2.value, value: t48.data };\n }\n _getInvalidInput(t48) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { code: D_.invalid_type, expected: O_.bigint, received: e2.parsedType }), G_;\n }\n gte(t48, e2) {\n return this.setLimit(\"min\", t48, true, W_.toString(e2));\n }\n gt(t48, e2) {\n return this.setLimit(\"min\", t48, false, W_.toString(e2));\n }\n lte(t48, e2) {\n return this.setLimit(\"max\", t48, true, W_.toString(e2));\n }\n lt(t48, e2) {\n return this.setLimit(\"max\", t48, false, W_.toString(e2));\n }\n setLimit(e2, n2, o2, i2) {\n return new t21({ ...this._def, checks: [...this._def.checks, { kind: e2, value: n2, inclusive: o2, message: W_.toString(i2) }] });\n }\n _addCheck(e2) {\n return new t21({ ...this._def, checks: [...this._def.checks, e2] });\n }\n positive(t48) {\n return this._addCheck({ kind: \"min\", value: BigInt(0), inclusive: false, message: W_.toString(t48) });\n }\n negative(t48) {\n return this._addCheck({ kind: \"max\", value: BigInt(0), inclusive: false, message: W_.toString(t48) });\n }\n nonpositive(t48) {\n return this._addCheck({ kind: \"max\", value: BigInt(0), inclusive: true, message: W_.toString(t48) });\n }\n nonnegative(t48) {\n return this._addCheck({ kind: \"min\", value: BigInt(0), inclusive: true, message: W_.toString(t48) });\n }\n multipleOf(t48, e2) {\n return this._addCheck({ kind: \"multipleOf\", value: t48, message: W_.toString(e2) });\n }\n get minValue() {\n let t48 = null;\n for (const e2 of this._def.checks) \"min\" === e2.kind \u0026\u0026 (null === t48 || e2.value \u003e t48) \u0026\u0026 (t48 = e2.value);\n return t48;\n }\n get maxValue() {\n let t48 = null;\n for (const e2 of this._def.checks) \"max\" === e2.kind \u0026\u0026 (null === t48 || e2.value \u003c t48) \u0026\u0026 (t48 = e2.value);\n return t48;\n }\n};\nEy.create = (t48) =\u003e new Ey({ checks: [], typeName: yb.ZodBigInt, coerce: t48?.coerce ?? false, ...oy(t48) });\nvar Ay = class extends ry {\n _parse(t48) {\n this._def.coerce \u0026\u0026 (t48.data = Boolean(t48.data));\n if (this._getType(t48) !== O_.boolean) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { code: D_.invalid_type, expected: O_.boolean, received: e2.parsedType }), G_;\n }\n return q_(t48.data);\n }\n};\nAy.create = (t48) =\u003e new Ay({ typeName: yb.ZodBoolean, coerce: t48?.coerce || false, ...oy(t48) });\nvar Oy = class t22 extends ry {\n _parse(t48) {\n this._def.coerce \u0026\u0026 (t48.data = new Date(t48.data));\n if (this._getType(t48) !== O_.date) {\n const e3 = this._getOrReturnCtx(t48);\n return H_(e3, { code: D_.invalid_type, expected: O_.date, received: e3.parsedType }), G_;\n }\n if (Number.isNaN(t48.data.getTime())) {\n return H_(this._getOrReturnCtx(t48), { code: D_.invalid_date }), G_;\n }\n const e2 = new U_();\n let n2;\n for (const o2 of this._def.checks) \"min\" === o2.kind ? t48.data.getTime() \u003c o2.value \u0026\u0026 (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.too_small, message: o2.message, inclusive: true, exact: false, minimum: o2.value, type: \"date\" }), e2.dirty()) : \"max\" === o2.kind ? t48.data.getTime() \u003e o2.value \u0026\u0026 (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.too_big, message: o2.message, inclusive: true, exact: false, maximum: o2.value, type: \"date\" }), e2.dirty()) : w_.assertNever(o2);\n return { status: e2.value, value: new Date(t48.data.getTime()) };\n }\n _addCheck(e2) {\n return new t22({ ...this._def, checks: [...this._def.checks, e2] });\n }\n min(t48, e2) {\n return this._addCheck({ kind: \"min\", value: t48.getTime(), message: W_.toString(e2) });\n }\n max(t48, e2) {\n return this._addCheck({ kind: \"max\", value: t48.getTime(), message: W_.toString(e2) });\n }\n get minDate() {\n let t48 = null;\n for (const e2 of this._def.checks) \"min\" === e2.kind \u0026\u0026 (null === t48 || e2.value \u003e t48) \u0026\u0026 (t48 = e2.value);\n return null != t48 ? new Date(t48) : null;\n }\n get maxDate() {\n let t48 = null;\n for (const e2 of this._def.checks) \"max\" === e2.kind \u0026\u0026 (null === t48 || e2.value \u003c t48) \u0026\u0026 (t48 = e2.value);\n return null != t48 ? new Date(t48) : null;\n }\n};\nOy.create = (t48) =\u003e new Oy({ checks: [], coerce: t48?.coerce || false, typeName: yb.ZodDate, ...oy(t48) });\nvar Ly = class extends ry {\n _parse(t48) {\n if (this._getType(t48) !== O_.symbol) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { code: D_.invalid_type, expected: O_.symbol, received: e2.parsedType }), G_;\n }\n return q_(t48.data);\n }\n};\nLy.create = (t48) =\u003e new Ly({ typeName: yb.ZodSymbol, ...oy(t48) });\nvar Dy = class extends ry {\n _parse(t48) {\n if (this._getType(t48) !== O_.undefined) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { code: D_.invalid_type, expected: O_.undefined, received: e2.parsedType }), G_;\n }\n return q_(t48.data);\n }\n};\nDy.create = (t48) =\u003e new Dy({ typeName: yb.ZodUndefined, ...oy(t48) });\nvar zy = class extends ry {\n _parse(t48) {\n if (this._getType(t48) !== O_.null) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { code: D_.invalid_type, expected: O_.null, received: e2.parsedType }), G_;\n }\n return q_(t48.data);\n }\n};\nzy.create = (t48) =\u003e new zy({ typeName: yb.ZodNull, ...oy(t48) });\nvar ky = class extends ry {\n constructor() {\n super(...arguments), this._any = true;\n }\n _parse(t48) {\n return q_(t48.data);\n }\n};\nky.create = (t48) =\u003e new ky({ typeName: yb.ZodAny, ...oy(t48) });\nvar Fy = class extends ry {\n constructor() {\n super(...arguments), this._unknown = true;\n }\n _parse(t48) {\n return q_(t48.data);\n }\n};\nFy.create = (t48) =\u003e new Fy({ typeName: yb.ZodUnknown, ...oy(t48) });\nvar jy = class extends ry {\n _parse(t48) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { code: D_.invalid_type, expected: O_.never, received: e2.parsedType }), G_;\n }\n};\njy.create = (t48) =\u003e new jy({ typeName: yb.ZodNever, ...oy(t48) });\nvar Yy = class extends ry {\n _parse(t48) {\n if (this._getType(t48) !== O_.undefined) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { code: D_.invalid_type, expected: O_.void, received: e2.parsedType }), G_;\n }\n return q_(t48.data);\n }\n};\nYy.create = (t48) =\u003e new Yy({ typeName: yb.ZodVoid, ...oy(t48) });\nvar $y = class t23 extends ry {\n _parse(t48) {\n const { ctx: e2, status: n2 } = this._processInputParams(t48), o2 = this._def;\n if (e2.parsedType !== O_.array) return H_(e2, { code: D_.invalid_type, expected: O_.array, received: e2.parsedType }), G_;\n if (null !== o2.exactLength) {\n const t49 = e2.data.length \u003e o2.exactLength.value, i3 = e2.data.length \u003c o2.exactLength.value;\n (t49 || i3) \u0026\u0026 (H_(e2, { code: t49 ? D_.too_big : D_.too_small, minimum: i3 ? o2.exactLength.value : void 0, maximum: t49 ? o2.exactLength.value : void 0, type: \"array\", inclusive: true, exact: true, message: o2.exactLength.message }), n2.dirty());\n }\n if (null !== o2.minLength \u0026\u0026 e2.data.length \u003c o2.minLength.value \u0026\u0026 (H_(e2, { code: D_.too_small, minimum: o2.minLength.value, type: \"array\", inclusive: true, exact: false, message: o2.minLength.message }), n2.dirty()), null !== o2.maxLength \u0026\u0026 e2.data.length \u003e o2.maxLength.value \u0026\u0026 (H_(e2, { code: D_.too_big, maximum: o2.maxLength.value, type: \"array\", inclusive: true, exact: false, message: o2.maxLength.message }), n2.dirty()), e2.common.async) return Promise.all([...e2.data].map((t49, n3) =\u003e o2.type._parseAsync(new ey(e2, t49, e2.path, n3)))).then((t49) =\u003e U_.mergeArray(n2, t49));\n const i2 = [...e2.data].map((t49, n3) =\u003e o2.type._parseSync(new ey(e2, t49, e2.path, n3)));\n return U_.mergeArray(n2, i2);\n }\n get element() {\n return this._def.type;\n }\n min(e2, n2) {\n return new t23({ ...this._def, minLength: { value: e2, message: W_.toString(n2) } });\n }\n max(e2, n2) {\n return new t23({ ...this._def, maxLength: { value: e2, message: W_.toString(n2) } });\n }\n length(e2, n2) {\n return new t23({ ...this._def, exactLength: { value: e2, message: W_.toString(n2) } });\n }\n nonempty(t48) {\n return this.min(1, t48);\n }\n};\nfunction Xy(t48) {\n if (t48 instanceof By) {\n const e2 = {};\n for (const n2 in t48.shape) {\n const o2 = t48.shape[n2];\n e2[n2] = ab.create(Xy(o2));\n }\n return new By({ ...t48._def, shape: () =\u003e e2 });\n }\n return t48 instanceof $y ? new $y({ ...t48._def, type: Xy(t48.element) }) : t48 instanceof ab ? ab.create(Xy(t48.unwrap())) : t48 instanceof cb ? cb.create(Xy(t48.unwrap())) : t48 instanceof Zy ? Zy.create(t48.items.map((t49) =\u003e Xy(t49))) : t48;\n}\n$y.create = (t48, e2) =\u003e new $y({ type: t48, minLength: null, maxLength: null, exactLength: null, typeName: yb.ZodArray, ...oy(e2) });\nvar By = class t24 extends ry {\n constructor() {\n super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;\n }\n _getCached() {\n if (null !== this._cached) return this._cached;\n const t48 = this._def.shape(), e2 = w_.objectKeys(t48);\n return this._cached = { shape: t48, keys: e2 }, this._cached;\n }\n _parse(t48) {\n if (this._getType(t48) !== O_.object) {\n const e3 = this._getOrReturnCtx(t48);\n return H_(e3, { code: D_.invalid_type, expected: O_.object, received: e3.parsedType }), G_;\n }\n const { status: e2, ctx: n2 } = this._processInputParams(t48), { shape: o2, keys: i2 } = this._getCached(), r2 = [];\n if (!(this._def.catchall instanceof jy \u0026\u0026 \"strip\" === this._def.unknownKeys)) for (const t49 in n2.data) i2.includes(t49) || r2.push(t49);\n const s2 = [];\n for (const t49 of i2) {\n const e3 = o2[t49], i3 = n2.data[t49];\n s2.push({ key: { status: \"valid\", value: t49 }, value: e3._parse(new ey(n2, i3, n2.path, t49)), alwaysSet: t49 in n2.data });\n }\n if (this._def.catchall instanceof jy) {\n const t49 = this._def.unknownKeys;\n if (\"passthrough\" === t49) for (const t50 of r2) s2.push({ key: { status: \"valid\", value: t50 }, value: { status: \"valid\", value: n2.data[t50] } });\n else if (\"strict\" === t49) r2.length \u003e 0 \u0026\u0026 (H_(n2, { code: D_.unrecognized_keys, keys: r2 }), e2.dirty());\n else if (\"strip\" !== t49) throw new Error(\"Internal ZodObject error: invalid unknownKeys value.\");\n } else {\n const t49 = this._def.catchall;\n for (const e3 of r2) {\n const o3 = n2.data[e3];\n s2.push({ key: { status: \"valid\", value: e3 }, value: t49._parse(new ey(n2, o3, n2.path, e3)), alwaysSet: e3 in n2.data });\n }\n }\n return n2.common.async ? Promise.resolve().then(async () =\u003e {\n const t49 = [];\n for (const e3 of s2) {\n const n3 = await e3.key, o3 = await e3.value;\n t49.push({ key: n3, value: o3, alwaysSet: e3.alwaysSet });\n }\n return t49;\n }).then((t49) =\u003e U_.mergeObjectSync(e2, t49)) : U_.mergeObjectSync(e2, s2);\n }\n get shape() {\n return this._def.shape();\n }\n strict(e2) {\n return W_.errToObj, new t24({ ...this._def, unknownKeys: \"strict\", ...void 0 !== e2 ? { errorMap: (t48, n2) =\u003e {\n const o2 = this._def.errorMap?.(t48, n2).message ?? n2.defaultError;\n return \"unrecognized_keys\" === t48.code ? { message: W_.errToObj(e2).message ?? o2 } : { message: o2 };\n } } : {} });\n }\n strip() {\n return new t24({ ...this._def, unknownKeys: \"strip\" });\n }\n passthrough() {\n return new t24({ ...this._def, unknownKeys: \"passthrough\" });\n }\n extend(e2) {\n return new t24({ ...this._def, shape: () =\u003e ({ ...this._def.shape(), ...e2 }) });\n }\n merge(e2) {\n return new t24({ unknownKeys: e2._def.unknownKeys, catchall: e2._def.catchall, shape: () =\u003e ({ ...this._def.shape(), ...e2._def.shape() }), typeName: yb.ZodObject });\n }\n setKey(t48, e2) {\n return this.augment({ [t48]: e2 });\n }\n catchall(e2) {\n return new t24({ ...this._def, catchall: e2 });\n }\n pick(e2) {\n const n2 = {};\n for (const t48 of w_.objectKeys(e2)) e2[t48] \u0026\u0026 this.shape[t48] \u0026\u0026 (n2[t48] = this.shape[t48]);\n return new t24({ ...this._def, shape: () =\u003e n2 });\n }\n omit(e2) {\n const n2 = {};\n for (const t48 of w_.objectKeys(this.shape)) e2[t48] || (n2[t48] = this.shape[t48]);\n return new t24({ ...this._def, shape: () =\u003e n2 });\n }\n deepPartial() {\n return Xy(this);\n }\n partial(e2) {\n const n2 = {};\n for (const t48 of w_.objectKeys(this.shape)) {\n const o2 = this.shape[t48];\n e2 \u0026\u0026 !e2[t48] ? n2[t48] = o2 : n2[t48] = o2.optional();\n }\n return new t24({ ...this._def, shape: () =\u003e n2 });\n }\n required(e2) {\n const n2 = {};\n for (const t48 of w_.objectKeys(this.shape)) if (e2 \u0026\u0026 !e2[t48]) n2[t48] = this.shape[t48];\n else {\n let e3 = this.shape[t48];\n for (; e3 instanceof ab; ) e3 = e3._def.innerType;\n n2[t48] = e3;\n }\n return new t24({ ...this._def, shape: () =\u003e n2 });\n }\n keyof() {\n return nb(w_.objectKeys(this.shape));\n }\n};\nBy.create = (t48, e2) =\u003e new By({ shape: () =\u003e t48, unknownKeys: \"strip\", catchall: jy.create(), typeName: yb.ZodObject, ...oy(e2) }), By.strictCreate = (t48, e2) =\u003e new By({ shape: () =\u003e t48, unknownKeys: \"strict\", catchall: jy.create(), typeName: yb.ZodObject, ...oy(e2) }), By.lazycreate = (t48, e2) =\u003e new By({ shape: t48, unknownKeys: \"strip\", catchall: jy.create(), typeName: yb.ZodObject, ...oy(e2) });\nvar Hy = class extends ry {\n _parse(t48) {\n const { ctx: e2 } = this._processInputParams(t48), n2 = this._def.options;\n if (e2.common.async) return Promise.all(n2.map(async (t49) =\u003e {\n const n3 = { ...e2, common: { ...e2.common, issues: [] }, parent: null };\n return { result: await t49._parseAsync({ data: e2.data, path: e2.path, parent: n3 }), ctx: n3 };\n })).then(function(t49) {\n for (const e3 of t49) if (\"valid\" === e3.result.status) return e3.result;\n for (const n4 of t49) if (\"dirty\" === n4.result.status) return e2.common.issues.push(...n4.ctx.common.issues), n4.result;\n const n3 = t49.map((t50) =\u003e new k_(t50.ctx.common.issues));\n return H_(e2, { code: D_.invalid_union, unionErrors: n3 }), G_;\n });\n {\n let t49;\n const o2 = [];\n for (const i3 of n2) {\n const n3 = { ...e2, common: { ...e2.common, issues: [] }, parent: null }, r2 = i3._parseSync({ data: e2.data, path: e2.path, parent: n3 });\n if (\"valid\" === r2.status) return r2;\n \"dirty\" !== r2.status || t49 || (t49 = { result: r2, ctx: n3 }), n3.common.issues.length \u0026\u0026 o2.push(n3.common.issues);\n }\n if (t49) return e2.common.issues.push(...t49.ctx.common.issues), t49.result;\n const i2 = o2.map((t50) =\u003e new k_(t50));\n return H_(e2, { code: D_.invalid_union, unionErrors: i2 }), G_;\n }\n }\n get options() {\n return this._def.options;\n }\n};\nHy.create = (t48, e2) =\u003e new Hy({ options: t48, typeName: yb.ZodUnion, ...oy(e2) });\nvar Wy = (t48) =\u003e t48 instanceof tb ? Wy(t48.schema) : t48 instanceof sb ? Wy(t48.innerType()) : t48 instanceof eb ? [t48.value] : t48 instanceof ob ? t48.options : t48 instanceof ib ? w_.objectValues(t48.enum) : t48 instanceof lb ? Wy(t48._def.innerType) : t48 instanceof Dy ? [void 0] : t48 instanceof zy ? [null] : t48 instanceof ab ? [void 0, ...Wy(t48.unwrap())] : t48 instanceof cb ? [null, ...Wy(t48.unwrap())] : t48 instanceof pb || t48 instanceof gb ? Wy(t48.unwrap()) : t48 instanceof hb ? Wy(t48._def.innerType) : [];\nvar Vy = class t25 extends ry {\n _parse(t48) {\n const { ctx: e2 } = this._processInputParams(t48);\n if (e2.parsedType !== O_.object) return H_(e2, { code: D_.invalid_type, expected: O_.object, received: e2.parsedType }), G_;\n const n2 = this.discriminator, o2 = e2.data[n2], i2 = this.optionsMap.get(o2);\n return i2 ? e2.common.async ? i2._parseAsync({ data: e2.data, path: e2.path, parent: e2 }) : i2._parseSync({ data: e2.data, path: e2.path, parent: e2 }) : (H_(e2, { code: D_.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [n2] }), G_);\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n static create(e2, n2, o2) {\n const i2 = /* @__PURE__ */ new Map();\n for (const t48 of n2) {\n const n3 = Wy(t48.shape[e2]);\n if (!n3.length) throw new Error(`A discriminator value for key \\`${e2}\\` could not be extracted from all schema options`);\n for (const o3 of n3) {\n if (i2.has(o3)) throw new Error(`Discriminator property ${String(e2)} has duplicate value ${String(o3)}`);\n i2.set(o3, t48);\n }\n }\n return new t25({ typeName: yb.ZodDiscriminatedUnion, discriminator: e2, options: n2, optionsMap: i2, ...oy(o2) });\n }\n};\nfunction Uy(t48, e2) {\n const n2 = L_(t48), o2 = L_(e2);\n if (t48 === e2) return { valid: true, data: t48 };\n if (n2 === O_.object \u0026\u0026 o2 === O_.object) {\n const n3 = w_.objectKeys(e2), o3 = w_.objectKeys(t48).filter((t49) =\u003e -1 !== n3.indexOf(t49)), i2 = { ...t48, ...e2 };\n for (const n4 of o3) {\n const o4 = Uy(t48[n4], e2[n4]);\n if (!o4.valid) return { valid: false };\n i2[n4] = o4.data;\n }\n return { valid: true, data: i2 };\n }\n if (n2 === O_.array \u0026\u0026 o2 === O_.array) {\n if (t48.length !== e2.length) return { valid: false };\n const n3 = [];\n for (let o3 = 0; o3 \u003c t48.length; o3++) {\n const i2 = Uy(t48[o3], e2[o3]);\n if (!i2.valid) return { valid: false };\n n3.push(i2.data);\n }\n return { valid: true, data: n3 };\n }\n return n2 === O_.date \u0026\u0026 o2 === O_.date \u0026\u0026 +t48 === +e2 ? { valid: true, data: t48 } : { valid: false };\n}\nvar Gy = class extends ry {\n _parse(t48) {\n const { status: e2, ctx: n2 } = this._processInputParams(t48), o2 = (t49, o3) =\u003e {\n if (J_(t49) || J_(o3)) return G_;\n const i2 = Uy(t49.value, o3.value);\n return i2.valid ? ((K_(t49) || K_(o3)) \u0026\u0026 e2.dirty(), { status: e2.value, value: i2.data }) : (H_(n2, { code: D_.invalid_intersection_types }), G_);\n };\n return n2.common.async ? Promise.all([this._def.left._parseAsync({ data: n2.data, path: n2.path, parent: n2 }), this._def.right._parseAsync({ data: n2.data, path: n2.path, parent: n2 })]).then(([t49, e3]) =\u003e o2(t49, e3)) : o2(this._def.left._parseSync({ data: n2.data, path: n2.path, parent: n2 }), this._def.right._parseSync({ data: n2.data, path: n2.path, parent: n2 }));\n }\n};\nGy.create = (t48, e2, n2) =\u003e new Gy({ left: t48, right: e2, typeName: yb.ZodIntersection, ...oy(n2) });\nvar Zy = class t26 extends ry {\n _parse(t48) {\n const { status: e2, ctx: n2 } = this._processInputParams(t48);\n if (n2.parsedType !== O_.array) return H_(n2, { code: D_.invalid_type, expected: O_.array, received: n2.parsedType }), G_;\n if (n2.data.length \u003c this._def.items.length) return H_(n2, { code: D_.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: \"array\" }), G_;\n !this._def.rest \u0026\u0026 n2.data.length \u003e this._def.items.length \u0026\u0026 (H_(n2, { code: D_.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: \"array\" }), e2.dirty());\n const o2 = [...n2.data].map((t49, e3) =\u003e {\n const o3 = this._def.items[e3] || this._def.rest;\n return o3 ? o3._parse(new ey(n2, t49, n2.path, e3)) : null;\n }).filter((t49) =\u003e !!t49);\n return n2.common.async ? Promise.all(o2).then((t49) =\u003e U_.mergeArray(e2, t49)) : U_.mergeArray(e2, o2);\n }\n get items() {\n return this._def.items;\n }\n rest(e2) {\n return new t26({ ...this._def, rest: e2 });\n }\n};\nZy.create = (t48, e2) =\u003e {\n if (!Array.isArray(t48)) throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n return new Zy({ items: t48, typeName: yb.ZodTuple, rest: null, ...oy(e2) });\n};\nvar qy = class t27 extends ry {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(t48) {\n const { status: e2, ctx: n2 } = this._processInputParams(t48);\n if (n2.parsedType !== O_.object) return H_(n2, { code: D_.invalid_type, expected: O_.object, received: n2.parsedType }), G_;\n const o2 = [], i2 = this._def.keyType, r2 = this._def.valueType;\n for (const t49 in n2.data) o2.push({ key: i2._parse(new ey(n2, t49, n2.path, t49)), value: r2._parse(new ey(n2, n2.data[t49], n2.path, t49)), alwaysSet: t49 in n2.data });\n return n2.common.async ? U_.mergeObjectAsync(e2, o2) : U_.mergeObjectSync(e2, o2);\n }\n get element() {\n return this._def.valueType;\n }\n static create(e2, n2, o2) {\n return new t27(n2 instanceof ry ? { keyType: e2, valueType: n2, typeName: yb.ZodRecord, ...oy(o2) } : { keyType: wy.create(), valueType: e2, typeName: yb.ZodRecord, ...oy(n2) });\n }\n};\nvar Jy = class extends ry {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(t48) {\n const { status: e2, ctx: n2 } = this._processInputParams(t48);\n if (n2.parsedType !== O_.map) return H_(n2, { code: D_.invalid_type, expected: O_.map, received: n2.parsedType }), G_;\n const o2 = this._def.keyType, i2 = this._def.valueType, r2 = [...n2.data.entries()].map(([t49, e3], r3) =\u003e ({ key: o2._parse(new ey(n2, t49, n2.path, [r3, \"key\"])), value: i2._parse(new ey(n2, e3, n2.path, [r3, \"value\"])) }));\n if (n2.common.async) {\n const t49 = /* @__PURE__ */ new Map();\n return Promise.resolve().then(async () =\u003e {\n for (const n3 of r2) {\n const o3 = await n3.key, i3 = await n3.value;\n if (\"aborted\" === o3.status || \"aborted\" === i3.status) return G_;\n \"dirty\" !== o3.status \u0026\u0026 \"dirty\" !== i3.status || e2.dirty(), t49.set(o3.value, i3.value);\n }\n return { status: e2.value, value: t49 };\n });\n }\n {\n const t49 = /* @__PURE__ */ new Map();\n for (const n3 of r2) {\n const o3 = n3.key, i3 = n3.value;\n if (\"aborted\" === o3.status || \"aborted\" === i3.status) return G_;\n \"dirty\" !== o3.status \u0026\u0026 \"dirty\" !== i3.status || e2.dirty(), t49.set(o3.value, i3.value);\n }\n return { status: e2.value, value: t49 };\n }\n }\n};\nJy.create = (t48, e2, n2) =\u003e new Jy({ valueType: e2, keyType: t48, typeName: yb.ZodMap, ...oy(n2) });\nvar Ky = class t28 extends ry {\n _parse(t48) {\n const { status: e2, ctx: n2 } = this._processInputParams(t48);\n if (n2.parsedType !== O_.set) return H_(n2, { code: D_.invalid_type, expected: O_.set, received: n2.parsedType }), G_;\n const o2 = this._def;\n null !== o2.minSize \u0026\u0026 n2.data.size \u003c o2.minSize.value \u0026\u0026 (H_(n2, { code: D_.too_small, minimum: o2.minSize.value, type: \"set\", inclusive: true, exact: false, message: o2.minSize.message }), e2.dirty()), null !== o2.maxSize \u0026\u0026 n2.data.size \u003e o2.maxSize.value \u0026\u0026 (H_(n2, { code: D_.too_big, maximum: o2.maxSize.value, type: \"set\", inclusive: true, exact: false, message: o2.maxSize.message }), e2.dirty());\n const i2 = this._def.valueType;\n function r2(t49) {\n const n3 = /* @__PURE__ */ new Set();\n for (const o3 of t49) {\n if (\"aborted\" === o3.status) return G_;\n \"dirty\" === o3.status \u0026\u0026 e2.dirty(), n3.add(o3.value);\n }\n return { status: e2.value, value: n3 };\n }\n const s2 = [...n2.data.values()].map((t49, e3) =\u003e i2._parse(new ey(n2, t49, n2.path, e3)));\n return n2.common.async ? Promise.all(s2).then((t49) =\u003e r2(t49)) : r2(s2);\n }\n min(e2, n2) {\n return new t28({ ...this._def, minSize: { value: e2, message: W_.toString(n2) } });\n }\n max(e2, n2) {\n return new t28({ ...this._def, maxSize: { value: e2, message: W_.toString(n2) } });\n }\n size(t48, e2) {\n return this.min(t48, e2).max(t48, e2);\n }\n nonempty(t48) {\n return this.min(1, t48);\n }\n};\nKy.create = (t48, e2) =\u003e new Ky({ valueType: t48, minSize: null, maxSize: null, typeName: yb.ZodSet, ...oy(e2) });\nvar Qy = class t29 extends ry {\n constructor() {\n super(...arguments), this.validate = this.implement;\n }\n _parse(t48) {\n const { ctx: e2 } = this._processInputParams(t48);\n if (e2.parsedType !== O_.function) return H_(e2, { code: D_.invalid_type, expected: O_.function, received: e2.parsedType }), G_;\n function n2(t49, n3) {\n return X_({ data: t49, path: e2.path, errorMaps: [e2.common.contextualErrorMap, e2.schemaErrorMap, $_(), F_].filter((t50) =\u003e !!t50), issueData: { code: D_.invalid_arguments, argumentsError: n3 } });\n }\n function o2(t49, n3) {\n return X_({ data: t49, path: e2.path, errorMaps: [e2.common.contextualErrorMap, e2.schemaErrorMap, $_(), F_].filter((t50) =\u003e !!t50), issueData: { code: D_.invalid_return_type, returnTypeError: n3 } });\n }\n const i2 = { errorMap: e2.common.contextualErrorMap }, r2 = e2.data;\n if (this._def.returns instanceof rb) {\n const t49 = this;\n return q_(async function(...e3) {\n const s2 = new k_([]), a2 = await t49._def.args.parseAsync(e3, i2).catch((t50) =\u003e {\n throw s2.addIssue(n2(e3, t50)), s2;\n }), c2 = await Reflect.apply(r2, this, a2);\n return await t49._def.returns._def.type.parseAsync(c2, i2).catch((t50) =\u003e {\n throw s2.addIssue(o2(c2, t50)), s2;\n });\n });\n }\n {\n const t49 = this;\n return q_(function(...e3) {\n const s2 = t49._def.args.safeParse(e3, i2);\n if (!s2.success) throw new k_([n2(e3, s2.error)]);\n const a2 = Reflect.apply(r2, this, s2.data), c2 = t49._def.returns.safeParse(a2, i2);\n if (!c2.success) throw new k_([o2(a2, c2.error)]);\n return c2.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...e2) {\n return new t29({ ...this._def, args: Zy.create(e2).rest(Fy.create()) });\n }\n returns(e2) {\n return new t29({ ...this._def, returns: e2 });\n }\n implement(t48) {\n return this.parse(t48);\n }\n strictImplement(t48) {\n return this.parse(t48);\n }\n static create(e2, n2, o2) {\n return new t29({ args: e2 || Zy.create([]).rest(Fy.create()), returns: n2 || Fy.create(), typeName: yb.ZodFunction, ...oy(o2) });\n }\n};\nvar tb = class extends ry {\n get schema() {\n return this._def.getter();\n }\n _parse(t48) {\n const { ctx: e2 } = this._processInputParams(t48);\n return this._def.getter()._parse({ data: e2.data, path: e2.path, parent: e2 });\n }\n};\ntb.create = (t48, e2) =\u003e new tb({ getter: t48, typeName: yb.ZodLazy, ...oy(e2) });\nvar eb = class extends ry {\n _parse(t48) {\n if (t48.data !== this._def.value) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { received: e2.data, code: D_.invalid_literal, expected: this._def.value }), G_;\n }\n return { status: \"valid\", value: t48.data };\n }\n get value() {\n return this._def.value;\n }\n};\nfunction nb(t48, e2) {\n return new ob({ values: t48, typeName: yb.ZodEnum, ...oy(e2) });\n}\neb.create = (t48, e2) =\u003e new eb({ value: t48, typeName: yb.ZodLiteral, ...oy(e2) });\nvar ob = class t30 extends ry {\n _parse(t48) {\n if (\"string\" != typeof t48.data) {\n const e2 = this._getOrReturnCtx(t48), n2 = this._def.values;\n return H_(e2, { expected: w_.joinValues(n2), received: e2.parsedType, code: D_.invalid_type }), G_;\n }\n if (this._cache || (this._cache = new Set(this._def.values)), !this._cache.has(t48.data)) {\n const e2 = this._getOrReturnCtx(t48), n2 = this._def.values;\n return H_(e2, { received: e2.data, code: D_.invalid_enum_value, options: n2 }), G_;\n }\n return q_(t48.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const t48 = {};\n for (const e2 of this._def.values) t48[e2] = e2;\n return t48;\n }\n get Values() {\n const t48 = {};\n for (const e2 of this._def.values) t48[e2] = e2;\n return t48;\n }\n get Enum() {\n const t48 = {};\n for (const e2 of this._def.values) t48[e2] = e2;\n return t48;\n }\n extract(e2, n2 = this._def) {\n return t30.create(e2, { ...this._def, ...n2 });\n }\n exclude(e2, n2 = this._def) {\n return t30.create(this.options.filter((t48) =\u003e !e2.includes(t48)), { ...this._def, ...n2 });\n }\n};\nob.create = nb;\nvar ib = class extends ry {\n _parse(t48) {\n const e2 = w_.getValidEnumValues(this._def.values), n2 = this._getOrReturnCtx(t48);\n if (n2.parsedType !== O_.string \u0026\u0026 n2.parsedType !== O_.number) {\n const t49 = w_.objectValues(e2);\n return H_(n2, { expected: w_.joinValues(t49), received: n2.parsedType, code: D_.invalid_type }), G_;\n }\n if (this._cache || (this._cache = new Set(w_.getValidEnumValues(this._def.values))), !this._cache.has(t48.data)) {\n const t49 = w_.objectValues(e2);\n return H_(n2, { received: n2.data, code: D_.invalid_enum_value, options: t49 }), G_;\n }\n return q_(t48.data);\n }\n get enum() {\n return this._def.values;\n }\n};\nib.create = (t48, e2) =\u003e new ib({ values: t48, typeName: yb.ZodNativeEnum, ...oy(e2) });\nvar rb = class extends ry {\n unwrap() {\n return this._def.type;\n }\n _parse(t48) {\n const { ctx: e2 } = this._processInputParams(t48);\n if (e2.parsedType !== O_.promise \u0026\u0026 false === e2.common.async) return H_(e2, { code: D_.invalid_type, expected: O_.promise, received: e2.parsedType }), G_;\n const n2 = e2.parsedType === O_.promise ? e2.data : Promise.resolve(e2.data);\n return q_(n2.then((t49) =\u003e this._def.type.parseAsync(t49, { path: e2.path, errorMap: e2.common.contextualErrorMap })));\n }\n};\nrb.create = (t48, e2) =\u003e new rb({ type: t48, typeName: yb.ZodPromise, ...oy(e2) });\nvar sb = class extends ry {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === yb.ZodEffects ? this._def.schema.sourceType() : this._def.schema;\n }\n _parse(t48) {\n const { status: e2, ctx: n2 } = this._processInputParams(t48), o2 = this._def.effect || null, i2 = { addIssue: (t49) =\u003e {\n H_(n2, t49), t49.fatal ? e2.abort() : e2.dirty();\n }, get path() {\n return n2.path;\n } };\n if (i2.addIssue = i2.addIssue.bind(i2), \"preprocess\" === o2.type) {\n const t49 = o2.transform(n2.data, i2);\n if (n2.common.async) return Promise.resolve(t49).then(async (t50) =\u003e {\n if (\"aborted\" === e2.value) return G_;\n const o3 = await this._def.schema._parseAsync({ data: t50, path: n2.path, parent: n2 });\n return \"aborted\" === o3.status ? G_ : \"dirty\" === o3.status || \"dirty\" === e2.value ? Z_(o3.value) : o3;\n });\n {\n if (\"aborted\" === e2.value) return G_;\n const o3 = this._def.schema._parseSync({ data: t49, path: n2.path, parent: n2 });\n return \"aborted\" === o3.status ? G_ : \"dirty\" === o3.status || \"dirty\" === e2.value ? Z_(o3.value) : o3;\n }\n }\n if (\"refinement\" === o2.type) {\n const t49 = (t50) =\u003e {\n const e3 = o2.refinement(t50, i2);\n if (n2.common.async) return Promise.resolve(e3);\n if (e3 instanceof Promise) throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n return t50;\n };\n if (false === n2.common.async) {\n const o3 = this._def.schema._parseSync({ data: n2.data, path: n2.path, parent: n2 });\n return \"aborted\" === o3.status ? G_ : (\"dirty\" === o3.status \u0026\u0026 e2.dirty(), t49(o3.value), { status: e2.value, value: o3.value });\n }\n return this._def.schema._parseAsync({ data: n2.data, path: n2.path, parent: n2 }).then((n3) =\u003e \"aborted\" === n3.status ? G_ : (\"dirty\" === n3.status \u0026\u0026 e2.dirty(), t49(n3.value).then(() =\u003e ({ status: e2.value, value: n3.value }))));\n }\n if (\"transform\" === o2.type) {\n if (false === n2.common.async) {\n const t49 = this._def.schema._parseSync({ data: n2.data, path: n2.path, parent: n2 });\n if (!Q_(t49)) return G_;\n const r2 = o2.transform(t49.value, i2);\n if (r2 instanceof Promise) throw new Error(\"Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.\");\n return { status: e2.value, value: r2 };\n }\n return this._def.schema._parseAsync({ data: n2.data, path: n2.path, parent: n2 }).then((t49) =\u003e Q_(t49) ? Promise.resolve(o2.transform(t49.value, i2)).then((t50) =\u003e ({ status: e2.value, value: t50 })) : G_);\n }\n w_.assertNever(o2);\n }\n};\nsb.create = (t48, e2, n2) =\u003e new sb({ schema: t48, typeName: yb.ZodEffects, effect: e2, ...oy(n2) }), sb.createWithPreprocess = (t48, e2, n2) =\u003e new sb({ schema: e2, effect: { type: \"preprocess\", transform: t48 }, typeName: yb.ZodEffects, ...oy(n2) });\nvar ab = class extends ry {\n _parse(t48) {\n return this._getType(t48) === O_.undefined ? q_(void 0) : this._def.innerType._parse(t48);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nab.create = (t48, e2) =\u003e new ab({ innerType: t48, typeName: yb.ZodOptional, ...oy(e2) });\nvar cb = class extends ry {\n _parse(t48) {\n return this._getType(t48) === O_.null ? q_(null) : this._def.innerType._parse(t48);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\ncb.create = (t48, e2) =\u003e new cb({ innerType: t48, typeName: yb.ZodNullable, ...oy(e2) });\nvar lb = class extends ry {\n _parse(t48) {\n const { ctx: e2 } = this._processInputParams(t48);\n let n2 = e2.data;\n return e2.parsedType === O_.undefined \u0026\u0026 (n2 = this._def.defaultValue()), this._def.innerType._parse({ data: n2, path: e2.path, parent: e2 });\n }\n removeDefault() {\n return this._def.innerType;\n }\n};\nlb.create = (t48, e2) =\u003e new lb({ innerType: t48, typeName: yb.ZodDefault, defaultValue: \"function\" == typeof e2.default ? e2.default : () =\u003e e2.default, ...oy(e2) });\nvar hb = class extends ry {\n _parse(t48) {\n const { ctx: e2 } = this._processInputParams(t48), n2 = { ...e2, common: { ...e2.common, issues: [] } }, o2 = this._def.innerType._parse({ data: n2.data, path: n2.path, parent: { ...n2 } });\n return ty(o2) ? o2.then((t49) =\u003e ({ status: \"valid\", value: \"valid\" === t49.status ? t49.value : this._def.catchValue({ get error() {\n return new k_(n2.common.issues);\n }, input: n2.data }) })) : { status: \"valid\", value: \"valid\" === o2.status ? o2.value : this._def.catchValue({ get error() {\n return new k_(n2.common.issues);\n }, input: n2.data }) };\n }\n removeCatch() {\n return this._def.innerType;\n }\n};\nhb.create = (t48, e2) =\u003e new hb({ innerType: t48, typeName: yb.ZodCatch, catchValue: \"function\" == typeof e2.catch ? e2.catch : () =\u003e e2.catch, ...oy(e2) });\nvar db = class extends ry {\n _parse(t48) {\n if (this._getType(t48) !== O_.nan) {\n const e2 = this._getOrReturnCtx(t48);\n return H_(e2, { code: D_.invalid_type, expected: O_.nan, received: e2.parsedType }), G_;\n }\n return { status: \"valid\", value: t48.data };\n }\n};\ndb.create = (t48) =\u003e new db({ typeName: yb.ZodNaN, ...oy(t48) });\nvar ub = /* @__PURE__ */ Symbol(\"zod_brand\");\nvar pb = class extends ry {\n _parse(t48) {\n const { ctx: e2 } = this._processInputParams(t48), n2 = e2.data;\n return this._def.type._parse({ data: n2, path: e2.path, parent: e2 });\n }\n unwrap() {\n return this._def.type;\n }\n};\nvar mb = class t31 extends ry {\n _parse(t48) {\n const { status: e2, ctx: n2 } = this._processInputParams(t48);\n if (n2.common.async) {\n return (async () =\u003e {\n const t49 = await this._def.in._parseAsync({ data: n2.data, path: n2.path, parent: n2 });\n return \"aborted\" === t49.status ? G_ : \"dirty\" === t49.status ? (e2.dirty(), Z_(t49.value)) : this._def.out._parseAsync({ data: t49.value, path: n2.path, parent: n2 });\n })();\n }\n {\n const t49 = this._def.in._parseSync({ data: n2.data, path: n2.path, parent: n2 });\n return \"aborted\" === t49.status ? G_ : \"dirty\" === t49.status ? (e2.dirty(), { status: \"dirty\", value: t49.value }) : this._def.out._parseSync({ data: t49.value, path: n2.path, parent: n2 });\n }\n }\n static create(e2, n2) {\n return new t31({ in: e2, out: n2, typeName: yb.ZodPipeline });\n }\n};\nvar gb = class extends ry {\n _parse(t48) {\n const e2 = this._def.innerType._parse(t48), n2 = (t49) =\u003e (Q_(t49) \u0026\u0026 (t49.value = Object.freeze(t49.value)), t49);\n return ty(e2) ? e2.then((t49) =\u003e n2(t49)) : n2(e2);\n }\n unwrap() {\n return this._def.innerType;\n }\n};\nfunction fb(t48, e2) {\n const n2 = \"function\" == typeof t48 ? t48(e2) : \"string\" == typeof t48 ? { message: t48 } : t48;\n return \"string\" == typeof n2 ? { message: n2 } : n2;\n}\nfunction _b(t48, e2 = {}, n2) {\n return t48 ? ky.create().superRefine((o2, i2) =\u003e {\n const r2 = t48(o2);\n if (r2 instanceof Promise) return r2.then((t49) =\u003e {\n if (!t49) {\n const t50 = fb(e2, o2), r3 = t50.fatal ?? n2 ?? true;\n i2.addIssue({ code: \"custom\", ...t50, fatal: r3 });\n }\n });\n if (!r2) {\n const t49 = fb(e2, o2), r3 = t49.fatal ?? n2 ?? true;\n i2.addIssue({ code: \"custom\", ...t49, fatal: r3 });\n }\n }) : ky.create();\n}\ngb.create = (t48, e2) =\u003e new gb({ innerType: t48, typeName: yb.ZodReadonly, ...oy(e2) });\nvar yb;\nvar bb;\nvar xb = { object: By.lazycreate };\n(bb = yb || (yb = {})).ZodString = \"ZodString\", bb.ZodNumber = \"ZodNumber\", bb.ZodNaN = \"ZodNaN\", bb.ZodBigInt = \"ZodBigInt\", bb.ZodBoolean = \"ZodBoolean\", bb.ZodDate = \"ZodDate\", bb.ZodSymbol = \"ZodSymbol\", bb.ZodUndefined = \"ZodUndefined\", bb.ZodNull = \"ZodNull\", bb.ZodAny = \"ZodAny\", bb.ZodUnknown = \"ZodUnknown\", bb.ZodNever = \"ZodNever\", bb.ZodVoid = \"ZodVoid\", bb.ZodArray = \"ZodArray\", bb.ZodObject = \"ZodObject\", bb.ZodUnion = \"ZodUnion\", bb.ZodDiscriminatedUnion = \"ZodDiscriminatedUnion\", bb.ZodIntersection = \"ZodIntersection\", bb.ZodTuple = \"ZodTuple\", bb.ZodRecord = \"ZodRecord\", bb.ZodMap = \"ZodMap\", bb.ZodSet = \"ZodSet\", bb.ZodFunction = \"ZodFunction\", bb.ZodLazy = \"ZodLazy\", bb.ZodLiteral = \"ZodLiteral\", bb.ZodEnum = \"ZodEnum\", bb.ZodEffects = \"ZodEffects\", bb.ZodNativeEnum = \"ZodNativeEnum\", bb.ZodOptional = \"ZodOptional\", bb.ZodNullable = \"ZodNullable\", bb.ZodDefault = \"ZodDefault\", bb.ZodCatch = \"ZodCatch\", bb.ZodPromise = \"ZodPromise\", bb.ZodBranded = \"ZodBranded\", bb.ZodPipeline = \"ZodPipeline\", bb.ZodReadonly = \"ZodReadonly\";\nvar vb = (t48, e2 = { message: `Input not instance of ${t48.name}` }) =\u003e _b((e3) =\u003e e3 instanceof t48, e2);\nvar Sb = wy.create;\nvar Ib = Ry.create;\nvar Pb = db.create;\nvar Mb = Ey.create;\nvar Cb = Ay.create;\nvar Nb = Oy.create;\nvar wb = Ly.create;\nvar Tb = Dy.create;\nvar Rb = zy.create;\nvar Eb = ky.create;\nvar Ab = Fy.create;\nvar Ob = jy.create;\nvar Lb = Yy.create;\nvar Db = $y.create;\nvar zb = By.create;\nvar kb = By.strictCreate;\nvar Fb = Hy.create;\nvar jb = Vy.create;\nvar Yb = Gy.create;\nvar $b = Zy.create;\nvar Xb = qy.create;\nvar Bb = Jy.create;\nvar Hb = Ky.create;\nvar Wb = Qy.create;\nvar Vb = tb.create;\nvar Ub = eb.create;\nvar Gb = ob.create;\nvar Zb = ib.create;\nvar qb = rb.create;\nvar Jb = sb.create;\nvar Kb = ab.create;\nvar Qb = cb.create;\nvar tx = sb.createWithPreprocess;\nvar ex = mb.create;\nvar nx = () =\u003e Sb().optional();\nvar ox = () =\u003e Ib().optional();\nvar ix = () =\u003e Cb().optional();\nvar rx = { string: (t48) =\u003e wy.create({ ...t48, coerce: true }), number: (t48) =\u003e Ry.create({ ...t48, coerce: true }), boolean: (t48) =\u003e Ay.create({ ...t48, coerce: true }), bigint: (t48) =\u003e Ey.create({ ...t48, coerce: true }), date: (t48) =\u003e Oy.create({ ...t48, coerce: true }) };\nvar sx = G_;\nvar ax = A_.string().or(A_.number()).transform((t48) =\u003e N_(t48, \"\\u03A9\").value);\nvar cx = A_.string().or(A_.number()).transform((t48) =\u003e N_(t48, \"F\").value).transform((t48) =\u003e Number.parseFloat(t48.toPrecision(12)));\nvar lx = A_.string().or(A_.number()).transform((t48) =\u003e N_(t48, \"H\").value);\nvar hx = A_.string().or(A_.number()).transform((t48) =\u003e N_(t48, \"V\").value);\nvar dx = A_.string().or(A_.number()).transform((t48) =\u003e N_(t48).value);\nvar ux = A_.string().or(A_.number()).transform((t48) =\u003e N_(t48, \"Hz\").value);\nvar px = dx;\nvar mx = A_.string().or(A_.number()).transform((t48) =\u003e N_(t48, \"A\").value);\nvar gx = A_.string().or(A_.number()).transform((t48) =\u003e N_(t48).value);\nvar fx = gx;\nvar _x = gx;\nvar yx = A_.string().datetime();\nvar bx = A_.string().or(A_.number()).transform((t48) =\u003e \"number\" == typeof t48 ? t48 : t48.endsWith(\"deg\") ? Number.parseFloat(t48.split(\"deg\")[0]) : t48.endsWith(\"rad\") ? 180 * Number.parseFloat(t48.split(\"rad\")[0]) / Math.PI : Number.parseFloat(t48));\nvar xx = A_.number().or(A_.string().endsWith(\"mAh\")).transform((t48) =\u003e {\n if (\"string\" == typeof t48) {\n const e2 = t48.replace(\"mAh\", \"\"), n2 = Number.parseFloat(e2);\n if (Number.isNaN(n2)) throw new Error(\"Invalid capacity\");\n return n2;\n }\n return t48;\n}).describe(\"Battery capacity in mAh\");\nvar vx = A_.object({ x: px, y: px });\nvar Sx = vx;\nvar Ix = A_.object({ x: px, y: px, z: px });\nvar Px = Ix;\nvar Mx = A_.object({ width: A_.number(), height: A_.number() });\nvar Cx = (t48) =\u003e A_.string().optional().default(() =\u003e `${t48}_${((t49) =\u003e {\n const e2 = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n return Array.from({ length: t49 }, () =\u003e e2[Math.floor(62 * Math.random())]).join(\"\");\n})(10)}`);\nvar Nx = A_.enum([\"top_left\", \"top_center\", \"top_right\", \"center_left\", \"center\", \"center_right\", \"bottom_left\", \"bottom_center\", \"bottom_right\"]);\nvar wx = A_.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\"]);\nvar Tx = A_.object({ project_relative_path: A_.string(), url: A_.string(), mimetype: A_.string() });\nvar Rx = vx.extend({ rotation: bx.optional() });\nvar Ex = A_.object({ size: vx.optional(), thickness: px.optional() });\nvar Ax = A_.object({ font: Ex.optional() });\nvar Ox = A_.object({ value: A_.string(), at: Rx.optional(), layer: A_.string().optional(), uuid: A_.string().optional(), hide: A_.boolean().optional(), effects: Ax.optional() });\nvar Lx = A_.object({ Reference: Ox.optional(), Value: Ox.optional(), Datasheet: Ox.optional(), Description: Ox.optional() });\nvar Dx = A_.object({ through_hole: A_.boolean().optional(), smd: A_.boolean().optional(), exclude_from_pos_files: A_.boolean().optional(), exclude_from_bom: A_.boolean().optional() });\nvar zx = A_.object({ name: A_.string(), type: A_.string(), shape: A_.string().optional(), at: Rx.optional(), size: vx.optional(), drill: px.optional(), layers: A_.array(A_.string()).optional(), removeUnusedLayers: A_.boolean().optional(), uuid: A_.string().optional() });\nvar kx = A_.object({ path: A_.string(), offset: Ix.optional(), scale: Ix.optional(), rotate: Ix.optional() });\nvar Fx = A_.object({ footprintName: A_.string().optional(), version: A_.union([A_.number(), A_.string()]).optional(), generator: A_.string().optional(), generatorVersion: A_.union([A_.number(), A_.string()]).optional(), layer: A_.string().optional(), properties: Lx.optional(), attributes: Dx.optional(), pads: A_.array(zx).optional(), embeddedFonts: A_.boolean().optional(), model: kx.optional() });\nvar jx = A_.object({ hide: A_.boolean().optional() });\nvar Yx = A_.object({ offset: px.optional(), hide: A_.boolean().optional() });\nvar $x = A_.object({ font: Ex.optional(), justify: A_.union([A_.string(), A_.array(A_.string())]).optional(), hide: A_.boolean().optional() });\nvar Xx = A_.object({ value: A_.string(), id: A_.union([A_.number(), A_.string()]).optional(), at: Rx.optional(), effects: $x.optional() });\nvar Bx = A_.object({ Reference: Xx.optional(), Value: Xx.optional(), Footprint: Xx.optional(), Datasheet: Xx.optional(), Description: Xx.optional(), ki_keywords: Xx.optional(), ki_fp_filters: Xx.optional() });\nvar Hx = A_.object({ symbolName: A_.string().optional(), extends: A_.string().optional(), pinNumbers: jx.optional(), pinNames: Yx.optional(), excludeFromSim: A_.boolean().optional(), inBom: A_.boolean().optional(), onBoard: A_.boolean().optional(), properties: Bx.optional(), embeddedFonts: A_.boolean().optional() });\nvar Wx = A_.object({ error_type: A_.string(), message: A_.string(), is_fatal: A_.boolean().optional() });\nvar Vx = A_.enum([\"jlcpcb\", \"macrofab\", \"pcbway\", \"digikey\", \"mouser\", \"lcsc\"]);\nvar Ux = A_.object({ type: A_.literal(\"source_component\"), ftype: A_.string().optional(), source_component_id: A_.string(), name: A_.string(), manufacturer_part_number: A_.string().optional(), supplier_part_numbers: A_.record(Vx, A_.array(A_.string())).optional(), display_value: A_.string().optional(), display_name: A_.string().optional(), are_pins_interchangeable: A_.boolean().optional(), internally_connected_source_port_ids: A_.array(A_.array(A_.string())).optional(), source_group_id: A_.string().optional(), subcircuit_id: A_.string().optional() });\nvar Gx = Ux.extend({ ftype: A_.literal(\"simple_capacitor\"), capacitance: cx, max_voltage_rating: hx.optional(), display_capacitance: A_.string().optional(), max_decoupling_trace_length: px.optional() });\nvar Zx = Ux.extend({ ftype: A_.literal(\"simple_resistor\"), resistance: ax, display_resistance: A_.string().optional() });\nvar qx = Ux.extend({ ftype: A_.literal(\"simple_diode\") });\nvar Jx = Ux.extend({ ftype: A_.literal(\"simple_fiducial\") });\nvar Kx = qx.extend({ ftype: A_.literal(\"simple_led\"), color: A_.string().optional(), wavelength: A_.string().optional() });\nvar Qx = Ux.extend({ ftype: A_.literal(\"simple_ground\") });\nvar tv = Ux.extend({ ftype: A_.literal(\"simple_chip\") });\nvar ev = Ux.extend({ ftype: A_.literal(\"simple_power_source\"), voltage: hx });\nvar nv = Ux.extend({ ftype: A_.literal(\"simple_current_source\"), current: mx, frequency: ux.optional(), peak_to_peak_current: mx.optional(), wave_shape: A_.enum([\"sine\", \"square\", \"triangle\", \"sawtooth\", \"dc\"]).optional().default(\"dc\"), phase: A_.number().optional(), duty_cycle: A_.number().min(0).max(1).optional() });\nvar ov = Ux.extend({ ftype: A_.literal(\"simple_fuse\"), current_rating_amps: A_.number().describe(\"Nominal current in amps the fuse is rated for\"), voltage_rating_volts: A_.number().describe(\"Voltage rating in volts, e.g. \\xB15V would be 5\") });\nvar iv = Ux.extend({ ftype: A_.literal(\"simple_ammeter\") });\nvar rv = A_.object({ must_be_connected: A_.boolean().optional(), provides_power: A_.boolean().optional(), requires_power: A_.boolean().optional(), provides_ground: A_.boolean().optional(), requires_ground: A_.boolean().optional(), provides_voltage: A_.union([A_.string(), A_.number()]).optional(), requires_voltage: A_.union([A_.string(), A_.number()]).optional(), do_not_connect: A_.boolean().optional(), include_in_board_pinout: A_.boolean().optional(), can_use_internal_pullup: A_.boolean().optional(), is_using_internal_pullup: A_.boolean().optional(), needs_external_pullup: A_.boolean().optional(), can_use_internal_pulldown: A_.boolean().optional(), is_using_internal_pulldown: A_.boolean().optional(), needs_external_pulldown: A_.boolean().optional(), can_use_open_drain: A_.boolean().optional(), is_using_open_drain: A_.boolean().optional(), can_use_push_pull: A_.boolean().optional(), is_using_push_pull: A_.boolean().optional(), should_have_decoupling_capacitor: A_.boolean().optional(), recommended_decoupling_capacitor_capacitance: A_.union([A_.string(), A_.number()]).optional(), is_configured_for_i2c_sda: A_.boolean().optional(), is_configured_for_i2c_scl: A_.boolean().optional(), is_configured_for_spi_mosi: A_.boolean().optional(), is_configured_for_spi_miso: A_.boolean().optional(), is_configured_for_spi_sck: A_.boolean().optional(), is_configured_for_spi_cs: A_.boolean().optional(), is_configured_for_uart_tx: A_.boolean().optional(), is_configured_for_uart_rx: A_.boolean().optional(), supports_i2c_sda: A_.boolean().optional(), supports_i2c_scl: A_.boolean().optional(), supports_spi_mosi: A_.boolean().optional(), supports_spi_miso: A_.boolean().optional(), supports_spi_sck: A_.boolean().optional(), supports_spi_cs: A_.boolean().optional(), supports_uart_tx: A_.boolean().optional(), supports_uart_rx: A_.boolean().optional() });\nvar sv = Ux.extend({ ftype: A_.literal(\"simple_battery\"), capacity: xx });\nvar av = Ux.extend({ ftype: A_.literal(\"simple_inductor\"), inductance: lx, display_inductance: A_.string().optional(), max_current_rating: A_.number().optional() });\nvar cv = Ux.extend({ ftype: A_.literal(\"simple_push_button\") });\nvar lv = Ux.extend({ ftype: A_.literal(\"simple_potentiometer\"), max_resistance: ax, display_max_resistance: A_.string().optional() });\nvar hv = Ux.extend({ ftype: A_.literal(\"simple_crystal\"), frequency: A_.number().describe(\"Frequency in Hz\"), load_capacitance: A_.number().optional().describe(\"Load capacitance in pF\"), pin_variant: A_.enum([\"two_pin\", \"four_pin\"]).optional() });\nvar dv = Ux.extend({ ftype: A_.literal(\"simple_pin_header\"), pin_count: A_.number(), gender: A_.enum([\"male\", \"female\"]).optional().default(\"male\") });\nvar uv = Ux.extend({ ftype: A_.literal(\"simple_connector\"), standard: A_.enum([\"usb_c\", \"m2\"]).optional() });\nvar pv = Ux.extend({ ftype: A_.literal(\"simple_pinout\") });\nvar mv = Ux.extend({ ftype: A_.literal(\"simple_resonator\"), load_capacitance: cx, equivalent_series_resistance: ax.optional(), frequency: ux });\nvar gv = Ux.extend({ ftype: A_.literal(\"simple_transistor\"), transistor_type: A_.enum([\"npn\", \"pnp\"]) });\nvar fv = Ux.extend({ ftype: A_.literal(\"simple_test_point\"), footprint_variant: A_.enum([\"pad\", \"through_hole\"]).optional(), pad_shape: A_.enum([\"rect\", \"circle\"]).optional(), pad_diameter: A_.union([A_.number(), A_.string()]).optional(), hole_diameter: A_.union([A_.number(), A_.string()]).optional(), width: A_.union([A_.number(), A_.string()]).optional(), height: A_.union([A_.number(), A_.string()]).optional() });\nvar _v = Ux.extend({ ftype: A_.literal(\"simple_mosfet\"), channel_type: A_.enum([\"n\", \"p\"]), mosfet_mode: A_.enum([\"enhancement\", \"depletion\"]) });\nvar yv = Ux.extend({ ftype: A_.literal(\"simple_op_amp\") });\nvar bv = Ux.extend({ ftype: A_.literal(\"simple_switch\") });\nvar xv = A_.object({ type: A_.literal(\"source_project_metadata\"), name: A_.string().optional(), software_used_string: A_.string().optional(), project_url: A_.string().optional(), source_filesystem_md5_hash: A_.string().optional(), created_at: yx.optional() });\nvar vv = Wx.extend({ type: A_.literal(\"source_missing_property_error\"), source_missing_property_error_id: Cx(\"source_missing_property_error\"), source_component_id: A_.string(), property_name: A_.string(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"source_missing_property_error\").default(\"source_missing_property_error\") }).describe(\"The source code is missing a property\");\nvar Sv = Wx.extend({ type: A_.literal(\"source_failed_to_create_component_error\"), source_failed_to_create_component_error_id: Cx(\"source_failed_to_create_component_error\"), error_type: A_.literal(\"source_failed_to_create_component_error\").default(\"source_failed_to_create_component_error\"), component_name: A_.string().optional(), subcircuit_id: A_.string().optional(), parent_source_component_id: A_.string().optional(), pcb_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), schematic_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional() }).describe(\"Error emitted when a component fails to be constructed\");\nvar Iv = Wx.extend({ type: A_.literal(\"source_invalid_component_property_error\"), source_invalid_component_property_error_id: Cx(\"source_invalid_component_property_error\"), source_component_id: A_.string(), property_name: A_.string(), property_value: A_.unknown().optional(), expected_format: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"source_invalid_component_property_error\").default(\"source_invalid_component_property_error\") }).describe(\"The source component property is invalid\");\nvar Pv = Wx.extend({ type: A_.literal(\"source_trace_not_connected_error\"), source_trace_not_connected_error_id: Cx(\"source_trace_not_connected_error\"), error_type: A_.literal(\"source_trace_not_connected_error\").default(\"source_trace_not_connected_error\"), subcircuit_id: A_.string().optional(), source_group_id: A_.string().optional(), source_trace_id: A_.string().optional(), connected_source_port_ids: A_.array(A_.string()).optional(), selectors_not_found: A_.array(A_.string()).optional() }).describe(\"Occurs when a source trace selector does not match any ports\");\nvar Mv = A_.object({ type: A_.literal(\"source_property_ignored_warning\"), source_property_ignored_warning_id: Cx(\"source_property_ignored_warning\"), source_component_id: A_.string(), property_name: A_.string(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"source_property_ignored_warning\").default(\"source_property_ignored_warning\"), message: A_.string() }).describe(\"The source property was ignored\");\nvar Cv = A_.object({ type: A_.literal(\"source_pin_missing_trace_warning\"), source_pin_missing_trace_warning_id: Cx(\"source_pin_missing_trace_warning\"), warning_type: A_.literal(\"source_pin_missing_trace_warning\").default(\"source_pin_missing_trace_warning\"), message: A_.string(), source_component_id: A_.string(), source_port_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a source component pin is missing a trace connection\");\nvar Nv = A_.object({ type: A_.literal(\"source_missing_manufacturer_part_number_warning\"), source_missing_manufacturer_part_number_warning_id: Cx(\"source_missing_manufacturer_part_number_warning\"), warning_type: A_.literal(\"source_missing_manufacturer_part_number_warning\").default(\"source_missing_manufacturer_part_number_warning\"), message: A_.string(), source_component_id: A_.string(), standard: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a standard connector is missing manufacturer part number\");\nvar wv = A_.object({ type: A_.literal(\"source_refdes_convention_warning\"), source_refdes_convention_warning_id: Cx(\"source_refdes_convention_warning\"), warning_type: A_.literal(\"source_refdes_convention_warning\").default(\"source_refdes_convention_warning\"), message: A_.string(), source_component_id: A_.string(), refdes: A_.string(), source_component_ftype: A_.string(), expected_prefixes: A_.array(A_.string()), actual_prefix: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a source component reference designator does not match the component type convention\");\nvar Tv = Ux.extend({ ftype: A_.literal(\"simple_voltage_probe\") });\nvar Rv = Ux.extend({ ftype: A_.literal(\"interconnect\") });\nvar Ev = Wx.extend({ type: A_.literal(\"source_i2c_misconfigured_error\"), source_i2c_misconfigured_error_id: Cx(\"source_i2c_misconfigured_error\"), error_type: A_.literal(\"source_i2c_misconfigured_error\").default(\"source_i2c_misconfigured_error\"), source_port_ids: A_.array(A_.string()) }).describe(\"Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net\");\nvar Av = Wx.extend({ type: A_.literal(\"source_component_misconfigured_error\"), source_component_misconfigured_error_id: Cx(\"source_component_misconfigured_error\"), error_type: A_.literal(\"source_component_misconfigured_error\").default(\"source_component_misconfigured_error\"), source_component_ids: A_.array(A_.string()), source_port_ids: A_.array(A_.string()).optional() }).describe(\"Error emitted when one or more source components have an invalid or conflicting configuration\");\nvar Ov = Ux.extend({ ftype: A_.literal(\"simple_voltage_source\"), voltage: hx, frequency: ux.optional(), peak_to_peak_voltage: hx.optional(), wave_shape: A_.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]).optional(), phase: bx.optional(), duty_cycle: A_.number().optional().describe(\"Duty cycle as a fraction (0 to 1)\"), pulse_delay: _x.optional(), rise_time: _x.optional(), fall_time: _x.optional(), pulse_width: _x.optional(), period: _x.optional() });\nvar Lv = A_.union([Zx, Gx, qx, Jx, Kx, Qx, tv, ev, nv, iv, sv, av, cv, lv, hv, dv, uv, pv, mv, bv, gv, fv, _v, yv, ov, Tv, Rv, Ov, xv, vv, Iv, Sv, Pv, Mv, Cv, Nv, wv, Ev, Av]);\nvar Dv = A_.object({ type: A_.literal(\"source_port\"), pin_number: A_.number().optional(), port_hints: A_.array(A_.string()).optional(), name: A_.string(), source_port_id: A_.string(), source_component_id: A_.string().optional(), source_group_id: A_.string().optional(), most_frequently_referenced_by_name: A_.string().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() }).merge(rv);\nvar zv = A_.object({ type: A_.literal(\"source_component_internal_connection\"), source_component_internal_connection_id: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() });\nvar kv = A_.object({ type: A_.literal(\"source_trace\"), source_trace_id: A_.string(), connected_source_port_ids: A_.array(A_.string()), connected_source_net_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), max_length: A_.number().optional(), name: A_.string().optional(), min_trace_thickness: A_.number().optional(), display_name: A_.string().optional() });\nvar Fv = A_.object({ type: A_.literal(\"source_group\"), source_group_id: A_.string(), subcircuit_id: A_.string().optional(), parent_subcircuit_id: A_.string().optional(), parent_source_group_id: A_.string().optional(), is_subcircuit: A_.boolean().optional(), show_as_schematic_box: A_.boolean().optional(), name: A_.string().optional(), was_automatically_named: A_.boolean().optional() });\nvar jv = A_.object({ type: A_.literal(\"source_net\"), source_net_id: A_.string(), name: A_.string(), member_source_group_ids: A_.array(A_.string()), is_power: A_.boolean().optional(), is_ground: A_.boolean().optional(), is_digital_signal: A_.boolean().optional(), is_analog_signal: A_.boolean().optional(), is_positive_voltage_source: A_.boolean().optional(), trace_width: A_.number().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() });\nvar Yv = A_.object({ type: A_.literal(\"source_board\"), source_board_id: A_.string(), source_group_id: A_.string(), title: A_.string().optional() }).describe(\"Defines a board in the source domain\");\nvar $v = Wx.extend({ type: A_.literal(\"source_ambiguous_port_reference\"), source_ambiguous_port_reference_id: Cx(\"source_ambiguous_port_reference\"), error_type: A_.literal(\"source_ambiguous_port_reference\").default(\"source_ambiguous_port_reference\"), source_port_id: A_.string().optional(), source_component_id: A_.string().optional() }).describe(\"Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous\");\nvar Xv = A_.object({ type: A_.literal(\"source_pcb_ground_plane\"), source_pcb_ground_plane_id: A_.string(), source_group_id: A_.string(), source_net_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Defines a ground plane in the source domain\");\nvar Bv = [\"top\", \"bottom\", \"inner1\", \"inner2\", \"inner3\", \"inner4\", \"inner5\", \"inner6\", \"inner7\", \"inner8\"];\nvar Hv = A_.enum(Bv);\nvar Wv = Hv.or(A_.object({ name: Hv })).transform((t48) =\u003e \"string\" == typeof t48 ? t48 : t48.name);\nvar Vv = A_.enum([\"top\", \"bottom\"]);\nvar Uv = A_.object({ type: A_.literal(\"source_manually_placed_via\"), source_manually_placed_via_id: A_.string(), source_group_id: A_.string(), source_net_id: A_.string(), subcircuit_id: A_.string().optional(), source_trace_id: A_.string().optional() }).describe(\"Defines a via that is manually placed in the source domain\");\nvar Gv = A_.object({ type: A_.literal(\"source_unnamed_trace_warning\"), source_unnamed_trace_warning_id: Cx(\"source_unnamed_trace_warning\"), warning_type: A_.literal(\"source_unnamed_trace_warning\").default(\"source_unnamed_trace_warning\"), message: A_.string(), source_trace_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a source trace is missing a name\");\nvar Zv = A_.object({ type: A_.literal(\"source_no_power_pin_defined_warning\"), source_no_power_pin_defined_warning_id: Cx(\"source_no_power_pin_defined_warning\"), warning_type: A_.literal(\"source_no_power_pin_defined_warning\").default(\"source_no_power_pin_defined_warning\"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a chip has no source ports with requires_power=true\");\nvar qv = A_.object({ type: A_.literal(\"source_no_ground_pin_defined_warning\"), source_no_ground_pin_defined_warning_id: Cx(\"source_no_ground_pin_defined_warning\"), warning_type: A_.literal(\"source_no_ground_pin_defined_warning\").default(\"source_no_ground_pin_defined_warning\"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a chip has no source ports marked as ground pins\");\nvar Jv = A_.object({ type: A_.literal(\"source_component_pins_underspecified_warning\"), source_component_pins_underspecified_warning_id: Cx(\"source_component_pins_underspecified_warning\"), warning_type: A_.literal(\"source_component_pins_underspecified_warning\").default(\"source_component_pins_underspecified_warning\"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when all ports on a source component are underspecified\");\nvar Kv = Wx.extend({ type: A_.literal(\"source_pin_must_be_connected_error\"), source_pin_must_be_connected_error_id: Cx(\"source_pin_must_be_connected_error\"), error_type: A_.literal(\"source_pin_must_be_connected_error\").default(\"source_pin_must_be_connected_error\"), source_component_id: A_.string(), source_port_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a pin with mustBeConnected attribute is not connected to any trace\");\nvar Qv = Wx.extend({ type: A_.literal(\"unknown_error_finding_part\"), unknown_error_finding_part_id: Cx(\"unknown_error_finding_part\"), error_type: A_.literal(\"unknown_error_finding_part\").default(\"unknown_error_finding_part\"), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when an unexpected error occurs while finding a part\");\nvar tS = A_.object({ type: A_.literal(\"source_part_not_found_warning\"), source_part_not_found_warning_id: Cx(\"source_part_not_found_warning\"), warning_type: A_.literal(\"source_part_not_found_warning\").default(\"source_part_not_found_warning\"), message: A_.string(), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional(), supplier_name: Vx.optional(), manufacturer_part_number: A_.string().optional(), supplier_part_number: A_.string().optional(), part_name: A_.string().optional() }).describe(\"Warning emitted when a requested part can not be found\");\nvar eS = A_.object({ type: A_.literal(\"schematic_box\"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), width: px, height: px, is_dashed: A_.boolean().default(false), x: px, y: px, subcircuit_id: A_.string().optional() }).describe(\"Draws a box on the schematic\");\nvar nS = A_.object({ type: A_.literal(\"schematic_path\"), schematic_path_id: Cx(\"schematic_path\"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), fill_color: A_.string().optional(), is_filled: A_.boolean().optional(), is_dashed: A_.boolean().default(false), stroke_width: px.nullable().optional(), stroke_color: A_.string().optional(), dash_length: px.optional(), dash_gap: px.optional(), points: A_.array(vx), subcircuit_id: A_.string().optional() });\nvar oS = A_.record(A_.object({ left_margin: dx.optional(), right_margin: dx.optional(), top_margin: dx.optional(), bottom_margin: dx.optional() }));\nvar iS = A_.object({ left_size: A_.number(), right_size: A_.number(), top_size: A_.number().optional(), bottom_size: A_.number().optional() });\nvar rS = A_.object({ left_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), right_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), top_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional(), bottom_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional() });\nvar sS = A_.union([iS, rS]);\nvar aS = A_.object({ type: A_.literal(\"schematic_component\"), size: Mx, center: vx, source_component_id: A_.string().optional(), schematic_component_id: A_.string(), schematic_sheet_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), pin_spacing: dx.optional(), pin_styles: oS.optional(), box_width: dx.optional(), symbol_name: A_.string().optional(), port_arrangement: sS.optional(), port_labels: A_.record(A_.string()).optional(), symbol_display_value: A_.string().optional(), subcircuit_id: A_.string().optional(), schematic_group_id: A_.string().optional(), is_schematic_group: A_.boolean().optional(), source_group_id: A_.string().optional(), is_box_with_pins: A_.boolean().optional().default(true) });\nvar cS = A_.object({ kicad_symbol: Hx.optional() }).catchall(A_.unknown());\nvar lS = A_.object({ type: A_.literal(\"schematic_symbol\"), schematic_symbol_id: A_.string(), name: A_.string().optional(), metadata: cS.optional() }).describe(\"Defines a named schematic symbol that can be referenced by components.\");\nvar hS = A_.object({ type: A_.literal(\"schematic_line\"), schematic_line_id: Cx(\"schematic_line\"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), x1: px, y1: px, x2: px, y2: px, stroke_width: px.nullable().optional(), color: A_.string().default(\"#000000\"), is_dashed: A_.boolean().default(false), dash_length: px.optional(), dash_gap: px.optional(), subcircuit_id: A_.string().optional() }).describe(\"Draws a styled line on the schematic\");\nvar dS = A_.object({ type: A_.literal(\"schematic_rect\"), schematic_rect_id: Cx(\"schematic_rect\"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: vx, width: px, height: px, rotation: bx.default(0), stroke_width: px.nullable().optional(), color: A_.string().default(\"#000000\"), is_filled: A_.boolean().default(false), fill_color: A_.string().optional(), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe(\"Draws a styled rectangle on the schematic\");\nvar uS = A_.object({ type: A_.literal(\"schematic_circle\"), schematic_circle_id: Cx(\"schematic_circle\"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: vx, radius: px, stroke_width: px.nullable().optional(), color: A_.string().default(\"#000000\"), is_filled: A_.boolean().default(false), fill_color: A_.string().optional(), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe(\"Draws a styled circle on the schematic\");\nvar pS = A_.object({ type: A_.literal(\"schematic_arc\"), schematic_arc_id: Cx(\"schematic_arc\"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: vx, radius: px, start_angle_degrees: bx, end_angle_degrees: bx, direction: A_.enum([\"clockwise\", \"counterclockwise\"]).default(\"counterclockwise\"), stroke_width: px.nullable().optional(), color: A_.string().default(\"#000000\"), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe(\"Draws a styled arc on the schematic\");\nvar mS = A_.object({ type: A_.literal(\"schematic_trace\"), schematic_trace_id: A_.string(), schematic_sheet_id: A_.string().optional(), source_trace_id: A_.string().optional(), junctions: A_.array(A_.object({ x: A_.number(), y: A_.number() })), edges: A_.array(A_.object({ from: A_.object({ x: A_.number(), y: A_.number() }), to: A_.object({ x: A_.number(), y: A_.number() }), is_crossing: A_.boolean().optional(), from_schematic_port_id: A_.string().optional(), to_schematic_port_id: A_.string().optional() })), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() });\nvar gS = A_.enum([\"center\", \"left\", \"right\", \"top\", \"bottom\"]);\nvar fS = A_.object({ type: A_.literal(\"schematic_text\"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), schematic_text_id: A_.string(), text: A_.string(), font_size: A_.number().default(0.18), position: A_.object({ x: px, y: px }), rotation: A_.number().default(0), anchor: A_.union([gS.describe(\"legacy\"), Nx]).default(\"center\"), color: A_.string().default(\"#000000\"), subcircuit_id: A_.string().optional() });\nvar _S = A_.object({ type: A_.literal(\"schematic_port\"), schematic_port_id: A_.string(), source_port_id: A_.string(), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), center: vx, facing_direction: A_.enum([\"up\", \"down\", \"left\", \"right\"]).optional(), distance_from_component_edge: A_.number().optional(), side_of_component: A_.enum([\"top\", \"bottom\", \"left\", \"right\"]).optional(), true_ccw_index: A_.number().optional(), pin_number: A_.number().optional(), display_pin_label: A_.string().optional(), subcircuit_id: A_.string().optional(), is_connected: A_.boolean().optional(), has_input_arrow: A_.boolean().optional(), has_output_arrow: A_.boolean().optional(), is_drawn_with_inversion_circle: A_.boolean().optional() }).describe(\"Defines a port on a schematic component\");\nvar yS = A_.object({ type: A_.literal(\"schematic_net_label\"), schematic_net_label_id: Cx(\"schematic_net_label\"), schematic_sheet_id: A_.string().optional(), schematic_trace_id: A_.string().optional(), source_trace_id: A_.string().optional(), source_net_id: A_.string(), center: vx, anchor_position: vx.optional(), anchor_side: A_.enum([\"top\", \"bottom\", \"left\", \"right\"]), text: A_.string(), symbol_name: A_.string().optional(), is_movable: A_.boolean().optional(), subcircuit_id: A_.string().optional() });\nvar bS = Wx.extend({ type: A_.literal(\"schematic_error\"), schematic_error_id: A_.string(), error_type: A_.literal(\"schematic_port_not_found\").default(\"schematic_port_not_found\"), subcircuit_id: A_.string().optional() }).describe(\"Defines a schematic error on the schematic\");\nvar xS = Wx.extend({ type: A_.literal(\"schematic_layout_error\"), schematic_layout_error_id: Cx(\"schematic_layout_error\"), error_type: A_.literal(\"schematic_layout_error\").default(\"schematic_layout_error\"), source_group_id: A_.string(), schematic_group_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when schematic layout fails for a group\");\nvar vS = A_.object({ type: A_.literal(\"schematic_debug_object\"), label: A_.string().optional(), subcircuit_id: A_.string().optional() });\nvar SS = vS.extend({ shape: A_.literal(\"rect\"), center: vx, size: Mx });\nvar IS = vS.extend({ shape: A_.literal(\"line\"), start: vx, end: vx });\nvar PS = vS.extend({ shape: A_.literal(\"point\"), center: vx });\nvar MS = A_.discriminatedUnion(\"shape\", [SS, IS, PS]);\nvar CS = A_.object({ type: A_.literal(\"schematic_voltage_probe\"), schematic_voltage_probe_id: A_.string(), schematic_sheet_id: A_.string().optional(), source_component_id: A_.string().optional(), name: A_.string().optional(), position: vx, schematic_trace_id: A_.string(), voltage: hx.optional(), subcircuit_id: A_.string().optional(), color: A_.string().optional(), label_alignment: Nx.optional() }).describe(\"Defines a voltage probe measurement point on a schematic trace\");\nvar NS = A_.object({ type: A_.literal(\"schematic_manual_edit_conflict_warning\"), schematic_manual_edit_conflict_warning_id: Cx(\"schematic_manual_edit_conflict_warning\"), warning_type: A_.literal(\"schematic_manual_edit_conflict_warning\").default(\"schematic_manual_edit_conflict_warning\"), message: A_.string(), schematic_component_id: A_.string(), schematic_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_component_id: A_.string() }).describe(\"Warning emitted when a component has both manual placement and explicit schX/schY coordinates\");\nvar wS = A_.object({ type: A_.literal(\"schematic_group\"), schematic_group_id: Cx(\"schematic_group\"), schematic_sheet_id: A_.string().optional(), source_group_id: A_.string(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), width: dx, height: dx, center: vx, schematic_component_ids: A_.array(A_.string()), show_as_schematic_box: A_.boolean().optional(), name: A_.string().optional(), description: A_.string().optional() }).describe(\"Defines a group of components on the schematic\");\nvar TS = A_.object({ type: A_.literal(\"schematic_table\"), schematic_table_id: Cx(\"schematic_table\"), schematic_sheet_id: A_.string().optional(), anchor_position: vx, column_widths: A_.array(px), row_heights: A_.array(px), cell_padding: px.optional(), border_width: px.optional(), subcircuit_id: A_.string().optional(), schematic_component_id: A_.string().optional(), anchor: Nx.optional() }).describe(\"Defines a table on the schematic\");\nvar RS = A_.object({ type: A_.literal(\"schematic_table_cell\"), schematic_table_cell_id: Cx(\"schematic_table_cell\"), schematic_sheet_id: A_.string().optional(), schematic_table_id: A_.string(), start_row_index: A_.number(), end_row_index: A_.number(), start_column_index: A_.number(), end_column_index: A_.number(), text: A_.string().optional(), center: vx, width: px, height: px, horizontal_align: A_.enum([\"left\", \"center\", \"right\"]).optional(), vertical_align: A_.enum([\"top\", \"middle\", \"bottom\"]).optional(), font_size: px.optional(), subcircuit_id: A_.string().optional() }).describe(\"Defines a cell within a schematic_table\");\nvar ES = A_.object({ type: A_.literal(\"schematic_sheet\"), schematic_sheet_id: Cx(\"schematic_sheet\"), name: A_.string().optional(), sheet_index: A_.number().optional(), subcircuit_id: A_.string().optional(), outline_color: A_.string().optional() }).describe(\"Defines a schematic sheet or page that components can be placed on\");\nvar AS = A_.object({ x: px, y: px, bulge: A_.number().optional() });\nvar OS = A_.object({ vertices: A_.array(AS) });\nvar LS = A_.object({ outer_ring: OS, inner_rings: A_.array(OS).default([]) });\nvar DS = A_.object({ x: px, y: px, via: A_.boolean().optional(), via_to_layer: Wv.optional() });\nvar zS = A_.array(DS);\nvar kS = A_.object({ x: px, y: px, via: A_.boolean().optional(), to_layer: Wv.optional(), trace_width: px.optional() });\nvar FS = A_.object({ min_trace_width: dx.optional(), min_board_edge_clearance: dx.optional(), min_via_hole_edge_to_via_hole_edge_clearance: dx.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: dx.optional(), min_trace_to_pad_edge_clearance: dx.optional(), min_pad_edge_to_pad_edge_clearance: dx.optional(), min_same_net_trace_edge_to_trace_edge_clearance: dx.optional(), min_different_net_trace_edge_to_trace_edge_clearance: dx.optional(), min_via_edge_to_pad_edge_clearance: dx.optional(), min_via_hole_diameter: dx.optional(), min_via_pad_diameter: dx.optional() });\nvar jS = A_.object({ type: A_.literal(\"pcb_component\"), pcb_component_id: Cx(\"pcb_component\"), source_component_id: A_.string(), center: vx, layer: Wv, rotation: bx, display_offset_x: A_.string().optional().describe(\"How to display the x offset for this part, usually corresponding with how the user specified it\"), display_offset_y: A_.string().optional().describe(\"How to display the y offset for this part, usually corresponding with how the user specified it\"), width: dx, height: dx, do_not_place: A_.boolean().optional(), is_allowed_to_be_off_board: A_.boolean().optional(), subcircuit_id: A_.string().optional(), pcb_group_id: A_.string().optional(), position_mode: A_.enum([\"packed\", \"relative_to_group_anchor\", \"relative_to_another_component\", \"none\"]).optional(), anchor_position: vx.optional(), anchor_alignment: Nx.optional(), positioned_relative_to_pcb_group_id: A_.string().optional(), positioned_relative_to_pcb_board_id: A_.string().optional(), cable_insertion_center: vx.optional(), insertion_direction: A_.enum([\"from_above\", \"from_left\", \"from_right\", \"from_front\", \"from_back\"]).optional(), metadata: A_.object({ kicad_footprint: Fx.optional() }).optional(), obstructs_within_bounds: A_.boolean().default(true).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\");\nvar YS = A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: Cx(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"circle\"), hole_diameter: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar $S = YS.describe(\"Defines a circular hole on the PCB\");\nvar XS = A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: Cx(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"rect\"), hole_width: A_.number(), hole_height: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar BS = XS.describe(\"Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.\");\nvar HS = A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: Cx(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.enum([\"circle\", \"square\"]), hole_diameter: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar WS = HS.describe(\"Defines a circular or square hole on the PCB\");\nvar VS = A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: Cx(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"oval\"), hole_width: A_.number(), hole_height: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar US = VS.describe(\"Defines an oval hole on the PCB\");\nvar GS = A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: Cx(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"pill\"), hole_width: A_.number(), hole_height: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar ZS = GS.describe(\"Defines a pill-shaped hole on the PCB\");\nvar qS = A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: Cx(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"rotated_pill\"), hole_width: A_.number(), hole_height: A_.number(), x: px, y: px, ccw_rotation: bx, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar JS = qS.describe(\"Defines a rotated pill-shaped hole on the PCB\");\nvar KS = HS.or(VS).or(GS).or(qS).or(YS).or(XS);\nvar QS = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"circle\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), outer_diameter: A_.number(), hole_diameter: A_.number(), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional() });\nvar tI = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.enum([\"oval\", \"pill\"]), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), outer_width: A_.number(), outer_height: A_.number(), hole_width: A_.number(), hole_height: A_.number(), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, ccw_rotation: bx, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional() });\nvar eI = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"circular_hole_with_rect_pad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal(\"circle\"), pad_shape: A_.literal(\"rect\"), hole_diameter: A_.number(), rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), hole_offset_x: px.default(0), hole_offset_y: px.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional(), rect_ccw_rotation: bx.optional() });\nvar nI = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"pill_hole_with_rect_pad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal(\"pill\"), pad_shape: A_.literal(\"rect\"), hole_width: A_.number(), hole_height: A_.number(), rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), hole_offset_x: px.default(0), hole_offset_y: px.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional() });\nvar oI = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"rotated_pill_hole_with_rect_pad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal(\"rotated_pill\"), pad_shape: A_.literal(\"rect\"), hole_width: A_.number(), hole_height: A_.number(), hole_ccw_rotation: bx, rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), rect_ccw_rotation: bx, hole_offset_x: px.default(0), hole_offset_y: px.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional() });\nvar iI = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"hole_with_polygon_pad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.enum([\"circle\", \"oval\", \"pill\", \"rotated_pill\"]), hole_diameter: A_.number().optional(), hole_width: A_.number().optional(), hole_height: A_.number().optional(), pad_outline: A_.array(A_.object({ x: px, y: px })).min(3), hole_offset_x: px.default(0), hole_offset_y: px.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional(), ccw_rotation: bx.optional() });\nvar rI = A_.union([QS, tI, eI, nI, oI, iI]);\nvar sI = A_.object({ type: A_.literal(\"pcb_port\"), pcb_port_id: Cx(\"pcb_port\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_port_id: A_.string(), pcb_component_id: A_.string().optional(), x: px, y: px, layers: A_.array(Wv), is_board_pinout: A_.boolean().optional() }).describe(\"Defines a port on the PCB\");\nvar aI = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"circle\"), pcb_smtpad_id: Cx(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, radius: A_.number(), layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar cI = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"rect\"), pcb_smtpad_id: Cx(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), rect_border_radius: A_.number().optional(), corner_radius: A_.number().optional(), layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional(), soldermask_margin_left: A_.number().optional(), soldermask_margin_top: A_.number().optional(), soldermask_margin_right: A_.number().optional(), soldermask_margin_bottom: A_.number().optional() });\nvar lI = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"rotated_rect\"), pcb_smtpad_id: Cx(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), rect_border_radius: A_.number().optional(), corner_radius: A_.number().optional(), ccw_rotation: bx, layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional(), soldermask_margin_left: A_.number().optional(), soldermask_margin_top: A_.number().optional(), soldermask_margin_right: A_.number().optional(), soldermask_margin_bottom: A_.number().optional() });\nvar hI = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"pill\"), pcb_smtpad_id: Cx(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), radius: A_.number(), layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar dI = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"rotated_pill\"), pcb_smtpad_id: Cx(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), radius: A_.number(), ccw_rotation: bx, layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar uI = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"polygon\"), pcb_smtpad_id: Cx(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), points: A_.array(vx), layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar pI = A_.discriminatedUnion(\"shape\", [aI, cI, lI, dI, hI, uI]).describe(\"Defines an SMT pad on the PCB\");\nvar mI = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"circle\"), pcb_solder_paste_id: Cx(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, radius: A_.number(), layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar gI = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"rect\"), pcb_solder_paste_id: Cx(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar fI = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"pill\"), pcb_solder_paste_id: Cx(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), radius: A_.number(), layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar _I = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"rotated_rect\"), pcb_solder_paste_id: Cx(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), ccw_rotation: px, layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar yI = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"oval\"), pcb_solder_paste_id: Cx(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar bI = A_.union([mI, gI, fI, _I, yI]).describe(\"Defines solderpaste on the PCB\");\nvar xI = A_.object({ type: A_.literal(\"pcb_text\"), pcb_text_id: Cx(\"pcb_text\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), text: A_.string(), center: vx, layer: Wv, width: dx, height: dx, lines: A_.number(), align: A_.enum([\"bottom-left\"]) }).describe(\"Defines text on the PCB\");\nvar vI = A_.object({ route_type: A_.literal(\"wire\"), x: px, y: px, width: px, copper_pour_id: A_.string().optional(), is_inside_copper_pour: A_.boolean().optional(), start_pcb_port_id: A_.string().optional(), end_pcb_port_id: A_.string().optional(), layer: Wv });\nvar SI = A_.object({ route_type: A_.literal(\"via\"), x: px, y: px, copper_pour_id: A_.string().optional(), is_inside_copper_pour: A_.boolean().optional(), hole_diameter: px.optional(), outer_diameter: px.optional(), from_layer: Wv, to_layer: Wv });\nvar II = A_.object({ route_type: A_.literal(\"through_pad\"), start: vx, end: vx, width: px, start_layer: Wv, end_layer: Wv, pcb_smtpad_id: A_.string().optional(), pcb_plated_hole_id: A_.string().optional() });\nvar PI2 = A_.union([vI, SI, II]);\nvar MI = A_.object({ type: A_.literal(\"pcb_trace\"), source_trace_id: A_.string().optional(), pcb_component_id: A_.string().optional(), pcb_trace_id: Cx(\"pcb_trace\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), route_thickness_mode: A_.enum([\"constant\", \"interpolated\"]).default(\"constant\").optional(), route_order_index: A_.number().optional(), should_round_corners: A_.boolean().optional(), trace_length: A_.number().optional(), highlight_color: A_.string().optional(), route: A_.array(PI2) }).describe(\"Defines a trace on the PCB\");\nvar CI = A_.object({ type: A_.literal(\"pcb_trace_warning\"), pcb_trace_warning_id: Cx(\"pcb_trace_warning\"), warning_type: A_.literal(\"pcb_trace_warning\").default(\"pcb_trace_warning\"), message: A_.string(), center: vx.optional(), pcb_trace_id: A_.string(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines a trace warning on the PCB\");\nvar NI = A_.object({ type: A_.literal(\"pcb_trace_too_long_warning\"), pcb_trace_too_long_warning_id: Cx(\"pcb_trace_too_long_warning\"), warning_type: A_.literal(\"pcb_trace_too_long_warning\").default(\"pcb_trace_too_long_warning\"), message: A_.string(), pcb_trace_id: A_.string(), source_net_id: A_.string().optional(), source_trace_id: A_.string().optional(), actual_trace_length: px, maximum_trace_length: px, subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a PCB trace is longer than its maximum allowed length\");\nvar wI = Wx.extend({ type: A_.literal(\"pcb_trace_error\"), pcb_trace_error_id: Cx(\"pcb_trace_error\"), error_type: A_.literal(\"pcb_trace_error\").default(\"pcb_trace_error\"), center: vx.optional(), pcb_trace_id: A_.string(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines a trace error on the PCB\");\nvar TI = Wx.extend({ type: A_.literal(\"pcb_trace_missing_error\"), pcb_trace_missing_error_id: Cx(\"pcb_trace_missing_error\"), error_type: A_.literal(\"pcb_trace_missing_error\").default(\"pcb_trace_missing_error\"), center: vx.optional(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines an error when a source trace has no corresponding PCB trace\");\nvar RI = Wx.extend({ type: A_.literal(\"pcb_port_not_matched_error\"), pcb_error_id: Cx(\"pcb_error\"), error_type: A_.literal(\"pcb_port_not_matched_error\").default(\"pcb_port_not_matched_error\"), pcb_component_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines a trace error on the PCB where a port is not matched\");\nvar EI = Wx.extend({ type: A_.literal(\"pcb_port_not_connected_error\"), pcb_port_not_connected_error_id: Cx(\"pcb_port_not_connected_error\"), error_type: A_.literal(\"pcb_port_not_connected_error\").default(\"pcb_port_not_connected_error\"), pcb_port_ids: A_.array(A_.string()), pcb_component_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines an error when a pcb port is not connected to any trace\");\nvar AI = A_.object({ type: A_.literal(\"pcb_net\"), pcb_net_id: Cx(\"pcb_net\"), source_net_id: A_.string().optional(), highlight_color: A_.string().optional() }).describe(\"Defines a net on the PCB\");\nvar OI = A_.object({ type: A_.literal(\"pcb_via\"), pcb_via_id: Cx(\"pcb_via\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), x: px, y: px, outer_diameter: px.default(\"0.6mm\"), hole_diameter: px.default(\"0.25mm\"), from_layer: Wv.optional(), to_layer: Wv.optional(), layers: A_.array(Wv), pcb_trace_id: A_.string().optional(), net_is_assignable: A_.boolean().optional(), net_assigned: A_.boolean().optional(), is_tented: A_.boolean().optional() }).describe(\"Defines a via on the PCB\");\nvar LI = A_.object({ type: A_.literal(\"pcb_board\"), pcb_board_id: Cx(\"pcb_board\"), pcb_panel_id: A_.string().optional(), carrier_pcb_board_id: A_.string().optional(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), is_mounted_to_carrier_board: A_.boolean().optional(), width: dx.optional(), height: dx.optional(), center: vx, display_offset_x: A_.string().optional().describe(\"How to display the x offset for this board, usually corresponding with how the user specified it\"), display_offset_y: A_.string().optional().describe(\"How to display the y offset for this board, usually corresponding with how the user specified it\"), thickness: dx.optional().default(1.4), num_layers: A_.number().optional().default(4), outline: A_.array(vx).optional(), shape: A_.enum([\"rect\", \"polygon\"]).optional(), material: A_.enum([\"fr4\", \"fr1\"]).default(\"fr4\"), solder_mask_color: A_.string().optional(), silkscreen_color: A_.string().optional(), anchor_position: vx.optional(), anchor_alignment: Nx.optional(), position_mode: A_.enum([\"relative_to_panel_anchor\", \"none\"]).optional() }).merge(FS).describe(\"Defines the board outline of the PCB\");\nvar DI = A_.object({ type: A_.literal(\"pcb_panel\"), pcb_panel_id: Cx(\"pcb_panel\"), width: dx, height: dx, center: vx, thickness: dx.optional().default(1.4), covered_with_solder_mask: A_.boolean().optional().default(true) }).describe(\"Defines a PCB panel that can contain multiple boards\");\nvar zI = Wx.extend({ type: A_.literal(\"pcb_placement_error\"), pcb_placement_error_id: Cx(\"pcb_placement_error\"), error_type: A_.literal(\"pcb_placement_error\").default(\"pcb_placement_error\"), subcircuit_id: A_.string().optional() }).describe(\"Defines a placement error on the PCB\");\nvar kI = Wx.extend({ type: A_.literal(\"pcb_panelization_placement_error\"), pcb_panelization_placement_error_id: Cx(\"pcb_panelization_placement_error\"), error_type: A_.literal(\"pcb_panelization_placement_error\").default(\"pcb_panelization_placement_error\"), pcb_panel_id: A_.string().optional(), pcb_board_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Defines a panelization placement error on the PCB\");\nvar FI = A_.object({ type: A_.literal(\"pcb_trace_hint\"), pcb_trace_hint_id: Cx(\"pcb_trace_hint\"), pcb_port_id: A_.string(), pcb_component_id: A_.string(), route: A_.array(kS), subcircuit_id: A_.string().optional() }).describe(\"A hint that can be used during generation of a PCB trace\");\nvar jI = A_.object({ type: A_.literal(\"pcb_silkscreen_line\"), pcb_silkscreen_line_id: Cx(\"pcb_silkscreen_line\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), stroke_width: px.default(\"0.1mm\"), x1: px, y1: px, x2: px, y2: px, layer: Vv }).describe(\"Defines a silkscreen line on the PCB\");\nvar YI = A_.object({ type: A_.literal(\"pcb_silkscreen_path\"), pcb_silkscreen_path_id: Cx(\"pcb_silkscreen_path\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, route: A_.array(vx), stroke_width: dx }).describe(\"Defines a silkscreen path on the PCB\");\nvar $I = A_.object({ type: A_.literal(\"pcb_silkscreen_text\"), pcb_silkscreen_text_id: Cx(\"pcb_silkscreen_text\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: px.default(\"0.2mm\"), pcb_component_id: A_.string(), text: A_.string(), is_knockout: A_.boolean().default(false).optional(), knockout_padding: A_.object({ left: dx, top: dx, bottom: dx, right: dx }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: A_.number().optional(), layer: Wv, is_mirrored: A_.boolean().default(false).optional(), anchor_position: vx.default({ x: 0, y: 0 }), anchor_alignment: Nx.default(\"center\") }).describe(\"Defines silkscreen text on the PCB\");\nvar XI = A_.object({ type: A_.literal(\"pcb_copper_text\"), pcb_copper_text_id: Cx(\"pcb_copper_text\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: px.default(\"0.2mm\"), pcb_component_id: A_.string(), text: A_.string(), is_knockout: A_.boolean().default(false).optional(), knockout_padding: A_.object({ left: dx, top: dx, bottom: dx, right: dx }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: A_.number().optional(), layer: Wv, is_mirrored: A_.boolean().default(false).optional(), anchor_position: vx.default({ x: 0, y: 0 }), anchor_alignment: Nx.default(\"center\") }).describe(\"Defines copper text on the PCB\");\nvar BI = A_.object({ type: A_.literal(\"pcb_silkscreen_rect\"), pcb_silkscreen_rect_id: Cx(\"pcb_silkscreen_rect\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, layer: Wv, stroke_width: dx.default(\"1mm\"), corner_radius: dx.optional(), is_filled: A_.boolean().default(true).optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), ccw_rotation: A_.number().optional() }).describe(\"Defines a silkscreen rect on the PCB\");\nvar HI = A_.object({ type: A_.literal(\"pcb_silkscreen_circle\"), pcb_silkscreen_circle_id: Cx(\"pcb_silkscreen_circle\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, radius: dx, layer: Vv, stroke_width: dx.default(\"1mm\"), is_filled: A_.boolean().optional() }).describe(\"Defines a silkscreen circle on the PCB\");\nvar WI = A_.object({ type: A_.literal(\"pcb_silkscreen_oval\"), pcb_silkscreen_oval_id: Cx(\"pcb_silkscreen_oval\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, radius_x: px, radius_y: px, layer: Vv, ccw_rotation: bx.optional() }).describe(\"Defines a silkscreen oval on the PCB\");\nvar VI = A_.object({ type: A_.literal(\"pcb_silkscreen_graphic\"), pcb_silkscreen_graphic_id: Cx(\"pcb_silkscreen_graphic\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, image_asset: Tx.optional() }).extend({ shape: A_.literal(\"brep\"), brep_shape: LS }).describe(\"Defines a BRep silkscreen graphic on the PCB\");\nvar UI = A_.discriminatedUnion(\"shape\", [VI]).describe(\"Defines a silkscreen graphic on the PCB\");\nvar GI = A_.object({ type: A_.literal(\"pcb_silkscreen_pill\"), pcb_silkscreen_pill_id: Cx(\"pcb_silkscreen_pill\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, layer: Wv, ccw_rotation: A_.number().optional() }).describe(\"Defines a silkscreen pill on the PCB\");\nvar ZI = A_.object({ type: A_.literal(\"pcb_fabrication_note_text\"), pcb_fabrication_note_text_id: Cx(\"pcb_fabrication_note_text\"), subcircuit_id: A_.string().optional(), pcb_group_id: A_.string().optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: px.default(\"1mm\"), pcb_component_id: A_.string(), text: A_.string(), ccw_rotation: A_.number().optional(), layer: Vv, anchor_position: vx.default({ x: 0, y: 0 }), anchor_alignment: A_.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), color: A_.string().optional() }).describe(\"Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators\");\nvar qI = A_.object({ type: A_.literal(\"pcb_fabrication_note_path\"), pcb_fabrication_note_path_id: Cx(\"pcb_fabrication_note_path\"), pcb_component_id: A_.string(), subcircuit_id: A_.string().optional(), layer: Wv, route: A_.array(vx), stroke_width: dx, color: A_.string().optional() }).describe(\"Defines a fabrication path on the PCB for fabricators or assemblers\");\nvar JI = A_.object({ type: A_.literal(\"pcb_fabrication_note_rect\"), pcb_fabrication_note_rect_id: Cx(\"pcb_fabrication_note_rect\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, layer: Vv, stroke_width: dx.default(\"0.1mm\"), corner_radius: dx.optional(), is_filled: A_.boolean().optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), color: A_.string().optional() }).describe(\"Defines a fabrication note rectangle on the PCB\");\nvar KI = A_.object({ type: A_.literal(\"pcb_fabrication_note_dimension\"), pcb_fabrication_note_dimension_id: Cx(\"pcb_fabrication_note_dimension\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, from: vx, to: vx, text: A_.string().optional(), text_ccw_rotation: A_.number().optional(), offset: dx.optional(), offset_distance: dx.optional(), offset_direction: A_.object({ x: A_.number(), y: A_.number() }).optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: dx.default(\"1mm\"), color: A_.string().optional(), arrow_size: dx.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB fabrication notes\");\nvar QI = A_.object({ type: A_.literal(\"pcb_note_text\"), pcb_note_text_id: Cx(\"pcb_note_text\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: px.default(\"1mm\"), text: A_.string().optional(), anchor_position: vx.default({ x: 0, y: 0 }), anchor_alignment: A_.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), layer: Vv.default(\"top\"), is_mirrored_from_top_view: A_.boolean().optional(), color: A_.string().optional() }).describe(\"Defines a documentation note in text on the PCB\");\nvar tP = A_.object({ type: A_.literal(\"pcb_note_rect\"), pcb_note_rect_id: Cx(\"pcb_note_rect\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), center: vx, width: dx, height: dx, layer: Vv.default(\"top\"), stroke_width: dx.default(\"0.1mm\"), corner_radius: dx.optional(), is_filled: A_.boolean().optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), color: A_.string().optional() }).describe(\"Defines a rectangular documentation note on the PCB\");\nvar eP = A_.object({ type: A_.literal(\"pcb_note_path\"), pcb_note_path_id: Cx(\"pcb_note_path\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), route: A_.array(vx), layer: Vv.default(\"top\"), stroke_width: dx.default(\"0.1mm\"), color: A_.string().optional() }).describe(\"Defines a polyline documentation note on the PCB\");\nvar nP = A_.object({ type: A_.literal(\"pcb_note_line\"), pcb_note_line_id: Cx(\"pcb_note_line\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), x1: px, y1: px, x2: px, y2: px, layer: Vv.default(\"top\"), stroke_width: px.default(\"0.1mm\"), color: A_.string().optional(), is_dashed: A_.boolean().optional() }).describe(\"Defines a straight documentation note line on the PCB\");\nvar oP = A_.object({ type: A_.literal(\"pcb_note_dimension\"), pcb_note_dimension_id: Cx(\"pcb_note_dimension\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), from: vx, to: vx, text: A_.string().optional(), text_ccw_rotation: A_.number().optional(), offset_distance: dx.optional(), offset_direction: A_.object({ x: A_.number(), y: A_.number() }).optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: dx.default(\"1mm\"), layer: Vv.default(\"top\"), color: A_.string().optional(), arrow_size: dx.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB documentation notes\");\nvar iP = Wx.extend({ type: A_.literal(\"pcb_footprint_overlap_error\"), pcb_error_id: Cx(\"pcb_error\"), error_type: A_.literal(\"pcb_footprint_overlap_error\").default(\"pcb_footprint_overlap_error\"), pcb_smtpad_ids: A_.array(A_.string()).optional(), pcb_plated_hole_ids: A_.array(A_.string()).optional(), pcb_hole_ids: A_.array(A_.string()).optional(), pcb_keepout_ids: A_.array(A_.string()).optional() }).describe(\"Error emitted when a pcb footprint overlaps with another element\");\nvar rP = Wx.extend({ type: A_.literal(\"pcb_courtyard_overlap_error\"), pcb_error_id: Cx(\"pcb_error\"), error_type: A_.literal(\"pcb_courtyard_overlap_error\").default(\"pcb_courtyard_overlap_error\"), pcb_component_ids: A_.tuple([A_.string(), A_.string()]) }).describe(\"Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another\");\nvar sP = A_.object({ type: A_.literal(\"pcb_keepout\"), shape: A_.literal(\"rect\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: px, height: px, pcb_keepout_id: A_.string(), layers: A_.array(A_.string()), description: A_.string().optional() }).or(A_.object({ type: A_.literal(\"pcb_keepout\"), shape: A_.literal(\"circle\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, radius: px, pcb_keepout_id: A_.string(), layers: A_.array(A_.string()), description: A_.string().optional() }));\nvar aP = A_.object({ type: A_.literal(\"pcb_cutout\"), pcb_cutout_id: Cx(\"pcb_cutout\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_board_id: A_.string().optional(), pcb_panel_id: A_.string().optional() });\nvar cP = aP.extend({ shape: A_.literal(\"rect\"), center: vx, width: dx, height: dx, rotation: bx.optional(), corner_radius: dx.optional() });\nvar lP = aP.extend({ shape: A_.literal(\"circle\"), center: vx, radius: dx });\nvar hP = aP.extend({ shape: A_.literal(\"polygon\"), points: A_.array(vx) });\nvar dP = aP.extend({ shape: A_.literal(\"path\"), route: A_.array(vx), slot_width: dx, slot_length: dx.optional(), space_between_slots: dx.optional(), slot_corner_radius: dx.optional() });\nvar uP = A_.discriminatedUnion(\"shape\", [cP, lP, hP, dP]).describe(\"Defines a cutout on the PCB, removing board material.\");\nvar pP = Wx.extend({ type: A_.literal(\"pcb_missing_footprint_error\"), pcb_missing_footprint_error_id: Cx(\"pcb_missing_footprint_error\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"pcb_missing_footprint_error\").default(\"pcb_missing_footprint_error\"), source_component_id: A_.string() }).describe(\"Defines a missing footprint error on the PCB\");\nvar mP = Wx.extend({ type: A_.literal(\"external_footprint_load_error\"), external_footprint_load_error_id: Cx(\"external_footprint_load_error\"), pcb_component_id: A_.string(), source_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), footprinter_string: A_.string().optional(), error_type: A_.literal(\"external_footprint_load_error\").default(\"external_footprint_load_error\") }).describe(\"Defines an error when an external footprint fails to load\");\nvar gP = Wx.extend({ type: A_.literal(\"circuit_json_footprint_load_error\"), circuit_json_footprint_load_error_id: Cx(\"circuit_json_footprint_load_error\"), pcb_component_id: A_.string(), source_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"circuit_json_footprint_load_error\").default(\"circuit_json_footprint_load_error\"), circuit_json: A_.array(A_.any()).optional() }).describe(\"Defines an error when a circuit JSON footprint fails to load\");\nvar fP = A_.object({ type: A_.literal(\"pcb_group\"), pcb_group_id: Cx(\"pcb_group\"), source_group_id: A_.string(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), width: dx.optional(), height: dx.optional(), center: vx, display_offset_x: A_.string().optional().describe(\"How to display the x offset for this group, usually corresponding with how the user specified it\"), display_offset_y: A_.string().optional().describe(\"How to display the y offset for this group, usually corresponding with how the user specified it\"), outline: A_.array(vx).optional(), anchor_position: vx.optional(), anchor_alignment: Nx.default(\"center\"), position_mode: A_.enum([\"packed\", \"relative_to_group_anchor\", \"none\"]).optional(), positioned_relative_to_pcb_group_id: A_.string().optional(), positioned_relative_to_pcb_board_id: A_.string().optional(), pcb_component_ids: A_.array(A_.string()), child_layout_mode: A_.enum([\"packed\", \"none\"]).optional(), name: A_.string().optional(), description: A_.string().optional(), layout_mode: A_.string().optional(), autorouter_configuration: A_.object({ trace_clearance: dx }).optional(), autorouter_used_string: A_.string().optional() }).describe(\"Defines a group of components on the PCB\");\nvar _P = Wx.extend({ type: A_.literal(\"pcb_autorouting_error\"), pcb_error_id: Cx(\"pcb_autorouting_error\"), error_type: A_.literal(\"pcb_autorouting_error\").default(\"pcb_autorouting_error\"), subcircuit_id: A_.string().optional() }).describe(\"The autorouting has failed to route a portion of the board\");\nvar yP = A_.object({ type: A_.literal(\"pcb_manual_edit_conflict_warning\"), pcb_manual_edit_conflict_warning_id: Cx(\"pcb_manual_edit_conflict_warning\"), warning_type: A_.literal(\"pcb_manual_edit_conflict_warning\").default(\"pcb_manual_edit_conflict_warning\"), message: A_.string(), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_component_id: A_.string() }).describe(\"Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates\");\nvar bP = A_.enum([\"x-\", \"x+\", \"y+\", \"y-\"]);\nvar xP = A_.object({ type: A_.literal(\"pcb_connector_not_in_accessible_orientation_warning\"), pcb_connector_not_in_accessible_orientation_warning_id: Cx(\"pcb_connector_not_in_accessible_orientation_warning\"), warning_type: A_.literal(\"pcb_connector_not_in_accessible_orientation_warning\").default(\"pcb_connector_not_in_accessible_orientation_warning\"), message: A_.string(), pcb_component_id: A_.string(), source_component_id: A_.string().optional(), pcb_board_id: A_.string().optional(), facing_direction: bP, recommended_facing_direction: bP, subcircuit_id: A_.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\");\nvar vP = A_.object({ type: A_.literal(\"supplier_footprint_mismatch_warning\"), supplier_footprint_mismatch_warning_id: Cx(\"supplier_footprint_mismatch_warning\"), warning_type: A_.literal(\"supplier_footprint_mismatch_warning\").default(\"supplier_footprint_mismatch_warning\"), message: A_.string(), source_component_id: A_.string(), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), supplier_name: Vx.optional(), supplier_part_number: A_.string().optional(), supplier_footprint_url: A_.string().optional(), footprint_copper_intersection_over_union: A_.number() }).describe(\"Warning emitted when a supplier part footprint does not match the expected footprint\");\nvar SP = A_.object({ type: A_.literal(\"pcb_breakout_point\"), pcb_breakout_point_id: Cx(\"pcb_breakout_point\"), pcb_group_id: A_.string(), subcircuit_id: A_.string().optional(), source_trace_id: A_.string().optional(), source_port_id: A_.string().optional(), source_net_id: A_.string().optional(), x: px, y: px }).describe(\"Defines a routing target within a pcb_group for a source_trace or source_net\");\nvar IP = A_.object({ type: A_.literal(\"pcb_ground_plane\"), pcb_ground_plane_id: Cx(\"pcb_ground_plane\"), source_pcb_ground_plane_id: A_.string(), source_net_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Defines a ground plane on the PCB\");\nvar PP = A_.object({ type: A_.literal(\"pcb_ground_plane_region\"), pcb_ground_plane_region_id: Cx(\"pcb_ground_plane_region\"), pcb_ground_plane_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Wv, points: A_.array(vx) }).describe(\"Defines a polygon region of a ground plane\");\nvar MP = A_.object({ type: A_.literal(\"pcb_thermal_spoke\"), pcb_thermal_spoke_id: Cx(\"pcb_thermal_spoke\"), pcb_ground_plane_id: A_.string(), shape: A_.string(), spoke_count: A_.number(), spoke_thickness: px, spoke_inner_diameter: px, spoke_outer_diameter: px, pcb_plated_hole_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Pattern for connecting a ground plane to a plated hole\");\nvar CP = A_.object({ type: A_.literal(\"pcb_copper_pour\"), pcb_copper_pour_id: Cx(\"pcb_copper_pour\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Wv, source_net_id: A_.string().optional(), covered_with_solder_mask: A_.boolean().optional().default(true) });\nvar NP = CP.extend({ shape: A_.literal(\"rect\"), center: vx, width: dx, height: dx, rotation: bx.optional() });\nvar wP = CP.extend({ shape: A_.literal(\"brep\"), brep_shape: LS });\nvar TP = CP.extend({ shape: A_.literal(\"polygon\"), points: A_.array(vx) });\nvar RP = A_.discriminatedUnion(\"shape\", [NP, wP, TP]).describe(\"Defines a copper pour on the PCB.\");\nvar EP = Wx.extend({ type: A_.literal(\"pcb_component_outside_board_error\"), pcb_component_outside_board_error_id: Cx(\"pcb_component_outside_board_error\"), error_type: A_.literal(\"pcb_component_outside_board_error\").default(\"pcb_component_outside_board_error\"), pcb_component_id: A_.string(), pcb_board_id: A_.string(), component_center: vx, component_bounds: A_.object({ min_x: A_.number(), max_x: A_.number(), min_y: A_.number(), max_y: A_.number() }), subcircuit_id: A_.string().optional(), source_component_id: A_.string().optional() }).describe(\"Error emitted when a PCB component is placed outside the board boundaries\");\nvar AP = Wx.extend({ type: A_.literal(\"pcb_component_not_on_board_edge_error\"), pcb_component_not_on_board_edge_error_id: Cx(\"pcb_component_not_on_board_edge_error\"), error_type: A_.literal(\"pcb_component_not_on_board_edge_error\").default(\"pcb_component_not_on_board_edge_error\"), pcb_component_id: A_.string(), pcb_board_id: A_.string(), component_center: vx, pad_to_nearest_board_edge_distance: A_.number(), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a component that must be placed on the board edge is centered away from the edge\");\nvar OP = Wx.extend({ type: A_.literal(\"pcb_component_invalid_layer_error\"), pcb_component_invalid_layer_error_id: Cx(\"pcb_component_invalid_layer_error\"), error_type: A_.literal(\"pcb_component_invalid_layer_error\").default(\"pcb_component_invalid_layer_error\"), pcb_component_id: A_.string().optional(), source_component_id: A_.string(), layer: Wv, subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)\");\nvar LP = Wx.extend({ type: A_.literal(\"pcb_via_clearance_error\"), pcb_error_id: Cx(\"pcb_error\"), error_type: A_.literal(\"pcb_via_clearance_error\").default(\"pcb_via_clearance_error\"), pcb_via_ids: A_.array(A_.string()).min(2), minimum_clearance: px.optional(), actual_clearance: px.optional(), pcb_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when vias are closer than the allowed clearance\");\nvar DP = Wx.extend({ type: A_.literal(\"pcb_via_trace_clearance_error\"), pcb_via_trace_clearance_error_id: Cx(\"pcb_via_trace_clearance_error\"), error_type: A_.literal(\"pcb_via_trace_clearance_error\").default(\"pcb_via_trace_clearance_error\"), pcb_via_id: A_.string(), pcb_trace_id: A_.string(), minimum_clearance: px.optional(), actual_clearance: px.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a via and trace are closer than the allowed clearance\");\nvar zP = Wx.extend({ type: A_.literal(\"pcb_pad_pad_clearance_error\"), pcb_pad_pad_clearance_error_id: Cx(\"pcb_pad_pad_clearance_error\"), error_type: A_.literal(\"pcb_pad_pad_clearance_error\").default(\"pcb_pad_pad_clearance_error\"), pcb_pad_ids: A_.array(A_.string()).min(2), minimum_clearance: px.optional(), actual_clearance: px.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when pads are closer than the allowed clearance\");\nvar kP = Wx.extend({ type: A_.literal(\"pcb_pad_trace_clearance_error\"), pcb_pad_trace_clearance_error_id: Cx(\"pcb_pad_trace_clearance_error\"), error_type: A_.literal(\"pcb_pad_trace_clearance_error\").default(\"pcb_pad_trace_clearance_error\"), pcb_pad_id: A_.string(), pcb_trace_id: A_.string(), minimum_clearance: px.optional(), actual_clearance: px.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a pad and trace are closer than allowed clearance\");\nvar FP = A_.object({ type: A_.literal(\"pcb_courtyard_rect\"), pcb_courtyard_rect_id: Cx(\"pcb_courtyard_rect\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, layer: Vv, ccw_rotation: bx.optional(), color: A_.string().optional() }).describe(\"Defines a courtyard rectangle on the PCB\");\nvar jP = A_.object({ type: A_.literal(\"pcb_courtyard_outline\"), pcb_courtyard_outline_id: Cx(\"pcb_courtyard_outline\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, outline: A_.array(vx).min(2) }).describe(\"Defines a courtyard outline on the PCB\");\nvar YP = A_.object({ type: A_.literal(\"pcb_courtyard_polygon\"), pcb_courtyard_polygon_id: Cx(\"pcb_courtyard_polygon\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, points: A_.array(vx).min(3), color: A_.string().optional() }).describe(\"Defines a courtyard polygon on the PCB\");\nvar $P = A_.object({ type: A_.literal(\"pcb_courtyard_circle\"), pcb_courtyard_circle_id: Cx(\"pcb_courtyard_circle\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, radius: dx, layer: Vv, color: A_.string().optional() }).describe(\"Defines a courtyard circle on the PCB\");\nvar XP = A_.object({ type: A_.literal(\"pcb_courtyard_pill\"), pcb_courtyard_pill_id: Cx(\"pcb_courtyard_pill\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, radius: dx, layer: Vv, color: A_.string().optional() }).describe(\"Defines a courtyard pill on the PCB\");\nvar BP = [\"obj\", \"stl\", \"3mf\", \"gltf\", \"glb\", \"step\", \"wrl\"];\nvar HP = [\"x+\", \"x-\", \"y+\", \"y-\", \"z+\", \"z-\"];\nvar WP = { obj: \"z+\", stl: \"z+\", \"3mf\": \"z+\", gltf: \"y+\", glb: \"y+\", step: \"z+\", wrl: \"y+\" };\nvar VP = A_.object({ type: A_.literal(\"cad_component\"), cad_component_id: A_.string(), pcb_component_id: A_.string(), source_component_id: A_.string(), position: Ix, rotation: Ix.optional(), size: Ix.optional(), layer: Wv.optional(), subcircuit_id: A_.string().optional(), footprinter_string: A_.string().optional(), model_obj_url: A_.string().optional(), model_stl_url: A_.string().optional(), model_3mf_url: A_.string().optional(), model_gltf_url: A_.string().optional(), model_glb_url: A_.string().optional(), model_step_url: A_.string().optional(), model_wrl_url: A_.string().optional(), model_asset: Tx.optional(), model_unit_to_mm_scale_factor: A_.number().optional(), model_board_normal_direction: A_.enum(HP).optional().describe(`The direction in the model's coordinate space that is considered \"up\" or \"coming out of the board surface\"`), model_origin_position: Ix.optional(), model_origin_alignment: A_.enum([\"unknown\", \"center\", \"center_of_component_on_board_surface\", \"bottom_center_of_component\"]).optional(), model_object_fit: A_.enum([\"contain_within_bounds\", \"fill_bounds\"]).optional().default(\"contain_within_bounds\"), model_jscad: A_.any().optional(), show_as_translucent_model: A_.boolean().optional(), show_as_bounding_box: A_.boolean().optional(), anchor_alignment: A_.enum([\"center\", \"center_of_component_on_board_surface\"]).optional().default(\"center\") }).describe(\"Defines a component on the PCB\");\nvar UP = A_.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]);\nvar GP = A_.union([A_.string(), A_.number()]).transform((t48) =\u003e \"string\" == typeof t48 ? t48.endsWith(\"%\") ? parseFloat(t48.slice(0, -1)) / 100 : parseFloat(t48) : t48).pipe(A_.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar ZP = A_.object({ type: A_.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: Cx(\"simulation_voltage_source\"), is_dc_source: A_.literal(true).optional().default(true), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), voltage: hx }).describe(\"Defines a DC voltage source for simulation\");\nvar qP = A_.object({ type: A_.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: Cx(\"simulation_voltage_source\"), is_dc_source: A_.literal(false), terminal1_source_port_id: A_.string().optional(), terminal2_source_port_id: A_.string().optional(), terminal1_source_net_id: A_.string().optional(), terminal2_source_net_id: A_.string().optional(), voltage: hx.optional(), frequency: ux.optional(), peak_to_peak_voltage: hx.optional(), wave_shape: UP.optional(), phase: bx.optional(), duty_cycle: GP.optional(), pulse_delay: _x.optional(), rise_time: _x.optional(), fall_time: _x.optional(), pulse_width: _x.optional(), period: _x.optional() }).describe(\"Defines an AC voltage source for simulation\");\nvar JP = A_.union([ZP, qP]).describe(\"Defines a voltage source for simulation\");\nvar KP = A_.union([A_.string(), A_.number()]).transform((t48) =\u003e \"string\" == typeof t48 ? t48.endsWith(\"%\") ? parseFloat(t48.slice(0, -1)) / 100 : parseFloat(t48) : t48).pipe(A_.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar QP = A_.object({ type: A_.literal(\"simulation_current_source\"), simulation_current_source_id: Cx(\"simulation_current_source\"), is_dc_source: A_.literal(true).optional().default(true), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), current: mx }).describe(\"Defines a DC current source for simulation\");\nvar tM = A_.object({ type: A_.literal(\"simulation_current_source\"), simulation_current_source_id: Cx(\"simulation_current_source\"), is_dc_source: A_.literal(false), terminal1_source_port_id: A_.string().optional(), terminal2_source_port_id: A_.string().optional(), terminal1_source_net_id: A_.string().optional(), terminal2_source_net_id: A_.string().optional(), current: mx.optional(), frequency: ux.optional(), peak_to_peak_current: mx.optional(), wave_shape: UP.optional(), phase: bx.optional(), duty_cycle: KP.optional() }).describe(\"Defines an AC current source for simulation\");\nvar eM = A_.union([QP, tM]).describe(\"Defines a current source for simulation\");\nvar nM = A_.union([A_.literal(\"spice_dc_sweep\"), A_.literal(\"spice_dc_operating_point\"), A_.literal(\"spice_transient_analysis\"), A_.literal(\"spice_ac_analysis\")]);\nvar oM = A_.object({ method: A_.enum([\"trap\", \"gear\"]).optional(), reltol: A_.union([A_.number(), A_.string()]).optional(), abstol: A_.union([A_.number(), A_.string()]).optional(), vntol: A_.union([A_.number(), A_.string()]).optional() }).describe(\"SPICE solver options for a simulation experiment\");\nvar iM = A_.object({ type: A_.literal(\"simulation_experiment\"), simulation_experiment_id: Cx(\"simulation_experiment\"), name: A_.string(), experiment_type: nM, time_per_step: gx.optional(), start_time_ms: _x.optional(), end_time_ms: _x.optional(), spice_options: oM.optional() }).describe(\"Defines a simulation experiment configuration\");\nvar rM = A_.object({ type: A_.literal(\"simulation_transient_voltage_graph\"), simulation_transient_voltage_graph_id: Cx(\"simulation_transient_voltage_graph\"), simulation_experiment_id: A_.string(), timestamps_ms: A_.array(A_.number()).optional(), voltage_levels: A_.array(A_.number()), source_component_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), time_per_step: gx, start_time_ms: _x, end_time_ms: _x, name: A_.string().optional(), color: A_.string().optional() }).describe(\"Stores voltage measurements over time for a simulation\");\nvar sM = A_.object({ type: A_.literal(\"simulation_transient_current_graph\"), simulation_transient_current_graph_id: Cx(\"simulation_transient_current_graph\"), simulation_experiment_id: A_.string(), timestamps_ms: A_.array(A_.number()).optional(), current_levels: A_.array(A_.number()), source_component_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), time_per_step: gx, start_time_ms: _x, end_time_ms: _x, name: A_.string().optional(), color: A_.string().optional() }).describe(\"Stores current measurements over time for a simulation\");\nvar aM = A_.object({ type: A_.literal(\"simulation_switch\"), simulation_switch_id: Cx(\"simulation_switch\"), source_component_id: A_.string().optional(), closes_at: _x.optional(), opens_at: _x.optional(), starts_closed: A_.boolean().optional(), switching_frequency: ux.optional() }).describe(\"Defines a switch for simulation timing control\");\nvar cM = A_.object({ type: A_.literal(\"simulation_voltage_probe\"), simulation_voltage_probe_id: Cx(\"simulation_voltage_probe\"), source_component_id: A_.string().optional(), name: A_.string().optional(), signal_input_source_port_id: A_.string().optional(), signal_input_source_net_id: A_.string().optional(), reference_input_source_port_id: A_.string().optional(), reference_input_source_net_id: A_.string().optional(), subcircuit_id: A_.string().optional(), color: A_.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((t48, e2) =\u003e {\n if (t48.reference_input_source_port_id || t48.reference_input_source_net_id) {\n const n2 = !!t48.signal_input_source_port_id || !!t48.reference_input_source_port_id, o2 = !!t48.signal_input_source_net_id || !!t48.reference_input_source_net_id;\n n2 \u0026\u0026 o2 ? e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Cannot mix port and net connections in a differential probe.\" }) : n2 ? t48.signal_input_source_port_id \u0026\u0026 t48.reference_input_source_port_id || e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id.\" }) : o2 \u0026\u0026 (t48.signal_input_source_net_id \u0026\u0026 t48.reference_input_source_net_id || e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id.\" }));\n } else !!t48.signal_input_source_port_id == !!t48.signal_input_source_net_id \u0026\u0026 e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id.\" });\n});\nvar lM = A_.object({ type: A_.literal(\"simulation_current_probe\"), simulation_current_probe_id: Cx(\"simulation_current_probe\"), source_component_id: A_.string().optional(), name: A_.string().optional(), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), subcircuit_id: A_.string().optional(), color: A_.string().optional() }).describe(\"Defines a current probe for simulation. It measures current flowing from the positive endpoint to the negative endpoint.\").superRefine((t48, e2) =\u003e {\n const n2 = !!t48.positive_source_port_id, o2 = !!t48.negative_source_port_id, i2 = !!t48.positive_source_net_id, r2 = !!t48.negative_source_net_id, s2 = n2 || o2, a2 = i2 || r2;\n s2 \u0026\u0026 a2 ? e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Cannot mix port and net connections in a current probe.\" }) : s2 ? n2 \u0026\u0026 o2 || e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Current probe using source ports requires both positive_source_port_id and negative_source_port_id.\" }) : a2 ? i2 \u0026\u0026 r2 || e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Current probe using source nets requires both positive_source_net_id and negative_source_net_id.\" }) : e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"A current probe must have either positive/negative source port ids or positive/negative source net ids.\" });\n});\nvar hM = Wx.extend({ type: A_.literal(\"simulation_unknown_experiment_error\"), simulation_unknown_experiment_error_id: Cx(\"simulation_unknown_experiment_error\"), error_type: A_.literal(\"simulation_unknown_experiment_error\").default(\"simulation_unknown_experiment_error\"), simulation_experiment_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"An unknown error occurred during the simulation experiment.\");\nvar dM = A_.object({ type: A_.literal(\"simulation_op_amp\"), simulation_op_amp_id: Cx(\"simulation_op_amp\"), source_component_id: A_.string().optional(), inverting_input_source_port_id: A_.string(), non_inverting_input_source_port_id: A_.string(), output_source_port_id: A_.string(), positive_supply_source_port_id: A_.string(), negative_supply_source_port_id: A_.string() }).describe(\"Defines a simple ideal operational amplifier for simulation\");\nvar uM = A_.object({ type: A_.literal(\"simulation_spice_subcircuit\"), simulation_spice_subcircuit_id: Cx(\"simulation_spice_subcircuit\"), source_component_id: A_.string(), spice_pin_to_source_port_map: A_.record(A_.string(), A_.string()), subcircuit_source: A_.string() }).describe(\"Defines a custom SPICE subcircuit model for simulation\");\nvar pM = (t48) =\u003e void 0 !== t48;\nvar mM = A_.object({ type: A_.literal(\"simulation_oscilloscope_trace\"), simulation_oscilloscope_trace_id: Cx(\"simulation_oscilloscope_trace\"), simulation_transient_voltage_graph_id: A_.string().optional(), simulation_transient_current_graph_id: A_.string().optional(), simulation_voltage_probe_id: A_.string().optional(), simulation_current_probe_id: A_.string().optional(), display_name: A_.string().optional(), color: A_.string().optional(), display_center_value: A_.number().optional(), display_center_offset_divs: A_.number().optional(), volts_per_div: A_.number().positive().optional(), amps_per_div: A_.number().positive().optional() }).describe(\"Defines how a simulation measurement is rendered as an oscilloscope-style trace.\").superRefine((t48, e2) =\u003e {\n const n2 = [t48.simulation_transient_voltage_graph_id, t48.simulation_voltage_probe_id].filter(pM).length, o2 = [t48.simulation_transient_current_graph_id, t48.simulation_current_probe_id].filter(pM).length;\n n2 + o2 !== 1 \u0026\u0026 e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"An oscilloscope trace must reference exactly one voltage graph, current graph, voltage probe, or current probe.\" }), n2 \u003e 0 \u0026\u0026 void 0 !== t48.amps_per_div \u0026\u0026 e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Voltage oscilloscope traces must use volts_per_div, not amps_per_div.\" }), o2 \u003e 0 \u0026\u0026 void 0 !== t48.volts_per_div \u0026\u0026 e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Current oscilloscope traces must use amps_per_div, not volts_per_div.\" });\n});\nvar gM = A_.union([kv, Dv, zv, Lv, jv, Fv, tv, Gx, qx, Kx, Zx, ev, sv, av, dv, pv, mv, bv, gv, fv, _v, yv, lv, cv, Xv, Uv, Yv, xv, Iv, Pv, Cv, Gv, Nv, wv, Zv, qv, Jv, Kv, Qv, tS, Ev, Av, $v, jS, KS, pP, mP, gP, yP, xP, vP, rI, sP, sI, AI, xI, MI, CI, NI, OI, pI, bI, LI, DI, fP, FI, jI, YI, $I, GI, XI, BI, HI, WI, UI, wI, TI, zI, kI, RI, EI, LP, DP, zP, kP, qI, ZI, JI, KI, QI, tP, eP, nP, oP, _P, iP, rP, SP, uP, IP, PP, MP, RP, EP, AP, OP, FP, jP, YP, $P, XP, eS, fS, hS, dS, uS, pS, aS, lS, _S, mS, nS, bS, xS, yS, MS, CS, NS, wS, ES, TS, RS, VP, JP, eM, iM, rM, sM, aM, cM, lM, mM, hM, dM, uM]);\nvar fM = gM;\nfunction _M(t48, e2, n2) {\n if (!e2 || !n2) return;\n let o2 = t48.get(e2);\n o2 || (o2 = /* @__PURE__ */ new Set(), t48.set(e2, o2)), o2.add(n2);\n let i2 = t48.get(n2);\n i2 || (i2 = /* @__PURE__ */ new Set(), t48.set(n2, i2)), i2.add(e2);\n}\nvar yM = (t48, e2 = {}) =\u003e {\n const n2 = t48;\n let o2 = n2._internal_store;\n if (!o2) {\n o2 = { counts: {}, editCount: 0 }, n2._internal_store = o2;\n for (const t49 of n2) {\n const e3 = t49.type, n3 = t49[`${e3}_id`];\n if (!n3) continue;\n const i3 = Number.parseInt(n3.split(\"_\").pop());\n Number.isNaN(i3) || (o2.counts[e3] = Math.max(o2.counts[e3] ?? 0, i3));\n }\n }\n const i2 = new Proxy({}, { get: (t49, r2) =\u003e {\n if (\"toArray\" === r2) return () =\u003e (n2.editCount = o2.editCount, n2);\n if (\"editCount\" === r2) return o2.editCount;\n if (\"subtree\" === r2) return (t50) =\u003e yM((function(t51, e3) {\n if (!e3.subcircuit_id \u0026\u0026 !e3.source_group_id) return [...t51];\n let n3 = e3;\n if (e3.subcircuit_id) {\n const o4 = /* @__PURE__ */ new Set([e3.subcircuit_id]), i4 = /* @__PURE__ */ new Map(), r4 = /* @__PURE__ */ new Map();\n for (const e4 of t51) if (\"source_group\" === e4.type) {\n const t52 = e4.source_group_id, n4 = e4.subcircuit_id;\n n4 \u0026\u0026 r4.set(t52, n4);\n const o5 = e4.parent_source_group_id;\n o5 \u0026\u0026 (i4.has(o5) || i4.set(o5, []), i4.get(o5).push(t52));\n }\n let s4;\n for (const [t52, n4] of r4) if (n4 === e3.subcircuit_id) {\n s4 = t52;\n break;\n }\n if (s4) {\n const t52 = (e4) =\u003e {\n const n4 = i4.get(e4) || [];\n for (const e5 of n4) {\n const n5 = r4.get(e5);\n n5 \u0026\u0026 o4.add(n5), t52(e5);\n }\n };\n t52(s4), n3 = { ...e3, subcircuit_ids: Array.from(o4) };\n }\n }\n const o3 = /* @__PURE__ */ new Map();\n for (const e4 of t51) {\n const t52 = e4[`${e4.type}_id`];\n \"string\" == typeof t52 \u0026\u0026 o3.set(t52, e4);\n }\n const i3 = /* @__PURE__ */ new Map();\n for (const e4 of t51) {\n const t52 = Object.entries(e4);\n for (const [n4, r4] of t52) if (\"parent_source_group_id\" !== n4) {\n if (n4.endsWith(\"_id\") \u0026\u0026 \"string\" == typeof r4) _M(i3, e4, o3.get(r4));\n else if (n4.endsWith(\"_ids\") \u0026\u0026 Array.isArray(r4)) for (const t53 of r4) \"string\" == typeof t53 \u0026\u0026 _M(i3, e4, o3.get(t53));\n }\n }\n const r3 = [], s3 = /* @__PURE__ */ new Set();\n for (const e4 of t51) {\n let t52 = false;\n (n3.subcircuit_id \u0026\u0026 \"subcircuit_id\" in e4 \u0026\u0026 e4.subcircuit_id === n3.subcircuit_id || n3.subcircuit_ids \u0026\u0026 \"subcircuit_id\" in e4 \u0026\u0026 e4.subcircuit_id \u0026\u0026 n3.subcircuit_ids.includes(e4.subcircuit_id) || n3.source_group_id \u0026\u0026 \"source_group_id\" in e4 \u0026\u0026 e4.source_group_id === n3.source_group_id || n3.source_group_id \u0026\u0026 \"member_source_group_ids\" in e4 \u0026\u0026 Array.isArray(e4.member_source_group_ids) \u0026\u0026 e4.member_source_group_ids.includes(n3.source_group_id)) \u0026\u0026 (t52 = true), t52 \u0026\u0026 (r3.push(e4), s3.add(e4));\n }\n for (; r3.length \u003e 0; ) {\n const t52 = r3.shift(), e4 = i3.get(t52);\n if (e4) for (const t53 of e4) s3.has(t53) || (s3.add(t53), r3.push(t53));\n }\n return t51.filter((t52) =\u003e s3.has(t52));\n })(n2, t50), e2);\n if (\"insert\" === r2) return (t50) =\u003e {\n const i3 = t50.type;\n if (!i3) throw new Error(\"insert requires an element with a type\");\n o2.counts[i3] ??= -1, o2.counts[i3]++;\n const r3 = o2.counts[i3], s3 = { ...t50, type: i3, [`${i3}_id`]: `${i3}_${r3}` };\n if (e2.validateInserts) {\n (v_[i3] ?? fM).parse(s3);\n }\n return n2.push(s3), o2.editCount++, s3;\n };\n if (\"insertAll\" === r2) return (t50) =\u003e t50.map((t51) =\u003e i2.insert(t51));\n const s2 = r2;\n return { get: (t50) =\u003e n2.find((e3) =\u003e e3.type === s2 \u0026\u0026 e3[`${s2}_id`] === t50), getUsing: (t50) =\u003e {\n const e3 = Object.keys(t50);\n if (1 !== e3.length) throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");\n const o3 = e3[0], i3 = o3.replace(\"_id\", \"\"), r3 = n2.find((e4) =\u003e e4.type === i3 \u0026\u0026 e4[o3] === t50[o3]);\n return r3 ? n2.find((t51) =\u003e t51.type === s2 \u0026\u0026 t51[`${s2}_id`] === r3[`${s2}_id`]) : null;\n }, getWhere: (t50) =\u003e {\n const e3 = Object.keys(t50);\n return n2.find((n3) =\u003e n3.type === s2 \u0026\u0026 e3.every((e4) =\u003e n3[e4] === t50[e4]));\n }, list: (t50) =\u003e {\n const e3 = t50 ? Object.keys(t50) : [];\n return n2.filter((n3) =\u003e n3.type === s2 \u0026\u0026 e3.every((e4) =\u003e n3[e4] === t50[e4]));\n }, insert: (t50) =\u003e {\n o2.counts[s2] ??= -1, o2.counts[s2]++;\n const i3 = o2.counts[s2], r3 = { type: s2, [`${s2}_id`]: `${s2}_${i3}`, ...t50 };\n if (e2.validateInserts) {\n (v_[s2] ?? fM).parse(r3);\n }\n return n2.push(r3), o2.editCount++, r3;\n }, delete: (t50) =\u003e {\n const e3 = n2.find((e4) =\u003e e4[`${s2}_id`] === t50);\n e3 \u0026\u0026 (n2.splice(n2.indexOf(e3), 1), o2.editCount++);\n }, update: (t50, e3) =\u003e {\n const i3 = n2.find((e4) =\u003e e4.type === s2 \u0026\u0026 e4[`${s2}_id`] === t50);\n return i3 ? (Object.assign(i3, e3), o2.editCount++, i3) : null;\n }, select: (t50) =\u003e {\n if (\"source_component\" === s2) return n2.find((e3) =\u003e \"source_component\" === e3.type \u0026\u0026 e3.name === t50.replace(/\\./g, \"\"));\n if (\"pcb_port\" === s2 || \"source_port\" === s2 || \"schematic_port\" === s2) {\n const [e3, o3] = t50.replace(/\\./g, \"\").split(/[\\s\\\u003e]+/), i3 = n2.find((t51) =\u003e \"source_component\" === t51.type \u0026\u0026 t51.name === e3);\n if (!i3) return null;\n const r3 = n2.find((t51) =\u003e \"source_port\" === t51.type \u0026\u0026 t51.source_component_id === i3.source_component_id \u0026\u0026 (t51.name === o3 || (t51.port_hints ?? []).includes(o3)));\n if (!r3) return null;\n if (\"source_port\" === s2) return r3;\n if (\"pcb_port\" === s2) return n2.find((t51) =\u003e \"pcb_port\" === t51.type \u0026\u0026 t51.source_port_id === r3.source_port_id);\n if (\"schematic_port\" === s2) return n2.find((t51) =\u003e \"schematic_port\" === t51.type \u0026\u0026 t51.source_port_id === r3.source_port_id);\n }\n } };\n } });\n return i2;\n};\nyM.unparsed = yM;\nfunction xM(t48) {\n const e2 = t48.type;\n return `${e2}:${t48[`${e2}_id`]}`;\n}\nvar vM = (t48, e2 = {}) =\u003e {\n let n2 = t48._internal_store_indexed;\n if (!n2) {\n n2 = { counts: {}, editCount: 0, indexes: {} };\n for (const e3 of t48) {\n const t49 = e3.type, o3 = e3[`${t49}_id`];\n if (!o3) continue;\n const i3 = Number.parseInt(o3.split(\"_\").pop() || \"\");\n Number.isNaN(i3) || (n2.counts[t49] = Math.max(n2.counts[t49] ?? 0, i3));\n }\n const o2 = e2.indexConfig || {}, i2 = n2.indexes;\n if (o2.byId \u0026\u0026 (i2.byId = /* @__PURE__ */ new Map()), o2.byType \u0026\u0026 (i2.byType = /* @__PURE__ */ new Map()), o2.byRelation \u0026\u0026 (i2.byRelation = /* @__PURE__ */ new Map()), o2.bySubcircuit \u0026\u0026 (i2.bySubcircuit = /* @__PURE__ */ new Map()), o2.byCustomField \u0026\u0026 o2.byCustomField.length \u003e 0) {\n i2.byCustomField = /* @__PURE__ */ new Map();\n for (const t49 of o2.byCustomField) i2.byCustomField.set(t49, /* @__PURE__ */ new Map());\n }\n for (const e3 of t48) {\n if (o2.byId) {\n const t49 = xM(e3);\n i2.byId.set(t49, e3);\n }\n if (o2.byType) {\n const t49 = i2.byType.get(e3.type) || [];\n t49.push(e3), i2.byType.set(e3.type, t49);\n }\n if (o2.byRelation) {\n const t49 = Object.entries(e3);\n for (const [n3, o3] of t49) if (n3.endsWith(\"_id\") \u0026\u0026 n3 !== `${e3.type}_id` \u0026\u0026 \"string\" == typeof o3) {\n const t50 = i2.byRelation.get(n3) || /* @__PURE__ */ new Map(), r2 = t50.get(o3) || [];\n r2.push(e3), t50.set(o3, r2), i2.byRelation.set(n3, t50);\n }\n }\n if (o2.bySubcircuit \u0026\u0026 \"subcircuit_id\" in e3) {\n const t49 = e3.subcircuit_id;\n if (t49 \u0026\u0026 \"string\" == typeof t49) {\n const n3 = i2.bySubcircuit.get(t49) || [];\n n3.push(e3), i2.bySubcircuit.set(t49, n3);\n }\n }\n if (o2.byCustomField \u0026\u0026 i2.byCustomField) {\n for (const t49 of o2.byCustomField) if (t49 in e3) {\n const n3 = e3[t49];\n if (void 0 !== n3 \u0026\u0026 (\"string\" == typeof n3 || \"number\" == typeof n3)) {\n const o3 = String(n3), r2 = i2.byCustomField.get(t49), s2 = r2.get(o3) || [];\n s2.push(e3), r2.set(o3, s2);\n }\n }\n }\n }\n t48._internal_store_indexed = n2;\n }\n return new Proxy({}, { get: (o2, i2) =\u003e {\n if (\"toArray\" === i2) return () =\u003e (t48.editCount = n2.editCount, t48);\n if (\"editCount\" === i2) return n2.editCount;\n const r2 = i2;\n return { get: (o3) =\u003e {\n const i3 = e2.indexConfig || {};\n if (i3.byId \u0026\u0026 n2.indexes.byId) return n2.indexes.byId.get(`${r2}:${o3}`) || null;\n if (i3.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r2) || []).find((t49) =\u003e t49[`${r2}_id`] === o3) || null;\n }\n return t48.find((t49) =\u003e t49.type === r2 \u0026\u0026 t49[`${r2}_id`] === o3) || null;\n }, getUsing: (o3) =\u003e {\n const i3 = e2.indexConfig || {}, s2 = Object.keys(o3);\n if (1 !== s2.length) throw new Error(\"getUsing requires exactly one key, e.g. { pcb_component_id }\");\n const a2 = s2[0], c2 = a2.replace(\"_id\", \"\");\n if (i3.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const e3 = n2.indexes.byRelation.get(a2);\n if (e3) {\n const s3 = (e3.get(o3[a2]) || []).find((t49) =\u003e t49.type === c2);\n if (!s3) return null;\n const l3 = s3[`${r2}_id`];\n if (i3.byId \u0026\u0026 n2.indexes.byId) return n2.indexes.byId.get(`${r2}:${l3}`) || null;\n if (i3.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r2) || []).find((t49) =\u003e t49[`${r2}_id`] === l3) || null;\n }\n return t48.find((t49) =\u003e t49.type === r2 \u0026\u0026 t49[`${r2}_id`] === l3) || null;\n }\n }\n const l2 = t48.find((t49) =\u003e t49.type === c2 \u0026\u0026 t49[a2] === o3[a2]);\n return l2 \u0026\u0026 t48.find((t49) =\u003e t49.type === r2 \u0026\u0026 t49[`${r2}_id`] === l2[`${r2}_id`]) || null;\n }, getWhere: (o3) =\u003e {\n const i3 = e2.indexConfig || {}, s2 = Object.keys(o3);\n if (1 === s2.length \u0026\u0026 i3.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n const t49 = s2[0], e3 = n2.indexes.byCustomField.get(t49);\n if (e3) {\n const n3 = String(o3[t49]);\n return (e3.get(n3) || []).find((t50) =\u003e t50.type === r2) || null;\n }\n }\n if (\"subcircuit_id\" in o3 \u0026\u0026 i3.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit) {\n const t49 = o3.subcircuit_id;\n return (n2.indexes.bySubcircuit.get(t49) || []).find((t50) =\u003e t50.type === r2 \u0026\u0026 s2.every((e3) =\u003e t50[e3] === o3[e3])) || null;\n }\n if (i3.byType \u0026\u0026 n2.indexes.byType) {\n return (n2.indexes.byType.get(r2) || []).find((t49) =\u003e s2.every((e3) =\u003e t49[e3] === o3[e3])) || null;\n }\n return t48.find((t49) =\u003e t49.type === r2 \u0026\u0026 s2.every((e3) =\u003e t49[e3] === o3[e3])) || null;\n }, list: (o3) =\u003e {\n const i3 = e2.indexConfig || {}, s2 = o3 ? Object.keys(o3) : [];\n if (0 === s2.length \u0026\u0026 i3.byType \u0026\u0026 n2.indexes.byType) return n2.indexes.byType.get(r2) || [];\n if (1 === s2.length \u0026\u0026 \"subcircuit_id\" === s2[0] \u0026\u0026 i3.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit) {\n const t49 = o3.subcircuit_id;\n return (n2.indexes.bySubcircuit.get(t49) || []).filter((t50) =\u003e t50.type === r2);\n }\n let a2;\n return a2 = i3.byType \u0026\u0026 n2.indexes.byType ? n2.indexes.byType.get(r2) || [] : t48.filter((t49) =\u003e t49.type === r2), s2.length \u003e 0 ? a2.filter((t49) =\u003e s2.every((e3) =\u003e t49[e3] === o3[e3])) : a2;\n }, insert: (o3) =\u003e {\n n2.counts[r2] ??= -1, n2.counts[r2]++;\n const i3 = n2.counts[r2], s2 = { type: r2, [`${r2}_id`]: `${r2}_${i3}`, ...o3 };\n if (e2.validateInserts) {\n (v_[r2] ?? fM).parse(s2);\n }\n t48.push(s2), n2.editCount++;\n const a2 = e2.indexConfig || {};\n if (a2.byId \u0026\u0026 n2.indexes.byId) {\n const t49 = xM(s2);\n n2.indexes.byId.set(t49, s2);\n }\n if (a2.byType \u0026\u0026 n2.indexes.byType) {\n const t49 = n2.indexes.byType.get(r2) || [];\n t49.push(s2), n2.indexes.byType.set(r2, t49);\n }\n if (a2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const t49 = Object.entries(s2);\n for (const [e3, o4] of t49) if (e3.endsWith(\"_id\") \u0026\u0026 e3 !== `${s2.type}_id` \u0026\u0026 \"string\" == typeof o4) {\n const t50 = n2.indexes.byRelation.get(e3) || /* @__PURE__ */ new Map(), i4 = t50.get(o4) || [];\n i4.push(s2), t50.set(o4, i4), n2.indexes.byRelation.set(e3, t50);\n }\n }\n if (a2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in s2) {\n const t49 = s2.subcircuit_id;\n if (t49 \u0026\u0026 \"string\" == typeof t49) {\n const e3 = n2.indexes.bySubcircuit.get(t49) || [];\n e3.push(s2), n2.indexes.bySubcircuit.set(t49, e3);\n }\n }\n if (a2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const t49 of a2.byCustomField) if (t49 in s2) {\n const e3 = s2[t49];\n if (void 0 !== e3 \u0026\u0026 (\"string\" == typeof e3 || \"number\" == typeof e3)) {\n const o4 = String(e3), i4 = n2.indexes.byCustomField.get(t49), r3 = i4.get(o4) || [];\n r3.push(s2), i4.set(o4, r3);\n }\n }\n }\n return s2;\n }, delete: (o3) =\u003e {\n const i3 = e2.indexConfig || {};\n let s2;\n if (i3.byId \u0026\u0026 n2.indexes.byId) s2 = n2.indexes.byId.get(`${r2}:${o3}`);\n else if (i3.byType \u0026\u0026 n2.indexes.byType) {\n const t49 = n2.indexes.byType.get(r2) || [];\n s2 = t49.find((t50) =\u003e t50[`${r2}_id`] === o3);\n } else s2 = t48.find((t49) =\u003e t49[`${r2}_id`] === o3);\n if (!s2) return;\n const a2 = t48.indexOf(s2);\n if (a2 \u003e= 0 \u0026\u0026 (t48.splice(a2, 1), n2.editCount++), i3.byId \u0026\u0026 n2.indexes.byId) {\n const t49 = xM(s2);\n n2.indexes.byId.delete(t49);\n }\n if (i3.byType \u0026\u0026 n2.indexes.byType) {\n const t49 = (n2.indexes.byType.get(r2) || []).filter((t50) =\u003e t50[`${r2}_id`] !== o3);\n n2.indexes.byType.set(r2, t49);\n }\n if (i3.byRelation \u0026\u0026 n2.indexes.byRelation) for (const [t49, e3] of n2.indexes.byRelation.entries()) for (const [t50, n3] of e3.entries()) {\n const o4 = n3.filter((t51) =\u003e t51 !== s2);\n 0 === o4.length ? e3.delete(t50) : e3.set(t50, o4);\n }\n if (i3.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in s2) {\n const t49 = s2.subcircuit_id;\n if (t49) {\n const e3 = (n2.indexes.bySubcircuit.get(t49) || []).filter((t50) =\u003e t50 !== s2);\n 0 === e3.length ? n2.indexes.bySubcircuit.delete(t49) : n2.indexes.bySubcircuit.set(t49, e3);\n }\n }\n if (i3.byCustomField \u0026\u0026 n2.indexes.byCustomField) for (const t49 of n2.indexes.byCustomField.values()) for (const [e3, n3] of t49.entries()) {\n const o4 = n3.filter((t50) =\u003e t50 !== s2);\n 0 === o4.length ? t49.delete(e3) : t49.set(e3, o4);\n }\n }, update: (o3, i3) =\u003e {\n const s2 = e2.indexConfig || {};\n let a2;\n if (s2.byId \u0026\u0026 n2.indexes.byId) a2 = n2.indexes.byId.get(`${r2}:${o3}`);\n else if (s2.byType \u0026\u0026 n2.indexes.byType) {\n const t49 = n2.indexes.byType.get(r2) || [];\n a2 = t49.find((t50) =\u003e t50[`${r2}_id`] === o3);\n } else a2 = t48.find((t49) =\u003e t49.type === r2 \u0026\u0026 t49[`${r2}_id`] === o3);\n if (!a2) return null;\n if (s2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const t49 = Object.entries(a2);\n for (const [e3, o4] of t49) if (e3.endsWith(\"_id\") \u0026\u0026 e3 !== `${a2.type}_id` \u0026\u0026 \"string\" == typeof o4 \u0026\u0026 e3 in i3 \u0026\u0026 i3[e3] !== o4) {\n const t50 = n2.indexes.byRelation.get(e3);\n if (t50) {\n const e4 = (t50.get(o4) || []).filter((t51) =\u003e t51 !== a2);\n 0 === e4.length ? t50.delete(o4) : t50.set(o4, e4);\n }\n }\n }\n if (s2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in a2 \u0026\u0026 \"subcircuit_id\" in i3) {\n const t49 = a2.subcircuit_id;\n if (t49 !== i3.subcircuit_id) {\n const e3 = (n2.indexes.bySubcircuit.get(t49) || []).filter((t50) =\u003e t50 !== a2);\n 0 === e3.length ? n2.indexes.bySubcircuit.delete(t49) : n2.indexes.bySubcircuit.set(t49, e3);\n }\n }\n if (s2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const t49 of s2.byCustomField) if (t49 in a2 \u0026\u0026 t49 in i3 \u0026\u0026 a2[t49] !== i3[t49]) {\n const e3 = n2.indexes.byCustomField.get(t49);\n if (e3) {\n const n3 = String(a2[t49]), o4 = (e3.get(n3) || []).filter((t50) =\u003e t50 !== a2);\n 0 === o4.length ? e3.delete(n3) : e3.set(n3, o4);\n }\n }\n }\n if (Object.assign(a2, i3), n2.editCount++, s2.byRelation \u0026\u0026 n2.indexes.byRelation) {\n const t49 = Object.entries(a2);\n for (const [e3, o4] of t49) if (e3.endsWith(\"_id\") \u0026\u0026 e3 !== `${a2.type}_id` \u0026\u0026 \"string\" == typeof o4 \u0026\u0026 e3 in i3) {\n const t50 = n2.indexes.byRelation.get(e3) || /* @__PURE__ */ new Map(), i4 = t50.get(o4) || [];\n i4.includes(a2) || (i4.push(a2), t50.set(o4, i4), n2.indexes.byRelation.set(e3, t50));\n }\n }\n if (s2.bySubcircuit \u0026\u0026 n2.indexes.bySubcircuit \u0026\u0026 \"subcircuit_id\" in a2 \u0026\u0026 \"subcircuit_id\" in i3) {\n const t49 = a2.subcircuit_id;\n if (t49 \u0026\u0026 \"string\" == typeof t49) {\n const e3 = n2.indexes.bySubcircuit.get(t49) || [];\n e3.includes(a2) || (e3.push(a2), n2.indexes.bySubcircuit.set(t49, e3));\n }\n }\n if (s2.byCustomField \u0026\u0026 n2.indexes.byCustomField) {\n for (const t49 of s2.byCustomField) if (t49 in a2 \u0026\u0026 t49 in i3) {\n const e3 = a2[t49];\n if (void 0 !== e3 \u0026\u0026 (\"string\" == typeof e3 || \"number\" == typeof e3)) {\n const o4 = String(e3), i4 = n2.indexes.byCustomField.get(t49), r3 = i4.get(o4) || [];\n r3.includes(a2) || (r3.push(a2), i4.set(o4, r3));\n }\n }\n }\n return a2;\n }, select: (e3) =\u003e {\n if (\"source_component\" === r2) return t48.find((t49) =\u003e \"source_component\" === t49.type \u0026\u0026 t49.name === e3.replace(/\\./g, \"\")) || null;\n if (\"pcb_port\" === r2 || \"source_port\" === r2 || \"schematic_port\" === r2) {\n const [n3, o3] = e3.replace(/\\./g, \"\").split(/[\\s\\\u003e]+/), i3 = t48.find((t49) =\u003e \"source_component\" === t49.type \u0026\u0026 t49.name === n3);\n if (!i3) return null;\n const s2 = t48.find((t49) =\u003e \"source_port\" === t49.type \u0026\u0026 t49.source_component_id === i3.source_component_id \u0026\u0026 (t49.name === o3 || (t49.port_hints ?? []).includes(o3)));\n if (!s2) return null;\n if (\"source_port\" === r2) return s2;\n if (\"pcb_port\" === r2) return t48.find((t49) =\u003e \"pcb_port\" === t49.type \u0026\u0026 t49.source_port_id === s2.source_port_id) || null;\n if (\"schematic_port\" === r2) return t48.find((t49) =\u003e \"schematic_port\" === t49.type \u0026\u0026 t49.source_port_id === s2.source_port_id) || null;\n }\n return null;\n } };\n } });\n};\nvM.unparsed = vM;\nvar EM = { Hz: { baseUnit: \"Hz\", variants: { MHz: 1e6, kHz: 1e3, Hz: 1 } }, g: { baseUnit: \"g\", variants: { kg: 1e3, g: 1 } }, \"\\u03A9\": { baseUnit: \"\\u03A9\", variants: { \"m\\u03A9\": 1e-3, \"\\u03A9\": 1, \"k\\u03A9\": 1e3, \"K\\u03A9\": 1e3, kohm: 1e3, \"M\\u03A9\": 1e6, \"G\\u03A9\": 1e9, \"T\\u03A9\": 1e12 } }, V: { baseUnit: \"V\", variants: { mV: 1e-3, V: 1, kV: 1e3, KV: 1e3, MV: 1e6, GV: 1e9, TV: 1e12 } }, A: { baseUnit: \"A\", variants: { \"\\xB5A\": 1e-6, mA: 1e-3, ma: 1e-3, A: 1, kA: 1e3, MA: 1e6 } }, F: { baseUnit: \"F\", variants: { pF: 1e-12, nF: 1e-9, \"\\xB5F\": 1e-6, uF: 1e-6, mF: 1e-3, 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: 1e-3, \"\\xB5s\": 1e-3, ms: 1, s: 1e3 } }, mm: { baseUnit: \"mm\", variants: { nm: 1e-6, \"\\xB5m\": 1e-3, um: 1e-3, 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: 0.0254 } } };\nvar AM = /* @__PURE__ */ new Set();\nfor (const [t48, e2] of Object.entries(EM)) {\n AM.add(t48);\n for (const t49 of Object.keys(e2.variants)) AM.add(t49);\n}\nvar OM = { tera: 1e12, T: 1e12, giga: 1e9, G: 1e9, mega: 1e6, M: 1e6, kilo: 1e3, k: 1e3, deci: 0.1, d: 0.1, centi: 0.01, c: 0.01, milli: 1e-3, m: 1e-3, micro: 1e-6, u: 1e-6, \"\\xB5\": 1e-6, nano: 1e-9, n: 1e-9, pico: 1e-12, p: 1e-12 };\nfunction LM(t48) {\n if (null == t48) return { parsedUnit: null, unitOfValue: null, value: null };\n if (\"string\" == typeof t48 \u0026\u0026 t48.match(/^-?[\\d\\.]+$/)) return { value: Number.parseFloat(t48), parsedUnit: null, unitOfValue: null };\n if (\"number\" == typeof t48) return { value: t48, parsedUnit: null, unitOfValue: null };\n if (\"object\" == typeof t48 \u0026\u0026 \"x\" in t48 \u0026\u0026 \"y\" in t48) {\n const { parsedUnit: e3, unitOfValue: n3 } = LM(t48.x), o3 = LM(t48.x), i3 = LM(t48.y);\n return null === o3.value || null === i3.value ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: e3, unitOfValue: n3, value: { x: o3.value, y: i3.value } };\n }\n const e2 = t48.toString().split(\"\").reverse().join(\"\"), n2 = e2.match(/[^\\d\\s]+/)?.[0];\n if (!n2) throw new Error(`Could not determine unit: \"${t48}\"`);\n const o2 = n2.split(\"\").reverse().join(\"\"), i2 = t48.slice(0, -o2.length);\n if (o2 in OM \u0026\u0026 !AM.has(o2)) {\n const t49 = OM[o2];\n return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(i2) * t49 };\n }\n const { baseUnit: r2, conversionFactor: s2 } = (function(t49) {\n for (const [e3, n3] of Object.entries(EM)) if (t49 in n3.variants) return { baseUnit: n3.baseUnit, conversionFactor: n3.variants[t49] };\n return { baseUnit: t49, conversionFactor: 1 };\n })(o2);\n return { parsedUnit: o2, unitOfValue: r2, value: s2 * Number.parseFloat(i2) };\n}\nvar DM = A_.string().or(A_.number()).transform((t48) =\u003e LM(t48).value);\nvar zM = A_.string().or(A_.number()).transform((t48) =\u003e LM(t48).value).transform((t48) =\u003e Number.parseFloat(t48.toPrecision(12)));\nvar kM = A_.string().or(A_.number()).transform((t48) =\u003e LM(t48).value);\nvar FM = A_.string().or(A_.number()).transform((t48) =\u003e LM(t48).value);\nvar jM = A_.string().or(A_.number()).transform((t48) =\u003e LM(t48).value);\nvar YM = A_.string().or(A_.number()).transform((t48) =\u003e LM(t48).value);\nvar $M = jM;\nvar XM = A_.string().or(A_.number()).transform((t48) =\u003e LM(t48).value);\nvar BM = A_.string().or(A_.number()).transform((t48) =\u003e LM(t48).value);\nvar HM = BM;\nvar WM = A_.string().datetime();\nvar VM = A_.string().or(A_.number()).transform((t48) =\u003e \"number\" == typeof t48 ? t48 : t48.endsWith(\"deg\") ? Number.parseFloat(t48.split(\"deg\")[0]) : t48.endsWith(\"rad\") ? 180 * Number.parseFloat(t48.split(\"rad\")[0]) / Math.PI : Number.parseFloat(t48));\nvar UM = A_.number().or(A_.string().endsWith(\"mAh\")).transform((t48) =\u003e {\n if (\"string\" == typeof t48) {\n const e2 = t48.replace(\"mAh\", \"\"), n2 = Number.parseFloat(e2);\n if (Number.isNaN(n2)) throw new Error(\"Invalid capacity\");\n return n2;\n }\n return t48;\n}).describe(\"Battery capacity in mAh\");\nvar GM = A_.object({ x: $M, y: $M });\nvar ZM = A_.object({ x: $M, y: $M, z: $M });\nvar qM = A_.object({ width: A_.number(), height: A_.number() });\nvar JM = (t48) =\u003e A_.string().optional().default(() =\u003e `${t48}_${((t49) =\u003e {\n const e2 = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\";\n return Array.from({ length: t49 }, () =\u003e e2[Math.floor(62 * Math.random())]).join(\"\");\n})(10)}`);\nvar KM = A_.enum([\"top_left\", \"top_center\", \"top_right\", \"center_left\", \"center\", \"center_right\", \"bottom_left\", \"bottom_center\", \"bottom_right\"]);\nvar QM = (A_.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\"]), A_.object({ project_relative_path: A_.string(), url: A_.string(), mimetype: A_.string() }));\nvar tC = GM.extend({ rotation: VM.optional() });\nvar eC = A_.object({ size: GM.optional(), thickness: $M.optional() });\nvar nC = A_.object({ font: eC.optional() });\nvar oC = A_.object({ value: A_.string(), at: tC.optional(), layer: A_.string().optional(), uuid: A_.string().optional(), hide: A_.boolean().optional(), effects: nC.optional() });\nvar iC = A_.object({ Reference: oC.optional(), Value: oC.optional(), Datasheet: oC.optional(), Description: oC.optional() });\nvar rC = A_.object({ through_hole: A_.boolean().optional(), smd: A_.boolean().optional(), exclude_from_pos_files: A_.boolean().optional(), exclude_from_bom: A_.boolean().optional() });\nvar sC = A_.object({ name: A_.string(), type: A_.string(), shape: A_.string().optional(), at: tC.optional(), size: GM.optional(), drill: $M.optional(), layers: A_.array(A_.string()).optional(), removeUnusedLayers: A_.boolean().optional(), uuid: A_.string().optional() });\nvar aC = A_.object({ path: A_.string(), offset: ZM.optional(), scale: ZM.optional(), rotate: ZM.optional() });\nvar cC = A_.object({ footprintName: A_.string().optional(), version: A_.union([A_.number(), A_.string()]).optional(), generator: A_.string().optional(), generatorVersion: A_.union([A_.number(), A_.string()]).optional(), layer: A_.string().optional(), properties: iC.optional(), attributes: rC.optional(), pads: A_.array(sC).optional(), embeddedFonts: A_.boolean().optional(), model: aC.optional() });\nvar lC = A_.object({ hide: A_.boolean().optional() });\nvar hC = A_.object({ offset: $M.optional(), hide: A_.boolean().optional() });\nvar dC = A_.object({ font: eC.optional(), justify: A_.union([A_.string(), A_.array(A_.string())]).optional(), hide: A_.boolean().optional() });\nvar uC = A_.object({ value: A_.string(), id: A_.union([A_.number(), A_.string()]).optional(), at: tC.optional(), effects: dC.optional() });\nvar pC = A_.object({ Reference: uC.optional(), Value: uC.optional(), Footprint: uC.optional(), Datasheet: uC.optional(), Description: uC.optional(), ki_keywords: uC.optional(), ki_fp_filters: uC.optional() });\nvar mC = A_.object({ symbolName: A_.string().optional(), extends: A_.string().optional(), pinNumbers: lC.optional(), pinNames: hC.optional(), excludeFromSim: A_.boolean().optional(), inBom: A_.boolean().optional(), onBoard: A_.boolean().optional(), properties: pC.optional(), embeddedFonts: A_.boolean().optional() });\nvar gC = A_.object({ error_type: A_.string(), message: A_.string(), is_fatal: A_.boolean().optional() });\nvar fC = A_.enum([\"jlcpcb\", \"macrofab\", \"pcbway\", \"digikey\", \"mouser\", \"lcsc\"]);\nvar _C = A_.object({ type: A_.literal(\"source_component\"), ftype: A_.string().optional(), source_component_id: A_.string(), name: A_.string(), manufacturer_part_number: A_.string().optional(), supplier_part_numbers: A_.record(fC, A_.array(A_.string())).optional(), display_value: A_.string().optional(), display_name: A_.string().optional(), are_pins_interchangeable: A_.boolean().optional(), internally_connected_source_port_ids: A_.array(A_.array(A_.string())).optional(), source_group_id: A_.string().optional(), subcircuit_id: A_.string().optional() });\nvar yC = _C.extend({ ftype: A_.literal(\"simple_capacitor\"), capacitance: zM, max_voltage_rating: FM.optional(), display_capacitance: A_.string().optional(), max_decoupling_trace_length: $M.optional() });\nvar bC = _C.extend({ ftype: A_.literal(\"simple_resistor\"), resistance: DM, display_resistance: A_.string().optional() });\nvar xC = _C.extend({ ftype: A_.literal(\"simple_diode\") });\nvar vC = _C.extend({ ftype: A_.literal(\"simple_fiducial\") });\nvar SC = xC.extend({ ftype: A_.literal(\"simple_led\"), color: A_.string().optional(), wavelength: A_.string().optional() });\nvar IC = _C.extend({ ftype: A_.literal(\"simple_ground\") });\nvar PC = _C.extend({ ftype: A_.literal(\"simple_chip\") });\nvar MC = _C.extend({ ftype: A_.literal(\"simple_power_source\"), voltage: FM });\nvar CC = _C.extend({ ftype: A_.literal(\"simple_current_source\"), current: XM, frequency: YM.optional(), peak_to_peak_current: XM.optional(), wave_shape: A_.enum([\"sine\", \"square\", \"triangle\", \"sawtooth\", \"dc\"]).optional().default(\"dc\"), phase: A_.number().optional(), duty_cycle: A_.number().min(0).max(1).optional() });\nvar NC = A_.object({ must_be_connected: A_.boolean().optional(), provides_power: A_.boolean().optional(), requires_power: A_.boolean().optional(), provides_ground: A_.boolean().optional(), requires_ground: A_.boolean().optional(), provides_voltage: A_.union([A_.string(), A_.number()]).optional(), requires_voltage: A_.union([A_.string(), A_.number()]).optional(), do_not_connect: A_.boolean().optional(), include_in_board_pinout: A_.boolean().optional(), can_use_internal_pullup: A_.boolean().optional(), is_using_internal_pullup: A_.boolean().optional(), needs_external_pullup: A_.boolean().optional(), can_use_internal_pulldown: A_.boolean().optional(), is_using_internal_pulldown: A_.boolean().optional(), needs_external_pulldown: A_.boolean().optional(), can_use_open_drain: A_.boolean().optional(), is_using_open_drain: A_.boolean().optional(), can_use_push_pull: A_.boolean().optional(), is_using_push_pull: A_.boolean().optional(), should_have_decoupling_capacitor: A_.boolean().optional(), recommended_decoupling_capacitor_capacitance: A_.union([A_.string(), A_.number()]).optional(), is_configured_for_i2c_sda: A_.boolean().optional(), is_configured_for_i2c_scl: A_.boolean().optional(), is_configured_for_spi_mosi: A_.boolean().optional(), is_configured_for_spi_miso: A_.boolean().optional(), is_configured_for_spi_sck: A_.boolean().optional(), is_configured_for_spi_cs: A_.boolean().optional(), is_configured_for_uart_tx: A_.boolean().optional(), is_configured_for_uart_rx: A_.boolean().optional(), supports_i2c_sda: A_.boolean().optional(), supports_i2c_scl: A_.boolean().optional(), supports_spi_mosi: A_.boolean().optional(), supports_spi_miso: A_.boolean().optional(), supports_spi_sck: A_.boolean().optional(), supports_spi_cs: A_.boolean().optional(), supports_uart_tx: A_.boolean().optional(), supports_uart_rx: A_.boolean().optional() });\nvar wC = _C.extend({ ftype: A_.literal(\"simple_fuse\"), current_rating_amps: A_.number().describe(\"Nominal current in amps the fuse is rated for\"), voltage_rating_volts: A_.number().describe(\"Voltage rating in volts, e.g. \\xB15V would be 5\") });\nvar TC = _C.extend({ ftype: A_.literal(\"simple_battery\"), capacity: UM });\nvar RC = _C.extend({ ftype: A_.literal(\"simple_inductor\"), inductance: kM, display_inductance: A_.string().optional(), max_current_rating: A_.number().optional() });\nvar EC = _C.extend({ ftype: A_.literal(\"simple_push_button\") });\nvar AC = _C.extend({ ftype: A_.literal(\"simple_potentiometer\"), max_resistance: DM, display_max_resistance: A_.string().optional() });\nvar OC = _C.extend({ ftype: A_.literal(\"simple_crystal\"), frequency: A_.number().describe(\"Frequency in Hz\"), load_capacitance: A_.number().optional().describe(\"Load capacitance in pF\"), pin_variant: A_.enum([\"two_pin\", \"four_pin\"]).optional() });\nvar LC = _C.extend({ ftype: A_.literal(\"simple_pin_header\"), pin_count: A_.number(), gender: A_.enum([\"male\", \"female\"]).optional().default(\"male\") });\nvar DC = _C.extend({ ftype: A_.literal(\"simple_connector\"), standard: A_.enum([\"usb_c\", \"m2\"]).optional() });\nvar zC = _C.extend({ ftype: A_.literal(\"simple_pinout\") });\nvar kC = _C.extend({ ftype: A_.literal(\"simple_resonator\"), load_capacitance: zM, equivalent_series_resistance: DM.optional(), frequency: YM });\nvar FC = _C.extend({ ftype: A_.literal(\"simple_transistor\"), transistor_type: A_.enum([\"npn\", \"pnp\"]) });\nvar jC = _C.extend({ ftype: A_.literal(\"simple_test_point\"), footprint_variant: A_.enum([\"pad\", \"through_hole\"]).optional(), pad_shape: A_.enum([\"rect\", \"circle\"]).optional(), pad_diameter: A_.union([A_.number(), A_.string()]).optional(), hole_diameter: A_.union([A_.number(), A_.string()]).optional(), width: A_.union([A_.number(), A_.string()]).optional(), height: A_.union([A_.number(), A_.string()]).optional() });\nvar YC = _C.extend({ ftype: A_.literal(\"simple_mosfet\"), channel_type: A_.enum([\"n\", \"p\"]), mosfet_mode: A_.enum([\"enhancement\", \"depletion\"]) });\nvar $C = _C.extend({ ftype: A_.literal(\"simple_op_amp\") });\nvar XC = _C.extend({ ftype: A_.literal(\"simple_switch\") });\nvar BC = A_.object({ type: A_.literal(\"source_project_metadata\"), name: A_.string().optional(), software_used_string: A_.string().optional(), project_url: A_.string().optional(), created_at: WM.optional() });\nvar HC = gC.extend({ type: A_.literal(\"source_missing_property_error\"), source_missing_property_error_id: JM(\"source_missing_property_error\"), source_component_id: A_.string(), property_name: A_.string(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"source_missing_property_error\").default(\"source_missing_property_error\") }).describe(\"The source code is missing a property\");\nvar WC = gC.extend({ type: A_.literal(\"source_failed_to_create_component_error\"), source_failed_to_create_component_error_id: JM(\"source_failed_to_create_component_error\"), error_type: A_.literal(\"source_failed_to_create_component_error\").default(\"source_failed_to_create_component_error\"), component_name: A_.string().optional(), subcircuit_id: A_.string().optional(), parent_source_component_id: A_.string().optional(), pcb_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), schematic_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional() }).describe(\"Error emitted when a component fails to be constructed\");\nvar VC = gC.extend({ type: A_.literal(\"source_invalid_component_property_error\"), source_invalid_component_property_error_id: JM(\"source_invalid_component_property_error\"), source_component_id: A_.string(), property_name: A_.string(), property_value: A_.unknown().optional(), expected_format: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"source_invalid_component_property_error\").default(\"source_invalid_component_property_error\") }).describe(\"The source component property is invalid\");\nvar UC = gC.extend({ type: A_.literal(\"source_trace_not_connected_error\"), source_trace_not_connected_error_id: JM(\"source_trace_not_connected_error\"), error_type: A_.literal(\"source_trace_not_connected_error\").default(\"source_trace_not_connected_error\"), subcircuit_id: A_.string().optional(), source_group_id: A_.string().optional(), source_trace_id: A_.string().optional(), connected_source_port_ids: A_.array(A_.string()).optional(), selectors_not_found: A_.array(A_.string()).optional() }).describe(\"Occurs when a source trace selector does not match any ports\");\nvar GC = A_.object({ type: A_.literal(\"source_property_ignored_warning\"), source_property_ignored_warning_id: JM(\"source_property_ignored_warning\"), source_component_id: A_.string(), property_name: A_.string(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"source_property_ignored_warning\").default(\"source_property_ignored_warning\"), message: A_.string() }).describe(\"The source property was ignored\");\nvar ZC = A_.object({ type: A_.literal(\"source_pin_missing_trace_warning\"), source_pin_missing_trace_warning_id: JM(\"source_pin_missing_trace_warning\"), warning_type: A_.literal(\"source_pin_missing_trace_warning\").default(\"source_pin_missing_trace_warning\"), message: A_.string(), source_component_id: A_.string(), source_port_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a source component pin is missing a trace connection\");\nvar qC = A_.object({ type: A_.literal(\"source_missing_manufacturer_part_number_warning\"), source_missing_manufacturer_part_number_warning_id: JM(\"source_missing_manufacturer_part_number_warning\"), warning_type: A_.literal(\"source_missing_manufacturer_part_number_warning\").default(\"source_missing_manufacturer_part_number_warning\"), message: A_.string(), source_component_id: A_.string(), standard: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a standard connector is missing manufacturer part number\");\nvar JC = _C.extend({ ftype: A_.literal(\"simple_voltage_probe\") });\nvar KC = _C.extend({ ftype: A_.literal(\"interconnect\") });\nvar QC = gC.extend({ type: A_.literal(\"source_i2c_misconfigured_error\"), source_i2c_misconfigured_error_id: JM(\"source_i2c_misconfigured_error\"), error_type: A_.literal(\"source_i2c_misconfigured_error\").default(\"source_i2c_misconfigured_error\"), source_port_ids: A_.array(A_.string()) }).describe(\"Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net\");\nvar tN = _C.extend({ ftype: A_.literal(\"simple_voltage_source\"), voltage: FM, frequency: YM.optional(), peak_to_peak_voltage: FM.optional(), wave_shape: A_.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]).optional(), phase: VM.optional(), duty_cycle: A_.number().optional().describe(\"Duty cycle as a fraction (0 to 1)\") });\nvar eN = A_.union([bC, yC, xC, vC, SC, IC, PC, MC, CC, TC, RC, EC, AC, OC, LC, DC, zC, kC, XC, FC, jC, YC, $C, wC, JC, KC, tN, BC, HC, VC, WC, UC, GC, ZC, qC, QC]);\nvar nN = A_.object({ type: A_.literal(\"source_port\"), pin_number: A_.number().optional(), port_hints: A_.array(A_.string()).optional(), name: A_.string(), source_port_id: A_.string(), source_component_id: A_.string().optional(), source_group_id: A_.string().optional(), most_frequently_referenced_by_name: A_.string().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() }).merge(NC);\nvar oN = A_.object({ type: A_.literal(\"source_component_internal_connection\"), source_component_internal_connection_id: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() });\nvar iN = A_.object({ type: A_.literal(\"source_trace\"), source_trace_id: A_.string(), connected_source_port_ids: A_.array(A_.string()), connected_source_net_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), max_length: A_.number().optional(), min_trace_thickness: A_.number().optional(), display_name: A_.string().optional() });\nvar rN = A_.object({ type: A_.literal(\"source_group\"), source_group_id: A_.string(), subcircuit_id: A_.string().optional(), parent_subcircuit_id: A_.string().optional(), parent_source_group_id: A_.string().optional(), is_subcircuit: A_.boolean().optional(), show_as_schematic_box: A_.boolean().optional(), name: A_.string().optional(), was_automatically_named: A_.boolean().optional() });\nvar sN = A_.object({ type: A_.literal(\"source_net\"), source_net_id: A_.string(), name: A_.string(), member_source_group_ids: A_.array(A_.string()), is_power: A_.boolean().optional(), is_ground: A_.boolean().optional(), is_digital_signal: A_.boolean().optional(), is_analog_signal: A_.boolean().optional(), is_positive_voltage_source: A_.boolean().optional(), trace_width: A_.number().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() });\nvar aN = A_.object({ type: A_.literal(\"source_board\"), source_board_id: A_.string(), source_group_id: A_.string(), title: A_.string().optional() }).describe(\"Defines a board in the source domain\");\nvar cN = gC.extend({ type: A_.literal(\"source_ambiguous_port_reference\"), source_ambiguous_port_reference_id: JM(\"source_ambiguous_port_reference\"), error_type: A_.literal(\"source_ambiguous_port_reference\").default(\"source_ambiguous_port_reference\"), source_port_id: A_.string().optional(), source_component_id: A_.string().optional() }).describe(\"Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous\");\nvar lN = A_.object({ type: A_.literal(\"source_pcb_ground_plane\"), source_pcb_ground_plane_id: A_.string(), source_group_id: A_.string(), source_net_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Defines a ground plane in the source domain\");\nvar hN = [\"top\", \"bottom\", \"inner1\", \"inner2\", \"inner3\", \"inner4\", \"inner5\", \"inner6\"];\nvar dN = A_.enum(hN);\nvar uN = dN.or(A_.object({ name: dN })).transform((t48) =\u003e \"string\" == typeof t48 ? t48 : t48.name);\nvar pN = A_.enum([\"top\", \"bottom\"]);\nvar mN = A_.object({ type: A_.literal(\"source_manually_placed_via\"), source_manually_placed_via_id: A_.string(), source_group_id: A_.string(), source_net_id: A_.string(), subcircuit_id: A_.string().optional(), source_trace_id: A_.string().optional() }).describe(\"Defines a via that is manually placed in the source domain\");\nvar gN = A_.object({ type: A_.literal(\"source_no_power_pin_defined_warning\"), source_no_power_pin_defined_warning_id: JM(\"source_no_power_pin_defined_warning\"), warning_type: A_.literal(\"source_no_power_pin_defined_warning\").default(\"source_no_power_pin_defined_warning\"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a chip has no source ports with requires_power=true\");\nvar fN = A_.object({ type: A_.literal(\"source_no_ground_pin_defined_warning\"), source_no_ground_pin_defined_warning_id: JM(\"source_no_ground_pin_defined_warning\"), warning_type: A_.literal(\"source_no_ground_pin_defined_warning\").default(\"source_no_ground_pin_defined_warning\"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when a chip has no source ports marked as ground pins\");\nvar _N = A_.object({ type: A_.literal(\"source_component_pins_underspecified_warning\"), source_component_pins_underspecified_warning_id: JM(\"source_component_pins_underspecified_warning\"), warning_type: A_.literal(\"source_component_pins_underspecified_warning\").default(\"source_component_pins_underspecified_warning\"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Warning emitted when all ports on a source component are underspecified\");\nvar yN = gC.extend({ type: A_.literal(\"source_pin_must_be_connected_error\"), source_pin_must_be_connected_error_id: JM(\"source_pin_must_be_connected_error\"), error_type: A_.literal(\"source_pin_must_be_connected_error\").default(\"source_pin_must_be_connected_error\"), source_component_id: A_.string(), source_port_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a pin with mustBeConnected attribute is not connected to any trace\");\nvar bN = gC.extend({ type: A_.literal(\"unknown_error_finding_part\"), unknown_error_finding_part_id: JM(\"unknown_error_finding_part\"), error_type: A_.literal(\"unknown_error_finding_part\").default(\"unknown_error_finding_part\"), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when an unexpected error occurs while finding a part\");\nvar xN = A_.object({ type: A_.literal(\"schematic_box\"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), width: $M, height: $M, is_dashed: A_.boolean().default(false), x: $M, y: $M, subcircuit_id: A_.string().optional() }).describe(\"Draws a box on the schematic\");\nvar vN = A_.object({ type: A_.literal(\"schematic_path\"), schematic_path_id: JM(\"schematic_path\"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), fill_color: A_.string().optional(), is_filled: A_.boolean().optional(), stroke_width: $M.nullable().optional(), stroke_color: A_.string().optional(), points: A_.array(GM), subcircuit_id: A_.string().optional() });\nvar SN = A_.record(A_.object({ left_margin: jM.optional(), right_margin: jM.optional(), top_margin: jM.optional(), bottom_margin: jM.optional() }));\nvar IN = A_.object({ left_size: A_.number(), right_size: A_.number(), top_size: A_.number().optional(), bottom_size: A_.number().optional() });\nvar PN = A_.object({ left_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), right_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum([\"top-to-bottom\", \"bottom-to-top\"]).optional() }).optional(), top_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional(), bottom_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum([\"left-to-right\", \"right-to-left\"]).optional() }).optional() });\nvar MN = A_.union([IN, PN]);\nvar CN = A_.object({ type: A_.literal(\"schematic_component\"), size: qM, center: GM, source_component_id: A_.string().optional(), schematic_component_id: A_.string(), schematic_symbol_id: A_.string().optional(), pin_spacing: jM.optional(), pin_styles: SN.optional(), box_width: jM.optional(), symbol_name: A_.string().optional(), port_arrangement: MN.optional(), port_labels: A_.record(A_.string()).optional(), symbol_display_value: A_.string().optional(), subcircuit_id: A_.string().optional(), schematic_group_id: A_.string().optional(), is_schematic_group: A_.boolean().optional(), source_group_id: A_.string().optional(), is_box_with_pins: A_.boolean().optional().default(true) });\nvar NN = A_.object({ kicad_symbol: mC.optional() }).catchall(A_.unknown());\nvar wN = A_.object({ type: A_.literal(\"schematic_symbol\"), schematic_symbol_id: A_.string(), name: A_.string().optional(), metadata: NN.optional() }).describe(\"Defines a named schematic symbol that can be referenced by components.\");\nvar TN = A_.object({ type: A_.literal(\"schematic_line\"), schematic_line_id: JM(\"schematic_line\"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), x1: $M, y1: $M, x2: $M, y2: $M, stroke_width: $M.nullable().optional(), color: A_.string().default(\"#000000\"), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe(\"Draws a styled line on the schematic\");\nvar RN = A_.object({ type: A_.literal(\"schematic_rect\"), schematic_rect_id: JM(\"schematic_rect\"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: GM, width: $M, height: $M, rotation: VM.default(0), stroke_width: $M.nullable().optional(), color: A_.string().default(\"#000000\"), is_filled: A_.boolean().default(false), fill_color: A_.string().optional(), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe(\"Draws a styled rectangle on the schematic\");\nvar EN = A_.object({ type: A_.literal(\"schematic_circle\"), schematic_circle_id: JM(\"schematic_circle\"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: GM, radius: $M, stroke_width: $M.nullable().optional(), color: A_.string().default(\"#000000\"), is_filled: A_.boolean().default(false), fill_color: A_.string().optional(), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe(\"Draws a styled circle on the schematic\");\nvar AN = A_.object({ type: A_.literal(\"schematic_arc\"), schematic_arc_id: JM(\"schematic_arc\"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: GM, radius: $M, start_angle_degrees: VM, end_angle_degrees: VM, direction: A_.enum([\"clockwise\", \"counterclockwise\"]).default(\"counterclockwise\"), stroke_width: $M.nullable().optional(), color: A_.string().default(\"#000000\"), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe(\"Draws a styled arc on the schematic\");\nvar ON = A_.object({ type: A_.literal(\"schematic_trace\"), schematic_trace_id: A_.string(), source_trace_id: A_.string().optional(), junctions: A_.array(A_.object({ x: A_.number(), y: A_.number() })), edges: A_.array(A_.object({ from: A_.object({ x: A_.number(), y: A_.number() }), to: A_.object({ x: A_.number(), y: A_.number() }), is_crossing: A_.boolean().optional(), from_schematic_port_id: A_.string().optional(), to_schematic_port_id: A_.string().optional() })), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() });\nvar LN = A_.enum([\"center\", \"left\", \"right\", \"top\", \"bottom\"]);\nvar DN = A_.object({ type: A_.literal(\"schematic_text\"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), schematic_text_id: A_.string(), text: A_.string(), font_size: A_.number().default(0.18), position: A_.object({ x: $M, y: $M }), rotation: A_.number().default(0), anchor: A_.union([LN.describe(\"legacy\"), KM]).default(\"center\"), color: A_.string().default(\"#000000\"), subcircuit_id: A_.string().optional() });\nvar zN = A_.object({ type: A_.literal(\"schematic_port\"), schematic_port_id: A_.string(), source_port_id: A_.string(), schematic_component_id: A_.string().optional(), center: GM, facing_direction: A_.enum([\"up\", \"down\", \"left\", \"right\"]).optional(), distance_from_component_edge: A_.number().optional(), side_of_component: A_.enum([\"top\", \"bottom\", \"left\", \"right\"]).optional(), true_ccw_index: A_.number().optional(), pin_number: A_.number().optional(), display_pin_label: A_.string().optional(), subcircuit_id: A_.string().optional(), is_connected: A_.boolean().optional(), has_input_arrow: A_.boolean().optional(), has_output_arrow: A_.boolean().optional(), is_drawn_with_inversion_circle: A_.boolean().optional() }).describe(\"Defines a port on a schematic component\");\nvar kN = A_.object({ type: A_.literal(\"schematic_net_label\"), schematic_net_label_id: JM(\"schematic_net_label\"), schematic_trace_id: A_.string().optional(), source_trace_id: A_.string().optional(), source_net_id: A_.string(), center: GM, anchor_position: GM.optional(), anchor_side: A_.enum([\"top\", \"bottom\", \"left\", \"right\"]), text: A_.string(), symbol_name: A_.string().optional(), is_movable: A_.boolean().optional(), subcircuit_id: A_.string().optional() });\nvar FN = gC.extend({ type: A_.literal(\"schematic_error\"), schematic_error_id: A_.string(), error_type: A_.literal(\"schematic_port_not_found\").default(\"schematic_port_not_found\"), subcircuit_id: A_.string().optional() }).describe(\"Defines a schematic error on the schematic\");\nvar jN = gC.extend({ type: A_.literal(\"schematic_layout_error\"), schematic_layout_error_id: JM(\"schematic_layout_error\"), error_type: A_.literal(\"schematic_layout_error\").default(\"schematic_layout_error\"), source_group_id: A_.string(), schematic_group_id: A_.string(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when schematic layout fails for a group\");\nvar YN = A_.object({ type: A_.literal(\"schematic_debug_object\"), label: A_.string().optional(), subcircuit_id: A_.string().optional() });\nvar $N = YN.extend({ shape: A_.literal(\"rect\"), center: GM, size: qM });\nvar XN = YN.extend({ shape: A_.literal(\"line\"), start: GM, end: GM });\nvar BN = YN.extend({ shape: A_.literal(\"point\"), center: GM });\nvar HN = A_.discriminatedUnion(\"shape\", [$N, XN, BN]);\nvar WN = A_.object({ type: A_.literal(\"schematic_voltage_probe\"), schematic_voltage_probe_id: A_.string(), source_component_id: A_.string().optional(), name: A_.string().optional(), position: GM, schematic_trace_id: A_.string(), voltage: FM.optional(), subcircuit_id: A_.string().optional(), color: A_.string().optional(), label_alignment: KM.optional() }).describe(\"Defines a voltage probe measurement point on a schematic trace\");\nvar VN = A_.object({ type: A_.literal(\"schematic_manual_edit_conflict_warning\"), schematic_manual_edit_conflict_warning_id: JM(\"schematic_manual_edit_conflict_warning\"), warning_type: A_.literal(\"schematic_manual_edit_conflict_warning\").default(\"schematic_manual_edit_conflict_warning\"), message: A_.string(), schematic_component_id: A_.string(), schematic_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_component_id: A_.string() }).describe(\"Warning emitted when a component has both manual placement and explicit schX/schY coordinates\");\nvar UN = A_.object({ type: A_.literal(\"schematic_group\"), schematic_group_id: JM(\"schematic_group\"), source_group_id: A_.string(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), width: jM, height: jM, center: GM, schematic_component_ids: A_.array(A_.string()), show_as_schematic_box: A_.boolean().optional(), name: A_.string().optional(), description: A_.string().optional() }).describe(\"Defines a group of components on the schematic\");\nvar GN = A_.object({ type: A_.literal(\"schematic_table\"), schematic_table_id: JM(\"schematic_table\"), anchor_position: GM, column_widths: A_.array($M), row_heights: A_.array($M), cell_padding: $M.optional(), border_width: $M.optional(), subcircuit_id: A_.string().optional(), schematic_component_id: A_.string().optional(), anchor: KM.optional() }).describe(\"Defines a table on the schematic\");\nvar ZN = A_.object({ type: A_.literal(\"schematic_table_cell\"), schematic_table_cell_id: JM(\"schematic_table_cell\"), schematic_table_id: A_.string(), start_row_index: A_.number(), end_row_index: A_.number(), start_column_index: A_.number(), end_column_index: A_.number(), text: A_.string().optional(), center: GM, width: $M, height: $M, horizontal_align: A_.enum([\"left\", \"center\", \"right\"]).optional(), vertical_align: A_.enum([\"top\", \"middle\", \"bottom\"]).optional(), font_size: $M.optional(), subcircuit_id: A_.string().optional() }).describe(\"Defines a cell within a schematic_table\");\nvar qN = A_.object({ type: A_.literal(\"schematic_sheet\"), schematic_sheet_id: JM(\"schematic_sheet\"), name: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Defines a schematic sheet or page that components can be placed on\");\nvar JN = A_.object({ x: $M, y: $M, bulge: A_.number().optional() });\nvar KN = A_.object({ vertices: A_.array(JN) });\nvar QN = A_.object({ outer_ring: KN, inner_rings: A_.array(KN).default([]) });\nvar tw = A_.object({ x: $M, y: $M, via: A_.boolean().optional(), via_to_layer: uN.optional() });\nvar ew = (A_.array(tw), A_.object({ x: $M, y: $M, via: A_.boolean().optional(), to_layer: uN.optional(), trace_width: $M.optional() }));\nvar nw = A_.object({ min_trace_width: jM.optional(), min_board_edge_clearance: jM.optional(), min_via_hole_edge_to_via_hole_edge_clearance: jM.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: jM.optional(), min_trace_to_pad_edge_clearance: jM.optional(), min_pad_edge_to_pad_edge_clearance: jM.optional(), min_same_net_trace_edge_to_trace_edge_clearance: jM.optional(), min_different_net_trace_edge_to_trace_edge_clearance: jM.optional(), min_via_hole_diameter: jM.optional(), min_via_pad_diameter: jM.optional() });\nvar ow = A_.object({ type: A_.literal(\"pcb_component\"), pcb_component_id: JM(\"pcb_component\"), source_component_id: A_.string(), center: GM, layer: uN, rotation: VM, display_offset_x: A_.string().optional().describe(\"How to display the x offset for this part, usually corresponding with how the user specified it\"), display_offset_y: A_.string().optional().describe(\"How to display the y offset for this part, usually corresponding with how the user specified it\"), width: jM, height: jM, do_not_place: A_.boolean().optional(), is_allowed_to_be_off_board: A_.boolean().optional(), subcircuit_id: A_.string().optional(), pcb_group_id: A_.string().optional(), position_mode: A_.enum([\"packed\", \"relative_to_group_anchor\", \"relative_to_another_component\", \"none\"]).optional(), anchor_position: GM.optional(), anchor_alignment: KM.optional(), positioned_relative_to_pcb_group_id: A_.string().optional(), positioned_relative_to_pcb_board_id: A_.string().optional(), cable_insertion_center: GM.optional(), insertion_direction: A_.enum([\"from_above\", \"from_left\", \"from_right\", \"from_front\", \"from_back\"]).optional(), metadata: A_.object({ kicad_footprint: cC.optional() }).optional(), obstructs_within_bounds: A_.boolean().default(true).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\");\nvar iw = A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: JM(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"circle\"), hole_diameter: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar rw = (iw.describe(\"Defines a circular hole on the PCB\"), A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: JM(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"rect\"), hole_width: A_.number(), hole_height: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));\nvar sw = (rw.describe(\"Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.\"), A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: JM(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.enum([\"circle\", \"square\"]), hole_diameter: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));\nvar aw = (sw.describe(\"Defines a circular or square hole on the PCB\"), A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: JM(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"oval\"), hole_width: A_.number(), hole_height: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));\nvar cw = (aw.describe(\"Defines an oval hole on the PCB\"), A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: JM(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"pill\"), hole_width: A_.number(), hole_height: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));\nvar lw = (cw.describe(\"Defines a pill-shaped hole on the PCB\"), A_.object({ type: A_.literal(\"pcb_hole\"), pcb_hole_id: JM(\"pcb_hole\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal(\"rotated_pill\"), hole_width: A_.number(), hole_height: A_.number(), x: $M, y: $M, ccw_rotation: VM, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));\nvar hw = (lw.describe(\"Defines a rotated pill-shaped hole on the PCB\"), sw.or(aw).or(cw).or(lw).or(iw).or(rw));\nvar dw = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"circle\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), outer_diameter: A_.number(), hole_diameter: A_.number(), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional() });\nvar uw = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.enum([\"oval\", \"pill\"]), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), outer_width: A_.number(), outer_height: A_.number(), hole_width: A_.number(), hole_height: A_.number(), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, ccw_rotation: VM, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional() });\nvar pw = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"circular_hole_with_rect_pad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal(\"circle\"), pad_shape: A_.literal(\"rect\"), hole_diameter: A_.number(), rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), hole_offset_x: $M.default(0), hole_offset_y: $M.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional(), rect_ccw_rotation: VM.optional() });\nvar mw = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"pill_hole_with_rect_pad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal(\"pill\"), pad_shape: A_.literal(\"rect\"), hole_width: A_.number(), hole_height: A_.number(), rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), hole_offset_x: $M.default(0), hole_offset_y: $M.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional() });\nvar gw = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"rotated_pill_hole_with_rect_pad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal(\"rotated_pill\"), pad_shape: A_.literal(\"rect\"), hole_width: A_.number(), hole_height: A_.number(), hole_ccw_rotation: VM, rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), rect_ccw_rotation: VM, hole_offset_x: $M.default(0), hole_offset_y: $M.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional() });\nvar fw = A_.object({ type: A_.literal(\"pcb_plated_hole\"), shape: A_.literal(\"hole_with_polygon_pad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.enum([\"circle\", \"oval\", \"pill\", \"rotated_pill\"]), hole_diameter: A_.number().optional(), hole_width: A_.number().optional(), hole_height: A_.number().optional(), pad_outline: A_.array(A_.object({ x: $M, y: $M })).min(3), hole_offset_x: $M.default(0), hole_offset_y: $M.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM(\"pcb_plated_hole\"), soldermask_margin: A_.number().optional(), ccw_rotation: VM.optional() });\nvar _w = A_.union([dw, uw, pw, mw, gw, fw]);\nvar yw = A_.object({ type: A_.literal(\"pcb_port\"), pcb_port_id: JM(\"pcb_port\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_port_id: A_.string(), pcb_component_id: A_.string().optional(), x: $M, y: $M, layers: A_.array(uN), is_board_pinout: A_.boolean().optional() }).describe(\"Defines a port on the PCB\");\nvar bw = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"circle\"), pcb_smtpad_id: JM(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, radius: A_.number(), layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar xw = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"rect\"), pcb_smtpad_id: JM(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), rect_border_radius: A_.number().optional(), corner_radius: A_.number().optional(), layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional(), soldermask_margin_left: A_.number().optional(), soldermask_margin_top: A_.number().optional(), soldermask_margin_right: A_.number().optional(), soldermask_margin_bottom: A_.number().optional() });\nvar vw = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"rotated_rect\"), pcb_smtpad_id: JM(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), rect_border_radius: A_.number().optional(), corner_radius: A_.number().optional(), ccw_rotation: VM, layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional(), soldermask_margin_left: A_.number().optional(), soldermask_margin_top: A_.number().optional(), soldermask_margin_right: A_.number().optional(), soldermask_margin_bottom: A_.number().optional() });\nvar Sw = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"pill\"), pcb_smtpad_id: JM(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), radius: A_.number(), layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar Iw = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"rotated_pill\"), pcb_smtpad_id: JM(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), radius: A_.number(), ccw_rotation: VM, layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar Pw = A_.object({ type: A_.literal(\"pcb_smtpad\"), shape: A_.literal(\"polygon\"), pcb_smtpad_id: JM(\"pcb_smtpad\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), points: A_.array(GM), layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });\nvar Mw = A_.discriminatedUnion(\"shape\", [bw, xw, vw, Iw, Sw, Pw]).describe(\"Defines an SMT pad on the PCB\");\nvar Cw = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"circle\"), pcb_solder_paste_id: JM(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, radius: A_.number(), layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar Nw = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"rect\"), pcb_solder_paste_id: JM(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar ww = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"pill\"), pcb_solder_paste_id: JM(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), radius: A_.number(), layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar Tw = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"rotated_rect\"), pcb_solder_paste_id: JM(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), ccw_rotation: $M, layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar Rw = A_.object({ type: A_.literal(\"pcb_solder_paste\"), shape: A_.literal(\"oval\"), pcb_solder_paste_id: JM(\"pcb_solder_paste\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });\nvar Ew = A_.union([Cw, Nw, ww, Tw, Rw]).describe(\"Defines solderpaste on the PCB\");\nvar Aw = A_.object({ type: A_.literal(\"pcb_text\"), pcb_text_id: JM(\"pcb_text\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), text: A_.string(), center: GM, layer: uN, width: jM, height: jM, lines: A_.number(), align: A_.enum([\"bottom-left\"]) }).describe(\"Defines text on the PCB\");\nvar Ow = A_.object({ route_type: A_.literal(\"wire\"), x: $M, y: $M, width: $M, copper_pour_id: A_.string().optional(), is_inside_copper_pour: A_.boolean().optional(), start_pcb_port_id: A_.string().optional(), end_pcb_port_id: A_.string().optional(), layer: uN });\nvar Lw = A_.object({ route_type: A_.literal(\"via\"), x: $M, y: $M, copper_pour_id: A_.string().optional(), is_inside_copper_pour: A_.boolean().optional(), hole_diameter: $M.optional(), outer_diameter: $M.optional(), from_layer: uN, to_layer: uN });\nvar Dw = A_.union([Ow, Lw]);\nvar zw = A_.object({ type: A_.literal(\"pcb_trace\"), source_trace_id: A_.string().optional(), pcb_component_id: A_.string().optional(), pcb_trace_id: JM(\"pcb_trace\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), route_thickness_mode: A_.enum([\"constant\", \"interpolated\"]).default(\"constant\").optional(), route_order_index: A_.number().optional(), should_round_corners: A_.boolean().optional(), trace_length: A_.number().optional(), highlight_color: A_.string().optional(), route: A_.array(Dw) }).describe(\"Defines a trace on the PCB\");\nvar kw = A_.object({ type: A_.literal(\"pcb_trace_warning\"), pcb_trace_warning_id: JM(\"pcb_trace_warning\"), warning_type: A_.literal(\"pcb_trace_warning\").default(\"pcb_trace_warning\"), message: A_.string(), center: GM.optional(), pcb_trace_id: A_.string(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines a trace warning on the PCB\");\nvar Fw = gC.extend({ type: A_.literal(\"pcb_trace_error\"), pcb_trace_error_id: JM(\"pcb_trace_error\"), error_type: A_.literal(\"pcb_trace_error\").default(\"pcb_trace_error\"), center: GM.optional(), pcb_trace_id: A_.string(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines a trace error on the PCB\");\nvar jw = gC.extend({ type: A_.literal(\"pcb_trace_missing_error\"), pcb_trace_missing_error_id: JM(\"pcb_trace_missing_error\"), error_type: A_.literal(\"pcb_trace_missing_error\").default(\"pcb_trace_missing_error\"), center: GM.optional(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines an error when a source trace has no corresponding PCB trace\");\nvar Yw = gC.extend({ type: A_.literal(\"pcb_port_not_matched_error\"), pcb_error_id: JM(\"pcb_error\"), error_type: A_.literal(\"pcb_port_not_matched_error\").default(\"pcb_port_not_matched_error\"), pcb_component_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines a trace error on the PCB where a port is not matched\");\nvar $w = gC.extend({ type: A_.literal(\"pcb_port_not_connected_error\"), pcb_port_not_connected_error_id: JM(\"pcb_port_not_connected_error\"), error_type: A_.literal(\"pcb_port_not_connected_error\").default(\"pcb_port_not_connected_error\"), pcb_port_ids: A_.array(A_.string()), pcb_component_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe(\"Defines an error when a pcb port is not connected to any trace\");\nvar Xw = A_.object({ type: A_.literal(\"pcb_net\"), pcb_net_id: JM(\"pcb_net\"), source_net_id: A_.string().optional(), highlight_color: A_.string().optional() }).describe(\"Defines a net on the PCB\");\nvar Bw = A_.object({ type: A_.literal(\"pcb_via\"), pcb_via_id: JM(\"pcb_via\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), x: $M, y: $M, outer_diameter: $M.default(\"0.6mm\"), hole_diameter: $M.default(\"0.25mm\"), from_layer: uN.optional(), to_layer: uN.optional(), layers: A_.array(uN), pcb_trace_id: A_.string().optional(), net_is_assignable: A_.boolean().optional(), net_assigned: A_.boolean().optional(), is_tented: A_.boolean().optional() }).describe(\"Defines a via on the PCB\");\nvar Hw = A_.object({ type: A_.literal(\"pcb_board\"), pcb_board_id: JM(\"pcb_board\"), pcb_panel_id: A_.string().optional(), carrier_pcb_board_id: A_.string().optional(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), is_mounted_to_carrier_board: A_.boolean().optional(), width: jM.optional(), height: jM.optional(), center: GM, display_offset_x: A_.string().optional().describe(\"How to display the x offset for this board, usually corresponding with how the user specified it\"), display_offset_y: A_.string().optional().describe(\"How to display the y offset for this board, usually corresponding with how the user specified it\"), thickness: jM.optional().default(1.4), num_layers: A_.number().optional().default(4), outline: A_.array(GM).optional(), shape: A_.enum([\"rect\", \"polygon\"]).optional(), material: A_.enum([\"fr4\", \"fr1\"]).default(\"fr4\"), anchor_position: GM.optional(), anchor_alignment: KM.optional(), position_mode: A_.enum([\"relative_to_panel_anchor\", \"none\"]).optional() }).merge(nw).describe(\"Defines the board outline of the PCB\");\nvar Ww = A_.object({ type: A_.literal(\"pcb_panel\"), pcb_panel_id: JM(\"pcb_panel\"), width: jM, height: jM, center: GM, thickness: jM.optional().default(1.4), covered_with_solder_mask: A_.boolean().optional().default(true) }).describe(\"Defines a PCB panel that can contain multiple boards\");\nvar Vw = gC.extend({ type: A_.literal(\"pcb_placement_error\"), pcb_placement_error_id: JM(\"pcb_placement_error\"), error_type: A_.literal(\"pcb_placement_error\").default(\"pcb_placement_error\"), subcircuit_id: A_.string().optional() }).describe(\"Defines a placement error on the PCB\");\nvar Uw = gC.extend({ type: A_.literal(\"pcb_panelization_placement_error\"), pcb_panelization_placement_error_id: JM(\"pcb_panelization_placement_error\"), error_type: A_.literal(\"pcb_panelization_placement_error\").default(\"pcb_panelization_placement_error\"), pcb_panel_id: A_.string().optional(), pcb_board_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Defines a panelization placement error on the PCB\");\nvar Gw = A_.object({ type: A_.literal(\"pcb_trace_hint\"), pcb_trace_hint_id: JM(\"pcb_trace_hint\"), pcb_port_id: A_.string(), pcb_component_id: A_.string(), route: A_.array(ew), subcircuit_id: A_.string().optional() }).describe(\"A hint that can be used during generation of a PCB trace\");\nvar Zw = A_.object({ type: A_.literal(\"pcb_silkscreen_line\"), pcb_silkscreen_line_id: JM(\"pcb_silkscreen_line\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), stroke_width: $M.default(\"0.1mm\"), x1: $M, y1: $M, x2: $M, y2: $M, layer: pN }).describe(\"Defines a silkscreen line on the PCB\");\nvar qw = A_.object({ type: A_.literal(\"pcb_silkscreen_path\"), pcb_silkscreen_path_id: JM(\"pcb_silkscreen_path\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: pN, route: A_.array(GM), stroke_width: jM }).describe(\"Defines a silkscreen path on the PCB\");\nvar Jw = A_.object({ type: A_.literal(\"pcb_silkscreen_text\"), pcb_silkscreen_text_id: JM(\"pcb_silkscreen_text\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: $M.default(\"0.2mm\"), pcb_component_id: A_.string(), text: A_.string(), is_knockout: A_.boolean().default(false).optional(), knockout_padding: A_.object({ left: jM, top: jM, bottom: jM, right: jM }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: A_.number().optional(), layer: uN, is_mirrored: A_.boolean().default(false).optional(), anchor_position: GM.default({ x: 0, y: 0 }), anchor_alignment: KM.default(\"center\") }).describe(\"Defines silkscreen text on the PCB\");\nvar Kw = A_.object({ type: A_.literal(\"pcb_copper_text\"), pcb_copper_text_id: JM(\"pcb_copper_text\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: $M.default(\"0.2mm\"), pcb_component_id: A_.string(), text: A_.string(), is_knockout: A_.boolean().default(false).optional(), knockout_padding: A_.object({ left: jM, top: jM, bottom: jM, right: jM }).default({ left: \"0.2mm\", top: \"0.2mm\", bottom: \"0.2mm\", right: \"0.2mm\" }).optional(), ccw_rotation: A_.number().optional(), layer: uN, is_mirrored: A_.boolean().default(false).optional(), anchor_position: GM.default({ x: 0, y: 0 }), anchor_alignment: KM.default(\"center\") }).describe(\"Defines copper text on the PCB\");\nvar Qw = A_.object({ type: A_.literal(\"pcb_silkscreen_rect\"), pcb_silkscreen_rect_id: JM(\"pcb_silkscreen_rect\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: jM, height: jM, layer: uN, stroke_width: jM.default(\"1mm\"), corner_radius: jM.optional(), is_filled: A_.boolean().default(true).optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), ccw_rotation: A_.number().optional() }).describe(\"Defines a silkscreen rect on the PCB\");\nvar tT = A_.object({ type: A_.literal(\"pcb_silkscreen_circle\"), pcb_silkscreen_circle_id: JM(\"pcb_silkscreen_circle\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, radius: jM, layer: pN, stroke_width: jM.default(\"1mm\"), is_filled: A_.boolean().optional() }).describe(\"Defines a silkscreen circle on the PCB\");\nvar eT = A_.object({ type: A_.literal(\"pcb_silkscreen_oval\"), pcb_silkscreen_oval_id: JM(\"pcb_silkscreen_oval\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, radius_x: $M, radius_y: $M, layer: pN, ccw_rotation: VM.optional() }).describe(\"Defines a silkscreen oval on the PCB\");\nvar nT = A_.object({ type: A_.literal(\"pcb_silkscreen_pill\"), pcb_silkscreen_pill_id: JM(\"pcb_silkscreen_pill\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: jM, height: jM, layer: uN, ccw_rotation: A_.number().optional() }).describe(\"Defines a silkscreen pill on the PCB\");\nvar oT = A_.object({ type: A_.literal(\"pcb_fabrication_note_text\"), pcb_fabrication_note_text_id: JM(\"pcb_fabrication_note_text\"), subcircuit_id: A_.string().optional(), pcb_group_id: A_.string().optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: $M.default(\"1mm\"), pcb_component_id: A_.string(), text: A_.string(), layer: pN, anchor_position: GM.default({ x: 0, y: 0 }), anchor_alignment: A_.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), color: A_.string().optional() }).describe(\"Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators\");\nvar iT = A_.object({ type: A_.literal(\"pcb_fabrication_note_path\"), pcb_fabrication_note_path_id: JM(\"pcb_fabrication_note_path\"), pcb_component_id: A_.string(), subcircuit_id: A_.string().optional(), layer: uN, route: A_.array(GM), stroke_width: jM, color: A_.string().optional() }).describe(\"Defines a fabrication path on the PCB for fabricators or assemblers\");\nvar rT = A_.object({ type: A_.literal(\"pcb_fabrication_note_rect\"), pcb_fabrication_note_rect_id: JM(\"pcb_fabrication_note_rect\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: jM, height: jM, layer: pN, stroke_width: jM.default(\"0.1mm\"), corner_radius: jM.optional(), is_filled: A_.boolean().optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), color: A_.string().optional() }).describe(\"Defines a fabrication note rectangle on the PCB\");\nvar sT = A_.object({ type: A_.literal(\"pcb_fabrication_note_dimension\"), pcb_fabrication_note_dimension_id: JM(\"pcb_fabrication_note_dimension\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: pN, from: GM, to: GM, text: A_.string().optional(), text_ccw_rotation: A_.number().optional(), offset: jM.optional(), offset_distance: jM.optional(), offset_direction: A_.object({ x: A_.number(), y: A_.number() }).optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: jM.default(\"1mm\"), color: A_.string().optional(), arrow_size: jM.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB fabrication notes\");\nvar aT = A_.object({ type: A_.literal(\"pcb_note_text\"), pcb_note_text_id: JM(\"pcb_note_text\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: $M.default(\"1mm\"), text: A_.string().optional(), anchor_position: GM.default({ x: 0, y: 0 }), anchor_alignment: A_.enum([\"center\", \"top_left\", \"top_right\", \"bottom_left\", \"bottom_right\"]).default(\"center\"), layer: pN.default(\"top\"), is_mirrored_from_top_view: A_.boolean().optional(), color: A_.string().optional() }).describe(\"Defines a documentation note in text on the PCB\");\nvar cT = A_.object({ type: A_.literal(\"pcb_note_rect\"), pcb_note_rect_id: JM(\"pcb_note_rect\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), center: GM, width: jM, height: jM, layer: pN.default(\"top\"), stroke_width: jM.default(\"0.1mm\"), corner_radius: jM.optional(), is_filled: A_.boolean().optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), color: A_.string().optional() }).describe(\"Defines a rectangular documentation note on the PCB\");\nvar lT = A_.object({ type: A_.literal(\"pcb_note_path\"), pcb_note_path_id: JM(\"pcb_note_path\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), route: A_.array(GM), layer: pN.default(\"top\"), stroke_width: jM.default(\"0.1mm\"), color: A_.string().optional() }).describe(\"Defines a polyline documentation note on the PCB\");\nvar hT = A_.object({ type: A_.literal(\"pcb_note_line\"), pcb_note_line_id: JM(\"pcb_note_line\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), x1: $M, y1: $M, x2: $M, y2: $M, layer: pN.default(\"top\"), stroke_width: $M.default(\"0.1mm\"), color: A_.string().optional(), is_dashed: A_.boolean().optional() }).describe(\"Defines a straight documentation note line on the PCB\");\nvar dT = A_.object({ type: A_.literal(\"pcb_note_dimension\"), pcb_note_dimension_id: JM(\"pcb_note_dimension\"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), from: GM, to: GM, text: A_.string().optional(), text_ccw_rotation: A_.number().optional(), offset_distance: jM.optional(), offset_direction: A_.object({ x: A_.number(), y: A_.number() }).optional(), font: A_.literal(\"tscircuit2024\").default(\"tscircuit2024\"), font_size: jM.default(\"1mm\"), layer: pN.default(\"top\"), color: A_.string().optional(), arrow_size: jM.default(\"1mm\") }).describe(\"Defines a measurement annotation within PCB documentation notes\");\nvar uT = gC.extend({ type: A_.literal(\"pcb_footprint_overlap_error\"), pcb_error_id: JM(\"pcb_error\"), error_type: A_.literal(\"pcb_footprint_overlap_error\").default(\"pcb_footprint_overlap_error\"), pcb_smtpad_ids: A_.array(A_.string()).optional(), pcb_plated_hole_ids: A_.array(A_.string()).optional(), pcb_hole_ids: A_.array(A_.string()).optional(), pcb_keepout_ids: A_.array(A_.string()).optional() }).describe(\"Error emitted when a pcb footprint overlaps with another element\");\nvar pT = gC.extend({ type: A_.literal(\"pcb_courtyard_overlap_error\"), pcb_error_id: JM(\"pcb_error\"), error_type: A_.literal(\"pcb_courtyard_overlap_error\").default(\"pcb_courtyard_overlap_error\"), pcb_component_ids: A_.tuple([A_.string(), A_.string()]) }).describe(\"Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another\");\nvar mT = A_.object({ type: A_.literal(\"pcb_keepout\"), shape: A_.literal(\"rect\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: $M, height: $M, pcb_keepout_id: A_.string(), layers: A_.array(A_.string()), description: A_.string().optional() }).or(A_.object({ type: A_.literal(\"pcb_keepout\"), shape: A_.literal(\"circle\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, radius: $M, pcb_keepout_id: A_.string(), layers: A_.array(A_.string()), description: A_.string().optional() }));\nvar gT = A_.object({ type: A_.literal(\"pcb_cutout\"), pcb_cutout_id: JM(\"pcb_cutout\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_board_id: A_.string().optional(), pcb_panel_id: A_.string().optional() });\nvar fT = gT.extend({ shape: A_.literal(\"rect\"), center: GM, width: jM, height: jM, rotation: VM.optional(), corner_radius: jM.optional() });\nvar _T = gT.extend({ shape: A_.literal(\"circle\"), center: GM, radius: jM });\nvar yT = gT.extend({ shape: A_.literal(\"polygon\"), points: A_.array(GM) });\nvar bT = gT.extend({ shape: A_.literal(\"path\"), route: A_.array(GM), slot_width: jM, slot_length: jM.optional(), space_between_slots: jM.optional(), slot_corner_radius: jM.optional() });\nvar xT = A_.discriminatedUnion(\"shape\", [fT, _T, yT, bT]).describe(\"Defines a cutout on the PCB, removing board material.\");\nvar vT = gC.extend({ type: A_.literal(\"pcb_missing_footprint_error\"), pcb_missing_footprint_error_id: JM(\"pcb_missing_footprint_error\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"pcb_missing_footprint_error\").default(\"pcb_missing_footprint_error\"), source_component_id: A_.string() }).describe(\"Defines a missing footprint error on the PCB\");\nvar ST = gC.extend({ type: A_.literal(\"external_footprint_load_error\"), external_footprint_load_error_id: JM(\"external_footprint_load_error\"), pcb_component_id: A_.string(), source_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), footprinter_string: A_.string().optional(), error_type: A_.literal(\"external_footprint_load_error\").default(\"external_footprint_load_error\") }).describe(\"Defines an error when an external footprint fails to load\");\nvar IT = gC.extend({ type: A_.literal(\"circuit_json_footprint_load_error\"), circuit_json_footprint_load_error_id: JM(\"circuit_json_footprint_load_error\"), pcb_component_id: A_.string(), source_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal(\"circuit_json_footprint_load_error\").default(\"circuit_json_footprint_load_error\"), circuit_json: A_.array(A_.any()).optional() }).describe(\"Defines an error when a circuit JSON footprint fails to load\");\nvar PT = A_.object({ type: A_.literal(\"pcb_group\"), pcb_group_id: JM(\"pcb_group\"), source_group_id: A_.string(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), width: jM.optional(), height: jM.optional(), center: GM, display_offset_x: A_.string().optional().describe(\"How to display the x offset for this group, usually corresponding with how the user specified it\"), display_offset_y: A_.string().optional().describe(\"How to display the y offset for this group, usually corresponding with how the user specified it\"), outline: A_.array(GM).optional(), anchor_position: GM.optional(), anchor_alignment: KM.default(\"center\"), position_mode: A_.enum([\"packed\", \"relative_to_group_anchor\", \"none\"]).optional(), positioned_relative_to_pcb_group_id: A_.string().optional(), positioned_relative_to_pcb_board_id: A_.string().optional(), pcb_component_ids: A_.array(A_.string()), child_layout_mode: A_.enum([\"packed\", \"none\"]).optional(), name: A_.string().optional(), description: A_.string().optional(), layout_mode: A_.string().optional(), autorouter_configuration: A_.object({ trace_clearance: jM }).optional(), autorouter_used_string: A_.string().optional() }).describe(\"Defines a group of components on the PCB\");\nvar MT = gC.extend({ type: A_.literal(\"pcb_autorouting_error\"), pcb_error_id: JM(\"pcb_autorouting_error\"), error_type: A_.literal(\"pcb_autorouting_error\").default(\"pcb_autorouting_error\"), subcircuit_id: A_.string().optional() }).describe(\"The autorouting has failed to route a portion of the board\");\nvar CT = A_.object({ type: A_.literal(\"pcb_manual_edit_conflict_warning\"), pcb_manual_edit_conflict_warning_id: JM(\"pcb_manual_edit_conflict_warning\"), warning_type: A_.literal(\"pcb_manual_edit_conflict_warning\").default(\"pcb_manual_edit_conflict_warning\"), message: A_.string(), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_component_id: A_.string() }).describe(\"Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates\");\nvar NT = A_.enum([\"x-\", \"x+\", \"y+\", \"y-\"]);\nvar wT = A_.object({ type: A_.literal(\"pcb_connector_not_in_accessible_orientation_warning\"), pcb_connector_not_in_accessible_orientation_warning_id: JM(\"pcb_connector_not_in_accessible_orientation_warning\"), warning_type: A_.literal(\"pcb_connector_not_in_accessible_orientation_warning\").default(\"pcb_connector_not_in_accessible_orientation_warning\"), message: A_.string(), pcb_component_id: A_.string(), source_component_id: A_.string().optional(), pcb_board_id: A_.string().optional(), facing_direction: NT, recommended_facing_direction: NT, subcircuit_id: A_.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\");\nvar TT = A_.object({ type: A_.literal(\"supplier_footprint_mismatch_warning\"), supplier_footprint_mismatch_warning_id: JM(\"supplier_footprint_mismatch_warning\"), warning_type: A_.literal(\"supplier_footprint_mismatch_warning\").default(\"supplier_footprint_mismatch_warning\"), message: A_.string(), source_component_id: A_.string(), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), supplier_name: fC.optional(), supplier_part_number: A_.string().optional(), supplier_footprint_url: A_.string().optional(), footprint_copper_intersection_over_union: A_.number() }).describe(\"Warning emitted when a supplier part footprint does not match the expected footprint\");\nvar RT = A_.object({ type: A_.literal(\"pcb_breakout_point\"), pcb_breakout_point_id: JM(\"pcb_breakout_point\"), pcb_group_id: A_.string(), subcircuit_id: A_.string().optional(), source_trace_id: A_.string().optional(), source_port_id: A_.string().optional(), source_net_id: A_.string().optional(), x: $M, y: $M }).describe(\"Defines a routing target within a pcb_group for a source_trace or source_net\");\nvar ET = A_.object({ type: A_.literal(\"pcb_ground_plane\"), pcb_ground_plane_id: JM(\"pcb_ground_plane\"), source_pcb_ground_plane_id: A_.string(), source_net_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Defines a ground plane on the PCB\");\nvar AT = A_.object({ type: A_.literal(\"pcb_ground_plane_region\"), pcb_ground_plane_region_id: JM(\"pcb_ground_plane_region\"), pcb_ground_plane_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: uN, points: A_.array(GM) }).describe(\"Defines a polygon region of a ground plane\");\nvar OT = A_.object({ type: A_.literal(\"pcb_thermal_spoke\"), pcb_thermal_spoke_id: JM(\"pcb_thermal_spoke\"), pcb_ground_plane_id: A_.string(), shape: A_.string(), spoke_count: A_.number(), spoke_thickness: $M, spoke_inner_diameter: $M, spoke_outer_diameter: $M, pcb_plated_hole_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Pattern for connecting a ground plane to a plated hole\");\nvar LT = A_.object({ type: A_.literal(\"pcb_copper_pour\"), pcb_copper_pour_id: JM(\"pcb_copper_pour\"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: uN, source_net_id: A_.string().optional(), covered_with_solder_mask: A_.boolean().optional().default(true) });\nvar DT = LT.extend({ shape: A_.literal(\"rect\"), center: GM, width: jM, height: jM, rotation: VM.optional() });\nvar zT = LT.extend({ shape: A_.literal(\"brep\"), brep_shape: QN });\nvar kT = LT.extend({ shape: A_.literal(\"polygon\"), points: A_.array(GM) });\nvar FT = A_.discriminatedUnion(\"shape\", [DT, zT, kT]).describe(\"Defines a copper pour on the PCB.\");\nvar jT = gC.extend({ type: A_.literal(\"pcb_component_outside_board_error\"), pcb_component_outside_board_error_id: JM(\"pcb_component_outside_board_error\"), error_type: A_.literal(\"pcb_component_outside_board_error\").default(\"pcb_component_outside_board_error\"), pcb_component_id: A_.string(), pcb_board_id: A_.string(), component_center: GM, component_bounds: A_.object({ min_x: A_.number(), max_x: A_.number(), min_y: A_.number(), max_y: A_.number() }), subcircuit_id: A_.string().optional(), source_component_id: A_.string().optional() }).describe(\"Error emitted when a PCB component is placed outside the board boundaries\");\nvar YT = gC.extend({ type: A_.literal(\"pcb_component_not_on_board_edge_error\"), pcb_component_not_on_board_edge_error_id: JM(\"pcb_component_not_on_board_edge_error\"), error_type: A_.literal(\"pcb_component_not_on_board_edge_error\").default(\"pcb_component_not_on_board_edge_error\"), pcb_component_id: A_.string(), pcb_board_id: A_.string(), component_center: GM, pad_to_nearest_board_edge_distance: A_.number(), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a component that must be placed on the board edge is centered away from the edge\");\nvar $T = gC.extend({ type: A_.literal(\"pcb_component_invalid_layer_error\"), pcb_component_invalid_layer_error_id: JM(\"pcb_component_invalid_layer_error\"), error_type: A_.literal(\"pcb_component_invalid_layer_error\").default(\"pcb_component_invalid_layer_error\"), pcb_component_id: A_.string().optional(), source_component_id: A_.string(), layer: uN, subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)\");\nvar XT = gC.extend({ type: A_.literal(\"pcb_via_clearance_error\"), pcb_error_id: JM(\"pcb_error\"), error_type: A_.literal(\"pcb_via_clearance_error\").default(\"pcb_via_clearance_error\"), pcb_via_ids: A_.array(A_.string()).min(2), minimum_clearance: $M.optional(), actual_clearance: $M.optional(), pcb_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when vias are closer than the allowed clearance\");\nvar BT = gC.extend({ type: A_.literal(\"pcb_via_trace_clearance_error\"), pcb_via_trace_clearance_error_id: JM(\"pcb_via_trace_clearance_error\"), error_type: A_.literal(\"pcb_via_trace_clearance_error\").default(\"pcb_via_trace_clearance_error\"), pcb_via_id: A_.string(), pcb_trace_id: A_.string(), minimum_clearance: $M.optional(), actual_clearance: $M.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a via and trace are closer than the allowed clearance\");\nvar HT = gC.extend({ type: A_.literal(\"pcb_pad_pad_clearance_error\"), pcb_pad_pad_clearance_error_id: JM(\"pcb_pad_pad_clearance_error\"), error_type: A_.literal(\"pcb_pad_pad_clearance_error\").default(\"pcb_pad_pad_clearance_error\"), pcb_pad_ids: A_.array(A_.string()).min(2), minimum_clearance: $M.optional(), actual_clearance: $M.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when pads are closer than the allowed clearance\");\nvar WT = gC.extend({ type: A_.literal(\"pcb_pad_trace_clearance_error\"), pcb_pad_trace_clearance_error_id: JM(\"pcb_pad_trace_clearance_error\"), error_type: A_.literal(\"pcb_pad_trace_clearance_error\").default(\"pcb_pad_trace_clearance_error\"), pcb_pad_id: A_.string(), pcb_trace_id: A_.string(), minimum_clearance: $M.optional(), actual_clearance: $M.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe(\"Error emitted when a pad and trace are closer than allowed clearance\");\nvar VT = A_.object({ type: A_.literal(\"pcb_courtyard_rect\"), pcb_courtyard_rect_id: JM(\"pcb_courtyard_rect\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: jM, height: jM, layer: pN, ccw_rotation: VM.optional(), color: A_.string().optional() }).describe(\"Defines a courtyard rectangle on the PCB\");\nvar UT = A_.object({ type: A_.literal(\"pcb_courtyard_outline\"), pcb_courtyard_outline_id: JM(\"pcb_courtyard_outline\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: pN, outline: A_.array(GM).min(2) }).describe(\"Defines a courtyard outline on the PCB\");\nvar GT = A_.object({ type: A_.literal(\"pcb_courtyard_polygon\"), pcb_courtyard_polygon_id: JM(\"pcb_courtyard_polygon\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: pN, points: A_.array(GM).min(3), color: A_.string().optional() }).describe(\"Defines a courtyard polygon on the PCB\");\nvar ZT = A_.object({ type: A_.literal(\"pcb_courtyard_circle\"), pcb_courtyard_circle_id: JM(\"pcb_courtyard_circle\"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, radius: jM, layer: pN, color: A_.string().optional() }).describe(\"Defines a courtyard circle on the PCB\");\nvar qT = A_.object({ type: A_.literal(\"cad_component\"), cad_component_id: A_.string(), pcb_component_id: A_.string(), source_component_id: A_.string(), position: ZM, rotation: ZM.optional(), size: ZM.optional(), layer: uN.optional(), subcircuit_id: A_.string().optional(), footprinter_string: A_.string().optional(), model_obj_url: A_.string().optional(), model_stl_url: A_.string().optional(), model_3mf_url: A_.string().optional(), model_gltf_url: A_.string().optional(), model_glb_url: A_.string().optional(), model_step_url: A_.string().optional(), model_wrl_url: A_.string().optional(), model_asset: QM.optional(), model_unit_to_mm_scale_factor: A_.number().optional(), model_board_normal_direction: A_.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: ZM.optional(), model_origin_alignment: A_.enum([\"unknown\", \"center\", \"center_of_component_on_board_surface\", \"bottom_center_of_component\"]).optional(), model_object_fit: A_.enum([\"contain_within_bounds\", \"fill_bounds\"]).optional().default(\"contain_within_bounds\"), model_jscad: A_.any().optional(), show_as_translucent_model: A_.boolean().optional(), anchor_alignment: A_.enum([\"center\", \"center_of_component_on_board_surface\"]).optional().default(\"center\") }).describe(\"Defines a component on the PCB\");\nvar JT = A_.enum([\"sinewave\", \"square\", \"triangle\", \"sawtooth\"]);\nvar KT = A_.union([A_.string(), A_.number()]).transform((t48) =\u003e \"string\" == typeof t48 ? t48.endsWith(\"%\") ? parseFloat(t48.slice(0, -1)) / 100 : parseFloat(t48) : t48).pipe(A_.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar QT = A_.object({ type: A_.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: JM(\"simulation_voltage_source\"), is_dc_source: A_.literal(true).optional().default(true), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), voltage: FM }).describe(\"Defines a DC voltage source for simulation\");\nvar tR = A_.object({ type: A_.literal(\"simulation_voltage_source\"), simulation_voltage_source_id: JM(\"simulation_voltage_source\"), is_dc_source: A_.literal(false), terminal1_source_port_id: A_.string().optional(), terminal2_source_port_id: A_.string().optional(), terminal1_source_net_id: A_.string().optional(), terminal2_source_net_id: A_.string().optional(), voltage: FM.optional(), frequency: YM.optional(), peak_to_peak_voltage: FM.optional(), wave_shape: JT.optional(), phase: VM.optional(), duty_cycle: KT.optional() }).describe(\"Defines an AC voltage source for simulation\");\nvar eR = A_.union([QT, tR]).describe(\"Defines a voltage source for simulation\");\nvar nR = A_.union([A_.string(), A_.number()]).transform((t48) =\u003e \"string\" == typeof t48 ? t48.endsWith(\"%\") ? parseFloat(t48.slice(0, -1)) / 100 : parseFloat(t48) : t48).pipe(A_.number().min(0, \"Duty cycle must be non-negative\").max(1, \"Duty cycle cannot be greater than 100%\"));\nvar oR = A_.object({ type: A_.literal(\"simulation_current_source\"), simulation_current_source_id: JM(\"simulation_current_source\"), is_dc_source: A_.literal(true).optional().default(true), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), current: XM }).describe(\"Defines a DC current source for simulation\");\nvar iR = A_.object({ type: A_.literal(\"simulation_current_source\"), simulation_current_source_id: JM(\"simulation_current_source\"), is_dc_source: A_.literal(false), terminal1_source_port_id: A_.string().optional(), terminal2_source_port_id: A_.string().optional(), terminal1_source_net_id: A_.string().optional(), terminal2_source_net_id: A_.string().optional(), current: XM.optional(), frequency: YM.optional(), peak_to_peak_current: XM.optional(), wave_shape: JT.optional(), phase: VM.optional(), duty_cycle: nR.optional() }).describe(\"Defines an AC current source for simulation\");\nvar rR = A_.union([oR, iR]).describe(\"Defines a current source for simulation\");\nvar sR = A_.union([A_.literal(\"spice_dc_sweep\"), A_.literal(\"spice_dc_operating_point\"), A_.literal(\"spice_transient_analysis\"), A_.literal(\"spice_ac_analysis\")]);\nvar aR = A_.object({ type: A_.literal(\"simulation_experiment\"), simulation_experiment_id: JM(\"simulation_experiment\"), name: A_.string(), experiment_type: sR, time_per_step: BM.optional(), start_time_ms: HM.optional(), end_time_ms: HM.optional() }).describe(\"Defines a simulation experiment configuration\");\nvar cR = A_.object({ type: A_.literal(\"simulation_transient_voltage_graph\"), simulation_transient_voltage_graph_id: JM(\"simulation_transient_voltage_graph\"), simulation_experiment_id: A_.string(), timestamps_ms: A_.array(A_.number()).optional(), voltage_levels: A_.array(A_.number()), source_component_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), time_per_step: BM, start_time_ms: HM, end_time_ms: HM, name: A_.string().optional(), color: A_.string().optional() }).describe(\"Stores voltage measurements over time for a simulation\");\nvar lR = A_.object({ type: A_.literal(\"simulation_switch\"), simulation_switch_id: JM(\"simulation_switch\"), source_component_id: A_.string().optional(), closes_at: HM.optional(), opens_at: HM.optional(), starts_closed: A_.boolean().optional(), switching_frequency: YM.optional() }).describe(\"Defines a switch for simulation timing control\");\nvar hR = A_.object({ type: A_.literal(\"simulation_voltage_probe\"), simulation_voltage_probe_id: JM(\"simulation_voltage_probe\"), source_component_id: A_.string().optional(), name: A_.string().optional(), signal_input_source_port_id: A_.string().optional(), signal_input_source_net_id: A_.string().optional(), reference_input_source_port_id: A_.string().optional(), reference_input_source_net_id: A_.string().optional(), subcircuit_id: A_.string().optional(), color: A_.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((t48, e2) =\u003e {\n if (t48.reference_input_source_port_id || t48.reference_input_source_net_id) {\n const n2 = !!t48.signal_input_source_port_id || !!t48.reference_input_source_port_id, o2 = !!t48.signal_input_source_net_id || !!t48.reference_input_source_net_id;\n n2 \u0026\u0026 o2 ? e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Cannot mix port and net connections in a differential probe.\" }) : n2 ? t48.signal_input_source_port_id \u0026\u0026 t48.reference_input_source_port_id || e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id.\" }) : o2 \u0026\u0026 (t48.signal_input_source_net_id \u0026\u0026 t48.reference_input_source_net_id || e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id.\" }));\n } else !!t48.signal_input_source_port_id == !!t48.signal_input_source_net_id \u0026\u0026 e2.addIssue({ code: A_.ZodIssueCode.custom, message: \"A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id.\" });\n});\nvar dR = gC.extend({ type: A_.literal(\"simulation_unknown_experiment_error\"), simulation_unknown_experiment_error_id: JM(\"simulation_unknown_experiment_error\"), error_type: A_.literal(\"simulation_unknown_experiment_error\").default(\"simulation_unknown_experiment_error\"), simulation_experiment_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe(\"An unknown error occurred during the simulation experiment.\");\nvar uR = A_.object({ type: A_.literal(\"simulation_op_amp\"), simulation_op_amp_id: JM(\"simulation_op_amp\"), source_component_id: A_.string().optional(), inverting_input_source_port_id: A_.string(), non_inverting_input_source_port_id: A_.string(), output_source_port_id: A_.string(), positive_supply_source_port_id: A_.string(), negative_supply_source_port_id: A_.string() }).describe(\"Defines a simple ideal operational amplifier for simulation\");\nvar pR = (A_.union([iN, nN, oN, eN, sN, rN, PC, yC, xC, SC, bC, MC, TC, RC, LC, zC, kC, XC, FC, jC, YC, $C, AC, EC, lN, mN, aN, BC, VC, UC, ZC, qC, gN, fN, _N, yN, bN, QC, cN, ow, hw, vT, ST, IT, CT, wT, TT, _w, mT, yw, Xw, Aw, zw, kw, Bw, Mw, Ew, Hw, Ww, PT, Gw, Zw, qw, Jw, nT, Kw, Qw, tT, eT, Fw, jw, Vw, Uw, Yw, $w, XT, BT, HT, WT, iT, oT, rT, sT, aT, cT, lT, hT, dT, MT, uT, pT, RT, xT, ET, AT, OT, FT, jT, YT, $T, VT, UT, GT, ZT, xN, DN, TN, RN, EN, AN, CN, wN, zN, ON, vN, FN, jN, kN, HN, WN, VN, UN, qN, GN, ZN, qT, eR, rR, aR, cR, lR, hR, dR, uR]), true);\nvar mR = { CCW: -1, CW: 1, NOT_ORIENTABLE: 0 };\nvar gR = 2 * Math.PI;\nvar fR = Object.freeze({ __proto__: null, BOUNDARY: 2, CCW: pR, CONTAINS: 3, CW: false, END_VERTEX: 2, INSIDE: 1, INTERLACE: 4, NOT_VERTEX: 0, ORIENTATION: mR, OUTSIDE: 0, OVERLAP_OPPOSITE: 2, OVERLAP_SAME: 1, PIx2: gR, START_VERTEX: 1 });\nvar _R = 1e-6;\nfunction yR(t48) {\n _R = t48;\n}\nfunction bR() {\n return _R;\n}\nfunction xR(t48) {\n return t48 \u003c _R \u0026\u0026 t48 \u003e -_R;\n}\nfunction vR(t48, e2) {\n return t48 - e2 \u003c _R \u0026\u0026 t48 - e2 \u003e -_R;\n}\nfunction SR(t48, e2) {\n return t48 - e2 \u003e _R;\n}\nfunction IR(t48, e2) {\n return t48 - e2 \u003c -_R;\n}\nvar PR = { Utils: Object.freeze({ __proto__: null, DECIMALS: 3, EQ: vR, EQ_0: xR, GE: function(t48, e2) {\n return t48 - e2 \u003e -_R;\n}, GT: SR, LE: function(t48, e2) {\n return t48 - e2 \u003c _R;\n}, LT: IR, getTolerance: bR, setTolerance: yR }), 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 };\nfor (let t48 in fR) PR[t48] = fR[t48];\nObject.defineProperty(PR, \"DP_TOL\", { get: function() {\n return bR();\n}, set: function(t48) {\n yR(t48);\n} });\nvar MR = class {\n static get ILLEGAL_PARAMETERS() {\n return new ReferenceError(\"Illegal Parameters\");\n }\n static get ZERO_DIVISION() {\n return new Error(\"Zero division\");\n }\n static get UNRESOLVED_BOUNDARY_CONFLICT() {\n return new Error(\"Unresolved boundary conflict in boolean operation\");\n }\n static get INFINITE_LOOP() {\n return new Error(\"Infinite loop\");\n }\n static get CANNOT_COMPLETE_BOOLEAN_OPERATION() {\n return new Error(\"Cannot complete boolean operation\");\n }\n static get CANNOT_INVOKE_ABSTRACT_METHOD() {\n return new Error(\"Abstract method cannot be invoked\");\n }\n static get OPERATION_IS_NOT_SUPPORTED() {\n return new Error(\"Operation is not supported\");\n }\n static get UNSUPPORTED_SHAPE_TYPE() {\n return new Error(\"Unsupported shape type\");\n }\n};\nPR.Errors = MR;\nvar CR = class {\n constructor(t48, e2) {\n this.first = t48, this.last = e2 || this.first;\n }\n [Symbol.iterator]() {\n let t48;\n return { next: () =\u003e (t48 = t48 ? t48.next : this.first, { value: t48, done: void 0 === t48 }) };\n }\n get size() {\n let t48 = 0;\n for (let e2 of this) t48++;\n return t48;\n }\n toArray(t48 = void 0, e2 = void 0) {\n let n2 = [], o2 = t48 || this.first, i2 = e2 || this.last, r2 = o2;\n if (void 0 === r2) return n2;\n do {\n n2.push(r2), r2 = r2.next;\n } while (r2 !== i2.next);\n return n2;\n }\n append(t48) {\n return this.isEmpty() ? this.first = t48 : (t48.prev = this.last, this.last.next = t48), this.last = t48, this.last.next = void 0, this.first.prev = void 0, this;\n }\n insert(t48, e2) {\n if (this.isEmpty()) this.first = t48, this.last = t48;\n else if (null == e2) t48.next = this.first, this.first.prev = t48, this.first = t48;\n else {\n let n2 = e2.next;\n e2.next = t48, n2 \u0026\u0026 (n2.prev = t48), t48.prev = e2, t48.next = n2, this.last === e2 \u0026\u0026 (this.last = t48);\n }\n return this.last.next = void 0, this.first.prev = void 0, this;\n }\n remove(t48) {\n return t48 === this.first \u0026\u0026 t48 === this.last ? (this.first = void 0, this.last = void 0) : (t48.prev \u0026\u0026 (t48.prev.next = t48.next), t48.next \u0026\u0026 (t48.next.prev = t48.prev), t48 === this.first \u0026\u0026 (this.first = t48.next), t48 === this.last \u0026\u0026 (this.last = t48.prev)), this;\n }\n isEmpty() {\n return void 0 === this.first;\n }\n static testInfiniteLoop(t48) {\n let e2 = t48, n2 = t48;\n do {\n if (e2 != t48 \u0026\u0026 e2 === n2) throw MR.INFINITE_LOOP;\n e2 = e2.next, n2 = n2.next.next;\n } while (e2 != t48);\n }\n};\nvar NR = { stroke: \"black\" };\nvar wR = class {\n constructor(t48 = NR) {\n for (const e2 in t48) this[e2] = t48[e2];\n this.stroke = t48.stroke ?? NR.stroke;\n }\n toAttributesString() {\n return Object.keys(this).reduce((t48, e2) =\u003e t48 + (void 0 !== this[e2] ? this.toAttrString(e2, this[e2]) : \"\"), \"\");\n }\n toAttrString(t48, e2) {\n const n2 = \"className\" === t48 ? \"class\" : this.convertCamelToKebabCase(t48);\n return null === e2 ? `${n2} ` : `${n2}=\"${e2.toString()}\" `;\n }\n convertCamelToKebabCase(t48) {\n return t48.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).join(\"-\").toLowerCase();\n }\n};\nfunction TR(t48) {\n return new wR(t48).toAttributesString();\n}\nfunction RR(t48, e2) {\n let n2 = [], [o2, i2, r2] = t48.standard, [s2, a2, c2] = e2.standard, l2 = o2 * a2 - i2 * s2, h2 = r2 * a2 - i2 * c2, d2 = o2 * c2 - r2 * s2;\n if (!PR.Utils.EQ_0(l2)) {\n let t49, e3;\n 0 === i2 ? (t49 = r2 / o2, e3 = d2 / l2) : 0 === a2 ? (t49 = c2 / s2, e3 = d2 / l2) : 0 === o2 ? (t49 = h2 / l2, e3 = r2 / i2) : 0 === s2 ? (t49 = h2 / l2, e3 = c2 / a2) : (t49 = h2 / l2, e3 = d2 / l2), n2.push(new PR.Point(t49, e3));\n }\n return n2;\n}\nfunction ER(t48, e2) {\n let n2 = [], o2 = e2.pc.projectionOn(t48), i2 = e2.pc.distanceTo(o2)[0];\n if (PR.Utils.EQ(i2, e2.r)) n2.push(o2);\n else if (PR.Utils.LT(i2, e2.r)) {\n let r2, s2, a2 = Math.sqrt(e2.r * e2.r - i2 * i2);\n r2 = t48.norm.rotate90CCW().multiply(a2), s2 = o2.translate(r2), n2.push(s2), r2 = t48.norm.rotate90CW().multiply(a2), s2 = o2.translate(r2), n2.push(s2);\n }\n return n2;\n}\nfunction AR(t48, e2) {\n let n2 = [];\n for (let o2 of e2.toSegments()) {\n let e3 = LR(o2, t48);\n for (let t49 of e3) QR(t49, n2) || n2.push(t49);\n }\n return n2;\n}\nfunction OR(t48, e2) {\n let n2 = [];\n if (0 === AR(t48, e2.box).length) return n2;\n let o2 = ER(t48, new PR.Circle(e2.pc, e2.r));\n for (let t49 of o2) t49.on(e2) \u0026\u0026 n2.push(t49);\n return n2;\n}\nfunction LR(t48, e2) {\n let n2 = [];\n return t48.ps.on(e2) \u0026\u0026 n2.push(t48.ps), t48.pe.on(e2) \u0026\u0026 !t48.isZeroLength() \u0026\u0026 n2.push(t48.pe), n2.length \u003e 0 || t48.isZeroLength() || t48.ps.leftTo(e2) \u0026\u0026 t48.pe.leftTo(e2) || !t48.ps.leftTo(e2) \u0026\u0026 !t48.pe.leftTo(e2) ? n2 : RR(new PR.Line(t48.ps, t48.pe), e2);\n}\nfunction DR(t48, e2) {\n let n2 = [];\n if (t48.isZeroLength()) return t48.ps.on(e2) \u0026\u0026 n2.push(t48.ps), n2;\n if (e2.isZeroLength()) return e2.ps.on(t48) \u0026\u0026 n2.push(e2.ps), n2;\n let o2 = new PR.Line(t48.ps, t48.pe), i2 = new PR.Line(e2.ps, e2.pe);\n if (o2.incidentTo(i2)) t48.ps.on(e2) \u0026\u0026 n2.push(t48.ps), t48.pe.on(e2) \u0026\u0026 n2.push(t48.pe), !e2.ps.on(t48) || e2.ps.equalTo(t48.ps) || e2.ps.equalTo(t48.pe) || n2.push(e2.ps), !e2.pe.on(t48) || e2.pe.equalTo(t48.ps) || e2.pe.equalTo(t48.pe) || n2.push(e2.pe);\n else if (o2.parallelTo(i2)) {\n const o3 = new PR.Vector(t48.ps, t48.pe), i3 = new PR.Vector(e2.ps, e2.pe), r2 = new PR.Vector(t48.ps, e2.ps), s2 = o3.cross(i3);\n if (!PR.Utils.EQ_0(s2)) {\n const a2 = r2.cross(i3) / s2, c2 = r2.cross(o3) / s2;\n PR.Utils.GE(a2, 0) \u0026\u0026 PR.Utils.LE(a2, 1) \u0026\u0026 PR.Utils.GE(c2, 0) \u0026\u0026 PR.Utils.LE(c2, 1) \u0026\u0026 n2.push(zR(t48.ps.translate(o3.multiply(a2)), t48, e2));\n }\n } else {\n let r2 = RR(o2, i2);\n r2.length \u003e 0 \u0026\u0026 kR(r2[0], t48) \u0026\u0026 kR(r2[0], e2) \u0026\u0026 n2.push(zR(r2[0], t48, e2));\n }\n return n2;\n}\nfunction zR(t48, e2, n2) {\n for (const o2 of [e2.ps, e2.pe, n2.ps, n2.pe]) if (t48.equalTo(o2)) return o2;\n return t48;\n}\nfunction kR(t48, e2) {\n const n2 = e2.box;\n return PR.Utils.LE(t48.x, n2.xmax) \u0026\u0026 PR.Utils.GE(t48.x, n2.xmin) \u0026\u0026 PR.Utils.LE(t48.y, n2.ymax) \u0026\u0026 PR.Utils.GE(t48.y, n2.ymin);\n}\nfunction FR(t48, e2) {\n let n2 = [];\n if (t48.isZeroLength()) {\n let [o3, i2] = t48.ps.distanceTo(e2.pc);\n return PR.Utils.EQ(o3, e2.r) \u0026\u0026 n2.push(t48.ps), n2;\n }\n let o2 = ER(new PR.Line(t48.ps, t48.pe), e2);\n for (let e3 of o2) e3.on(t48) \u0026\u0026 n2.push(e3);\n return n2;\n}\nfunction jR(t48, e2) {\n let n2 = [];\n if (t48.isZeroLength()) return t48.ps.on(e2) \u0026\u0026 n2.push(t48.ps), n2;\n let o2 = ER(new PR.Line(t48.ps, t48.pe), new PR.Circle(e2.pc, e2.r));\n for (let i2 of o2) i2.on(t48) \u0026\u0026 i2.on(e2) \u0026\u0026 n2.push(i2);\n return n2;\n}\nfunction YR(t48, e2) {\n let n2 = [], o2 = new PR.Vector(t48.pc, e2.pc), i2 = t48.r, r2 = e2.r;\n if (PR.Utils.EQ_0(i2) || PR.Utils.EQ_0(r2)) return n2;\n if (PR.Utils.EQ_0(o2.x) \u0026\u0026 PR.Utils.EQ_0(o2.y) \u0026\u0026 PR.Utils.EQ(i2, r2)) return n2.push(t48.pc.translate(-i2, 0)), n2;\n let s2, a2 = t48.pc.distanceTo(e2.pc)[0];\n if (PR.Utils.GT(a2, i2 + r2)) return n2;\n if (PR.Utils.LT(a2, Math.abs(i2 - r2))) return n2;\n if (o2.x /= a2, o2.y /= a2, PR.Utils.EQ(a2, i2 + r2) || PR.Utils.EQ(a2, Math.abs(i2 - r2))) return s2 = t48.pc.translate(i2 * o2.x, i2 * o2.y), n2.push(s2), n2;\n let c2 = i2 * i2 / (2 * a2) - r2 * r2 / (2 * a2) + a2 / 2, l2 = t48.pc.translate(c2 * o2.x, c2 * o2.y), h2 = Math.sqrt(i2 * i2 - c2 * c2);\n return s2 = l2.translate(o2.rotate90CCW().multiply(h2)), n2.push(s2), s2 = l2.translate(o2.rotate90CW().multiply(h2)), n2.push(s2), n2;\n}\nfunction $R(t48, e2) {\n let n2 = [];\n if (t48.pc.equalTo(e2.pc) \u0026\u0026 PR.Utils.EQ(t48.r, e2.r)) {\n let o3;\n return o3 = t48.start, o3.on(e2) \u0026\u0026 n2.push(o3), o3 = t48.end, o3.on(e2) \u0026\u0026 n2.push(o3), o3 = e2.start, o3.on(t48) \u0026\u0026 n2.push(o3), o3 = e2.end, o3.on(t48) \u0026\u0026 n2.push(o3), n2;\n }\n let o2 = new PR.Circle(t48.pc, t48.r), i2 = new PR.Circle(e2.pc, e2.r), r2 = o2.intersect(i2);\n for (let o3 of r2) o3.on(t48) \u0026\u0026 o3.on(e2) \u0026\u0026 n2.push(o3);\n return n2;\n}\nfunction XR(t48, e2) {\n let n2 = [];\n if (e2.pc.equalTo(t48.pc) \u0026\u0026 PR.Utils.EQ(e2.r, t48.r)) return n2.push(t48.start), n2.push(t48.end), n2;\n let o2 = YR(e2, new PR.Circle(t48.pc, t48.r));\n for (let e3 of o2) e3.on(t48) \u0026\u0026 n2.push(e3);\n return n2;\n}\nfunction BR(t48, e2) {\n return t48.isSegment ? DR(t48.shape, e2) : jR(e2, t48.shape);\n}\nfunction HR(t48, e2) {\n return t48.isSegment ? jR(t48.shape, e2) : $R(t48.shape, e2);\n}\nfunction WR(t48, e2) {\n return t48.isSegment ? LR(t48.shape, e2) : OR(e2, t48.shape);\n}\nfunction VR(t48, e2) {\n return t48.isSegment ? FR(t48.shape, e2) : XR(t48.shape, e2);\n}\nfunction UR(t48, e2) {\n let n2 = [];\n for (let o2 of e2.edges) for (let e3 of BR(o2, t48)) n2.push(e3);\n return n2;\n}\nfunction GR(t48, e2) {\n let n2 = [];\n for (let o2 of e2.edges) for (let e3 of HR(o2, t48)) n2.push(e3);\n return n2;\n}\nfunction ZR(t48, e2) {\n let n2 = [];\n if (e2.isEmpty()) return n2;\n for (let o2 of e2.edges) for (let e3 of WR(o2, t48)) QR(e3, n2) || n2.push(e3);\n return t48.sortPoints(n2);\n}\nfunction qR(t48, e2) {\n let n2 = [];\n if (e2.isEmpty()) return n2;\n for (let o2 of e2.edges) for (let e3 of VR(o2, t48)) n2.push(e3);\n return n2;\n}\nfunction JR(t48, e2) {\n return t48.isSegment ? BR(e2, t48.shape) : t48.isArc ? HR(e2, t48.shape) : t48.isLine ? WR(e2, t48.shape) : t48.isRay ? (n2 = e2, o2 = t48.shape, n2.isSegment ? eE(o2, n2.shape) : nE(o2, n2.shape)) : [];\n var n2, o2;\n}\nfunction KR(t48, e2) {\n let n2 = [];\n if (e2.isEmpty() || t48.shape.box.not_intersect(e2.box)) return n2;\n let o2 = e2.edges.search(t48.shape.box);\n for (let e3 of o2) n2 = [...n2, ...JR(t48, e3)];\n return n2;\n}\nfunction QR(t48, e2) {\n return e2.some((e3) =\u003e e3.equalTo(t48));\n}\nfunction tE(t48) {\n return new PR.Line(t48.start, t48.norm);\n}\nfunction eE(t48, e2) {\n return LR(e2, tE(t48)).filter((e3) =\u003e t48.contains(e3));\n}\nfunction nE(t48, e2) {\n return OR(tE(t48), e2).filter((e3) =\u003e t48.contains(e3));\n}\nfunction oE(t48, e2) {\n return ER(tE(t48), e2).filter((e3) =\u003e t48.contains(e3));\n}\nfunction iE(t48, e2) {\n return RR(tE(t48), e2).filter((e3) =\u003e t48.contains(e3));\n}\nfunction rE(t48, e2) {\n return ZR(tE(t48), e2).filter((e3) =\u003e t48.contains(e3));\n}\nfunction sE(t48, e2) {\n if (t48.intersect \u0026\u0026 t48.intersect instanceof Function) return t48.intersect(e2);\n throw MR.UNSUPPORTED_SHAPE_TYPE;\n}\nfunction aE(t48, e2) {\n let n2 = [];\n for (let o2 of e2) n2 = [...n2, ...sE(t48, o2.shape)];\n return n2;\n}\nvar cE = class t32 extends CR {\n constructor(...t48) {\n if (super(), this.isInfinite = false, 1 === t48.length \u0026\u0026 t48[0] instanceof Array \u0026\u0026 t48[0].length \u003e 0) {\n const e2 = t48[0], n2 = e2.length, o2 = (t49) =\u003e t49 instanceof PR.Segment || t49 instanceof PR.Arc || t49 instanceof PR.Ray, i2 = (t49) =\u003e t49 instanceof PR.Segment || t49 instanceof PR.Arc;\n if (!(1 === n2 \u0026\u0026 ((t49) =\u003e t49 instanceof PR.Segment || t49 instanceof PR.Arc || t49 instanceof PR.Ray || t49 instanceof PR.Line)(e2[0]) || n2 \u003e 1 \u0026\u0026 o2(e2[0]) \u0026\u0026 o2(e2[n2 - 1]) \u0026\u0026 e2.slice(1, n2 - 1).every(i2))) throw PR.Errors.ILLEGAL_PARAMETERS;\n this.isInfinite = e2.some((t49) =\u003e t49 instanceof PR.Ray || t49 instanceof PR.Line);\n for (let t49 of e2) {\n let e3 = new PR.Edge(t49);\n this.append(e3);\n }\n this.setArcLength();\n }\n }\n get edges() {\n return [...this];\n }\n get box() {\n return this.edges.reduce((t48, e2) =\u003e t48.merge(e2.box), new PR.Box());\n }\n get vertices() {\n let t48 = this.edges.map((t49) =\u003e t49.start);\n return t48.push(this.last.end), t48;\n }\n get length() {\n if (this.isEmpty()) return 0;\n if (this.isInfinite) return Number.POSITIVE_INFINITY;\n let t48 = 0;\n for (let e2 of this) t48 += e2.length;\n return t48;\n }\n clone() {\n return new t32(this.toShapes());\n }\n setArcLength() {\n for (let t48 of this) this.setOneEdgeArcLength(t48);\n }\n setOneEdgeArcLength(t48) {\n t48 === this.first ? t48.arc_length = 0 : t48.arc_length = t48.prev.arc_length + t48.prev.length;\n }\n pointAtLength(t48) {\n if (t48 \u003e this.length || t48 \u003c 0) return null;\n if (this.isInfinite) return null;\n let e2 = null;\n for (let n2 of this) if (t48 \u003e= n2.arc_length \u0026\u0026 (n2 === this.last || t48 \u003c n2.next.arc_length)) {\n e2 = n2.pointAtLength(t48 - n2.arc_length);\n break;\n }\n return e2;\n }\n addVertex(t48, e2) {\n let n2 = e2.shape.split(t48);\n if (null === n2[0]) return e2.prev;\n if (null === n2[1]) return e2;\n let o2 = new PR.Edge(n2[0]), i2 = e2.prev;\n return this.insert(o2, i2), e2.shape = n2[1], o2;\n }\n getChain(t48, e2) {\n let n2 = [];\n for (let o2 = t48; o2 !== e2.next; o2 = o2.next) n2.push(o2);\n return n2;\n }\n split(t48) {\n for (let e2 of t48) {\n let t49 = this.findEdgeByPoint(e2);\n this.addVertex(e2, t49);\n }\n return this;\n }\n findEdgeByPoint(t48) {\n let e2;\n for (let n2 of this) if (n2.shape.contains(t48)) {\n e2 = n2;\n break;\n }\n return e2;\n }\n distanceTo(t48) {\n if (t48 instanceof Point) {\n const [e2, n2] = PR.Distance.shape2multiline(t48, this);\n return [e2, n2.reverse()];\n }\n if (t48 instanceof PR.Line) {\n const [e2, n2] = PR.Distance.shape2multiline(t48, this);\n return [e2, n2.reverse()];\n }\n if (t48 instanceof PR.Circle) {\n const [e2, n2] = PR.Distance.shape2multiline(t48, this);\n return [e2, n2.reverse()];\n }\n if (t48 instanceof PR.Segment) {\n const [e2, n2] = PR.Distance.shape2multiline(t48, this);\n return [e2, n2.reverse()];\n }\n if (t48 instanceof PR.Arc) {\n const [e2, n2] = PR.Distance.shape2multiline(t48, this);\n return [e2, n2.reverse()];\n }\n if (t48 instanceof PR.Multiline) return PR.Distance.multiline2multiline(this, t48);\n throw PR.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n intersect(t48) {\n return t48 instanceof PR.Multiline ? (function(t49, e2) {\n let n2 = [];\n for (let o2 of t49) for (let t50 of e2) n2 = [...n2, ...sE(o2.shape, t50.shape)];\n return n2;\n })(this, t48) : aE(t48, this);\n }\n contains(t48) {\n if (t48 instanceof PR.Point) return this.edges.some((e2) =\u003e e2.shape.contains(t48));\n throw PR.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n translate(e2) {\n return new t32(this.edges.map((t48) =\u003e t48.shape.translate(e2)));\n }\n rotate(e2 = 0, n2 = new PR.Point()) {\n return new t32(this.edges.map((t48) =\u003e t48.shape.rotate(e2, n2)));\n }\n transform(e2 = new PR.Matrix()) {\n return new t32(this.edges.map((t48) =\u003e t48.shape.transform(e2)));\n }\n toShapes() {\n return this.edges.map((t48) =\u003e t48.shape.clone());\n }\n toJSON() {\n return this.edges.map((t48) =\u003e t48.toJSON());\n }\n svgPoints() {\n return this.vertices.map((t48) =\u003e `${t48.x},${t48.y}`).join(\" \");\n }\n dpath() {\n let t48 = `M${this.first.start.x},${this.first.start.y}`;\n for (let e2 of this) t48 += e2.svg();\n return t48;\n }\n svg(t48 = {}) {\n let e2 = `\n\u003cpath ${TR({ fill: \"none\", ...t48 })} d=\"`;\n e2 += `\nM${this.first.start.x},${this.first.start.y}`;\n for (let t49 of this) e2 += t49.svg();\n return e2 += '\" \u003e\\n\u003c/path\u003e', e2;\n }\n};\nPR.Multiline = cE;\nfunction lE(t48, e2, n2) {\n let o2 = n2.length, i2 = t48.shape.split(e2);\n if (0 === i2.length) return;\n let r2 = 0;\n r2 = null === i2[0] ? 0 : null === i2[1] ? t48.shape.length : i2[0].length;\n let s2, a2 = 0;\n vR(r2, 0) \u0026\u0026 (a2 |= 1), vR(r2, t48.shape.length) \u0026\u0026 (a2 |= 2), s2 = r2 === 1 / 0 ? i2[0].coord(e2) : 2 \u0026 a2 \u0026\u0026 t48.next \u0026\u0026 0 === t48.next.arc_length ? 0 : t48.arc_length + r2, n2.push({ id: o2, pt: e2, arc_length: s2, edge_before: t48, edge_after: void 0, face: t48.face, is_vertex: a2 });\n}\nfunction hE(t48) {\n t48.int_points1_sorted = dE(t48.int_points1), t48.int_points2_sorted = dE(t48.int_points2);\n}\nfunction dE(t48) {\n let e2 = /* @__PURE__ */ new Map(), n2 = 0;\n for (let o2 of t48) e2.has(o2.face) || (e2.set(o2.face, n2), n2++);\n for (let n3 of t48) n3.faceId = e2.get(n3.face);\n return t48.slice().sort(uE);\n}\nfunction uE(t48, e2) {\n return t48.faceId \u003c e2.faceId ? -1 : t48.faceId \u003e e2.faceId ? 1 : t48.arc_length \u003c e2.arc_length ? -1 : t48.arc_length \u003e e2.arc_length ? 1 : 0;\n}\nfunction pE(t48) {\n if (t48.int_points1.length \u003c 2) return;\n let e2, n2, o2, i2, r2 = false;\n for (let s2 = 0; s2 \u003c t48.int_points1_sorted.length; s2++) if (-1 !== t48.int_points1_sorted[s2].id) {\n e2 = t48.int_points1_sorted[s2], n2 = t48.int_points2[e2.id];\n for (let a2 = s2 + 1; a2 \u003c t48.int_points1_sorted.length \u0026\u0026 (o2 = t48.int_points1_sorted[a2], vR(o2.arc_length, e2.arc_length)); a2++) -1 !== o2.id \u0026\u0026 (i2 = t48.int_points2[o2.id], -1 !== i2.id \u0026\u0026 o2.edge_before === e2.edge_before \u0026\u0026 o2.edge_after === e2.edge_after \u0026\u0026 i2.edge_before === n2.edge_before \u0026\u0026 i2.edge_after === n2.edge_after \u0026\u0026 (o2.id = -1, i2.id = -1, r2 = true));\n }\n n2 = t48.int_points2_sorted[0], e2 = t48.int_points1[n2.id];\n for (let o3 = 1; o3 \u003c t48.int_points2_sorted.length; o3++) {\n let i3 = t48.int_points2_sorted[o3];\n if (-1 === i3.id) continue;\n if (-1 === n2.id || !vR(i3.arc_length, n2.arc_length)) {\n n2 = i3, e2 = t48.int_points1[n2.id];\n continue;\n }\n let s2 = t48.int_points1[i3.id];\n s2.edge_before === e2.edge_before \u0026\u0026 s2.edge_after === e2.edge_after \u0026\u0026 i3.edge_before === n2.edge_before \u0026\u0026 i3.edge_after === n2.edge_after \u0026\u0026 (s2.id = -1, i3.id = -1, r2 = true);\n }\n r2 \u0026\u0026 (t48.int_points1 = t48.int_points1.filter((t49) =\u003e t49.id \u003e= 0), t48.int_points2 = t48.int_points2.filter((t49) =\u003e t49.id \u003e= 0), t48.int_points1.forEach((t49, e3) =\u003e t49.id = e3), t48.int_points2.forEach((t49, e3) =\u003e t49.id = e3));\n}\nfunction mE(t48) {\n for (let e2 of t48) e2.edge_before \u0026\u0026 (e2.edge_before.bvStart = void 0, e2.edge_before.bvEnd = void 0, e2.edge_before.bv = void 0, e2.edge_before.overlap = void 0), e2.edge_after \u0026\u0026 (e2.edge_after.bvStart = void 0, e2.edge_after.bvEnd = void 0, e2.edge_after.bv = void 0, e2.edge_after.overlap = void 0);\n for (let e2 of t48) e2.edge_before \u0026\u0026 (e2.edge_before.bvEnd = 2), e2.edge_after \u0026\u0026 (e2.edge_after.bvStart = 2);\n}\nfunction gE(t48, e2) {\n for (let n2 of t48) n2.edge_before \u0026\u0026 n2.edge_before.setInclusion(e2), n2.edge_after \u0026\u0026 n2.edge_after.setInclusion(e2);\n}\nfunction fE(t48, e2, n2) {\n let o2, i2, r2 = 1;\n if (1 === t48.length) return 1;\n o2 = t48[e2];\n for (let s2 = e2 + 1; s2 \u003c t48.length \u0026\u0026 o2.face === n2 \u0026\u0026 (i2 = t48[s2], i2.pt.equalTo(o2.pt) \u0026\u0026 i2.edge_before === o2.edge_before \u0026\u0026 i2.edge_after === o2.edge_after); s2++) r2++;\n return r2;\n}\nfunction _E(t48, e2) {\n if (e2) {\n for (let n2 of e2) {\n let e3 = n2.edge_before;\n if (n2.is_vertex = 0, e3.shape.start \u0026\u0026 e3.shape.start.equalTo(n2.pt) \u0026\u0026 (n2.is_vertex |= 1), e3.shape.end \u0026\u0026 e3.shape.end.equalTo(n2.pt) \u0026\u0026 (n2.is_vertex |= 2), 1 \u0026 n2.is_vertex) {\n n2.edge_before = e3.prev, e3.prev \u0026\u0026 (n2.is_vertex = 2);\n continue;\n }\n if (2 \u0026 n2.is_vertex) continue;\n let o2 = t48.addVertex(n2.pt, e3);\n n2.edge_before = o2;\n }\n for (let n2 of e2) n2.edge_before ? n2.edge_after = n2.edge_before.next : t48 instanceof cE \u0026\u0026 1 \u0026 n2.is_vertex \u0026\u0026 (n2.edge_after = t48.first);\n }\n}\nfunction yE(t48, e2, n2) {\n const o2 = t48.edge_before, i2 = e2.edge_after, r2 = n2.length;\n o2.next = n2[0], n2[0].prev = o2, n2[r2 - 1].next = i2, i2.prev = n2[r2 - 1];\n}\nPR.multiline = (...t48) =\u003e new PR.Multiline(...t48);\nvar { INSIDE: bE, OUTSIDE: xE, BOUNDARY: vE, OVERLAP_SAME: SE, OVERLAP_OPPOSITE: IE } = fR;\nvar { NOT_VERTEX: PE, START_VERTEX: ME, END_VERTEX: CE } = fR;\nfunction NE(t48, e2) {\n let n2 = e2.clone().reverse(), [o2, i2] = OE(t48, n2, 3, true);\n return o2;\n}\nfunction wE(t48, e2) {\n let [n2, o2] = OE(t48, e2, 2, true);\n return n2;\n}\nfunction TE(t48, e2) {\n let [n2, o2] = OE(t48, e2, 2, false), i2 = [];\n for (let t49 of n2.faces) i2 = [...i2, ...[...t49.edges].map((t50) =\u003e t50.shape)];\n let r2 = [];\n for (let t49 of o2.faces) r2 = [...r2, ...[...t49.edges].map((t50) =\u003e t50.shape)];\n return [i2, r2];\n}\nfunction RE(t48, e2) {\n let [n2, o2] = OE(t48, e2, 3, false), i2 = [];\n for (let t49 of n2.faces) i2 = [...i2, ...[...t49.edges].map((t50) =\u003e t50.shape)];\n return i2;\n}\nfunction EE(t48, e2) {\n let n2 = t48.clone(), o2 = e2.clone(), i2 = LE(n2, o2);\n return hE(i2), _E(n2, i2.int_points1_sorted), _E(o2, i2.int_points2_sorted), pE(i2), hE(i2), [i2.int_points1_sorted.map((t49) =\u003e t49.pt), i2.int_points2_sorted.map((t49) =\u003e t49.pt)];\n}\nfunction AE(t48, e2, n2, o2) {\n let i2 = DE(t48, n2.int_points1), r2 = DE(e2, n2.int_points2);\n for (zE(i2, e2), zE(r2, t48), mE(n2.int_points1), mE(n2.int_points2), gE(n2.int_points1, e2), gE(n2.int_points2, t48); kE(t48, e2, n2.int_points1, n2.int_points1_sorted, n2.int_points2, n2); ) ;\n !(function(t49) {\n let e3, n3, o3, i3 = t49.int_points1.length;\n for (let r3 = 0; r3 \u003c i3; r3++) {\n let s2 = t49.int_points1_sorted[r3];\n s2.face !== e3 \u0026\u0026 (n3 = r3, e3 = s2.face);\n let a2, c2 = r3, l2 = fE(t49.int_points1_sorted, r3, e3);\n a2 = c2 + l2 \u003c i3 \u0026\u0026 t49.int_points1_sorted[c2 + l2].face === e3 ? c2 + l2 : n3;\n let h2 = fE(t49.int_points1_sorted, a2, e3);\n o3 = null;\n for (let n4 = a2; n4 \u003c a2 + h2; n4++) {\n let i4 = t49.int_points1_sorted[n4];\n if (i4.face === e3 \u0026\u0026 t49.int_points2[i4.id].face === t49.int_points2[s2.id].face) {\n o3 = i4;\n break;\n }\n }\n if (null === o3) continue;\n let d2 = s2.edge_after, u2 = o3.edge_before;\n if (2 !== d2.bv || 2 !== u2.bv) continue;\n if (d2 !== u2) continue;\n let p2 = t49.int_points2[s2.id], m2 = t49.int_points2[o3.id], g2 = p2.edge_after, f2 = m2.edge_before;\n 2 === g2.bv \u0026\u0026 2 === f2.bv \u0026\u0026 g2 === f2 || (p2 = t49.int_points2[o3.id], m2 = t49.int_points2[s2.id], g2 = p2.edge_after, f2 = m2.edge_before), 2 === g2.bv \u0026\u0026 2 === f2.bv \u0026\u0026 g2 === f2 \u0026\u0026 d2.setOverlap(g2);\n }\n })(n2), FE(t48, o2, n2.int_points1_sorted, true), FE(e2, o2, n2.int_points2_sorted, false), $E(t48, i2, o2, true), $E(e2, r2, o2, false);\n}\nfunction OE(t48, e2, n2, o2) {\n let i2 = t48.clone(), r2 = e2.clone(), s2 = LE(i2, r2);\n return hE(s2), _E(i2, s2.int_points1_sorted), _E(r2, s2.int_points2_sorted), pE(s2), hE(s2), AE(i2, r2, s2, n2), o2 \u0026\u0026 (function(t49, e3, n3) {\n !(function(t50, e4, n4, o3) {\n for (let n5 of e4.faces) {\n for (let e5 of n5) t50.edges.add(e5);\n void 0 === o3.find((t51) =\u003e t51.face === n5) \u0026\u0026 t50.addFace(n5.first, n5.last);\n }\n })(t49, e3, 0, n3.int_points2), (function(t50, e4, n4) {\n if (0 !== n4.int_points1.length) for (let t51 = 0; t51 \u003c n4.int_points1.length; t51++) {\n let e5 = n4.int_points1[t51], o3 = n4.int_points2[t51];\n if (void 0 !== e5.edge_before \u0026\u0026 void 0 === e5.edge_after \u0026\u0026 void 0 === o3.edge_before \u0026\u0026 void 0 !== o3.edge_after \u0026\u0026 (e5.edge_before.next = o3.edge_after, o3.edge_after.prev = e5.edge_before, e5.edge_after = o3.edge_after, o3.edge_before = e5.edge_before), void 0 !== o3.edge_before \u0026\u0026 void 0 === o3.edge_after \u0026\u0026 void 0 === e5.edge_before \u0026\u0026 void 0 !== e5.edge_after \u0026\u0026 (o3.edge_before.next = e5.edge_after, e5.edge_after.prev = o3.edge_before, o3.edge_after = e5.edge_after, e5.edge_before = o3.edge_before), void 0 !== e5.edge_before \u0026\u0026 void 0 === e5.edge_after) for (let t52 of n4.int_points1_sorted) t52 !== e5 \u0026\u0026 void 0 === t52.edge_before \u0026\u0026 void 0 !== t52.edge_after \u0026\u0026 t52.pt.equalTo(e5.pt) \u0026\u0026 (e5.edge_before.next = t52.edge_after, t52.edge_after.prev = e5.edge_before, e5.edge_after = t52.edge_after, t52.edge_before = e5.edge_before);\n if (void 0 !== o3.edge_before \u0026\u0026 void 0 === o3.edge_after) for (let t52 of n4.int_points2_sorted) t52 !== o3 \u0026\u0026 void 0 === t52.edge_before \u0026\u0026 void 0 !== t52.edge_after \u0026\u0026 t52.pt.equalTo(o3.pt) \u0026\u0026 (o3.edge_before.next = t52.edge_after, t52.edge_after.prev = o3.edge_before, o3.edge_after = t52.edge_after, t52.edge_before = o3.edge_before);\n }\n })(0, 0, n3), jE(t49, n3.int_points1), jE(e3, n3.int_points2), YE(t49, n3.int_points1, n3.int_points2), YE(t49, n3.int_points2, n3.int_points1), XE(t49), XE(e3);\n })(i2, r2, s2), [i2, r2];\n}\nfunction LE(t48, e2) {\n let n2 = { int_points1: [], int_points2: [] };\n for (let o2 of t48.edges) {\n let t49 = e2.edges.search(o2.box);\n for (let e3 of t49) {\n let t50 = o2.shape.intersect(e3.shape);\n for (let i2 of t50) lE(o2, i2, n2.int_points1), lE(e3, i2, n2.int_points2);\n }\n }\n return n2;\n}\nfunction DE(t48, e2) {\n let n2 = [];\n for (let o2 of t48.faces) e2.find((t49) =\u003e t49.face === o2) || n2.push(o2);\n return n2;\n}\nfunction zE(t48, e2) {\n for (let n2 of t48) n2.first.bv = n2.first.bvStart = n2.first.bvEnd = void 0, n2.first.setInclusion(e2);\n}\nfunction kE(t48, e2, n2, o2, i2, r2) {\n let s2, a2, c2, l2 = o2.length, h2 = false;\n for (let d2 = 0; d2 \u003c l2; d2++) {\n let u2 = o2[d2];\n u2.face !== s2 \u0026\u0026 (a2 = d2, s2 = u2.face);\n let p2, m2 = d2, g2 = fE(o2, d2, s2);\n p2 = m2 + g2 \u003c l2 \u0026\u0026 o2[m2 + g2].face === s2 ? m2 + g2 : a2;\n let f2 = fE(o2, p2, s2);\n c2 = null;\n for (let t49 = p2; t49 \u003c p2 + f2; t49++) {\n let e3 = o2[t49];\n if (e3.face === s2 \u0026\u0026 i2[e3.id].face === i2[u2.id].face) {\n c2 = e3;\n break;\n }\n }\n if (null === c2) continue;\n let _2 = u2.edge_after, y2 = c2.edge_before;\n if (_2.bv !== vE || y2.bv == vE) if (_2.bv == vE || y2.bv !== vE) {\n if (_2.bv === vE \u0026\u0026 y2.bv === vE \u0026\u0026 _2 != y2 || _2.bv === bE \u0026\u0026 y2.bv === xE || _2.bv === xE \u0026\u0026 y2.bv === bE) {\n let t49 = _2.next;\n for (; t49 != y2; ) t49.bvStart = void 0, t49.bvEnd = void 0, t49.bv = void 0, t49.setInclusion(e2), t49 = t49.next;\n }\n if (_2.bv === vE \u0026\u0026 y2.bv === vE \u0026\u0026 _2 != y2) {\n let t49, e3 = _2.next;\n for (; e3 != y2; ) {\n if (e3.bv != vE) {\n if (void 0 === t49) t49 = e3.bv;\n else if (e3.bv != t49) throw MR.UNRESOLVED_BOUNDARY_CONFLICT;\n }\n e3 = e3.next;\n }\n null != t49 \u0026\u0026 (_2.bv = t49, y2.bv = t49);\n continue;\n }\n if (_2.bv === bE \u0026\u0026 y2.bv === xE || _2.bv === xE \u0026\u0026 y2.bv === bE) {\n let o3 = _2;\n for (; o3 != y2; ) {\n if (o3.bvStart === _2.bv \u0026\u0026 o3.bvEnd === y2.bv) {\n let [s3, a3] = o3.shape.distanceTo(e2);\n if (s3 \u003c 10 * PR.DP_TOL) {\n lE(o3, a3.ps, n2);\n let s4 = n2[n2.length - 1];\n if (s4.is_vertex \u0026 ME) s4.edge_after = o3, s4.edge_before = o3.prev, o3.bvStart = vE, o3.bv = void 0, o3.setInclusion(e2);\n else if (s4.is_vertex \u0026 CE) s4.edge_after = o3.next, o3.bvEnd = vE, o3.bv = void 0, o3.setInclusion(e2);\n else {\n let t49 = e2.addVertex(s4.pt, o3);\n s4.edge_before = t49, s4.edge_after = t49.next, t49.setInclusion(e2), t49.next.bvStart = vE, t49.next.bvEnd = void 0, t49.next.bv = void 0, t49.next.setInclusion(e2);\n }\n let c3 = e2.findEdgeByPoint(a3.pe);\n lE(c3, a3.pe, i2);\n let l3 = i2[i2.length - 1];\n if (l3.is_vertex \u0026 ME) l3.edge_after = c3, l3.edge_before = c3.prev;\n else if (l3.is_vertex \u0026 CE) l3.edge_after = c3.next;\n else {\n let n3 = i2.find((t49) =\u003e t49.edge_after === c3), o4 = e2.addVertex(l3.pt, c3);\n l3.edge_before = o4, l3.edge_after = o4.next, n3 \u0026\u0026 (n3.edge_after = o4), o4.bvStart = void 0, o4.bvEnd = vE, o4.bv = void 0, o4.setInclusion(t48), o4.next.bvStart = vE, o4.next.bvEnd = void 0, o4.next.bv = void 0, o4.next.setInclusion(t48);\n }\n hE(r2), h2 = true;\n break;\n }\n }\n o3 = o3.next;\n }\n if (h2) break;\n throw MR.UNRESOLVED_BOUNDARY_CONFLICT;\n }\n } else y2.bv = _2.bv;\n else _2.bv = y2.bv;\n }\n return h2;\n}\nfunction FE(t48, e2, n2, o2) {\n if (!n2) return;\n let i2, r2, s2, a2;\n for (let c2 = 0; c2 \u003c n2.length; c2++) {\n if (s2 = n2[c2], s2.face !== i2 \u0026\u0026 (r2 = c2, i2 = s2.face), i2.isEmpty()) continue;\n let l2, h2 = c2, d2 = fE(n2, c2, i2);\n l2 = h2 + d2 \u003c n2.length \u0026\u0026 n2[h2 + d2].face === s2.face ? h2 + d2 : r2, a2 = n2[l2];\n let u2 = l2, p2 = fE(n2, u2, i2), m2 = s2.edge_after, g2 = a2.edge_before;\n if (m2.bv === bE \u0026\u0026 g2.bv === bE \u0026\u0026 1 === e2 || m2.bv === xE \u0026\u0026 g2.bv === xE \u0026\u0026 2 === e2 || (m2.bv === xE || g2.bv === xE) \u0026\u0026 3 === e2 \u0026\u0026 !o2 || (m2.bv === bE || g2.bv === bE) \u0026\u0026 3 === e2 \u0026\u0026 o2 || m2.bv === vE \u0026\u0026 g2.bv === vE \u0026\u0026 m2.overlap \u0026 SE \u0026\u0026 o2 || m2.bv === vE \u0026\u0026 g2.bv === vE \u0026\u0026 m2.overlap \u0026 IE) {\n t48.removeChain(i2, m2, g2);\n for (let t49 = h2; t49 \u003c h2 + d2; t49++) n2[t49].edge_after = void 0;\n for (let t49 = u2; t49 \u003c u2 + p2; t49++) n2[t49].edge_before = void 0;\n }\n c2 += d2 - 1;\n }\n}\nfunction jE(t48, e2) {\n for (let n2 of e2) t48.faces.delete(n2.face), n2.face = void 0, n2.edge_before \u0026\u0026 (n2.edge_before.face = void 0), n2.edge_after \u0026\u0026 (n2.edge_after.face = void 0);\n}\nfunction YE(t48, e2, n2) {\n for (let o2 of e2) {\n if (void 0 === o2.edge_before || void 0 === o2.edge_after) continue;\n if (o2.face) continue;\n if (o2.edge_after.face || o2.edge_before.face) continue;\n let i2 = o2.edge_after, r2 = o2.edge_before;\n try {\n CR.testInfiniteLoop(i2);\n } catch (t49) {\n throw MR.CANNOT_COMPLETE_BOOLEAN_OPERATION;\n }\n let s2 = t48.addFace(i2, r2);\n for (let t49 of e2) t49.edge_before \u0026\u0026 t49.edge_after \u0026\u0026 t49.edge_before.face === s2 \u0026\u0026 t49.edge_after.face === s2 \u0026\u0026 (t49.face = s2);\n for (let t49 of n2) t49.edge_before \u0026\u0026 t49.edge_after \u0026\u0026 t49.edge_before.face === s2 \u0026\u0026 t49.edge_after.face === s2 \u0026\u0026 (t49.face = s2);\n }\n}\nfunction $E(t48, e2, n2, o2) {\n for (let i2 of e2) {\n let e3 = i2.first.bv;\n (1 === n2 \u0026\u0026 e3 === bE || 3 === n2 \u0026\u0026 e3 === bE \u0026\u0026 o2 || 3 === n2 \u0026\u0026 e3 === xE \u0026\u0026 !o2 || 2 === n2 \u0026\u0026 e3 === xE) \u0026\u0026 t48.deleteFace(i2);\n }\n}\nfunction XE(t48) {\n const e2 = [];\n for (const n2 of t48.edges) n2.face \u0026\u0026 t48.faces.has(n2.face) || e2.push(n2);\n for (const n2 of e2) t48.edges.delete(n2);\n}\nvar BE = Object.freeze({ __proto__: null, BOOLEAN_INTERSECT: 2, BOOLEAN_SUBTRACT: 3, BOOLEAN_UNION: 1, calculateIntersections: EE, innerClip: TE, intersect: wE, outerClip: RE, removeNotRelevantChains: FE, removeOldFaces: jE, restoreFaces: YE, subtract: NE, unify: function(t48, e2) {\n let [n2, o2] = OE(t48, e2, 1, true);\n return n2;\n} });\nvar HE = RegExp(\"T.F..FFF.|T.F...F..\");\nvar WE = RegExp(\"T........|.T.......|...T.....|....T....\");\nvar VE = RegExp(\"FT.......|F..T.....|F...T....\");\nvar UE = RegExp(\"T.F..F...\");\nvar GE = RegExp(\"T.F..F...|.TF..F...|..FT.F...|..F.TF...\");\nvar ZE = class {\n constructor() {\n this.m = new Array(9).fill(void 0);\n }\n get I2I() {\n return this.m[0];\n }\n set I2I(t48) {\n this.m[0] = t48;\n }\n get I2B() {\n return this.m[1];\n }\n set I2B(t48) {\n this.m[1] = t48;\n }\n get I2E() {\n return this.m[2];\n }\n set I2E(t48) {\n this.m[2] = t48;\n }\n get B2I() {\n return this.m[3];\n }\n set B2I(t48) {\n this.m[3] = t48;\n }\n get B2B() {\n return this.m[4];\n }\n set B2B(t48) {\n this.m[4] = t48;\n }\n get B2E() {\n return this.m[5];\n }\n set B2E(t48) {\n this.m[5] = t48;\n }\n get E2I() {\n return this.m[6];\n }\n set E2I(t48) {\n this.m[6] = t48;\n }\n get E2B() {\n return this.m[7];\n }\n set E2B(t48) {\n this.m[7] = t48;\n }\n get E2E() {\n return this.m[8];\n }\n set E2E(t48) {\n this.m[8] = t48;\n }\n toString() {\n return this.m.map((t48) =\u003e t48 instanceof Array \u0026\u0026 t48.length \u003e 0 ? \"T\" : t48 instanceof Array \u0026\u0026 0 === t48.length ? \"F\" : \"*\").join(\"\");\n }\n equal() {\n return HE.test(this.toString());\n }\n intersect() {\n return WE.test(this.toString());\n }\n touch() {\n return VE.test(this.toString());\n }\n inside() {\n return UE.test(this.toString());\n }\n covered() {\n return GE.test(this.toString());\n }\n};\nfunction qE(t48, e2) {\n let n2, o2 = new PR.Ray(e2), i2 = new PR.Line(o2.pt, o2.norm);\n const r2 = new PR.Box(o2.box.xmin - PR.DP_TOL, o2.box.ymin - PR.DP_TOL, o2.box.xmax + PR.DP_TOL, o2.box.ymax + PR.DP_TOL);\n if (t48.box.not_intersect(r2)) return PR.OUTSIDE;\n let s2 = t48.edges.search(r2);\n if (0 === s2.length) return PR.OUTSIDE;\n for (let t49 of s2) if (t49.shape.contains(e2)) return PR.BOUNDARY;\n let a2 = [...t48.faces], c2 = [];\n for (let t49 of s2) for (let n3 of o2.intersect(t49.shape)) {\n if (n3.equalTo(e2)) return PR.BOUNDARY;\n c2.push({ pt: n3, edge: t49, face_index: a2.indexOf(t49.face) });\n }\n c2.sort((t49, e3) =\u003e IR(t49.pt.x, e3.pt.x) ? -1 : SR(t49.pt.x, e3.pt.x) ? 1 : t49.face_index \u003c e3.face_index ? -1 : t49.face_index \u003e e3.face_index ? 1 : t49.edge.arc_length \u003c e3.edge.arc_length ? -1 : t49.edge.arc_length \u003e e3.edge.arc_length ? 1 : 0);\n let l2 = 0;\n for (let t49 = 0; t49 \u003c c2.length; t49++) {\n let e3 = c2[t49];\n if (e3.pt.equalTo(e3.edge.shape.start)) {\n if (t49 \u003e 0 \u0026\u0026 e3.pt.equalTo(c2[t49 - 1].pt) \u0026\u0026 e3.face_index === c2[t49 - 1].face_index \u0026\u0026 e3.edge.prev === c2[t49 - 1].edge) continue;\n let n3 = e3.edge.prev;\n for (; xR(n3.length); ) n3 = n3.prev;\n let o3 = n3.shape.tangentInEnd(), r3 = e3.pt.translate(o3), s3 = e3.edge.shape.tangentInStart(), a3 = e3.pt.translate(s3), h2 = r3.leftTo(i2), d2 = a3.leftTo(i2);\n (h2 \u0026\u0026 !d2 || !h2 \u0026\u0026 d2) \u0026\u0026 l2++;\n } else if (e3.pt.equalTo(e3.edge.shape.end)) {\n if (t49 \u003e 0 \u0026\u0026 e3.pt.equalTo(c2[t49 - 1].pt) \u0026\u0026 e3.face_index === c2[t49 - 1].face_index \u0026\u0026 e3.edge.next === c2[t49 - 1].edge) continue;\n let n3 = e3.edge.next;\n for (; xR(n3.length); ) n3 = n3.next;\n let o3 = n3.shape.tangentInStart(), r3 = e3.pt.translate(o3), s3 = e3.edge.shape.tangentInEnd(), a3 = e3.pt.translate(s3), h2 = r3.leftTo(i2), d2 = a3.leftTo(i2);\n (h2 \u0026\u0026 !d2 || !h2 \u0026\u0026 d2) \u0026\u0026 l2++;\n } else if (e3.edge.shape instanceof PR.Segment) l2++;\n else {\n let t50 = e3.edge.shape.box;\n vR(e3.pt.y, t50.ymin) || vR(e3.pt.y, t50.ymax) || l2++;\n }\n }\n return n2 = l2 % 2 == 1 ? 1 : 0, n2;\n}\nfunction JE(t48, e2) {\n return eA(t48, e2).intersect();\n}\nfunction KE(t48, e2) {\n return eA(t48, e2).inside();\n}\nfunction QE(t48, e2) {\n return eA(t48, e2).covered();\n}\nfunction tA(t48, e2) {\n return QE(e2, t48);\n}\nfunction eA(t48, e2) {\n return t48 instanceof PR.Line \u0026\u0026 e2 instanceof PR.Line ? (function(t49, e3) {\n let n2 = new ZE(), o2 = RR(t49, e3);\n 0 === o2.length ? t49.contains(e3.pt) \u0026\u0026 e3.contains(t49.pt) ? (n2.I2I = [t49], n2.I2E = [], n2.E2I = []) : (n2.I2I = [], n2.I2E = [t49], n2.E2I = [e3]) : (n2.I2I = o2, n2.I2E = t49.split(o2), n2.E2I = e3.split(o2));\n return n2;\n })(t48, e2) : t48 instanceof PR.Line \u0026\u0026 e2 instanceof PR.Circle ? (function(t49, e3) {\n let n2 = new ZE(), o2 = ER(t49, e3);\n if (0 === o2.length) n2.I2I = [], n2.I2B = [], n2.I2E = [t49], n2.E2I = [e3];\n else if (1 === o2.length) n2.I2I = [], n2.I2B = o2, n2.I2E = t49.split(o2), n2.E2I = [e3];\n else {\n let i2 = new cE([t49]), r2 = t49.sortPoints(o2);\n i2.split(r2);\n let s2 = i2.toShapes();\n n2.I2I = [s2[1]], n2.I2B = r2, n2.I2E = [s2[0], s2[2]], n2.E2I = new PR.Polygon([e3.toArc()]).cutWithLine(t49);\n }\n return n2;\n })(t48, e2) : t48 instanceof PR.Line \u0026\u0026 e2 instanceof PR.Box ? (function(t49, e3) {\n let n2 = new ZE(), o2 = AR(t49, e3);\n if (0 === o2.length) n2.I2I = [], n2.I2B = [], n2.I2E = [t49], n2.E2I = [e3];\n else if (1 === o2.length) n2.I2I = [], n2.I2B = o2, n2.I2E = t49.split(o2), n2.E2I = [e3];\n else {\n let i2 = new cE([t49]), r2 = t49.sortPoints(o2);\n i2.split(r2);\n let s2 = i2.toShapes();\n e3.toSegments().some((t50) =\u003e t50.contains(o2[0]) \u0026\u0026 t50.contains(o2[1])) ? (n2.I2I = [], n2.I2B = [s2[1]], n2.I2E = [s2[0], s2[2]], n2.E2I = [e3]) : (n2.I2I = [s2[1]], n2.I2B = r2, n2.I2E = [s2[0], s2[2]], n2.E2I = new PR.Polygon(e3.toSegments()).cutWithLine(t49));\n }\n return n2;\n })(t48, e2) : t48 instanceof PR.Line \u0026\u0026 e2 instanceof PR.Polygon ? (function(t49, e3) {\n let n2 = new ZE(), o2 = ZR(t49, e3), i2 = new cE([t49]), r2 = o2.length \u003e 0 ? o2.slice() : t49.sortPoints(o2);\n return i2.split(r2), [...i2].forEach((t50) =\u003e t50.setInclusion(e3)), n2.I2I = [...i2].filter((t50) =\u003e t50.bv === PR.INSIDE).map((t50) =\u003e t50.shape), n2.I2B = [...i2].slice(1).map((t50) =\u003e t50.bv === PR.BOUNDARY ? t50.shape : t50.shape.start), n2.I2E = [...i2].filter((t50) =\u003e t50.bv === PR.OUTSIDE).map((t50) =\u003e t50.shape), n2.E2I = e3.cutWithLine(t49), n2;\n })(t48, e2) : (t48 instanceof PR.Segment || t48 instanceof PR.Arc) \u0026\u0026 e2 instanceof PR.Polygon ? nA(t48, e2) : (t48 instanceof PR.Segment || t48 instanceof PR.Arc) \u0026\u0026 (e2 instanceof PR.Circle || e2 instanceof PR.Box) ? nA(t48, new PR.Polygon(e2)) : t48 instanceof PR.Polygon \u0026\u0026 e2 instanceof PR.Polygon ? oA(t48, e2) : (t48 instanceof PR.Circle || t48 instanceof PR.Box) \u0026\u0026 (e2 instanceof PR.Circle || e2 instanceof PR.Box) ? oA(new PR.Polygon(t48), new PR.Polygon(e2)) : (t48 instanceof PR.Circle || t48 instanceof PR.Box) \u0026\u0026 e2 instanceof PR.Polygon ? oA(new PR.Polygon(t48), e2) : t48 instanceof PR.Polygon \u0026\u0026 (e2 instanceof PR.Circle || e2 instanceof PR.Box) ? oA(t48, new PR.Polygon(e2)) : void 0;\n}\nfunction nA(t48, e2) {\n let n2 = new ZE(), o2 = (function(t49, e3) {\n return t49 instanceof PR.Line ? ZR(t49, e3) : t49 instanceof PR.Segment ? UR(t49, e3) : t49 instanceof PR.Arc ? GR(t49, e3) : [];\n })(t48, e2), i2 = o2.length \u003e 0 ? o2.slice() : t48.sortPoints(o2), r2 = new cE([t48]);\n r2.split(i2), [...r2].forEach((t49) =\u003e t49.setInclusion(e2)), n2.I2I = [...r2].filter((t49) =\u003e t49.bv === PR.INSIDE).map((t49) =\u003e t49.shape), n2.I2B = [...r2].slice(1).map((t49) =\u003e t49.bv === PR.BOUNDARY ? t49.shape : t49.shape.start), n2.I2E = [...r2].filter((t49) =\u003e t49.bv === PR.OUTSIDE).map((t49) =\u003e t49.shape), n2.B2I = [], n2.B2B = [], n2.B2E = [];\n for (let o3 of [t48.start, t48.end]) switch (qE(e2, o3)) {\n case PR.INSIDE:\n n2.B2I.push(o3);\n break;\n case PR.BOUNDARY:\n n2.B2B.push(o3);\n break;\n case PR.OUTSIDE:\n n2.B2E.push(o3);\n }\n return n2;\n}\nfunction oA(t48, e2) {\n let n2 = new ZE(), [o2, i2] = EE(t48, e2), r2 = wE(t48, e2), s2 = NE(t48, e2), a2 = NE(e2, t48), [c2, l2] = TE(t48, e2), h2 = RE(t48, e2), d2 = RE(e2, t48);\n return n2.I2I = r2.isEmpty() ? [] : [r2], n2.I2B = l2, n2.I2E = s2.isEmpty() ? [] : [s2], n2.B2I = c2, n2.B2B = o2, n2.B2E = h2, n2.E2I = a2.isEmpty() ? [] : [a2], n2.E2B = d2, n2;\n}\nvar iA = Object.freeze({ __proto__: null, contain: function(t48, e2) {\n return KE(e2, t48);\n}, cover: tA, covered: QE, disjoint: function(t48, e2) {\n return !JE(t48, e2);\n}, equal: function(t48, e2) {\n return eA(t48, e2).equal();\n}, inside: KE, intersect: JE, relate: eA, touch: function(t48, e2) {\n return eA(t48, e2).touch();\n} });\nvar rA = class t33 {\n constructor(t48 = 1, e2 = 0, n2 = 0, o2 = 1, i2 = 0, r2 = 0) {\n this.a = t48, this.b = e2, this.c = n2, this.d = o2, this.tx = i2, this.ty = r2;\n }\n fromMatrix3x3(e2) {\n const [n2, o2, i2] = e2[0], [r2, s2, a2] = e2[1];\n return new t33(n2, r2, o2, s2, i2, a2);\n }\n toMatrix3x3() {\n return [[this.a, this.c, this.tx], [this.b, this.d, this.ty], [0, 0, 1]];\n }\n clone() {\n return new t33(this.a, this.b, this.c, this.d, this.tx, this.ty);\n }\n transform(t48) {\n return [t48[0] * this.a + t48[1] * this.c + this.tx, t48[0] * this.b + t48[1] * this.d + this.ty];\n }\n multiply(e2) {\n return new t33(this.a * e2.a + this.c * e2.b, this.b * e2.a + this.d * e2.b, this.a * e2.c + this.c * e2.d, this.b * e2.c + this.d * e2.d, this.a * e2.tx + this.c * e2.ty + this.tx, this.b * e2.tx + this.d * e2.ty + this.ty);\n }\n translate(...e2) {\n let n2, o2;\n if (1 != e2.length || isNaN(e2[0].x) || isNaN(e2[0].y)) {\n if (2 !== e2.length || \"number\" != typeof e2[0] || \"number\" != typeof e2[1]) throw MR.ILLEGAL_PARAMETERS;\n n2 = e2[0], o2 = e2[1];\n } else n2 = e2[0].x, o2 = e2[0].y;\n return this.multiply(new t33(1, 0, 0, 1, n2, o2));\n }\n rotate(e2, n2 = 0, o2 = 0) {\n let i2 = Math.cos(e2), r2 = Math.sin(e2);\n return this.translate(n2, o2).multiply(new t33(i2, r2, -r2, i2, 0, 0)).translate(-n2, -o2);\n }\n scale(e2, n2) {\n return this.multiply(new t33(e2, 0, 0, n2, 0, 0));\n }\n equalTo(t48) {\n return !!PR.Utils.EQ(this.tx, t48.tx) \u0026\u0026 (!!PR.Utils.EQ(this.ty, t48.ty) \u0026\u0026 (!!PR.Utils.EQ(this.a, t48.a) \u0026\u0026 (!!PR.Utils.EQ(this.b, t48.b) \u0026\u0026 (!!PR.Utils.EQ(this.c, t48.c) \u0026\u0026 !!PR.Utils.EQ(this.d, t48.d)))));\n }\n};\nPR.Matrix = rA;\nPR.matrix = (...t48) =\u003e new PR.Matrix(...t48);\nvar sA = class {\n constructor(t48, e2) {\n this.low = t48, this.high = e2;\n }\n get max() {\n return this.clone();\n }\n less_than(t48) {\n return this.low \u003c t48.low || this.low === t48.low \u0026\u0026 this.high \u003c t48.high;\n }\n equal_to(t48) {\n return this.low === t48.low \u0026\u0026 this.high === t48.high;\n }\n intersect(t48) {\n return !this.not_intersect(t48);\n }\n not_intersect(t48) {\n return this.high \u003c t48.low || t48.high \u003c this.low;\n }\n merge(t48) {\n const e2 = void 0 === this.low ? t48.low : this.low \u003c t48.low ? this.low : t48.low, n2 = void 0 === this.high ? t48.high : this.high \u003e t48.high ? this.high : t48.high, o2 = this.clone();\n return o2.low = e2, o2.high = n2, o2;\n }\n output() {\n return [this.low, this.high];\n }\n comparable_less_than(t48, e2) {\n return t48 \u003c e2;\n }\n};\nvar aA = class t34 extends sA {\n clone() {\n return new t34(this.low, this.high);\n }\n};\nvar cA = class {\n constructor(t48, e2, n2 = null, o2 = null, i2 = null, r2 = 0) {\n if (this.left = n2, this.right = o2, this.parent = i2, this.color = r2, this.item = { key: void 0, values: [] }, void 0 !== e2 \u0026\u0026 this.item.values.push(e2), void 0 !== t48) if (Array.isArray(t48)) {\n const [e3, n3] = t48;\n if (!Number.isNaN(e3) \u0026\u0026 !Number.isNaN(n3)) {\n let t49 = e3, o3 = n3;\n t49 \u003e o3 \u0026\u0026 ([t49, o3] = [o3, t49]), this.item.key = new aA(t49, o3);\n }\n } else this.item.key = t48;\n this.max = this.item.key ? this.item.key.max : void 0;\n }\n isNil() {\n return void 0 === this.item.key \u0026\u0026 0 === this.item.values.length \u0026\u0026 null === this.left \u0026\u0026 null === this.right \u0026\u0026 0 === this.color;\n }\n requireKey() {\n if (!this.item.key) throw new Error(\"Node key is undefined (nil/sentinel). Operation is not applicable.\");\n return this.item.key;\n }\n less_than(t48) {\n const e2 = this.requireKey(), n2 = t48.requireKey();\n return e2.less_than(n2);\n }\n _value_equal(t48) {\n const e2 = this.item.values[0], n2 = t48.item.values[0];\n return e2 \u0026\u0026 n2 \u0026\u0026 e2.equal_to ? e2.equal_to(n2) : e2 === n2;\n }\n equal_to(t48) {\n const e2 = this.requireKey(), n2 = t48.requireKey();\n return e2.equal_to(n2);\n }\n intersect(t48) {\n const e2 = this.requireKey(), n2 = t48.requireKey();\n return e2.intersect(n2);\n }\n copy_data(t48) {\n this.item.key = t48.item.key, this.item.values = t48.item.values.slice();\n }\n update_max() {\n this.max = this.item.key ? this.item.key.max : void 0, this.right \u0026\u0026 this.right.max \u0026\u0026 (this.max = this.max ? this.max.merge(this.right.max) : this.right.max), this.left \u0026\u0026 this.left.max \u0026\u0026 (this.max = this.max ? this.max.merge(this.left.max) : this.left.max);\n }\n not_intersect_left_subtree(t48) {\n if (!this.left) return true;\n const e2 = this.left.max ? this.left.max.high : this.left.item.key.high, n2 = this.requireKey(), o2 = t48.requireKey();\n return n2.comparable_less_than(e2, o2.low);\n }\n not_intersect_right_subtree(t48) {\n if (!this.right) return true;\n const e2 = this.right.max ? this.right.max.low : this.right.item.key.low, n2 = this.requireKey(), o2 = t48.requireKey();\n return n2.comparable_less_than(o2.high, e2);\n }\n};\nvar lA = class t35 {\n constructor() {\n this.root = null, this.nil_node = new cA();\n }\n get size() {\n let t48 = 0;\n return this.tree_walk(this.root, (e2) =\u003e t48 += e2.item.values.length), t48;\n }\n get keys() {\n const t48 = [];\n return this.tree_walk(this.root, (e2) =\u003e t48.push(e2.item.key.output())), t48;\n }\n get values() {\n const t48 = [];\n return this.tree_walk(this.root, (e2) =\u003e {\n for (const n2 of e2.item.values) t48.push(n2);\n }), t48;\n }\n get items() {\n const t48 = [];\n return this.tree_walk(this.root, (e2) =\u003e {\n const n2 = e2.item.key.output();\n for (const o2 of e2.item.values) t48.push({ key: n2, value: o2 });\n }), t48;\n }\n isEmpty() {\n return null == this.root || this.root === this.nil_node;\n }\n clear() {\n this.root = null;\n }\n insert(t48, e2 = t48) {\n if (void 0 === t48) return;\n const n2 = this.tree_search(this.root, new cA(t48));\n if (n2) return n2.item.values.push(e2), n2;\n const o2 = new cA(t48, e2, this.nil_node, this.nil_node, null, 1);\n return this.tree_insert(o2), this.recalc_max(o2), o2;\n }\n exist(t48, e2 = t48) {\n const n2 = this.tree_search(this.root, new cA(t48));\n return !!n2 \u0026\u0026 (arguments.length \u003c 2 || e2 === t48 || n2.item.values.some((t49) =\u003e t49 \u0026\u0026 t49.equal_to ? t49.equal_to(e2) : t49 === e2));\n }\n remove(t48, e2 = t48) {\n const n2 = this.tree_search(this.root, new cA(t48));\n if (!n2) return;\n if (arguments.length \u003c 2) return this.tree_delete(n2), n2;\n const o2 = n2.item.values.findIndex((t49) =\u003e t49 \u0026\u0026 t49.equal_to ? t49.equal_to(e2) : t49 === e2);\n return o2 \u003e= 0 ? (n2.item.values.splice(o2, 1), 0 === n2.item.values.length \u0026\u0026 this.tree_delete(n2), n2) : void 0;\n }\n search(t48, e2 = (t49, e3) =\u003e t49 === e3 ? e3.output() : t49) {\n const n2 = new cA(t48), o2 = [];\n this.tree_search_interval(this.root, n2, o2);\n const i2 = [];\n for (const t49 of o2) for (const n3 of t49.item.values) i2.push(e2(n3, t49.item.key));\n return i2;\n }\n intersect_any(t48) {\n const e2 = new cA(t48);\n return this.tree_find_any_interval(this.root, e2);\n }\n forEach(t48) {\n this.tree_walk(this.root, (e2) =\u003e {\n for (const n2 of e2.item.values) t48(e2.item.key, n2);\n });\n }\n map(e2) {\n const n2 = new t35();\n return this.tree_walk(this.root, (t48) =\u003e {\n for (const o2 of t48.item.values) n2.insert(t48.item.key, e2(o2, t48.item.key));\n }), n2;\n }\n *iterate(t48, e2 = (t49, e3) =\u003e t49 === e3 ? e3.output() : t49) {\n let n2 = null;\n for (t48 ? n2 = this.tree_search_nearest_forward(this.root, new cA(t48)) : this.root \u0026\u0026 (n2 = this.local_minimum(this.root)); n2; ) {\n for (const t49 of n2.item.values) yield e2(t49, n2.item.key);\n n2 = this.tree_successor(n2);\n }\n }\n recalc_max(t48) {\n let e2 = t48;\n for (; null != e2.parent; ) e2.parent.update_max(), e2 = e2.parent;\n }\n tree_insert(t48) {\n let e2 = this.root, n2 = null;\n if (null == this.root || this.root === this.nil_node) this.root = t48;\n else {\n for (; e2 !== this.nil_node; ) n2 = e2, e2 = t48.less_than(e2) ? e2.left : e2.right;\n t48.parent = n2, t48.less_than(n2) ? n2.left = t48 : n2.right = t48;\n }\n this.insert_fixup(t48);\n }\n insert_fixup(t48) {\n let e2, n2;\n for (e2 = t48; e2 !== this.root \u0026\u0026 1 === e2.parent.color; ) e2.parent === e2.parent.parent.left ? (n2 = e2.parent.parent.right, 1 === n2.color ? (e2.parent.color = 0, n2.color = 0, e2.parent.parent.color = 1, e2 = e2.parent.parent) : (e2 === e2.parent.right \u0026\u0026 (e2 = e2.parent, this.rotate_left(e2)), e2.parent.color = 0, e2.parent.parent.color = 1, this.rotate_right(e2.parent.parent))) : (n2 = e2.parent.parent.left, 1 === n2.color ? (e2.parent.color = 0, n2.color = 0, e2.parent.parent.color = 1, e2 = e2.parent.parent) : (e2 === e2.parent.left \u0026\u0026 (e2 = e2.parent, this.rotate_right(e2)), e2.parent.color = 0, e2.parent.parent.color = 1, this.rotate_left(e2.parent.parent)));\n this.root.color = 0;\n }\n tree_delete(t48) {\n let e2, n2;\n e2 = t48.left === this.nil_node || t48.right === this.nil_node ? t48 : this.tree_successor(t48), n2 = e2.left !== this.nil_node ? e2.left : e2.right, n2.parent = e2.parent, e2 === this.root ? this.root = n2 : (e2 === e2.parent.left ? e2.parent.left = n2 : e2.parent.right = n2, e2.parent.update_max()), this.recalc_max(n2), e2 !== t48 \u0026\u0026 (t48.copy_data(e2), t48.update_max(), this.recalc_max(t48)), 0 === e2.color \u0026\u0026 this.delete_fixup(n2);\n }\n delete_fixup(t48) {\n let e2, n2 = t48;\n for (; n2 !== this.root \u0026\u0026 null != n2.parent \u0026\u0026 0 === n2.color; ) n2 === n2.parent.left ? (e2 = n2.parent.right, 1 === e2.color \u0026\u0026 (e2.color = 0, n2.parent.color = 1, this.rotate_left(n2.parent), e2 = n2.parent.right), 0 === e2.left.color \u0026\u0026 0 === e2.right.color ? (e2.color = 1, n2 = n2.parent) : (0 === e2.right.color \u0026\u0026 (e2.color = 1, e2.left.color = 0, this.rotate_right(e2), e2 = n2.parent.right), e2.color = n2.parent.color, n2.parent.color = 0, e2.right.color = 0, this.rotate_left(n2.parent), n2 = this.root)) : (e2 = n2.parent.left, 1 === e2.color \u0026\u0026 (e2.color = 0, n2.parent.color = 1, this.rotate_right(n2.parent), e2 = n2.parent.left), 0 === e2.left.color \u0026\u0026 0 === e2.right.color ? (e2.color = 1, n2 = n2.parent) : (0 === e2.left.color \u0026\u0026 (e2.color = 1, e2.right.color = 0, this.rotate_left(e2), e2 = n2.parent.left), e2.color = n2.parent.color, n2.parent.color = 0, e2.left.color = 0, this.rotate_right(n2.parent), n2 = this.root));\n n2.color = 0;\n }\n tree_search(t48, e2) {\n if (null != t48 \u0026\u0026 t48 !== this.nil_node) return e2.equal_to(t48) ? t48 : e2.less_than(t48) ? this.tree_search(t48.left, e2) : this.tree_search(t48.right, e2);\n }\n tree_search_nearest_forward(t48, e2) {\n let n2 = null, o2 = t48;\n for (; o2 \u0026\u0026 o2 !== this.nil_node; ) o2.less_than(e2) ? o2.intersect(e2) ? (n2 = o2, o2 = o2.left) : o2 = o2.right : (n2 \u0026\u0026 !o2.less_than(n2) || (n2 = o2), o2 = o2.left);\n return n2 || null;\n }\n tree_search_interval(t48, e2, n2) {\n null != t48 \u0026\u0026 t48 !== this.nil_node \u0026\u0026 (t48.left === this.nil_node || t48.not_intersect_left_subtree(e2) || this.tree_search_interval(t48.left, e2, n2), t48.intersect(e2) \u0026\u0026 n2.push(t48), t48.right === this.nil_node || t48.not_intersect_right_subtree(e2) || this.tree_search_interval(t48.right, e2, n2));\n }\n tree_find_any_interval(t48, e2) {\n let n2 = false;\n return null != t48 \u0026\u0026 t48 !== this.nil_node \u0026\u0026 (t48.left === this.nil_node || t48.not_intersect_left_subtree(e2) || (n2 = this.tree_find_any_interval(t48.left, e2)), n2 || (n2 = t48.intersect(e2)), n2 || t48.right === this.nil_node || t48.not_intersect_right_subtree(e2) || (n2 = this.tree_find_any_interval(t48.right, e2))), n2;\n }\n local_minimum(t48) {\n let e2 = t48;\n for (; null != e2.left \u0026\u0026 e2.left !== this.nil_node; ) e2 = e2.left;\n return e2;\n }\n local_maximum(t48) {\n let e2 = t48;\n for (; null != e2.right \u0026\u0026 e2.right !== this.nil_node; ) e2 = e2.right;\n return e2;\n }\n tree_successor(t48) {\n let e2, n2, o2;\n if (t48.right !== this.nil_node) e2 = this.local_minimum(t48.right);\n else {\n for (n2 = t48, o2 = t48.parent; null != o2 \u0026\u0026 o2.right === n2; ) n2 = o2, o2 = o2.parent;\n e2 = o2;\n }\n return e2;\n }\n rotate_left(t48) {\n const e2 = t48.right;\n t48.right = e2.left, e2.left !== this.nil_node \u0026\u0026 (e2.left.parent = t48), e2.parent = t48.parent, t48 === this.root ? this.root = e2 : t48 === t48.parent.left ? t48.parent.left = e2 : t48.parent.right = e2, e2.left = t48, t48.parent = e2, null !== t48 \u0026\u0026 t48 !== this.nil_node \u0026\u0026 t48.update_max(), null != e2 \u0026\u0026 e2 !== this.nil_node \u0026\u0026 e2.update_max();\n }\n rotate_right(t48) {\n const e2 = t48.left;\n t48.left = e2.right, e2.right !== this.nil_node \u0026\u0026 (e2.right.parent = t48), e2.parent = t48.parent, t48 === this.root ? this.root = e2 : t48 === t48.parent.left ? t48.parent.left = e2 : t48.parent.right = e2, e2.right = t48, t48.parent = e2, null !== t48 \u0026\u0026 t48 !== this.nil_node \u0026\u0026 t48.update_max(), null != e2 \u0026\u0026 e2 !== this.nil_node \u0026\u0026 e2.update_max();\n }\n tree_walk(t48, e2) {\n null != t48 \u0026\u0026 t48 !== this.nil_node \u0026\u0026 (this.tree_walk(t48.left, e2), e2(t48), this.tree_walk(t48.right, e2));\n }\n testRedBlackProperty() {\n let t48 = true;\n return this.tree_walk(this.root, function(e2) {\n 1 === e2.color \u0026\u0026 (0 === e2.left.color \u0026\u0026 0 === e2.right.color || (t48 = false));\n }), t48;\n }\n testBlackHeightProperty(t48) {\n let e2 = 0, n2 = 0, o2 = 0;\n if (0 === t48.color \u0026\u0026 e2++, n2 = t48.left !== this.nil_node ? this.testBlackHeightProperty(t48.left) : 1, o2 = t48.right !== this.nil_node ? this.testBlackHeightProperty(t48.right) : 1, n2 !== o2) throw new Error(\"Red-black height property violated\");\n return e2 += n2, e2;\n }\n};\nvar hA = class extends Set {\n constructor(t48) {\n super(t48), this.index = new lA(), this.forEach((t49) =\u003e this.index.insert(t49));\n }\n add(t48) {\n let e2 = this.size;\n const { key: n2, value: o2 } = t48, i2 = n2 || t48.box, r2 = o2 || t48;\n return super.add(r2), this.size \u003e e2 \u0026\u0026 this.index.insert(i2, r2), this;\n }\n delete(t48) {\n const { key: e2, value: n2 } = t48, o2 = e2 || t48.box, i2 = n2 || t48;\n let r2 = super.delete(i2);\n return r2 \u0026\u0026 this.index.remove(o2, i2), r2;\n }\n clear() {\n super.clear(), this.index = new lA();\n }\n search(t48) {\n return this.index.search(t48);\n }\n hit(t48) {\n let e2 = new PR.Box(t48.x - 1, t48.y - 1, t48.x + 1, t48.y + 1);\n return this.index.search(e2).filter((e3) =\u003e t48.on(e3));\n }\n svg() {\n return [...this].reduce((t48, e2) =\u003e t48 + e2.svg(), \"\");\n }\n};\nPR.PlanarSet = hA;\nvar dA = class {\n get name() {\n throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n get box() {\n throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n clone() {\n throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n translate(...t48) {\n return this.transform(new rA().translate(...t48));\n }\n rotate(t48, e2 = new PR.Point()) {\n return this.transform(new rA().rotate(t48, e2.x, e2.y));\n }\n scale(t48, e2) {\n return this.transform(new rA().scale(t48, e2));\n }\n transform(...t48) {\n throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n toJSON() {\n return Object.assign({}, this, { name: this.name });\n }\n svg(t48 = {}) {\n throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;\n }\n};\nPR.Point = class t36 extends dA {\n constructor(...t48) {\n if (super(), this.x = 0, this.y = 0, 0 !== t48.length) {\n if (1 === t48.length \u0026\u0026 t48[0] instanceof Array \u0026\u0026 2 === t48[0].length) {\n let e2 = t48[0];\n if (\"number\" == typeof e2[0] \u0026\u0026 \"number\" == typeof e2[1]) return this.x = e2[0], void (this.y = e2[1]);\n }\n if (1 === t48.length \u0026\u0026 t48[0] instanceof Object \u0026\u0026 \"point\" === t48[0].name) {\n let { x: e2, y: n2 } = t48[0];\n return this.x = e2, void (this.y = n2);\n }\n if (2 === t48.length \u0026\u0026 \"number\" == typeof t48[0] \u0026\u0026 \"number\" == typeof t48[1]) return this.x = t48[0], void (this.y = t48[1]);\n throw MR.ILLEGAL_PARAMETERS;\n }\n }\n get box() {\n return new PR.Box(this.x, this.y, this.x, this.y);\n }\n clone() {\n return new PR.Point(this.x, this.y);\n }\n get vertices() {\n return [this.clone()];\n }\n equalTo(t48) {\n return PR.Utils.EQ(this.x, t48.x) \u0026\u0026 PR.Utils.EQ(this.y, t48.y);\n }\n lessThan(t48) {\n return !!PR.Utils.LT(this.y, t48.y) || !(!PR.Utils.EQ(this.y, t48.y) || !PR.Utils.LT(this.x, t48.x));\n }\n transform(t48) {\n return new PR.Point(t48.transform([this.x, this.y]));\n }\n projectionOn(t48) {\n if (this.equalTo(t48.pt)) return this.clone();\n let e2 = new PR.Vector(this, t48.pt);\n if (PR.Utils.EQ_0(e2.cross(t48.norm))) return t48.pt.clone();\n let n2 = e2.dot(t48.norm), o2 = t48.norm.multiply(n2);\n return this.translate(o2);\n }\n leftTo(t48) {\n let e2 = new PR.Vector(t48.pt, this);\n return PR.Utils.GT(e2.dot(t48.norm), 0);\n }\n distanceTo(e2) {\n if (e2 instanceof t36) {\n let t48 = e2.x - this.x, n2 = e2.y - this.y;\n return [Math.sqrt(t48 * t48 + n2 * n2), new PR.Segment(this, e2)];\n }\n return e2 instanceof PR.Line ? PR.Distance.point2line(this, e2) : e2 instanceof PR.Circle ? PR.Distance.point2circle(this, e2) : e2 instanceof PR.Segment ? PR.Distance.point2segment(this, e2) : e2 instanceof PR.Arc ? PR.Distance.point2arc(this, e2) : e2 instanceof PR.Polygon ? PR.Distance.point2polygon(this, e2) : e2 instanceof PR.PlanarSet ? PR.Distance.shape2planarSet(this, e2) : e2 instanceof PR.Multiline ? PR.Distance.shape2multiline(this, e2) : void 0;\n }\n on(t48) {\n if (t48 instanceof PR.Point) return this.equalTo(t48);\n if (t48.contains \u0026\u0026 t48.contains instanceof Function) return t48.contains(this);\n throw PR.Errors.UNSUPPORTED_SHAPE_TYPE;\n }\n get name() {\n return \"point\";\n }\n svg(t48 = {}) {\n const e2 = t48.r ?? 3;\n return `\n\u003ccircle cx=\"${this.x}\" cy=\"${this.y}\" r=\"${e2}\"\n ${TR({ fill: \"red\", ...t48 })} /\u003e`;\n }\n};\nvar uA = (...t48) =\u003e new PR.Point(...t48);\nPR.point = uA;\nPR.Vector = class extends dA {\n constructor(...t48) {\n if (super(), this.x = 0, this.y = 0, 0 !== t48.length) {\n if (1 === t48.length \u0026\u0026 t48[0] instanceof Array \u0026\u0026 2 === t48[0].length) {\n let e2 = t48[0];\n if (\"number\" == typeof e2[0] \u0026\u0026 \"number\" == typeof e2[1]) return this.x = e2[0], void (this.y = e2[1]);\n }\n if (1 === t48.length \u0026\u0026 t48[0] instanceof Object \u0026\u0026 \"vector\" === t48[0].name) {\n let { x: e2, y: n2 } = t48[0];\n return this.x = e2, void (this.y = n2);\n }\n if (1 === t48.length \u0026\u0026 t48[0] instanceof Object \u0026\u0026 \"segment\" === t48[0].name) {\n let { start: e2, end: n2 } = t48[0];\n return this.x = n2.x - e2.x, void (this.y = n2.y - e2.y);\n }\n if (2 === t48.length) {\n let e2 = t48[0], n2 = t48[1];\n if (\"number\" == typeof e2 \u0026\u0026 \"number\" == typeof n2) return this.x = e2, void (this.y = n2);\n if (e2 instanceof PR.Point \u0026\u0026 n2 instanceof PR.Point) return this.x = n2.x - e2.x, void (this.y = n2.y - e2.y);\n }\n throw MR.ILLEGAL_PARAMETERS;\n }\n }\n clone() {\n return new PR.Vector(this.x, this.y);\n }\n get slope() {\n let t48 = Math.atan2(this.y, this.x);\n return t48 \u003c 0 \u0026\u0026 (t48 = 2 * Math.PI + t48), t48;\n }\n get length() {\n return Math.sqrt(this.dot(this));\n }\n isZeroLength() {\n return PR.Utils.EQ_0(this.length);\n }\n equalTo(t48) {\n return PR.Utils.EQ(this.x, t48.x) \u0026\u0026 PR.Utils.EQ(this.y, t48.y);\n }\n multiply(t48) {\n return new PR.Vector(t48 * this.x, t48 * this.y);\n }\n dot(t48) {\n return this.x * t48.x + this.y * t48.y;\n }\n cross(t48) {\n return this.x * t48.y - this.y * t48.x;\n }\n normalize() {\n if (this.isZeroLength()) throw MR.ZERO_DIVISION;\n return new PR.Vector(this.x / this.length, this.y / this.length);\n }\n rotate(t48, e2 = new PR.Point()) {\n if (0 === e2.x \u0026\u0026 0 === e2.y) return this.transform(new rA().rotate(t48));\n throw MR.OPERATION_IS_NOT_SUPPORTED;\n }\n transform(t48) {\n return new PR.Vector(t48.transform([this.x, this.y]));\n }\n rotate90CCW() {\n return new PR.Vector(-this.y, this.x);\n }\n rotate90CW() {\n return new PR.Vector(this.y, -this.x);\n }\n invert() {\n return new PR.Vector(-this.x, -this.y);\n }\n add(t48) {\n return new PR.Vector(this.x + t48.x, this.y + t48.y);\n }\n subtract(t48) {\n return new PR.Vector(this.x - t48.x, this.y - t48.y);\n }\n angleTo(t48) {\n let e2 = this.normalize(), n2 = t48.normalize(), o2 = Math.atan2(e2.cross(n2), e2.dot(n2));\n return o2 \u003c 0 \u0026\u0026 (o2 += 2 * Math.PI), o2;\n }\n projectionOn(t48) {\n let e2 = t48.normalize(), n2 = this.dot(e2);\n return e2.multiply(n2);\n }\n get name() {\n return \"vector\";\n }\n};\nvar pA = (...t48) =\u003e new PR.Vector(...t48);\nPR.vector = pA;\nPR.Segment = class t37 extends dA {\n constructor(...t48) {\n if (super(), this.ps = new PR.Point(), this.pe = new PR.Point(), 0 !== t48.length) {\n if (1 === t48.length \u0026\u0026 t48[0] instanceof Array \u0026\u0026 4 === t48[0].length) {\n let e2 = t48[0];\n return this.ps = new PR.Point(e2[0], e2[1]), void (this.pe = new PR.Point(e2[2], e2[3]));\n }\n if (1 === t48.length \u0026\u0026 t48[0] instanceof Object \u0026\u0026 \"segment\" === t48[0].name) {\n let { ps: e2, pe: n2 } = t48[0];\n return this.ps = new PR.Point(e2.x, e2.y), void (this.pe = new PR.Point(n2.x, n2.y));\n }\n if (!(1 === t48.length \u0026\u0026 t48[0] instanceof PR.Point)) {\n if (2 === t48.length \u0026\u0026 t48[0] instanceof PR.Point \u0026\u0026 t48[1] instanceof PR.Point) return this.ps = t48[0].clone(), void (this.pe = t48[1].clone());\n if (4 === t48.length) return this.ps = new PR.Point(t48[0], t48[1]), void (this.pe = new PR.Point(t48[2], t48[3]));\n throw MR.ILLEGAL_PARAMETERS;\n }\n this.ps = t48[0].clone();\n }\n }\n clone() {\n return new PR.Segment(this.start, this.end);\n }\n get start() {\n return this.ps;\n }\n get end() {\n return this.pe;\n }\n get vertices() {\n return [this.ps.clone(), this.pe.clone()];\n }\n get length() {\n return this.start.distanceTo(this.end)[0];\n }\n get slope() {\n return new PR.Vector(this.start, this.end).slope;\n }\n get box() {\n return new PR.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));\n }\n equalTo(t48) {\n return this.ps.equalTo(t48.ps) \u0026\u0026 this.pe.equalTo(t48.pe);\n }\n contains(t48) {\n return PR.Utils.EQ_0(this.distanceToPoint(t48));\n }\n intersect(t48) {\n return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? LR(this, t48) : t48 instanceof PR.Ray ? eE(t48, this) : t48 instanceof PR.Segment ? DR(this, t48) : t48 instanceof PR.Circle ? FR(this, t48) : t48 instanceof PR.Box ? (function(t49, e2) {\n let n2 = [];\n for (let o2 of e2.toSegments()) {\n let e3 = DR(o2, t49);\n for (let t50 of e3) n2.push(t50);\n }\n return n2;\n })(this, t48) : t48 instanceof PR.Arc ? jR(this, t48) : t48 instanceof PR.Polygon ? UR(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;\n }\n distanceTo(t48) {\n if (t48 instanceof PR.Point) {\n let [e2, n2] = PR.Distance.point2segment(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Circle) {\n let [e2, n2] = PR.Distance.segment2circle(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Line) {\n let [e2, n2] = PR.Distance.segment2line(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Segment) {\n let [e2, n2] = PR.Distance.segment2segment(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Arc) {\n let [e2, n2] = PR.Distance.segment2arc(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Polygon) {\n let [e2, n2] = PR.Distance.shape2polygon(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.PlanarSet) {\n let [e2, n2] = PR.Distance.shape2planarSet(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Multiline) return PR.Distance.shape2multiline(this, t48);\n }\n tangentInStart() {\n return new PR.Vector(this.start, this.end).normalize();\n }\n tangentInEnd() {\n return new PR.Vector(this.end, this.start).normalize();\n }\n reverse() {\n return new t37(this.end, this.start);\n }\n split(t48) {\n return this.start.equalTo(t48) ? [null, this.clone()] : this.end.equalTo(t48) ? [this.clone(), null] : [new PR.Segment(this.start, t48), new PR.Segment(t48, this.end)];\n }\n middle() {\n return new PR.Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);\n }\n pointAtLength(t48) {\n if (t48 \u003e this.length || t48 \u003c 0) return null;\n if (0 == t48) return this.start;\n if (t48 == this.length) return this.end;\n let e2 = t48 / this.length;\n return new PR.Point((this.end.x - this.start.x) * e2 + this.start.x, (this.end.y - this.start.y) * e2 + this.start.y);\n }\n distanceToPoint(t48) {\n let [e2, ...n2] = PR.Distance.point2segment(t48, this);\n return e2;\n }\n definiteIntegral(t48 = 0) {\n return (this.end.x - this.start.x) * (this.start.y - t48 + (this.end.y - t48)) / 2;\n }\n transform(e2 = new PR.Matrix()) {\n return new t37(this.ps.transform(e2), this.pe.transform(e2));\n }\n isZeroLength() {\n return this.ps.equalTo(this.pe);\n }\n sortPoints(t48) {\n return new PR.Line(this.start, this.end).sortPoints(t48);\n }\n get name() {\n return \"segment\";\n }\n svg(t48 = {}) {\n return `\n\u003cline x1=\"${this.start.x}\" y1=\"${this.start.y}\" x2=\"${this.end.x}\" y2=\"${this.end.y}\" ${TR(t48)} /\u003e`;\n }\n};\nvar mA = (...t48) =\u003e new PR.Segment(...t48);\nPR.segment = mA;\nvar { vector: gA } = PR;\nPR.Line = class t38 extends dA {\n constructor(...e2) {\n if (super(), this.pt = new PR.Point(), this.norm = new PR.Vector(0, 1), 0 !== e2.length) {\n if (1 === e2.length \u0026\u0026 e2[0] instanceof Object \u0026\u0026 \"line\" === e2[0].name) {\n let { pt: t48, norm: n2 } = e2[0];\n return this.pt = new PR.Point(t48), void (this.norm = new PR.Vector(n2));\n }\n if (2 === e2.length) {\n let n2 = e2[0], o2 = e2[1];\n if (n2 instanceof PR.Point \u0026\u0026 o2 instanceof PR.Point) return this.pt = n2, this.norm = t38.points2norm(n2, o2), void (this.norm.dot(gA(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n if (n2 instanceof PR.Point \u0026\u0026 o2 instanceof PR.Vector) {\n if (PR.Utils.EQ_0(o2.x) \u0026\u0026 PR.Utils.EQ_0(o2.y)) throw MR.ILLEGAL_PARAMETERS;\n return this.pt = n2.clone(), this.norm = o2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(gA(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n }\n if (n2 instanceof PR.Vector \u0026\u0026 o2 instanceof PR.Point) {\n if (PR.Utils.EQ_0(n2.x) \u0026\u0026 PR.Utils.EQ_0(n2.y)) throw MR.ILLEGAL_PARAMETERS;\n return this.pt = o2.clone(), this.norm = n2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(gA(this.pt.x, this.pt.y)) \u003e= 0 \u0026\u0026 this.norm.invert());\n }\n }\n throw MR.ILLEGAL_PARAMETERS;\n }\n }\n clone() {\n return new PR.Line(this.pt, this.norm);\n }\n get start() {\n }\n get end() {\n }\n get length() {\n return Number.POSITIVE_INFINITY;\n }\n get box() {\n return new PR.Box(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);\n }\n get middle() {\n }\n get slope() {\n return new PR.Vector(this.norm.y, -this.norm.x).slope;\n }\n get standard() {\n return [this.norm.x, this.norm.y, this.norm.dot(gA(this.pt.x, this.pt.y))];\n }\n parallelTo(t48) {\n return PR.Utils.EQ_0(this.norm.cross(t48.norm));\n }\n incidentTo(t48) {\n return this.parallelTo(t48) \u0026\u0026 this.pt.on(t48);\n }\n contains(t48) {\n if (this.pt.equalTo(t48)) return true;\n let e2 = new PR.Vector(this.pt, t48);\n return PR.Utils.EQ_0(this.norm.dot(e2));\n }\n coord(t48) {\n return gA(t48.x, t48.y).cross(this.norm);\n }\n intersect(t48) {\n return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? RR(this, t48) : t48 instanceof PR.Ray ? iE(t48, this) : t48 instanceof PR.Circle ? ER(this, t48) : t48 instanceof PR.Box ? AR(this, t48) : t48 instanceof PR.Segment ? LR(t48, this) : t48 instanceof PR.Arc ? OR(this, t48) : t48 instanceof PR.Polygon ? ZR(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;\n }\n distanceTo(t48) {\n if (t48 instanceof PR.Point) {\n let [e2, n2] = PR.Distance.point2line(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Circle) {\n let [e2, n2] = PR.Distance.circle2line(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Segment) {\n let [e2, n2] = PR.Distance.segment2line(t48, this);\n return [e2, n2.reverse()];\n }\n if (t48 instanceof PR.Arc) {\n let [e2, n2] = PR.Distance.arc2line(t48, this);\n return [e2, n2.reverse()];\n }\n if (t48 instanceof PR.Polygon) {\n let [e2, n2] = PR.Distance.shape2polygon(this, t48);\n return [e2, n2];\n }\n }\n split(t48) {\n if (t48 instanceof PR.Point) return [new PR.Ray(t48, this.norm), new PR.Ray(t48, this.norm)];\n {\n let e2 = new PR.Multiline([this]), n2 = this.sortPoints(t48);\n return e2.split(n2), e2.toShapes();\n }\n }\n rotate(t48, e2 = new PR.Point()) {\n return new PR.Line(this.pt.rotate(t48, e2), this.norm.rotate(t48));\n }\n transform(t48) {\n return new PR.Line(this.pt.transform(t48), this.norm.clone());\n }\n sortPoints(t48) {\n return t48.slice().sort((t49, e2) =\u003e this.coord(t49) \u003c this.coord(e2) ? -1 : this.coord(t49) \u003e this.coord(e2) ? 1 : 0);\n }\n get name() {\n return \"line\";\n }\n svg(t48, e2 = {}) {\n let n2 = AR(this, t48);\n if (0 === n2.length) return \"\";\n let o2 = n2[0], i2 = 2 === n2.length ? n2[1] : n2.find((t49) =\u003e !t49.equalTo(o2));\n return void 0 === i2 \u0026\u0026 (i2 = o2), new PR.Segment(o2, i2).svg(e2);\n }\n static points2norm(t48, e2) {\n if (t48.equalTo(e2)) throw MR.ILLEGAL_PARAMETERS;\n return new PR.Vector(t48, e2).normalize().rotate90CCW();\n }\n};\nvar fA = (...t48) =\u003e new PR.Line(...t48);\nPR.line = fA;\nPR.Circle = class extends dA {\n constructor(...t48) {\n if (super(), this.pc = new PR.Point(), this.r = 1, 1 === t48.length \u0026\u0026 t48[0] instanceof Object \u0026\u0026 \"circle\" === t48[0].name) {\n let { pc: e2, r: n2 } = t48[0];\n this.pc = new PR.Point(e2), this.r = n2;\n } else {\n let [e2, n2] = [...t48];\n e2 \u0026\u0026 e2 instanceof PR.Point \u0026\u0026 (this.pc = e2.clone()), void 0 !== n2 \u0026\u0026 (this.r = n2);\n }\n }\n clone() {\n return new PR.Circle(this.pc.clone(), this.r);\n }\n get center() {\n return this.pc;\n }\n get box() {\n return new PR.Box(this.pc.x - this.r, this.pc.y - this.r, this.pc.x + this.r, this.pc.y + this.r);\n }\n contains(t48) {\n return t48 instanceof PR.Point ? PR.Utils.LE(t48.distanceTo(this.center)[0], this.r) : t48 instanceof PR.Segment ? PR.Utils.LE(t48.start.distanceTo(this.center)[0], this.r) \u0026\u0026 PR.Utils.LE(t48.end.distanceTo(this.center)[0], this.r) : t48 instanceof PR.Arc ? 0 === this.intersect(t48).length \u0026\u0026 PR.Utils.LE(t48.start.distanceTo(this.center)[0], this.r) \u0026\u0026 PR.Utils.LE(t48.end.distanceTo(this.center)[0], this.r) : t48 instanceof PR.Circle ? 0 === this.intersect(t48).length \u0026\u0026 PR.Utils.LE(t48.r, this.r) \u0026\u0026 PR.Utils.LE(t48.center.distanceTo(this.center)[0], this.r) : void 0;\n }\n toArc(t48 = true) {\n return new PR.Arc(this.center, this.r, Math.PI, -Math.PI, t48);\n }\n scale(t48, e2) {\n if (t48 !== e2) throw MR.OPERATION_IS_NOT_SUPPORTED;\n if (0 !== this.pc.x || 0 !== this.pc.y) throw MR.OPERATION_IS_NOT_SUPPORTED;\n return new PR.Circle(this.pc, this.r * t48);\n }\n transform(t48 = new PR.Matrix()) {\n return new PR.Circle(this.pc.transform(t48), this.r);\n }\n intersect(t48) {\n return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? ER(t48, this) : t48 instanceof PR.Ray ? oE(t48, this) : t48 instanceof PR.Segment ? FR(t48, this) : t48 instanceof PR.Circle ? YR(t48, this) : t48 instanceof PR.Box ? (function(t49, e2) {\n let n2 = [];\n for (let o2 of e2.toSegments()) {\n let e3 = FR(o2, t49);\n for (let t50 of e3) n2.push(t50);\n }\n return n2;\n })(this, t48) : t48 instanceof PR.Arc ? XR(t48, this) : t48 instanceof PR.Polygon ? qR(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;\n }\n distanceTo(t48) {\n if (t48 instanceof PR.Point) {\n let [e2, n2] = PR.Distance.point2circle(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Circle) {\n let [e2, n2] = PR.Distance.circle2circle(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Line) {\n let [e2, n2] = PR.Distance.circle2line(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Segment) {\n let [e2, n2] = PR.Distance.segment2circle(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Arc) {\n let [e2, n2] = PR.Distance.arc2circle(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Polygon) {\n let [e2, n2] = PR.Distance.shape2polygon(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.PlanarSet) {\n let [e2, n2] = PR.Distance.shape2planarSet(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Multiline) {\n let [e2, n2] = PR.Distance.shape2multiline(this, t48);\n return [e2, n2];\n }\n }\n get name() {\n return \"circle\";\n }\n svg(t48 = {}) {\n return `\n\u003ccircle cx=\"${this.pc.x}\" cy=\"${this.pc.y}\" r=\"${this.r}\"\n ${TR({ fill: \"none\", ...t48 })} /\u003e`;\n }\n};\nPR.circle = (...t48) =\u003e new PR.Circle(...t48);\nPR.Arc = class extends dA {\n constructor(...t48) {\n if (super(), this.pc = new PR.Point(), this.r = 1, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.counterClockwise = true, 0 !== t48.length) if (1 === t48.length \u0026\u0026 t48[0] instanceof Object \u0026\u0026 \"arc\" === t48[0].name) {\n let { pc: e2, r: n2, startAngle: o2, endAngle: i2, counterClockwise: r2 } = t48[0];\n this.pc = new PR.Point(e2.x, e2.y), this.r = n2, this.startAngle = o2, this.endAngle = i2, this.counterClockwise = r2;\n } else {\n let [e2, n2, o2, i2, r2] = [...t48];\n e2 \u0026\u0026 e2 instanceof PR.Point \u0026\u0026 (this.pc = e2.clone()), void 0 !== n2 \u0026\u0026 (this.r = n2), void 0 !== o2 \u0026\u0026 (this.startAngle = o2), void 0 !== i2 \u0026\u0026 (this.endAngle = i2), void 0 !== r2 \u0026\u0026 (this.counterClockwise = r2);\n }\n }\n clone() {\n return new PR.Arc(this.pc.clone(), this.r, this.startAngle, this.endAngle, this.counterClockwise);\n }\n get sweep() {\n let t48 = this.startAngle, e2 = this.endAngle;\n if (PR.Utils.EQ(Math.abs(t48 - e2), PR.PIx2)) return PR.PIx2;\n Math.abs(t48) \u003e PR.PIx2 \u0026\u0026 (t48 -= Math.trunc(t48 / PR.PIx2) * PR.PIx2), t48 \u003c 0 \u0026\u0026 (t48 += PR.PIx2), Math.abs(e2) \u003e PR.PIx2 \u0026\u0026 (e2 -= Math.trunc(e2 / PR.PIx2) * PR.PIx2), e2 \u003c 0 \u0026\u0026 (e2 += PR.PIx2);\n let n2 = this.counterClockwise ? e2 - t48 : t48 - e2;\n return n2 \u003c 0 \u0026\u0026 (n2 += PR.PIx2), n2;\n }\n get start() {\n return new PR.Point(this.pc.x + this.r, this.pc.y).rotate(this.startAngle, this.pc);\n }\n get end() {\n return new PR.Point(this.pc.x + this.r, this.pc.y).rotate(this.endAngle, this.pc);\n }\n get center() {\n return this.pc.clone();\n }\n get vertices() {\n return [this.start.clone(), this.end.clone()];\n }\n get length() {\n return Math.abs(this.sweep * this.r);\n }\n get box() {\n let t48 = this.breakToFunctional().reduce((t49, e2) =\u003e t49.merge(e2.start.box), new PR.Box());\n return t48 = t48.merge(this.end.box), t48;\n }\n contains(t48) {\n if (!PR.Utils.EQ(this.pc.distanceTo(t48)[0], this.r)) return false;\n if (t48.equalTo(this.start)) return true;\n let e2 = new PR.Vector(this.pc, t48).slope, n2 = new PR.Arc(this.pc, this.r, this.startAngle, e2, this.counterClockwise);\n return PR.Utils.LE(n2.length, this.length);\n }\n split(t48) {\n if (this.start.equalTo(t48)) return [null, this.clone()];\n if (this.end.equalTo(t48)) return [this.clone(), null];\n let e2 = new PR.Vector(this.pc, t48).slope;\n return [new PR.Arc(this.pc, this.r, this.startAngle, e2, this.counterClockwise), new PR.Arc(this.pc, this.r, e2, this.endAngle, this.counterClockwise)];\n }\n middle() {\n let t48 = this.counterClockwise ? this.startAngle + this.sweep / 2 : this.startAngle - this.sweep / 2;\n return new PR.Arc(this.pc, this.r, this.startAngle, t48, this.counterClockwise).end;\n }\n pointAtLength(t48) {\n if (t48 \u003e this.length || t48 \u003c 0) return null;\n if (0 === t48) return this.start;\n if (t48 === this.length) return this.end;\n let e2 = t48 / this.length, n2 = this.counterClockwise ? this.startAngle + this.sweep * e2 : this.startAngle - this.sweep * e2;\n return new PR.Arc(this.pc, this.r, this.startAngle, n2, this.counterClockwise).end;\n }\n chordHeight() {\n return (1 - Math.cos(Math.abs(this.sweep / 2))) * this.r;\n }\n intersect(t48) {\n return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? OR(t48, this) : t48 instanceof PR.Ray ? nE(t48, this) : t48 instanceof PR.Circle ? XR(this, t48) : t48 instanceof PR.Segment ? jR(t48, this) : t48 instanceof PR.Box ? (function(t49, e2) {\n let n2 = [];\n for (let o2 of e2.toSegments()) {\n let e3 = jR(o2, t49);\n for (let t50 of e3) n2.push(t50);\n }\n return n2;\n })(this, t48) : t48 instanceof PR.Arc ? $R(this, t48) : t48 instanceof PR.Polygon ? GR(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;\n }\n distanceTo(t48) {\n if (t48 instanceof PR.Point) {\n let [e2, n2] = PR.Distance.point2arc(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Circle) {\n let [e2, n2] = PR.Distance.arc2circle(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Line) {\n let [e2, n2] = PR.Distance.arc2line(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Segment) {\n let [e2, n2] = PR.Distance.segment2arc(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Arc) {\n let [e2, n2] = PR.Distance.arc2arc(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Polygon) {\n let [e2, n2] = PR.Distance.shape2polygon(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.PlanarSet) {\n let [e2, n2] = PR.Distance.shape2planarSet(this, t48);\n return [e2, n2];\n }\n if (t48 instanceof PR.Multiline) return PR.Distance.shape2multiline(this, t48);\n }\n breakToFunctional() {\n let t48 = [], e2 = [0, Math.PI / 2, Math.PI, 3 * Math.PI / 2], n2 = this.startAngle, o2 = this.endAngle;\n PR.Utils.EQ(Math.abs(n2 - o2), PR.PIx2) \u0026\u0026 (o2 = n2), Math.abs(n2) \u003e PR.PIx2 \u0026\u0026 (n2 -= Math.trunc(n2 / PR.PIx2) * PR.PIx2), n2 \u003c 0 \u0026\u0026 (n2 += PR.PIx2), Math.abs(o2) \u003e PR.PIx2 \u0026\u0026 (o2 -= Math.trunc(o2 / PR.PIx2) * PR.PIx2), o2 \u003c 0 \u0026\u0026 (o2 += PR.PIx2);\n let i2, r2, s2, a2 = n2;\n this.counterClockwise ? (r2 = Math.ceil(n2 / (Math.PI / 2)) % 4, s2 = 1) : (r2 = Math.floor(n2 / (Math.PI / 2)) % 4, s2 = -1);\n for (let o3 = 0, c2 = r2; o3 \u003c 4; o3++, c2 = (c2 + s2 + 4) % 4) {\n if (i2 = e2[c2], i2 === a2) continue;\n let o4 = this.counterClockwise ? i2 - n2 : n2 - i2;\n if (o4 \u003c 0 \u0026\u0026 (o4 += PR.PIx2), o4 \u003e this.sweep) break;\n t48.push(new PR.Arc(this.pc, this.r, a2, i2, this.counterClockwise)), a2 = i2;\n }\n return 0 === t48.length ? (t48.push(this), t48) : (i2 = o2, a2 !== i2 \u0026\u0026 t48.push(new PR.Arc(this.pc, this.r, a2, i2, this.counterClockwise)), t48);\n }\n tangentInStart() {\n let t48 = new PR.Vector(this.pc, this.start), e2 = this.counterClockwise ? Math.PI / 2 : -Math.PI / 2;\n return t48.rotate(e2).normalize();\n }\n tangentInEnd() {\n let t48 = new PR.Vector(this.pc, this.end), e2 = this.counterClockwise ? -Math.PI / 2 : Math.PI / 2;\n return t48.rotate(e2).normalize();\n }\n reverse() {\n return new PR.Arc(this.pc, this.r, this.endAngle, this.startAngle, !this.counterClockwise);\n }\n transform(t48 = new PR.Matrix()) {\n let e2 = this.start.transform(t48), n2 = this.end.transform(t48), o2 = this.pc.transform(t48), i2 = this.counterClockwise;\n return t48.a * t48.d \u003c 0 \u0026\u0026 (i2 = !i2), PR.Arc.arcSE(o2, e2, n2, i2);\n }\n static arcSE(t48, e2, n2, o2) {\n let { vector: i2 } = PR, r2 = i2(t48, e2).slope, s2 = i2(t48, n2).slope;\n PR.Utils.EQ(r2, s2) \u0026\u0026 (s2 += 2 * Math.PI, o2 = true);\n let a2 = i2(t48, e2).length;\n return new PR.Arc(t48, a2, r2, s2, o2);\n }\n definiteIntegral(t48 = 0) {\n return this.breakToFunctional().reduce((e2, n2) =\u003e e2 + n2.circularSegmentDefiniteIntegral(t48), 0);\n }\n circularSegmentDefiniteIntegral(t48) {\n let e2 = new PR.Segment(this.start, this.end).definiteIntegral(t48), n2 = PR.Utils.EQ(this.sweep, PR.PIx2) ? 0 : this.circularSegmentArea();\n return this.counterClockwise ? e2 - n2 : e2 + n2;\n }\n circularSegmentArea() {\n return 0.5 * this.r * this.r * (this.sweep - Math.sin(this.sweep));\n }\n sortPoints(t48) {\n let { vector: e2 } = PR;\n return t48.slice().sort((t49, n2) =\u003e {\n let o2 = e2(this.pc, t49).slope, i2 = e2(this.pc, n2).slope;\n return o2 \u003c i2 ? -1 : o2 \u003e i2 ? 1 : 0;\n });\n }\n get name() {\n return \"arc\";\n }\n svg(t48 = {}) {\n let e2 = this.sweep \u003c= Math.PI ? \"0\" : \"1\", n2 = this.counterClockwise ? \"1\" : \"0\";\n if (PR.Utils.EQ(this.sweep, 2 * Math.PI)) {\n return new PR.Circle(this.pc, this.r).svg(t48);\n }\n return `\n\u003cpath d=\"M${this.start.x},${this.start.y}\n A${this.r},${this.r} 0 ${e2},${n2} ${this.end.x},${this.end.y}\"\n ${TR({ fill: \"none\", ...t48 })} /\u003e`;\n }\n};\nPR.arc = (...t48) =\u003e new PR.Arc(...t48);\nPR.Box = class t39 extends dA {\n constructor(t48 = void 0, e2 = void 0, n2 = void 0, o2 = void 0) {\n super(), this.xmin = t48, this.ymin = e2, this.xmax = n2, this.ymax = o2;\n }\n clone() {\n return new t39(this.xmin, this.ymin, this.xmax, this.ymax);\n }\n get low() {\n return new PR.Point(this.xmin, this.ymin);\n }\n get high() {\n return new PR.Point(this.xmax, this.ymax);\n }\n get max() {\n return this.clone();\n }\n get center() {\n return new PR.Point((this.xmin + this.xmax) / 2, (this.ymin + this.ymax) / 2);\n }\n get width() {\n return Math.abs(this.xmax - this.xmin);\n }\n get height() {\n return Math.abs(this.ymax - this.ymin);\n }\n get box() {\n return this.clone();\n }\n not_intersect(t48) {\n return this.xmax \u003c t48.xmin || this.xmin \u003e t48.xmax || this.ymax \u003c t48.ymin || this.ymin \u003e t48.ymax;\n }\n intersect(t48) {\n return !this.not_intersect(t48);\n }\n merge(e2) {\n return new t39(void 0 === this.xmin ? e2.xmin : Math.min(this.xmin, e2.xmin), void 0 === this.ymin ? e2.ymin : Math.min(this.ymin, e2.ymin), void 0 === this.xmax ? e2.xmax : Math.max(this.xmax, e2.xmax), void 0 === this.ymax ? e2.ymax : Math.max(this.ymax, e2.ymax));\n }\n less_than(t48) {\n return !!this.low.lessThan(t48.low) || !(!this.low.equalTo(t48.low) || !this.high.lessThan(t48.high));\n }\n equal_to(t48) {\n return this.low.equalTo(t48.low) \u0026\u0026 this.high.equalTo(t48.high);\n }\n output() {\n return this.clone();\n }\n comparable_less_than(t48, e2) {\n return t48.lessThan(e2);\n }\n set(t48, e2, n2, o2) {\n this.xmin = t48, this.ymin = e2, this.xmax = n2, this.ymax = o2;\n }\n extend(e2) {\n return e2 \u003c= 0 ? this.clone() : new t39(this.xmin - e2, this.ymin - e2, this.xmax + e2, this.ymax + e2);\n }\n toPoints() {\n return [new PR.Point(this.xmin, this.ymin), new PR.Point(this.xmax, this.ymin), new PR.Point(this.xmax, this.ymax), new PR.Point(this.xmin, this.ymax)];\n }\n toSegments() {\n let t48 = this.toPoints();\n return [new PR.Segment(t48[0], t48[1]), new PR.Segment(t48[1], t48[2]), new PR.Segment(t48[2], t48[3]), new PR.Segment(t48[3], t48[0])];\n }\n rotate(t48, e2 = new PR.Point()) {\n throw MR.OPERATION_IS_NOT_SUPPORTED;\n }\n transform(e2 = new PR.Matrix()) {\n return this.toPoints().map((t48) =\u003e t48.transform(e2)).reduce((t48, e3) =\u003e t48.merge(e3.box), new t39());\n }\n contains(t48) {\n return t48 instanceof PR.Point ? t48.x \u003e= this.xmin \u0026\u0026 t48.x \u003c= this.xmax \u0026\u0026 t48.y \u003e= this.ymin \u0026\u0026 t48.y \u003c= this.ymax : t48 instanceof PR.Segment ? t48.vertices.every((t49) =\u003e this.contains(t49)) : t48 instanceof PR.Box ? t48.toSegments().every((t49) =\u003e this.contains(t49)) : t48 instanceof PR.Circle ? this.contains(t48.box) : t48 instanceof PR.Arc ? t48.vertices.every((t49) =\u003e this.contains(t49)) \u0026\u0026 this.toSegments().every((e2) =\u003e 0 === jR(e2, t48).length) : !(t48 instanceof PR.Line || t48 instanceof PR.Ray) \u0026\u0026 (t48 instanceof PR.Multiline ? t48.toShapes().every((t49) =\u003e this.contains(t49)) : t48 instanceof PR.Polygon ? this.contains(t48.box) : void 0);\n }\n distanceTo(t48) {\n const e2 = this.toSegments().map((e3) =\u003e e3.distanceTo(t48));\n let n2 = [Number.MAX_SAFE_INTEGER, null];\n return e2.forEach((t49) =\u003e {\n t49[0] \u003c n2[0] \u0026\u0026 (n2 = t49);\n }), n2;\n }\n get name() {\n return \"box\";\n }\n svg(t48 = {}) {\n const e2 = this.xmax - this.xmin, n2 = this.ymax - this.ymin;\n return `\n\u003crect x=\"${this.xmin}\" y=\"${this.ymin}\" width=\"${e2}\" height=\"${n2}\"\n ${TR({ fill: \"none\", ...t48 })} /\u003e`;\n }\n};\nPR.box = (...t48) =\u003e new PR.Box(...t48);\nPR.Edge = class {\n constructor(t48) {\n this.shape = t48, 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;\n }\n get start() {\n return this.shape.start;\n }\n get end() {\n return this.shape.end;\n }\n get length() {\n return this.shape.length;\n }\n get box() {\n return this.shape.box;\n }\n get isSegment() {\n return this.shape instanceof PR.Segment;\n }\n get isArc() {\n return this.shape instanceof PR.Arc;\n }\n get isLine() {\n return this.shape instanceof PR.Line;\n }\n get isRay() {\n return this.shape instanceof PR.Ray;\n }\n middle() {\n return this.shape.middle();\n }\n pointAtLength(t48) {\n return this.shape.pointAtLength(t48);\n }\n contains(t48) {\n return this.shape.contains(t48);\n }\n setInclusion(t48) {\n if (void 0 !== this.bv) return this.bv;\n if (this.shape instanceof PR.Line || this.shape instanceof PR.Ray) return this.bv = PR.OUTSIDE, this.bv;\n if (void 0 === this.bvStart \u0026\u0026 (this.bvStart = qE(t48, this.start)), void 0 === this.bvEnd \u0026\u0026 (this.bvEnd = qE(t48, this.end)), this.bvStart === PR.OUTSIDE || this.bvEnd == PR.OUTSIDE) this.bv = PR.OUTSIDE;\n else if (this.bvStart === PR.INSIDE || this.bvEnd == PR.INSIDE) this.bv = PR.INSIDE;\n else {\n let e2 = qE(t48, this.middle());\n this.bv = e2;\n }\n return this.bv;\n }\n setOverlap(t48) {\n let e2, n2 = this.shape, o2 = t48.shape;\n n2 instanceof PR.Segment \u0026\u0026 o2 instanceof PR.Segment ? n2.start.equalTo(o2.start) \u0026\u0026 n2.end.equalTo(o2.end) ? e2 = PR.OVERLAP_SAME : n2.start.equalTo(o2.end) \u0026\u0026 n2.end.equalTo(o2.start) \u0026\u0026 (e2 = PR.OVERLAP_OPPOSITE) : (n2 instanceof PR.Arc \u0026\u0026 o2 instanceof PR.Arc || n2 instanceof PR.Segment \u0026\u0026 o2 instanceof PR.Arc || n2 instanceof PR.Arc \u0026\u0026 o2 instanceof PR.Segment) \u0026\u0026 (n2.start.equalTo(o2.start) \u0026\u0026 n2.end.equalTo(o2.end) \u0026\u0026 n2.middle().equalTo(o2.middle()) ? e2 = PR.OVERLAP_SAME : n2.start.equalTo(o2.end) \u0026\u0026 n2.end.equalTo(o2.start) \u0026\u0026 n2.middle().equalTo(o2.middle()) \u0026\u0026 (e2 = PR.OVERLAP_OPPOSITE)), void 0 === this.overlap \u0026\u0026 (this.overlap = e2), void 0 === t48.overlap \u0026\u0026 (t48.overlap = e2);\n }\n svg() {\n if (this.shape instanceof PR.Segment) return ` L${this.shape.end.x},${this.shape.end.y}`;\n if (this.shape instanceof PR.Arc) {\n let t48, e2 = this.shape, n2 = e2.counterClockwise ? \"1\" : \"0\";\n if (PR.Utils.EQ(e2.sweep, 2 * Math.PI)) {\n let o2 = e2.counterClockwise ? 1 : -1, i2 = new PR.Arc(e2.pc, e2.r, e2.startAngle, e2.startAngle + o2 * Math.PI, e2.counterClockwise), r2 = new PR.Arc(e2.pc, e2.r, e2.startAngle + o2 * Math.PI, e2.endAngle, e2.counterClockwise);\n return t48 = \"0\", ` A${i2.r},${i2.r} 0 ${t48},${n2} ${i2.end.x},${i2.end.y}\n A${r2.r},${r2.r} 0 ${t48},${n2} ${r2.end.x},${r2.end.y}`;\n }\n return t48 = e2.sweep \u003c= Math.PI ? \"0\" : \"1\", ` A${e2.r},${e2.r} 0 ${t48},${n2} ${e2.end.x},${e2.end.y}`;\n }\n }\n toJSON() {\n return this.shape.toJSON();\n }\n};\nvar _A = class extends CR {\n constructor(t48, e2) {\n super(t48, e2), this.setCircularLinks();\n }\n setCircularLinks() {\n this.isEmpty() || (this.last.next = this.first, this.first.prev = this.last);\n }\n [Symbol.iterator]() {\n let t48;\n return { next: () =\u003e {\n let e2 = t48 || this.first, n2 = !this.first || !!t48 \u0026\u0026 t48 === this.first;\n return t48 = e2 ? e2.next : void 0, { value: e2, done: n2 };\n } };\n }\n append(t48) {\n return super.append(t48), this.setCircularLinks(), this;\n }\n insert(t48, e2) {\n return super.insert(t48, e2), this.setCircularLinks(), this;\n }\n remove(t48) {\n return super.remove(t48), this;\n }\n};\nPR.Face = class t40 extends _A {\n constructor(e2, ...n2) {\n if (super(), this._box = void 0, this._orientation = void 0, 0 !== n2.length) {\n if (1 === n2.length) {\n if (n2[0] instanceof Array) {\n let o2 = n2[0];\n if (0 === o2.length) return;\n if (o2.every((t48) =\u003e t48 instanceof PR.Point)) {\n let n3 = t40.points2segments(o2);\n this.shapes2face(e2.edges, n3);\n } else if (o2.every((t48) =\u003e t48 instanceof Array \u0026\u0026 2 === t48.length)) {\n let n3 = o2.map((t48) =\u003e new PR.Point(t48[0], t48[1])), i2 = t40.points2segments(n3);\n this.shapes2face(e2.edges, i2);\n } else if (o2.every((t48) =\u003e t48 instanceof PR.Segment || t48 instanceof PR.Arc)) this.shapes2face(e2.edges, o2);\n else if (o2.every((t48) =\u003e \"segment\" === t48.name || \"arc\" === t48.name)) {\n let t48 = [];\n for (let e3 of o2) {\n let n3;\n n3 = \"segment\" === e3.name ? new PR.Segment(e3) : new PR.Arc(e3), t48.push(n3);\n }\n this.shapes2face(e2.edges, t48);\n }\n } else if (n2[0] instanceof t40) {\n let t48 = n2[0];\n this.first = t48.first, this.last = t48.last;\n for (let n3 of t48) e2.edges.add(n3);\n } else if (n2[0] instanceof PR.Circle) this.shapes2face(e2.edges, [n2[0].toArc(pR)]);\n else if (n2[0] instanceof PR.Box) {\n let t48 = n2[0];\n this.shapes2face(e2.edges, [new PR.Segment(new PR.Point(t48.xmin, t48.ymin), new PR.Point(t48.xmax, t48.ymin)), new PR.Segment(new PR.Point(t48.xmax, t48.ymin), new PR.Point(t48.xmax, t48.ymax)), new PR.Segment(new PR.Point(t48.xmax, t48.ymax), new PR.Point(t48.xmin, t48.ymax)), new PR.Segment(new PR.Point(t48.xmin, t48.ymax), new PR.Point(t48.xmin, t48.ymin))]);\n }\n }\n 2 === n2.length \u0026\u0026 n2[0] instanceof PR.Edge \u0026\u0026 n2[1] instanceof PR.Edge \u0026\u0026 (this.first = n2[0], this.last = n2[1], this.last.next = this.first, this.first.prev = this.last, this.setArcLength());\n }\n }\n get edges() {\n return this.toArray();\n }\n get vertices() {\n return this.edges.map((t48) =\u003e t48.shape.start.clone());\n }\n get shapes() {\n return this.edges.map((t48) =\u003e t48.shape.clone());\n }\n get box() {\n if (void 0 === this._box) {\n let t48 = new PR.Box();\n for (let e2 of this) t48 = t48.merge(e2.box);\n this._box = t48;\n }\n return this._box;\n }\n get perimeter() {\n return this.last.arc_length + this.last.length;\n }\n pointAtLength(t48) {\n if (t48 \u003e this.perimeter || t48 \u003c 0) return null;\n let e2 = null;\n for (let n2 of this) if (t48 \u003e= n2.arc_length \u0026\u0026 (n2 === this.last || t48 \u003c n2.next.arc_length)) {\n e2 = n2.pointAtLength(t48 - n2.arc_length);\n break;\n }\n return e2;\n }\n static points2segments(t48) {\n let e2 = [];\n for (let n2 = 0; n2 \u003c t48.length; n2++) t48[n2].equalTo(t48[(n2 + 1) % t48.length]) || e2.push(new PR.Segment(t48[n2], t48[(n2 + 1) % t48.length]));\n return e2;\n }\n shapes2face(t48, e2) {\n for (let n2 of e2) {\n let e3 = new PR.Edge(n2);\n this.append(e3), t48.add(e3);\n }\n }\n append(t48) {\n return super.append(t48), this.setOneEdgeArcLength(t48), t48.face = this, this;\n }\n insert(t48, e2) {\n return super.insert(t48, e2), this.setOneEdgeArcLength(t48), t48.face = this, this;\n }\n remove(t48) {\n return super.remove(t48), this.setArcLength(), this;\n }\n merge_with_next_edge(t48) {\n return t48.shape.end.x = t48.next.shape.end.x, t48.shape.end.y = t48.next.shape.end.y, this.remove(t48.next), this;\n }\n reverse() {\n let t48 = [], e2 = this.last;\n do {\n e2.shape = e2.shape.reverse(), t48.push(e2), e2 = e2.prev;\n } while (e2 !== this.last);\n this.first = void 0, this.last = void 0;\n for (let e3 of t48) void 0 === this.first ? (e3.prev = e3, e3.next = e3, this.first = e3, this.last = e3) : (e3.prev = this.last, this.last.next = e3, this.last = e3, this.last.next = this.first, this.first.prev = this.last), this.setOneEdgeArcLength(e3);\n void 0 !== this._orientation \u0026\u0026 (this._orientation = void 0, this._orientation = this.orientation());\n }\n setArcLength() {\n for (let t48 of this) this.setOneEdgeArcLength(t48), t48.face = this;\n }\n setOneEdgeArcLength(t48) {\n t48 === this.first ? t48.arc_length = 0 : t48.arc_length = t48.prev.arc_length + t48.prev.length;\n }\n area() {\n return Math.abs(this.signedArea());\n }\n signedArea() {\n let t48 = 0, e2 = this.box.ymin;\n for (let n2 of this) t48 += n2.shape.definiteIntegral(e2);\n return t48;\n }\n orientation() {\n if (void 0 === this._orientation) {\n let t48 = this.signedArea();\n PR.Utils.EQ_0(t48) ? this._orientation = mR.NOT_ORIENTABLE : PR.Utils.LT(t48, 0) ? this._orientation = mR.CCW : this._orientation = mR.CW;\n }\n return this._orientation;\n }\n isSimple(e2) {\n return 0 === t40.getSelfIntersections(this, e2, true).length;\n }\n static getSelfIntersections(t48, e2, n2 = false) {\n let o2 = [];\n for (let i2 of t48) {\n let r2 = e2.search(i2.box);\n for (let e3 of r2) {\n if (i2 === e3) continue;\n if (e3.face !== t48) continue;\n if (i2.shape instanceof PR.Segment \u0026\u0026 e3.shape instanceof PR.Segment \u0026\u0026 (i2.next === e3 || i2.prev === e3)) continue;\n let r3 = i2.shape.intersect(e3.shape);\n for (let t49 of r3) if ((!t49.equalTo(i2.start) || !t49.equalTo(e3.end) || e3 !== i2.prev) \u0026\u0026 (!t49.equalTo(i2.end) || !t49.equalTo(e3.start) || e3 !== i2.next) \u0026\u0026 (o2.push(t49), n2)) break;\n if (o2.length \u003e 0 \u0026\u0026 n2) break;\n }\n if (o2.length \u003e 0 \u0026\u0026 n2) break;\n }\n return o2;\n }\n findEdgeByPoint(t48) {\n let e2;\n for (let n2 of this) if (!t48.equalTo(n2.shape.start) \u0026\u0026 (t48.equalTo(n2.shape.end) || n2.shape.contains(t48))) {\n e2 = n2;\n break;\n }\n return e2;\n }\n toPolygon() {\n return new PR.Polygon(this.shapes);\n }\n toJSON() {\n return this.edges.map((t48) =\u003e t48.toJSON());\n }\n svg() {\n let t48 = `M${this.first.start.x},${this.first.start.y}`;\n for (let e2 of this) t48 += e2.svg();\n return t48 += \" z\", t48;\n }\n};\nPR.Ray = class t41 extends dA {\n constructor(...t48) {\n if (super(), this.pt = new PR.Point(), this.norm = new PR.Vector(0, 1), 0 !== t48.length \u0026\u0026 (t48.length \u003e= 1 \u0026\u0026 t48[0] instanceof PR.Point \u0026\u0026 (this.pt = t48[0].clone()), 1 !== t48.length)) {\n if (!(2 === t48.length \u0026\u0026 t48[1] instanceof PR.Vector)) throw MR.ILLEGAL_PARAMETERS;\n this.norm = t48[1].clone();\n }\n }\n clone() {\n return new t41(this.pt, this.norm);\n }\n get slope() {\n return new PR.Vector(this.norm.y, -this.norm.x).slope;\n }\n get box() {\n let t48 = this.slope;\n return new PR.Box(t48 \u003e Math.PI / 2 \u0026\u0026 t48 \u003c 3 * Math.PI / 2 ? Number.NEGATIVE_INFINITY : this.pt.x, t48 \u003e= 0 \u0026\u0026 t48 \u003c= Math.PI ? this.pt.y : Number.NEGATIVE_INFINITY, t48 \u003e= Math.PI / 2 \u0026\u0026 t48 \u003c= 3 * Math.PI / 2 ? this.pt.x : Number.POSITIVE_INFINITY, t48 \u003e= Math.PI \u0026\u0026 t48 \u003c= 2 * Math.PI || 0 === t48 ? this.pt.y : Number.POSITIVE_INFINITY);\n }\n get start() {\n return this.pt;\n }\n get end() {\n }\n get length() {\n return Number.POSITIVE_INFINITY;\n }\n contains(t48) {\n if (this.pt.equalTo(t48)) return true;\n let e2 = new PR.Vector(this.pt, t48);\n return PR.Utils.EQ_0(this.norm.dot(e2)) \u0026\u0026 PR.Utils.GE(e2.cross(this.norm), 0);\n }\n coord(t48) {\n return pA(t48.x, t48.y).cross(this.norm);\n }\n split(t48) {\n return this.contains(t48) ? this.pt.equalTo(t48) ? [this] : [new PR.Segment(this.pt, t48), new PR.Ray(t48, this.norm)] : [];\n }\n intersect(t48) {\n return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Segment ? eE(this, t48) : t48 instanceof PR.Arc ? nE(this, t48) : t48 instanceof PR.Line ? iE(this, t48) : t48 instanceof PR.Ray ? (n2 = t48, RR(tE(e2 = this), tE(n2)).filter((t49) =\u003e e2.contains(t49)).filter((t49) =\u003e n2.contains(t49))) : t48 instanceof PR.Circle ? oE(this, t48) : t48 instanceof PR.Box ? (i2 = t48, AR(tE(o2 = this), i2).filter((t49) =\u003e o2.contains(t49))) : t48 instanceof PR.Polygon ? rE(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;\n var e2, n2, o2, i2;\n }\n rotate(t48, e2 = new PR.Point()) {\n return new PR.Ray(this.pt.rotate(t48, e2), this.norm.rotate(t48));\n }\n transform(t48) {\n return new PR.Ray(this.pt.transform(t48), this.norm.clone());\n }\n get name() {\n return \"ray\";\n }\n svg(t48, e2 = {}) {\n let n2 = AR(new PR.Line(this.pt, this.norm), t48);\n return n2 = n2.filter((t49) =\u003e this.contains(t49)), 0 === n2.length || 2 === n2.length ? \"\" : new PR.Segment(this.pt, n2[0]).svg(e2);\n }\n};\nPR.ray = (...t48) =\u003e new PR.Ray(...t48);\nvar yA = class t42 {\n constructor() {\n this.faces = new PR.PlanarSet(), this.edges = new PR.PlanarSet();\n let t48 = [...arguments];\n if (1 === t48.length \u0026\u0026 (t48[0] instanceof Array \u0026\u0026 t48[0].length \u003e 0 || t48[0] instanceof PR.Circle || t48[0] instanceof PR.Box)) {\n let e2 = t48[0];\n if (t48[0] instanceof Array \u0026\u0026 t48[0].every((t49) =\u003e t49 instanceof Array)) if (e2.every((t49) =\u003e t49 instanceof Array \u0026\u0026 2 === t49.length \u0026\u0026 \"number\" == typeof t49[0] \u0026\u0026 \"number\" == typeof t49[1])) this.faces.add(new PR.Face(this, e2));\n else for (let t49 of e2) if (t49 instanceof Array \u0026\u0026 t49[0] instanceof Array \u0026\u0026 t49[0].every((t50) =\u003e t50 instanceof Array \u0026\u0026 2 === t50.length \u0026\u0026 \"number\" == typeof t50[0] \u0026\u0026 \"number\" == typeof t50[1])) for (let e3 of t49) this.faces.add(new PR.Face(this, e3));\n else this.faces.add(new PR.Face(this, t49));\n else this.faces.add(new PR.Face(this, e2));\n }\n }\n get box() {\n return [...this.faces].reduce((t48, e2) =\u003e t48.merge(e2.box), new PR.Box());\n }\n get vertices() {\n return [...this.faces].flatMap((t48) =\u003e t48.vertices);\n }\n clone() {\n let e2 = new t42();\n for (let t48 of this.faces) e2.addFace(t48.shapes);\n return e2;\n }\n createFromArray(e2) {\n const n2 = new t42();\n return e2.forEach((t48) =\u003e [...t48.faces].forEach((t49) =\u003e n2.addFace(t49.shapes))), n2;\n }\n isEmpty() {\n return 0 === this.edges.size || 0 === this.faces.size;\n }\n isValid() {\n let t48 = true;\n for (let e2 of this.faces) if (!e2.isSimple(this.edges)) {\n t48 = false;\n break;\n }\n return t48;\n }\n area() {\n let t48 = [...this.faces].reduce((t49, e2) =\u003e t49 + e2.signedArea(), 0);\n return Math.abs(t48);\n }\n addFace(...t48) {\n let e2 = new PR.Face(this, ...t48);\n return this.faces.add(e2), e2;\n }\n deleteFace(t48) {\n for (let e2 of t48) this.edges.delete(e2);\n return this.faces.delete(t48);\n }\n recreateFaces() {\n this.faces.clear();\n for (let t49 of this.edges) t49.face = null;\n let t48, e2 = true;\n for (; e2; ) {\n e2 = false;\n for (let n2 of this.edges) if (null === n2.face) {\n t48 = n2, e2 = true;\n break;\n }\n if (e2) {\n let e3 = t48;\n do {\n e3 = e3.next;\n } while (e3.next !== t48);\n this.addFace(t48, e3);\n }\n }\n }\n removeChain(t48, e2, n2) {\n if (n2.next !== e2) {\n for (let o2 = e2; o2 !== n2.next; o2 = o2.next) if (t48.remove(o2), this.edges.delete(o2), t48.isEmpty()) {\n this.deleteFace(t48);\n break;\n }\n } else this.deleteFace(t48);\n }\n addVertex(t48, e2) {\n let n2 = e2.shape.split(t48);\n if (null === n2[0]) return e2.prev;\n if (null === n2[1]) return e2;\n let o2 = new PR.Edge(n2[0]), i2 = e2.prev;\n return e2.face.insert(o2, i2), this.edges.delete(e2), this.edges.add(o2), e2.shape = n2[1], this.edges.add(e2), o2;\n }\n removeEndVertex(t48) {\n const e2 = t48.next;\n e2 !== t48 \u0026\u0026 (t48.face.merge_with_next_edge(t48), this.edges.delete(e2));\n }\n cut(t48) {\n const e2 = this.splitToIslands().flatMap((e3) =\u003e e3._cutSingleIsland(t48)).filter((t49) =\u003e t49.isValid() \u0026\u0026 false === t49.isEmpty());\n return this.createFromArray(e2);\n }\n _cutSingleIsland(t48) {\n let e2 = this.clone();\n const n2 = t48.clone();\n let o2, i2, r2 = { int_points1: [], int_points2: [], int_points1_sorted: [], int_points2_sorted: [] };\n for (let t49 of n2.edges) for (let n3 of e2.edges) {\n let e3 = JR(t49, n3);\n for (let o3 of e3) lE(t49, o3, r2.int_points1), lE(n3, o3, r2.int_points2);\n }\n if (0 === r2.int_points1.length) return e2;\n r2.int_points1_sorted = dE(r2.int_points1), r2.int_points2_sorted = dE(r2.int_points2), _E(n2, r2.int_points1_sorted), _E(e2, r2.int_points2_sorted), pE(r2), r2.int_points1_sorted = dE(r2.int_points1), r2.int_points2_sorted = dE(r2.int_points2), mE(r2.int_points1), gE(r2.int_points1, e2);\n for (let t49 of r2.int_points1_sorted) t49.edge_before \u0026\u0026 t49.edge_after \u0026\u0026 t49.edge_before.bv === t49.edge_after.bv \u0026\u0026 (r2.int_points2[t49.id] = -1, t49.id = -1);\n if (r2.int_points1 = r2.int_points1.filter((t49) =\u003e t49.id \u003e= 0), r2.int_points2 = r2.int_points2.filter((t49) =\u003e t49.id \u003e= 0), r2.int_points1.forEach((t49, e3) =\u003e {\n t49.id = e3;\n }), r2.int_points2.forEach((t49, e3) =\u003e {\n t49.id = e3;\n }), 0 === r2.int_points1.length) return e2;\n r2.int_points1_sorted = dE(r2.int_points1), r2.int_points2_sorted = dE(r2.int_points2);\n for (let t49 = 1; t49 \u003c r2.int_points1_sorted.length; t49++) if (i2 = r2.int_points1_sorted[t49], o2 = r2.int_points1_sorted[t49 - 1], i2.edge_before \u0026\u0026 1 === i2.edge_before.bv) {\n let t50 = o2.edge_after, s2 = i2.edge_before, a2 = n2.getChain(t50, s2);\n yE(r2.int_points2[o2.id], r2.int_points2[i2.id], a2), a2.forEach((t51) =\u003e e2.edges.add(t51)), a2 = a2.reverse().map((t51) =\u003e new PR.Edge(t51.shape.reverse()));\n for (let t51 = 0; t51 \u003c a2.length - 1; t51++) a2[t51].next = a2[t51 + 1], a2[t51 + 1].prev = a2[t51];\n yE(r2.int_points2[i2.id], r2.int_points2[o2.id], a2), a2.forEach((t51) =\u003e e2.edges.add(t51));\n }\n return e2.recreateFaces(), e2;\n }\n cutWithLine(t48) {\n let e2 = new cE([t48]);\n return this.cut(e2);\n }\n findEdgeByPoint(t48) {\n let e2;\n for (let n2 of this.faces) if (e2 = n2.findEdgeByPoint(t48), void 0 !== e2) break;\n return e2;\n }\n splitToIslands() {\n if (this.isEmpty()) return [];\n let t48 = this.toArray();\n t48.sort((t49, e3) =\u003e e3.area() - t49.area());\n let e2 = [...t48[0].faces][0].orientation(), n2 = t48.filter((t49) =\u003e [...t49.faces][0].orientation() === e2);\n for (let o2 of t48) {\n let t49 = [...o2.faces][0];\n if (t49.orientation() !== e2) {\n for (let e3 of n2) if (t49.shapes.every((t50) =\u003e e3.contains(t50))) {\n e3.addFace(t49.shapes);\n break;\n }\n }\n }\n return n2;\n }\n rearrange() {\n if (this.faces.size \u003c= 1) return this.clone();\n const e2 = this.splitToIslands(), n2 = new t42();\n return e2.forEach((t48) =\u003e {\n t48.faces.forEach((t49) =\u003e n2.addFace(t49.shapes));\n }), n2;\n }\n orientation() {\n return this.isEmpty() ? mR.NOT_ORIENTABLE : [...this.faces][0].orientation();\n }\n isOuter(t48) {\n return t48.orientation() === this.orientation();\n }\n isMultiPolygon() {\n let t48 = 0;\n return this.faces.forEach((e2) =\u003e {\n this.isOuter(e2) \u0026\u0026 t48++;\n }), t48 \u003e 1;\n }\n reverse() {\n for (let t48 of this.faces) t48.reverse();\n return this;\n }\n contains(t48) {\n if (t48 instanceof PR.Point) {\n let e2 = qE(this, t48);\n return 1 === e2 || 2 === e2;\n }\n return tA(this, t48);\n }\n distanceTo(t48) {\n if (t48 instanceof PR.Point) {\n let [e2, n2] = PR.Distance.point2polygon(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Circle || t48 instanceof PR.Line || t48 instanceof PR.Segment || t48 instanceof PR.Arc) {\n let [e2, n2] = PR.Distance.shape2polygon(t48, this);\n return n2 = n2.reverse(), [e2, n2];\n }\n if (t48 instanceof PR.Polygon) {\n let e2, n2, o2 = [Number.POSITIVE_INFINITY, new PR.Segment()];\n for (let i2 of this.edges) {\n let r2 = o2[0];\n [e2, n2] = PR.Distance.shape2planarSet(i2.shape, t48.edges, r2), PR.Utils.LT(e2, r2) \u0026\u0026 (o2 = [e2, n2]);\n }\n return o2;\n }\n }\n intersect(t48) {\n return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? ZR(t48, this) : t48 instanceof PR.Ray ? rE(t48, this) : t48 instanceof PR.Circle ? qR(t48, this) : t48 instanceof PR.Segment ? UR(t48, this) : t48 instanceof PR.Arc ? GR(t48, this) : t48 instanceof PR.Polygon ? (function(t49, e2) {\n let n2 = [];\n if (t49.isEmpty() || e2.isEmpty()) return n2;\n if (t49.box.not_intersect(e2.box)) return n2;\n for (let o2 of t49.edges) n2 = [...n2, ...KR(o2, e2)];\n return n2;\n })(t48, this) : t48 instanceof PR.Multiline ? (function(t49, e2) {\n let n2 = [];\n if (e2.isEmpty() || 0 === t49.size) return n2;\n for (let o2 of t49) n2 = [...n2, ...KR(o2, e2)];\n return n2;\n })(t48, this) : void 0;\n }\n translate(e2) {\n let n2 = new t42();\n for (let t48 of this.faces) n2.addFace(t48.shapes.map((t49) =\u003e t49.translate(e2)));\n return n2;\n }\n rotate(e2 = 0, n2 = new PR.Point()) {\n let o2 = new t42();\n for (let t48 of this.faces) o2.addFace(t48.shapes.map((t49) =\u003e t49.rotate(e2, n2)));\n return o2;\n }\n scale(e2, n2) {\n let o2 = new t42();\n for (let t48 of this.faces) o2.addFace(t48.shapes.map((t49) =\u003e t49.scale(e2, n2)));\n return o2;\n }\n transform(e2 = new PR.Matrix()) {\n let n2 = new t42();\n for (let t48 of this.faces) n2.addFace(t48.shapes.map((t49) =\u003e t49.transform(e2)));\n return n2;\n }\n toJSON() {\n return [...this.faces].map((t48) =\u003e t48.toJSON());\n }\n toArray() {\n return [...this.faces].map((t48) =\u003e t48.toPolygon());\n }\n dpath() {\n return [...this.faces].reduce((t48, e2) =\u003e t48 + e2.svg(), \"\");\n }\n svg(t48 = {}) {\n let e2 = `\n\u003cpath ${TR({ fillRule: \"evenodd\", fill: \"lightcyan\", ...t48 })} d=\"`;\n for (let t49 of this.faces) e2 += `\n${t49.svg()}`;\n return e2 += '\" \u003e\\n\u003c/path\u003e', e2;\n }\n};\nPR.Polygon = yA;\nPR.polygon = (...t48) =\u003e new PR.Polygon(...t48);\nvar { Circle: bA, Line: xA, Point: vA, Vector: SA, Utils: IA } = PR;\nPR.Inversion = class t43 {\n constructor(t48) {\n this.circle = t48;\n }\n get inversion_circle() {\n return this.circle;\n }\n static inversePoint(t48, e2) {\n const n2 = new SA(t48.pc, e2), o2 = t48.r * t48.r, i2 = n2.dot(n2);\n return IA.EQ_0(i2) ? new vA(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY) : t48.pc.translate(n2.multiply(o2 / i2));\n }\n static inverseCircle(t48, e2) {\n const n2 = t48.pc.distanceTo(e2.pc)[0];\n if (IA.EQ(n2, e2.r)) {\n let n3 = t48.r * t48.r / (2 * e2.r), o2 = new SA(t48.pc, e2.pc);\n o2 = o2.normalize();\n let i2 = t48.pc.translate(o2.multiply(n3));\n return new xA(i2, o2);\n }\n {\n let n3 = new SA(t48.pc, e2.pc), o2 = t48.r * t48.r / (n3.dot(n3) - e2.r * e2.r), i2 = t48.pc.translate(n3.multiply(o2)), r2 = Math.abs(o2) * e2.r;\n return new bA(i2, r2);\n }\n }\n static inverseLine(t48, e2) {\n const [n2, o2] = t48.pc.distanceTo(e2);\n if (IA.EQ_0(n2)) return e2.clone();\n {\n let e3 = t48.r * t48.r / (2 * n2), i2 = new SA(t48.pc, o2.end);\n return i2 = i2.multiply(e3 / n2), new bA(t48.pc.translate(i2), e3);\n }\n }\n inverse(e2) {\n return e2 instanceof vA ? t43.inversePoint(this.circle, e2) : e2 instanceof bA ? t43.inverseCircle(this.circle, e2) : e2 instanceof xA ? t43.inverseLine(this.circle, e2) : void 0;\n }\n};\nPR.inversion = (t48) =\u003e new PR.Inversion(t48);\nPR.Distance = class t44 {\n static point2point(t48, e2) {\n return t48.distanceTo(e2);\n }\n static point2line(t48, e2) {\n let n2 = t48.projectionOn(e2);\n return [new PR.Vector(t48, n2).length, new PR.Segment(t48, n2)];\n }\n static point2circle(t48, e2) {\n let [n2, o2] = t48.distanceTo(e2.center);\n if (PR.Utils.EQ_0(n2)) return [e2.r, new PR.Segment(t48, e2.toArc().start)];\n {\n let o3 = Math.abs(n2 - e2.r), i2 = new PR.Vector(e2.pc, t48).normalize().multiply(e2.r), r2 = e2.pc.translate(i2);\n return [o3, new PR.Segment(t48, r2)];\n }\n }\n static point2segment(e2, n2) {\n if (n2.start.equalTo(n2.end)) return t44.point2point(e2, n2.start);\n let o2, i2, r2 = new PR.Vector(n2.start, n2.end), s2 = new PR.Vector(n2.start, e2), a2 = new PR.Vector(n2.end, e2), c2 = r2.dot(s2), l2 = -r2.dot(a2);\n if (PR.Utils.GE(c2, 0) \u0026\u0026 PR.Utils.GE(l2, 0)) {\n let t48 = n2.tangentInStart();\n return o2 = Math.abs(t48.cross(s2)), i2 = n2.start.translate(t48.multiply(t48.dot(s2))), [o2, new PR.Segment(e2, i2)];\n }\n return c2 \u003c 0 ? e2.distanceTo(n2.start) : e2.distanceTo(n2.end);\n }\n static point2arc(e2, n2) {\n let o2, i2, r2 = new PR.Circle(n2.pc, n2.r), s2 = [];\n return [o2, i2] = t44.point2circle(e2, r2), i2.end.on(n2) \u0026\u0026 s2.push(t44.point2circle(e2, r2)), s2.push(t44.point2point(e2, n2.start)), s2.push(t44.point2point(e2, n2.end)), t44.sort(s2), s2[0];\n }\n static point2edge(e2, n2) {\n return n2.shape instanceof PR.Segment ? t44.point2segment(e2, n2.shape) : t44.point2arc(e2, n2.shape);\n }\n static segment2line(e2, n2) {\n let o2 = e2.intersect(n2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n let i2 = [];\n return i2.push(t44.point2line(e2.start, n2)), i2.push(t44.point2line(e2.end, n2)), t44.sort(i2), i2[0];\n }\n static segment2segment(e2, n2) {\n let o2 = DR(e2, n2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n let i2, r2, s2 = [];\n return [i2, r2] = t44.point2segment(n2.start, e2), s2.push([i2, r2.reverse()]), [i2, r2] = t44.point2segment(n2.end, e2), s2.push([i2, r2.reverse()]), s2.push(t44.point2segment(e2.start, n2)), s2.push(t44.point2segment(e2.end, n2)), t44.sort(s2), s2[0];\n }\n static segment2circle(e2, n2) {\n let o2 = e2.intersect(n2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n let i2 = new PR.Line(e2.ps, e2.pe), [r2, s2] = t44.point2line(n2.center, i2);\n if (PR.Utils.GE(r2, n2.r) \u0026\u0026 s2.end.on(e2)) return t44.point2circle(s2.end, n2);\n {\n let [o3, i3] = t44.point2circle(e2.start, n2), [r3, s3] = t44.point2circle(e2.end, n2);\n return PR.Utils.LT(o3, r3) ? [o3, i3] : [r3, s3];\n }\n }\n static segment2arc(e2, n2) {\n let o2 = e2.intersect(n2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n let i2 = new PR.Line(e2.ps, e2.pe), r2 = new PR.Circle(n2.pc, n2.r), [s2, a2] = t44.point2line(r2.center, i2);\n if (PR.Utils.GE(s2, r2.r) \u0026\u0026 a2.end.on(e2)) {\n let [e3, o3] = t44.point2circle(a2.end, r2);\n if (o3.end.on(n2)) return [e3, o3];\n }\n let c2, l2, h2 = [];\n return h2.push(t44.point2arc(e2.start, n2)), h2.push(t44.point2arc(e2.end, n2)), [c2, l2] = t44.point2segment(n2.start, e2), h2.push([c2, l2.reverse()]), [c2, l2] = t44.point2segment(n2.end, e2), h2.push([c2, l2.reverse()]), t44.sort(h2), h2[0];\n }\n static circle2circle(e2, n2) {\n let o2 = e2.intersect(n2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n if (e2.center.equalTo(n2.center)) {\n let o3 = e2.toArc(), i2 = n2.toArc();\n return t44.point2point(o3.start, i2.start);\n }\n {\n let o3 = new PR.Line(e2.center, n2.center), i2 = o3.intersect(e2), r2 = o3.intersect(n2), s2 = [];\n return s2.push(t44.point2point(i2[0], r2[0])), s2.push(t44.point2point(i2[0], r2[1])), s2.push(t44.point2point(i2[1], r2[0])), s2.push(t44.point2point(i2[1], r2[1])), t44.sort(s2), s2[0];\n }\n }\n static circle2line(e2, n2) {\n let o2 = e2.intersect(n2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n let [i2, r2] = t44.point2line(e2.center, n2), [s2, a2] = t44.point2circle(r2.end, e2);\n return a2 = a2.reverse(), [s2, a2];\n }\n static arc2line(e2, n2) {\n let o2 = n2.intersect(e2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n let i2 = new PR.Circle(e2.center, e2.r), [r2, s2] = t44.point2line(i2.center, n2);\n if (!PR.Utils.GE(r2, i2.r)) {\n let o3 = [];\n return o3.push(t44.point2line(e2.start, n2)), o3.push(t44.point2line(e2.end, n2)), t44.sort(o3), o3[0];\n }\n {\n let [n3, o3] = t44.point2circle(s2.end, i2);\n if (o3.end.on(e2)) return [n3, o3];\n }\n }\n static arc2circle(e2, n2) {\n let o2 = e2.intersect(n2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n let i2 = new PR.Circle(e2.center, e2.r), [r2, s2] = t44.circle2circle(i2, n2);\n if (s2.start.on(e2)) return [r2, s2];\n {\n let o3 = [];\n return o3.push(t44.point2circle(e2.start, n2)), o3.push(t44.point2circle(e2.end, n2)), t44.sort(o3), o3[0];\n }\n }\n static arc2arc(e2, n2) {\n let o2 = e2.intersect(n2);\n if (o2.length \u003e 0) return [0, new PR.Segment(o2[0], o2[0])];\n let i2 = new PR.Circle(e2.center, e2.r), r2 = new PR.Circle(n2.center, n2.r), [s2, a2] = t44.circle2circle(i2, r2);\n if (a2.start.on(e2) \u0026\u0026 a2.end.on(n2)) return [s2, a2];\n {\n let o3, i3, r3 = [];\n return [o3, i3] = t44.point2arc(e2.start, n2), i3.end.on(n2) \u0026\u0026 r3.push([o3, i3]), [o3, i3] = t44.point2arc(e2.end, n2), i3.end.on(n2) \u0026\u0026 r3.push([o3, i3]), [o3, i3] = t44.point2arc(n2.start, e2), i3.end.on(e2) \u0026\u0026 r3.push([o3, i3.reverse()]), [o3, i3] = t44.point2arc(n2.end, e2), i3.end.on(e2) \u0026\u0026 r3.push([o3, i3.reverse()]), [o3, i3] = t44.point2point(e2.start, n2.start), r3.push([o3, i3]), [o3, i3] = t44.point2point(e2.start, n2.end), r3.push([o3, i3]), [o3, i3] = t44.point2point(e2.end, n2.start), r3.push([o3, i3]), [o3, i3] = t44.point2point(e2.end, n2.end), r3.push([o3, i3]), t44.sort(r3), r3[0];\n }\n }\n static point2polygon(e2, n2) {\n let o2 = [Number.POSITIVE_INFINITY, new PR.Segment()];\n for (let i2 of n2.edges) {\n let [n3, r2] = t44.point2edge(e2, i2);\n PR.Utils.LT(n3, o2[0]) \u0026\u0026 (o2 = [n3, r2]);\n }\n return o2;\n }\n static shape2polygon(t48, e2) {\n let n2 = [Number.POSITIVE_INFINITY, new PR.Segment()];\n for (let o2 of e2.edges) {\n let [e3, i2] = t48.distanceTo(o2.shape);\n PR.Utils.LT(e3, n2[0]) \u0026\u0026 (n2 = [e3, i2]);\n }\n return n2;\n }\n static polygon2polygon(t48, e2) {\n let n2 = [Number.POSITIVE_INFINITY, new PR.Segment()];\n for (let o2 of t48.edges) for (let t49 of e2.edges) {\n let [e3, i2] = o2.shape.distanceTo(t49.shape);\n PR.Utils.LT(e3, n2[0]) \u0026\u0026 (n2 = [e3, i2]);\n }\n return n2;\n }\n static box2box_minmax(t48, e2) {\n let n2 = Math.max(Math.max(t48.xmin - e2.xmax, 0), Math.max(e2.xmin - t48.xmax, 0)), o2 = Math.max(Math.max(t48.ymin - e2.ymax, 0), Math.max(e2.ymin - t48.ymax, 0)), i2 = n2 * n2 + o2 * o2, r2 = t48.merge(e2), s2 = r2.xmax - r2.xmin, a2 = r2.ymax - r2.ymin;\n return [i2, s2 * s2 + a2 * a2];\n }\n static minmax_tree_process_level(e2, n2, o2, i2) {\n let r2, s2;\n for (let a3 of n2) {\n [r2, s2] = t44.box2box_minmax(e2.box, a3.item.key);\n for (let t48 of a3.item.values) t48 instanceof PR.Edge ? i2.insert([r2, s2], t48.shape) : i2.insert([r2, s2], t48);\n PR.Utils.LT(s2, o2) \u0026\u0026 (o2 = s2);\n }\n if (0 === n2.length) return o2;\n let a2 = [...n2.map((t48) =\u003e t48.left.isNil() ? void 0 : t48.left).filter((t48) =\u003e void 0 !== t48), ...n2.map((t48) =\u003e t48.right.isNil() ? void 0 : t48.right).filter((t48) =\u003e void 0 !== t48)].filter((n3) =\u003e {\n let [i3, r3] = t44.box2box_minmax(e2.box, n3.max);\n return PR.Utils.LE(i3, o2);\n });\n return o2 = t44.minmax_tree_process_level(e2, a2, o2, i2);\n }\n static minmax_tree(e2, n2, o2) {\n let i2 = new lA(), r2 = [n2.index.root], s2 = o2 \u003c Number.POSITIVE_INFINITY ? o2 * o2 : Number.POSITIVE_INFINITY;\n return s2 = t44.minmax_tree_process_level(e2, r2, s2, i2), i2;\n }\n static minmax_tree_calc_distance(e2, n2, o2) {\n let i2, r2;\n if (null != n2 \u0026\u0026 !n2.isNil()) {\n if ([i2, r2] = t44.minmax_tree_calc_distance(e2, n2.left, o2), r2) return [i2, r2];\n if (PR.Utils.LT(i2[0], Math.sqrt(n2.item.key.low))) return [i2, true];\n let [s2, a2] = t44.distanceToArray(e2, n2.item.values);\n return PR.Utils.LT(s2, i2[0]) \u0026\u0026 (i2 = [s2, a2]), [i2, r2] = t44.minmax_tree_calc_distance(e2, n2.right, i2), [i2, r2];\n }\n return [o2, false];\n }\n static shape2planarSet(e2, n2, o2 = Number.POSITIVE_INFINITY) {\n let i2 = [o2, new PR.Segment()], r2 = false;\n if (n2 instanceof PR.PlanarSet) {\n let s2 = t44.minmax_tree(e2, n2, o2);\n [i2, r2] = t44.minmax_tree_calc_distance(e2, s2.root, i2);\n }\n return i2;\n }\n static sort(t48) {\n t48.sort((t49, e2) =\u003e PR.Utils.LT(t49[0], e2[0]) ? -1 : PR.Utils.GT(t49[0], e2[0]) ? 1 : 0);\n }\n static distance(t48, e2) {\n return t48.distanceTo(e2);\n }\n static distanceToArray(t48, e2) {\n let n2 = [Number.POSITIVE_INFINITY, new PR.Segment()];\n for (let o2 of e2) {\n let [e3, i2] = t48.distanceTo(o2);\n PR.Utils.LT(e3, n2[0]) \u0026\u0026 (n2 = [e3, i2]);\n }\n return n2;\n }\n static shape2multiline(e2, n2) {\n let o2 = [Number.POSITIVE_INFINITY, new PR.Segment()];\n for (let i2 of n2) {\n let [n3, r2] = t44.distance(e2, i2.shape);\n PR.Utils.LT(n3, o2[0]) \u0026\u0026 (o2 = [n3, r2]);\n }\n return o2;\n }\n static multiline2multiline(e2, n2) {\n let o2 = [Number.POSITIVE_INFINITY, new PR.Segment()];\n for (let i2 of e2) for (let e3 of n2) {\n let [n3, r2] = t44.distance(i2.shape, e3.shape);\n PR.Utils.LT(n3, o2[0]) \u0026\u0026 (o2 = [n3, r2]);\n }\n return o2;\n }\n};\nvar { Multiline: PA, Point: MA, Segment: CA, Polygon: NA } = PR;\nfunction wA(t48) {\n return new MA(t48.split(\" \").map(Number));\n}\nfunction TA(t48) {\n return t48.split(\", \").map(wA);\n}\nfunction RA(t48) {\n const e2 = TA(t48);\n let n2 = [];\n for (let t49 = 0; t49 \u003c e2.length - 1; t49++) n2.push(new CA(e2[t49], e2[t49 + 1]));\n return new PA(n2);\n}\nfunction EA(t48) {\n const e2 = t48.replace(/\\(\\(/, \"\").replace(/\\)\\)$/, \"\").split(\"), (\"), n2 = new NA();\n let o2;\n return e2.forEach((t49, e3) =\u003e {\n let i2 = t49.split(\", \").map((t50) =\u003e new MA(t50.split(\" \").map(Number)));\n const r2 = n2.addFace(i2);\n 0 === e3 ? o2 = r2.orientation() : r2.orientation() === o2 \u0026\u0026 r2.reverse();\n }), n2;\n}\nfunction AA(t48) {\n if (t48.startsWith(\"POLYGON\")) {\n return EA(t48.replace(/^POLYGON /, \"\"));\n }\n return (function(t49) {\n const e2 = t49.split(/\\)\\), \\(\\(/).map((t50) =\u003e \"((\" + t50 + \"))\").map(EA), n2 = new NA();\n return e2.reduce((t50, e3) =\u003e [...t50, ...e3?.faces], []).forEach((t50) =\u003e n2.addFace([...t50?.shapes])), n2;\n })(t48.replace(/^MULTIPOLYGON \\(\\(\\((.*)\\)\\)\\)$/, \"$1\"));\n}\nfunction OA(t48) {\n return t48.split(\"\\n\")?.every((t49) =\u003e t49.includes(\"POINT\"));\n}\nfunction LA(t48) {\n return t48.split(\"\\n\")?.every((t49) =\u003e t49.includes(\"LINESTRING\"));\n}\nPR.isWktString = function(t48) {\n return t48.startsWith(\"POINT\") || OA(t48) || t48.startsWith(\"LINESTRING\") || LA(t48) || t48.startsWith(\"MULTILINESTRING\") || t48.startsWith(\"POLYGON\") || t48.startsWith(\"MULTIPOINT\") || t48.startsWith(\"MULTIPOLYGON\") || t48.startsWith(\"GEOMETRYCOLLECTION\");\n}, PR.parseWKT = function t45(e2) {\n if (e2.startsWith(\"POINT\")) {\n return wA(e2.replace(/^POINT \\(/, \"\").replace(/\\)$/, \"\"));\n }\n if (e2.startsWith(\"MULTIPOINT\")) {\n return TA(e2.replace(/^MULTIPOINT \\(/, \"\").replace(/\\)$/, \"\"));\n }\n if (e2.startsWith(\"LINESTRING\")) {\n return RA(e2.replace(/^LINESTRING \\(/, \"\").replace(/\\)$/, \"\"));\n }\n if (e2.startsWith(\"MULTILINESTRING\")) {\n return (function(t48) {\n return t48.replace(/\\(\\(/, \"\").replace(/\\)\\)$/, \"\").split(\"), (\").map(RA);\n })(e2.replace(/^MULTILINESTRING /, \"\"));\n }\n if (e2.startsWith(\"POLYGON\") || e2.startsWith(\"MULTIPOLYGON\")) return AA(e2);\n if (e2.startsWith(\"GEOMETRYCOLLECTION\")) {\n const n2 = /(?\u003ctype\u003ePOINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \\((?:[^\\(\\)]|\\([^\\)]*\\))*\\)/g, o2 = e2.match(n2);\n o2[0].startsWith(\"GEOMETRYCOLLECTION\") \u0026\u0026 (o2[0] = o2[0].replace(\"GEOMETRYCOLLECTION (\", \"\"));\n return o2.map(t45).map((t48) =\u003e t48 instanceof Array ? t48 : [t48]).reduce((t48, e3) =\u003e [...t48, ...e3], []);\n }\n return OA(e2) ? (function(t48) {\n return t48.split(\"\\n\").map((t49) =\u003e t49.match(/\\(([^)]+)\\)/)[1]).map(wA);\n })(e2) : LA(e2) ? (function(t48) {\n return t48.split(\"\\n\").map((t49) =\u003e t49.match(/\\(([^)]+)\\)/)[1]).map(RA).reduce((t49, e3) =\u003e [...t49, ...e3], []);\n })(e2) : [];\n}, PR.BooleanOperations = BE, PR.Relations = iA;\nvar Jk = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_RAMP_ATTEMPTS: 16, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, MAX_ITERATIONS: 5e4, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY };\nnew Int32Array(0);\nvar lF = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_START: 0.05, RIP_THRESHOLD_END: 0.8, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: true, GREEDY_FINAL_ROUTE_ITERS: 4, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY };\nvar d$ = Math.PI / 2;\nvar j$ = 0.1;\nvar Y$ = 0.15;\nvar $ = j$ + Y$;\nvar X$ = 3 * $ / 4;\nvar vX = c(T(), 1);\nvar ZB = (Number.POSITIVE_INFINITY, 1e-9);\nvar xH = (new Int32Array(0), (t48) =\u003e (t48.ccwRotationDegrees ?? 0) * Math.PI / 180);\nvar xW = class t46 {\n static generators = /* @__PURE__ */ new Map();\n static register(e2) {\n t46.generators.set(e2.componentKind, e2);\n }\n static create(e2) {\n const n2 = e2.detectedComponent.componentKind, o2 = t46.generators.get(n2);\n if (!o2) throw new Error(`No topology generator registered for component kind \"${n2}\"`);\n return new o2(e2);\n }\n};\nvar vW = (t48) =\u003e [t48.obstacle.obstacleId ?? t48.obstacle.componentId ?? \"obstacle\", t48.start.x.toFixed(4), t48.start.y.toFixed(4), t48.end.x.toFixed(4), t48.end.y.toFixed(4), t48.expansionDirection.x, t48.expansionDirection.y].join(\":\");\nvar SW = (t48) =\u003e {\n let e2 = 0;\n for (const n2 of t48) e2 = 31 * e2 + n2.charCodeAt(0) \u003e\u003e\u003e 0;\n return e2;\n};\nvar IW = (t48, e2) =\u003e `hsla(${SW(vW(t48)) % 360},72%,36%,${e2})`;\nvar PW = (t48) =\u003e {\n const e2 = t48.expansionDirection;\n return e2.x \u003c 0 ? \"left\" : e2.x \u003e 0 ? \"right\" : e2.y \u003c 0 ? \"bottom\" : \"top\";\n};\nvar MW = (t48) =\u003e ({ x: (t48.start.x + t48.end.x) / 2, y: (t48.start.y + t48.end.y) / 2 });\nvar CW = (t48) =\u003e {\n const e2 = /^bga-gapfill-(\\d+)-/.exec(t48.capacityMeshNodeId);\n return e2 ? Number.parseInt(e2[1], 10) : null;\n};\nvar NW = (t48, e2) =\u003e {\n const n2 = MW(t48), o2 = MW(e2), i2 = n2.y - o2.y;\n if (Math.abs(i2) \u003e 1e-6) return i2;\n const r2 = n2.x - o2.x;\n return Math.abs(r2) \u003e 1e-6 ? r2 : vW(t48).localeCompare(vW(e2));\n};\nvar wW = (t48) =\u003e {\n const e2 = [...t48].sort(NW), n2 = [];\n let o2 = e2.shift();\n for (; o2 \u0026\u0026 (n2.push(o2), 0 !== e2.length); ) {\n const t49 = MW(o2);\n let n3 = 0, i2 = Number.POSITIVE_INFINITY;\n for (let o3 = 0; o3 \u003c e2.length; o3++) {\n const r2 = e2[o3], s2 = MW(r2), a2 = (s2.x - t49.x) ** 2 + (s2.y - t49.y) ** 2;\n a2 \u003c i2 - 1e-9 ? (i2 = a2, n3 = o3) : Math.abs(a2 - i2) \u003c= 1e-9 \u0026\u0026 NW(r2, e2[n3]) \u003c 0 \u0026\u0026 (n3 = o3);\n }\n o2 = e2.splice(n3, 1)[0];\n }\n return n2;\n};\nvar TW = (t48, e2) =\u003e {\n const n2 = vW(t48), o2 = e2.findIndex((t49) =\u003e vW(t49) === n2);\n return o2 \u003e= 0 ? `E${o2 + 1}` : `E${SW(n2).toString(36).slice(0, 4)}`;\n};\nvar RW = (t48) =\u003e t48.flatMap((t49) =\u003e {\n const e2 = ke(t49);\n return [{ obstacle: t49, start: { x: e2.minX, y: e2.minY }, end: { x: e2.minX, y: e2.maxY }, expansionDirection: { x: -1, y: 0 } }, { obstacle: t49, start: { x: e2.maxX, y: e2.minY }, end: { x: e2.maxX, y: e2.maxY }, expansionDirection: { x: 1, y: 0 } }, { obstacle: t49, start: { x: e2.minX, y: e2.minY }, end: { x: e2.maxX, y: e2.minY }, expansionDirection: { x: 0, y: -1 } }, { obstacle: t49, start: { x: e2.minX, y: e2.maxY }, end: { x: e2.maxX, y: e2.maxY }, expansionDirection: { x: 0, y: 1 } }];\n});\nvar EW = 1e-3;\nvar AW = 1e-3;\nvar OW = class extends wt {\n constructor(t48) {\n super(), this.inputProblem = t48;\n }\n inputProblem;\n meshIndex;\n allEdges = [];\n queueEdges = [];\n disconnectedEdges = [];\n currentEdge = null;\n lastSearchBounds = null;\n lastCandidateMeshNodes = [];\n lastMatchedMeshNode = null;\n _setup() {\n const t48 = Math.max(this.inputProblem.meshNodes.length, 1);\n this.meshIndex = new Ot(t48);\n for (const t49 of this.inputProblem.meshNodes) {\n const e3 = ke(t49);\n this.meshIndex.add(e3.minX, e3.minY, e3.maxX, e3.maxY);\n }\n this.meshIndex.finish();\n const e2 = RW(this.inputProblem.unmarkedComponentObstacles);\n this.queueEdges = e2, this.allEdges = wW(e2), this.currentEdge = null, this.lastSearchBounds = null, this.lastCandidateMeshNodes = [], this.lastMatchedMeshNode = null;\n }\n _step() {\n const t48 = this.queueEdges.shift();\n if (!t48) return this.currentEdge = null, this.lastSearchBounds = null, this.lastCandidateMeshNodes = [], this.lastMatchedMeshNode = null, void (this.solved = true);\n this.currentEdge = t48, this.lastMatchedMeshNode = null;\n const e2 = Math.abs(t48.start.x - t48.end.x) \u003c= EW, n2 = e2 ? { minX: t48.start.x - AW, maxX: t48.start.x + AW, minY: Math.min(t48.start.y, t48.end.y), maxY: Math.max(t48.start.y, t48.end.y) } : { minX: Math.min(t48.start.x, t48.end.x), maxX: Math.max(t48.start.x, t48.end.x), minY: t48.start.y - AW, maxY: t48.start.y + AW };\n this.lastSearchBounds = n2;\n const o2 = this.meshIndex.search(n2.minX, n2.minY, n2.maxX, n2.maxY);\n this.lastCandidateMeshNodes = o2.map((t49) =\u003e this.inputProblem.meshNodes[t49]);\n let i2 = false;\n for (const n3 of o2) {\n const o3 = this.inputProblem.meshNodes[n3], r2 = ke(o3);\n if (e2) {\n if (!(Math.min(r2.maxY, Math.max(t48.start.y, t48.end.y)) - Math.max(r2.minY, Math.min(t48.start.y, t48.end.y)) \u003e EW)) continue;\n if (-1 === t48.expansionDirection.x \u0026\u0026 Math.abs(r2.maxX - t48.start.x) \u003c= EW) {\n i2 = true, this.lastMatchedMeshNode = o3;\n break;\n }\n if (1 === t48.expansionDirection.x \u0026\u0026 Math.abs(r2.minX - t48.start.x) \u003c= EW) {\n i2 = true, this.lastMatchedMeshNode = o3;\n break;\n }\n continue;\n }\n if (Math.min(r2.maxX, Math.max(t48.start.x, t48.end.x)) - Math.max(r2.minX, Math.min(t48.start.x, t48.end.x)) \u003e EW) {\n if (-1 === t48.expansionDirection.y \u0026\u0026 Math.abs(r2.maxY - t48.start.y) \u003c= EW) {\n i2 = true, this.lastMatchedMeshNode = o3;\n break;\n }\n if (1 === t48.expansionDirection.y \u0026\u0026 Math.abs(r2.minY - t48.start.y) \u003c= EW) {\n i2 = true, this.lastMatchedMeshNode = o3;\n break;\n }\n }\n }\n i2 || this.disconnectedEdges.push(t48);\n }\n getOutput() {\n return this.disconnectedEdges;\n }\n visualize() {\n const t48 = this.disconnectedEdges, e2 = this.allEdges.length \u003e 0 ? this.allEdges : [...t48, ...this.currentEdge ? [this.currentEdge] : []], n2 = this.currentEdge ? IW(this.currentEdge, 0.88) : \"rgba(40,40,40,0.4)\", o2 = this.inputProblem.meshNodes.map((t49) =\u003e ({ ...ac(t49, { rectMargin: 0.01 }), fill: t49._containsObstacle ? \"rgba(120,120,120,0.18)\" : \"rgba(120,120,120,0.08)\", stroke: t49._containsObstacle ? \"rgba(120,120,120,0.42)\" : \"rgba(120,120,120,0.24)\" })), i2 = this.lastSearchBounds \u0026\u0026 this.currentEdge ? [{ center: (r2 = this.lastSearchBounds, { x: (r2.minX + r2.maxX) / 2, y: (r2.minY + r2.maxY) / 2 }), width: this.lastSearchBounds.maxX - this.lastSearchBounds.minX, height: this.lastSearchBounds.maxY - this.lastSearchBounds.minY, fill: IW(this.currentEdge, 0.1), stroke: IW(this.currentEdge, 0.36), label: [TW(this.currentEdge, e2), \"search band\"].join(\" \") }] : [];\n var r2;\n const s2 = this.lastCandidateMeshNodes.map((t49) =\u003e ({ ...ac(t49, { rectMargin: 0.018 }), fill: t49 === this.lastMatchedMeshNode ? \"rgba(0,180,90,0.24)\" : this.currentEdge ? IW(this.currentEdge, 0.16) : \"rgba(80,120,160,0.16)\", stroke: t49 === this.lastMatchedMeshNode ? \"rgba(0,150,80,0.88)\" : n2, label: [t49 === this.lastMatchedMeshNode ? \"matched\" : \"candidate\", t49.capacityMeshNodeId, `z:${t49.availableZ.join(\",\")}`].join(\"\\n\") })), a2 = this.inputProblem.unmarkedComponentObstacles.map((t49) =\u003e ({ center: t49.center, width: t49.width, height: t49.height, fill: \"rgba(160,160,160,0.10)\", stroke: \"rgba(160,160,160,0.40)\", label: t49.obstacleId ?? t49.componentId ?? \"obstacle\" })), c2 = t48.map((t49) =\u003e ({ points: [t49.start, t49.end], strokeColor: IW(t49, 0.14), strokeWidth: 0.01, strokeDash: \"5 4\", label: [TW(t49, e2), PW(t49), \"disconnected\"].join(\" \") })), l2 = [], h2 = [];\n if (this.currentEdge) {\n const t49 = MW(this.currentEdge);\n l2.push({ points: [this.currentEdge.start, this.currentEdge.end], strokeColor: IW(this.currentEdge, 1), strokeWidth: 0.06, label: [TW(this.currentEdge, e2), PW(this.currentEdge), \"checking\"].join(\" \") }, { points: [t49, { x: t49.x + 0.16 * this.currentEdge.expansionDirection.x, y: t49.y + 0.16 * this.currentEdge.expansionDirection.y }], strokeColor: IW(this.currentEdge, 0.82), strokeWidth: 0.02, strokeDash: \"3 3\" }), h2.push({ ...t49, color: IW(this.currentEdge, 1), label: TW(this.currentEdge, e2) });\n }\n return { rects: [...o2, ...i2, ...s2, ...a2], lines: [...c2, ...l2], points: h2 };\n }\n};\nvar LW = 1e-3;\nvar DW = 1e-3;\nvar zW = 1e-6;\nvar kW = class extends wt {\n constructor(t48) {\n super(), this.inputProblem = t48;\n }\n inputProblem;\n meshIndex;\n meshBounds;\n expandedNodes = [];\n _setup() {\n const t48 = Math.max(this.inputProblem.meshNodes.length, 1);\n this.meshIndex = new Ot(t48);\n let e2 = Number.POSITIVE_INFINITY, n2 = Number.NEGATIVE_INFINITY, o2 = Number.POSITIVE_INFINITY, i2 = Number.NEGATIVE_INFINITY;\n for (const t49 of this.inputProblem.meshNodes) {\n const r2 = ke(t49);\n this.meshIndex.add(r2.minX, r2.minY, r2.maxX, r2.maxY), e2 = Math.min(e2, r2.minX), n2 = Math.max(n2, r2.maxX), o2 = Math.min(o2, r2.minY), i2 = Math.max(i2, r2.maxY);\n }\n this.meshIndex.finish(), this.meshBounds = this.inputProblem.meshNodes.length ? { minX: e2, maxX: n2, minY: o2, maxY: i2 } : { minX: 0, maxX: 0, minY: 0, maxY: 0 };\n }\n getObstacleAvailableZ(t48) {\n return t48.__zLayers ?? t48.layers.map((t49) =\u003e No(t49, this.inputProblem.layerCount));\n }\n getSharedOverlapArea(t48, e2) {\n if (!t48.availableZ.some((t49) =\u003e e2.availableZ.includes(t49))) return 0;\n const n2 = ke(t48), o2 = ke(e2), i2 = Math.min(n2.maxX, o2.maxX) - Math.max(n2.minX, o2.minX), r2 = Math.min(n2.maxY, o2.maxY) - Math.max(n2.minY, o2.minY);\n return i2 \u003c= zW || r2 \u003c= zW ? 0 : i2 * r2;\n }\n getNodeObstacleOverlapArea(t48, e2) {\n const n2 = this.getObstacleAvailableZ(e2);\n if (!t48.availableZ.some((t49) =\u003e n2.includes(t49))) return 0;\n const o2 = ke(t48), i2 = ke(e2), r2 = Math.min(o2.maxX, i2.maxX) - Math.max(o2.minX, i2.minX), s2 = Math.min(o2.maxY, i2.maxY) - Math.max(o2.minY, i2.minY);\n return r2 \u003c= zW || s2 \u003c= zW ? 0 : r2 * s2;\n }\n getClosestMeshNode(t48, e2) {\n const n2 = Math.abs(t48.start.x - t48.end.x) \u003c= LW, o2 = this.getObstacleAvailableZ(t48.obstacle), i2 = n2 ? t48.expansionDirection.x \u003c 0 ? { minX: this.meshBounds.minX, maxX: t48.start.x, minY: Math.min(t48.start.y, t48.end.y) - DW, maxY: Math.max(t48.start.y, t48.end.y) + DW } : { minX: t48.start.x, maxX: this.meshBounds.maxX, minY: Math.min(t48.start.y, t48.end.y) - DW, maxY: Math.max(t48.start.y, t48.end.y) + DW } : t48.expansionDirection.y \u003c 0 ? { minX: Math.min(t48.start.x, t48.end.x) - DW, maxX: Math.max(t48.start.x, t48.end.x) + DW, minY: this.meshBounds.minY, maxY: t48.start.y } : { minX: Math.min(t48.start.x, t48.end.x) - DW, maxX: Math.max(t48.start.x, t48.end.x) + DW, minY: t48.start.y, maxY: this.meshBounds.maxY }, r2 = this.meshIndex.search(i2.minX, i2.minY, i2.maxX, i2.maxY);\n let s2 = null, a2 = Number.POSITIVE_INFINITY;\n const c2 = [...r2.map((t49) =\u003e this.inputProblem.meshNodes[t49]), ...e2];\n for (const e3 of c2) {\n if (e3._containsObstacle) continue;\n if (!e3.availableZ.some((t49) =\u003e o2.includes(t49))) continue;\n const i3 = ke(e3);\n if ((n2 ? Math.min(Math.max(t48.start.y, t48.end.y), i3.maxY) - Math.max(Math.min(t48.start.y, t48.end.y), i3.minY) : Math.min(Math.max(t48.start.x, t48.end.x), i3.maxX) - Math.max(Math.min(t48.start.x, t48.end.x), i3.minX)) \u003c= LW) continue;\n const r3 = n2 ? t48.expansionDirection.x \u003c 0 ? t48.start.x - i3.maxX : i3.minX - t48.start.x : t48.expansionDirection.y \u003c 0 ? t48.start.y - i3.maxY : i3.minY - t48.start.y;\n r3 \u003c LW || (r3 \u003e= a2 || (a2 = r3, s2 = e3));\n }\n return s2;\n }\n createExpandedNode(t48, e2, n2) {\n const o2 = ke(e2), i2 = this.getObstacleAvailableZ(t48.obstacle);\n if (Math.abs(t48.start.x - t48.end.x) \u003c= LW) {\n const r3 = Math.max(Math.min(t48.start.y, t48.end.y), o2.minY), s3 = Math.min(Math.max(t48.start.y, t48.end.y), o2.maxY), a3 = t48.expansionDirection.x \u003c 0 ? o2.maxX : t48.start.x, c3 = t48.expansionDirection.x \u003c 0 ? t48.start.x : o2.minX;\n return c3 - a3 \u003c= LW || s3 - r3 \u003c= LW ? null : { capacityMeshNodeId: `bga-gapfill-${n2}-${t48.obstacle.obstacleId ?? \"no-obstacle\"}-${e2.capacityMeshNodeId}`, center: { x: (a3 + c3) / 2, y: (r3 + s3) / 2 }, width: c3 - a3, height: s3 - r3, layer: `z${i2.join(\",\")}`, availableZ: i2 };\n }\n const r2 = Math.max(Math.min(t48.start.x, t48.end.x), o2.minX), s2 = Math.min(Math.max(t48.start.x, t48.end.x), o2.maxX), a2 = t48.expansionDirection.y \u003c 0 ? o2.maxY : t48.start.y, c2 = t48.expansionDirection.y \u003c 0 ? t48.start.y : o2.minY;\n return s2 - r2 \u003c= LW || c2 - a2 \u003c= LW ? null : { capacityMeshNodeId: `bga-gapfill-${n2}-${t48.obstacle.obstacleId ?? \"no-obstacle\"}-${e2.capacityMeshNodeId}`, center: { x: (r2 + s2) / 2, y: (a2 + c2) / 2 }, width: s2 - r2, height: c2 - a2, layer: `z${i2.join(\",\")}`, availableZ: i2 };\n }\n overlapsExistingGeometry(t48, e2) {\n for (const e3 of this.inputProblem.meshNodes) if (this.getSharedOverlapArea(t48, e3) \u003e 0) return true;\n for (const n2 of e2) if (this.getSharedOverlapArea(t48, n2) \u003e 0) return true;\n for (const e3 of this.inputProblem.edgesWithObstacle) if (this.getNodeObstacleOverlapArea(t48, e3.obstacle) \u003e 0) return true;\n return false;\n }\n _step() {\n const t48 = [];\n for (const [e2, n2] of this.inputProblem.edgesWithObstacle.entries()) {\n const o2 = this.getClosestMeshNode(n2, t48);\n if (!o2) continue;\n const i2 = this.createExpandedNode(n2, o2, e2);\n i2 \u0026\u0026 (this.overlapsExistingGeometry(i2, t48) || t48.push(i2));\n }\n this.expandedNodes = t48, this.solved = true;\n }\n getOutput() {\n return this.expandedNodes;\n }\n visualize() {\n const t48 = this.inputProblem.edgesWithObstacle, e2 = wW(t48);\n return { rects: [...this.inputProblem.meshNodes.map((t49) =\u003e ({ ...ac(t49, { rectMargin: 0.01 }), fill: t49._containsObstacle ? \"rgba(255,0,0,0.16)\" : \"rgba(0,120,255,0.08)\", stroke: t49._containsObstacle ? \"rgba(255,0,0,0.35)\" : \"rgba(0,120,255,0.28)\" })), ...this.expandedNodes.map((n2) =\u003e {\n const o2 = CW(n2), i2 = null === o2 ? null : t48[o2] ?? null;\n return { ...ac(n2, { rectMargin: 0.012, zOffset: 0.01 }), fill: i2 ? IW(i2, 0.24) : \"rgba(0,160,100,0.24)\", stroke: i2 ? IW(i2, 0.72) : \"rgba(0,160,100,0.68)\", label: [i2 ? TW(i2, e2) : \"E?\", \"expanded\", n2.capacityMeshNodeId, `z:${n2.availableZ.join(\",\")}`].join(\"\\n\") };\n })], lines: [...this.inputProblem.edgesWithObstacle.map((t49) =\u003e ({ points: [t49.start, t49.end], strokeColor: IW(t49, 0.9), strokeWidth: 0.034, label: [TW(t49, e2), PW(t49)].join(\" \") })), ...this.inputProblem.edgesWithObstacle.map((t49) =\u003e {\n const e3 = MW(t49);\n return { points: [e3, { x: e3.x + 0.16 * t49.expansionDirection.x, y: e3.y + 0.16 * t49.expansionDirection.y }], strokeColor: IW(t49, 0.7), strokeWidth: 0.016, strokeDash: \"3 3\" };\n })], points: this.inputProblem.edgesWithObstacle.map((t49) =\u003e ({ ...MW(t49), color: IW(t49, 0.95), label: TW(t49, e2) })) };\n }\n};\nvar FW = 1e-3;\nvar jW = class extends Rt {\n constructor(t48) {\n super(t48), this.inputProblem = t48;\n }\n inputProblem;\n detectEdgesNotConnectedToMesh;\n expandUnconnectedEdgesToMesh;\n pipelineDef = [Tt(\"detectEdgesNotConnectedToMesh\", OW, (t48) =\u003e [t48.inputProblem]), Tt(\"expandUnconnectedEdgesToMesh\", kW, (t48) =\u003e [{ meshNodes: t48.inputProblem.meshNodes, edgesWithObstacle: t48.detectEdgesNotConnectedToMesh.getOutput(), layerCount: t48.inputProblem.layerCount }])];\n getOutput() {\n return [...this.inputProblem.meshNodes, ...this.expandUnconnectedEdgesToMesh.getOutput()];\n }\n getExpandedNodes() {\n return this.expandUnconnectedEdgesToMesh.getOutput();\n }\n getObstacleLayer(t48) {\n return `z${(t48.obstacle.__zLayers ?? t48.obstacle.layers.map((t49) =\u003e No(t49, this.inputProblem.layerCount))).join(\",\")}`;\n }\n getObstacleRects() {\n return this.inputProblem.unmarkedComponentObstacles.map((t48) =\u003e {\n const e2 = t48.__zLayers ?? t48.layers.map((t49) =\u003e No(t49, this.inputProblem.layerCount));\n return { center: t48.center, width: t48.width, height: t48.height, fill: \"rgba(150,150,150,0.08)\", stroke: \"rgba(90,90,90,0.42)\", label: t48.obstacleId ?? t48.componentId ?? \"bga obstacle\", layer: `z${e2.join(\",\")}` };\n });\n }\n getBaseMeshRects() {\n return this.inputProblem.meshNodes.map((t48) =\u003e ({ ...ac(t48, { rectMargin: 0.025, zOffset: 0.01 }), fill: t48._containsObstacle ? \"rgba(210,60,60,0.14)\" : \"rgba(80,120,160,0.08)\", stroke: t48._containsObstacle ? \"rgba(190,40,40,0.42)\" : \"rgba(80,120,160,0.28)\", label: `mesh ${t48.capacityMeshNodeId}\nz:${t48.availableZ.join(\",\")}` }));\n }\n initialVisualize() {\n const t48 = RW(this.inputProblem.unmarkedComponentObstacles), e2 = wW(t48), n2 = [...t48.map((t49) =\u003e ({ points: [t49.start, t49.end], strokeColor: IW(t49, 0.72), strokeWidth: 0.018, strokeDash: \"0.05 0.035\", layer: this.getObstacleLayer(t49), label: [TW(t49, e2), PW(t49)].join(\" \") })), ...t48.map((t49) =\u003e {\n const e3 = MW(t49);\n return { points: [e3, { x: e3.x + 0.18 * t49.expansionDirection.x, y: e3.y + 0.18 * t49.expansionDirection.y }], strokeColor: IW(t49, 0.64), strokeWidth: 0.012, strokeDash: \"0.035 0.025\", layer: this.getObstacleLayer(t49) };\n })];\n return { title: \"BGA GapFill: candidate obstacle edges\", rects: [...this.getBaseMeshRects(), ...this.getObstacleRects()], lines: n2 };\n }\n finalVisualize() {\n const t48 = this.getStageOutput(\"detectEdgesNotConnectedToMesh\") ?? [], e2 = this.getStageOutput(\"expandUnconnectedEdgesToMesh\") ?? [], n2 = wW(RW(this.inputProblem.unmarkedComponentObstacles)), o2 = /* @__PURE__ */ new Map();\n for (const t49 of e2) {\n const e3 = CW(t49);\n null !== e3 \u0026\u0026 o2.set(e3, t49);\n }\n const i2 = e2.map((e3) =\u003e {\n const o3 = CW(e3), i3 = null === o3 ? null : t48[o3] ?? null, r3 = i3 ? (({ expandedNode: t49, edge: e4, meshNodes: n3 }) =\u003e {\n const o4 = ke(t49), i4 = Math.abs(e4.start.x - e4.end.x) \u003c= FW;\n return n3.filter((n4) =\u003e {\n if (n4._containsObstacle) return false;\n if (!t49.availableZ.some((t50) =\u003e n4.availableZ.includes(t50))) return false;\n const r4 = ke(n4);\n return i4 ? !(Math.min(o4.maxY, r4.maxY) - Math.max(o4.minY, r4.minY) \u003c= FW) \u0026\u0026 (e4.expansionDirection.x \u003c 0 ? Math.abs(r4.maxX - o4.minX) \u003c= FW : Math.abs(r4.minX - o4.maxX) \u003c= FW) : !(Math.min(o4.maxX, r4.maxX) - Math.max(o4.minX, r4.minX) \u003c= FW) \u0026\u0026 (e4.expansionDirection.y \u003c 0 ? Math.abs(r4.maxY - o4.minY) \u003c= FW : Math.abs(r4.minY - o4.maxY) \u003c= FW);\n }).map((t50) =\u003e t50.capacityMeshNodeId);\n })({ expandedNode: e3, edge: i3, meshNodes: this.inputProblem.meshNodes }) : [], s3 = i3 ? TW(i3, n2) : \"E?\", a3 = null === i3 ? \"rgba(0,160,100,0.72)\" : IW(i3, 0.72);\n return { ...ac(e3, { rectMargin: 0.012, zOffset: 0.01 }), fill: null === i3 ? \"rgba(0,160,100,0.24)\" : IW(i3, 0.16), stroke: a3, label: [`${s3} gap fill`, r3.length \u003e 0 ? `to ${r3.join(\",\")}` : \"target mesh not adjacent\", `z:${e3.availableZ.join(\",\")}`].join(\"\\n\") };\n }), r2 = t48.map((t49, e3) =\u003e {\n const i3 = o2.get(e3);\n return { points: [t49.start, t49.end], strokeColor: i3 ? IW(t49, 0.68) : \"rgba(80,80,80,0.14)\", strokeWidth: i3 ? 0.026 : 8e-3, ...i3 ? {} : { strokeDash: \"5 4\" }, layer: this.getObstacleLayer(t49), label: [[TW(t49, n2), PW(t49)].join(\" \"), i3 ? \"filled\" : \"no fill created\"].join(\"\\n\") };\n }), s2 = t48.flatMap((t49, e3) =\u003e {\n const n3 = MW(t49), i3 = o2.get(e3);\n return i3 ? [{ points: [n3, i3.center], strokeColor: IW(t49, 0.42), strokeWidth: 0.012, strokeDash: \"0.035 0.025\", layer: this.getObstacleLayer(t49) }] : [];\n }), a2 = t48.flatMap((t49, e3) =\u003e o2.has(e3) ? [{ ...MW(t49), color: IW(t49, 0.82), label: TW(t49, n2), layer: this.getObstacleLayer(t49) }] : []);\n return { title: \"BGA GapFill: disconnected edges and created mesh\", rects: [...this.getBaseMeshRects(), ...this.getObstacleRects(), ...i2], lines: [...r2, ...s2], points: a2 };\n }\n};\nfunction YW(t48, e2) {\n const n2 = [];\n for (let o2 = 0; o2 \u003c t48.length; o2++) {\n const i2 = t48[o2];\n n2.push(i2);\n const r2 = t48[o2 + 1];\n if (void 0 === r2) continue;\n const s2 = Math.round((r2 - i2) / e2);\n if (!(s2 \u003c= 1)) for (let t49 = 1; t49 \u003c s2; t49++) {\n const e3 = t49 / s2;\n n2.push(Number((i2 + (r2 - i2) * e3).toFixed(6)));\n }\n }\n return n2;\n}\nvar $W = 1e-3;\nfunction XW(t48) {\n const e2 = [];\n for (let n3 = 1; n3 \u003c t48.length; n3++) {\n const o3 = t48[n3] - t48[n3 - 1];\n o3 \u003e $W \u0026\u0026 e2.push(o3);\n }\n if (0 === e2.length) return null;\n const n2 = Math.min(...e2), o2 = e2.filter((t49) =\u003e t49 \u003c= 1.5 * n2).sort((t49, e3) =\u003e t49 - e3), i2 = Math.floor(o2.length / 2);\n return o2.length % 2 == 0 ? (o2[i2 - 1] + o2[i2]) / 2 : o2[i2];\n}\nfunction BW(t48) {\n return [...new Set(t48)].sort((t49, e2) =\u003e t49 - e2);\n}\nfunction HW(t48) {\n return Number(t48.toFixed(6));\n}\nvar WW = class t47 {\n static fromObstacles(e2) {\n if (0 === e2.length) return null;\n const n2 = BW(e2.map((t48) =\u003e t48.center.x)), o2 = BW(e2.map((t48) =\u003e t48.center.y)), i2 = XW(n2), r2 = XW(o2);\n return null === i2 || null === r2 ? null : new t47({ obstacles: e2, xCoordinates: YW(n2, i2), yCoordinates: YW(o2, r2), pitchX: i2, pitchY: r2 });\n }\n xCoordinates;\n yCoordinates;\n pitchX;\n pitchY;\n originX;\n originY;\n rowCount;\n colCount;\n padWidth;\n padHeight;\n slots = /* @__PURE__ */ new Map();\n constructor(t48) {\n this.xCoordinates = t48.xCoordinates, this.yCoordinates = t48.yCoordinates, this.pitchX = t48.pitchX, this.pitchY = t48.pitchY, this.originX = this.xCoordinates[0], this.originY = this.yCoordinates[0], this.colCount = this.xCoordinates.length, this.rowCount = this.yCoordinates.length, this.padWidth = t48.obstacles[0].width, this.padHeight = t48.obstacles[0].height;\n for (const e2 of t48.obstacles) {\n const t49 = this.getSlotForObstacle(e2);\n t49 \u0026\u0026 this.slots.set(this.getSlotKey(t49.row, t49.col), { ...t49, obstacle: e2 });\n }\n }\n getSlotKey(t48, e2) {\n return `${t48}:${e2}`;\n }\n getAxisIndex(t48, e2) {\n let n2 = -1, o2 = Number.POSITIVE_INFINITY;\n for (let i2 = 0; i2 \u003c t48.length; i2++) {\n const r2 = Math.abs(t48[i2] - e2);\n r2 \u003c o2 \u0026\u0026 (o2 = r2, n2 = i2);\n }\n return o2 \u003c= $W ? n2 : null;\n }\n getAxisCoordinate(t48, e2) {\n return t48[e2];\n }\n hasPadAt(t48, e2) {\n return this.slots.has(this.getSlotKey(t48, e2));\n }\n getSlotForObstacle(t48) {\n const e2 = this.getAxisIndex(this.yCoordinates, t48.center.y), n2 = this.getAxisIndex(this.xCoordinates, t48.center.x);\n return null === e2 || null === n2 || e2 \u003c 0 || e2 \u003e= this.rowCount || n2 \u003c 0 || n2 \u003e= this.colCount ? null : { row: e2, col: n2 };\n }\n getSlotCenter(t48, e2) {\n return { x: this.getAxisCoordinate(this.xCoordinates, e2), y: this.getAxisCoordinate(this.yCoordinates, t48) };\n }\n getHorizontalGap(t48, e2) {\n const n2 = this.getSlotCenter(t48, e2), o2 = this.getSlotCenter(t48, e2 + 1), i2 = Math.abs(o2.x - n2.x);\n return { orientation: \"horizontal\", row: t48, col: e2, center: { x: HW((n2.x + o2.x) / 2), y: n2.y }, width: i2 - this.padWidth, height: this.padHeight, isBetweenTwoPads: this.hasPadAt(t48, e2) \u0026\u0026 this.hasPadAt(t48, e2 + 1) };\n }\n getVerticalGap(t48, e2) {\n const n2 = this.getSlotCenter(t48, e2), o2 = this.getSlotCenter(t48 + 1, e2), i2 = Math.abs(o2.y - n2.y);\n return { orientation: \"vertical\", row: t48, col: e2, center: { x: n2.x, y: HW((n2.y + o2.y) / 2) }, width: this.padWidth, height: i2 - this.padHeight, isBetweenTwoPads: this.hasPadAt(t48, e2) \u0026\u0026 this.hasPadAt(t48 + 1, e2) };\n }\n getDiagonalGap(t48, e2) {\n const n2 = this.getSlotCenter(t48, e2), o2 = this.getSlotCenter(t48 + 1, e2 + 1), i2 = Math.abs(o2.x - n2.x), r2 = Math.abs(o2.y - n2.y);\n return { orientation: \"diagonal\", row: t48, col: e2, center: { x: HW((n2.x + o2.x) / 2), y: HW((n2.y + o2.y) / 2) }, width: i2 - this.padWidth, height: r2 - this.padHeight, isBetweenTwoPads: this.hasPadAt(t48, e2) \u0026\u0026 this.hasPadAt(t48 + 1, e2 + 1) };\n }\n getDiagonalGaps() {\n const t48 = [];\n for (let e2 = 0; e2 \u003c this.rowCount - 1; e2++) for (let n2 = 0; n2 \u003c this.colCount - 1; n2++) t48.push(this.getDiagonalGap(e2, n2));\n return t48.filter((t49) =\u003e t49.width \u003e $W \u0026\u0026 t49.height \u003e $W);\n }\n getAxisGaps() {\n const t48 = [];\n for (let e2 = 0; e2 \u003c this.rowCount; e2++) for (let n2 = 0; n2 \u003c this.colCount - 1; n2++) t48.push(this.getHorizontalGap(e2, n2));\n for (let e2 = 0; e2 \u003c this.rowCount - 1; e2++) for (let n2 = 0; n2 \u003c this.colCount; n2++) t48.push(this.getVerticalGap(e2, n2));\n return t48.filter((t49) =\u003e t49.width \u003e $W \u0026\u0026 t49.height \u003e $W);\n }\n getMissingSlots() {\n const t48 = [];\n for (let e2 = 0; e2 \u003c this.rowCount; e2++) for (let n2 = 0; n2 \u003c this.colCount; n2++) this.hasPadAt(e2, n2) || t48.push({ row: e2, col: n2, center: this.getSlotCenter(e2, n2), width: this.padWidth, height: this.padHeight });\n return t48;\n }\n};\nfunction VW(t48) {\n if ([t48.point.pointId, t48.point.pcb_port_id].filter((t49) =\u003e \"string\" == typeof t49).some((e3) =\u003e t48.obstacle.connectedTo.includes(e3))) return true;\n if (0 === t48.obstacle.connectedTo.length) return false;\n if (Oe(t48.point, t48.obstacle) \u003e 1e-3) return false;\n const e2 = uo(t48.point).map((e3) =\u003e No(e3, t48.layerCount)), n2 = t48.obstacle.layers.map((e3) =\u003e No(e3, t48.layerCount));\n return e2.some((t49) =\u003e n2.includes(t49));\n}\nfunction UW(t48) {\n return t48.obstacleId ?? [t48.componentId ?? \"no-component\", t48.center.x, t48.center.y, t48.width, t48.height, t48.layers.join(\",\")].join(\":\");\n}\nfunction GW({ componentId: t48, orientationKey: e2, row: n2, col: o2, center: i2, width: r2, height: s2 }) {\n return [\"cmn\", e2, t48, n2, o2, i2.x, i2.y, r2, s2].join(\"_\");\n}\nfunction ZW(t48) {\n const { componentId: e2, bgaGap: n2, freeLayers: o2, multiLayerThreshold: i2 } = t48, r2 = n2.width \u003e i2 \u0026\u0026 n2.height \u003e i2;\n let s2 = \"d\";\n \"horizontal\" === n2.orientation \u0026\u0026 (s2 = \"h\"), \"vertical\" === n2.orientation \u0026\u0026 (s2 = \"v\");\n const a2 = GW({ componentId: e2, orientationKey: s2, row: n2.row, col: n2.col, center: n2.center, width: n2.width, height: n2.height });\n return \"diagonal\" === n2.orientation \u0026\u0026 r2 || !n2.isBetweenTwoPads \u0026\u0026 r2 ? [{ center: n2.center, width: n2.width, height: n2.height, availableZ: [...o2], capacityMeshNodeId: `${a2}_all`, layer: \"\" }] : o2.map((t49) =\u003e ({ center: n2.center, width: n2.width, height: n2.height, availableZ: [t49], capacityMeshNodeId: `${a2}_${t49}`, layer: \"\" }));\n}\nfunction qW(t48) {\n const { componentId: e2, obstacle: n2, freeLayers: o2, layerCount: i2 } = t48, r2 = n2.layers.map((t49) =\u003e No(t49, i2)), s2 = o2.filter((t49) =\u003e !r2.includes(t49)), a2 = UW(n2);\n return s2.map((t49) =\u003e ({ capacityMeshNodeId: `free-${e2}-${a2}-${t49}`, center: n2.center, width: n2.width, height: n2.height, layer: `z${t49}`, availableZ: [t49] }));\n}\nfunction JW(t48, e2, n2) {\n const o2 = e2.layers.map((t49) =\u003e No(t49, n2.layerCount)), i2 = UW(e2), r2 = (function(t49) {\n for (const e3 of t49.srj.connections) for (const n3 of e3.pointsToConnect) if (VW({ point: n3, obstacle: t49.obstacle, layerCount: t49.srj.layerCount })) return e3.__rootConnectionNames?.[0] ?? e3.name;\n })({ obstacle: e2, srj: n2 });\n return { capacityMeshNodeId: `obstacle-${t48}-${i2}-${o2.join(\",\")}-${e2.center.x}-${e2.center.y}`, _containsObstacle: true, ...r2 ? { _containsTarget: true, _targetConnectionName: r2 } : {}, center: e2.center, width: e2.width, height: e2.height, layer: `z${o2.join(\",\")}`, availableZ: o2 };\n}\nvar KW = class extends wt {\n constructor(t48) {\n super(), this.inputProblem = t48;\n }\n inputProblem;\n componentObstacles = [];\n meshNodes = [];\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n const { srj: t48, componentBounds: e2, componentId: n2, markedComponentObstacles: o2, unmarkedComponentObstacles: i2 } = this.inputProblem, r2 = t48.obstacles.filter((t49) =\u003e true === t49.isCopperPour).filter((t49) =\u003e ze(ke(t49), e2)).flatMap((e3) =\u003e e3.layers.map((e4) =\u003e No(e4, t48.layerCount))), s2 = Array.from({ length: t48.layerCount }, (t49, e3) =\u003e e3).filter((t49) =\u003e !r2.includes(t49));\n if (this.componentObstacles = o2, 0 === o2.length || 0 === s2.length) return void (this.solved = true);\n const a2 = WW.fromObstacles(o2);\n if (!a2) return void (this.solved = true);\n const c2 = a2.getAxisGaps(), l2 = a2.getDiagonalGaps(), h2 = a2.getMissingSlots(), d2 = 1.2 * (this.inputProblem.viaDiameter ?? Do(t48).padDiameter);\n this.meshNodes = [...c2.flatMap((t49) =\u003e ZW({ componentId: n2, bgaGap: t49, freeLayers: s2, multiLayerThreshold: d2 })), ...l2.flatMap((t49) =\u003e ZW({ componentId: n2, bgaGap: t49, freeLayers: s2, multiLayerThreshold: d2 })), ...h2.flatMap((t49) =\u003e (function(t50) {\n const { componentId: e3, missingBgaSlot: n3, freeLayers: o3, multiLayerThreshold: i3 } = t50, r3 = GW({ componentId: e3, orientationKey: \"missing\", row: n3.row, col: n3.col, center: n3.center, width: n3.width, height: n3.height });\n return n3.width \u003e i3 \u0026\u0026 n3.height \u003e i3 ? [{ center: n3.center, width: n3.width, height: n3.height, availableZ: [...o3], capacityMeshNodeId: `${r3}_all`, layer: \"\" }] : o3.map((t51) =\u003e ({ center: n3.center, width: n3.width, height: n3.height, availableZ: [t51], capacityMeshNodeId: `${r3}_${t51}`, layer: \"\" }));\n })({ componentId: n2, missingBgaSlot: t49, freeLayers: s2, multiLayerThreshold: d2 })), ...o2.flatMap((e3) =\u003e [...qW({ componentId: n2, obstacle: e3, freeLayers: s2, layerCount: t48.layerCount }), JW(n2, e3, t48)]), ...i2.flatMap((e3) =\u003e [JW(n2, e3, t48)])], this.meshNodes = (function(t49) {\n const e3 = /* @__PURE__ */ new Map();\n return t49.map((t50) =\u003e {\n const n3 = e3.get(t50.capacityMeshNodeId) ?? 0;\n return e3.set(t50.capacityMeshNodeId, n3 + 1), 0 === n3 ? t50 : { ...t50, capacityMeshNodeId: `${t50.capacityMeshNodeId}__dup${n3}` };\n });\n })(this.meshNodes), this.solved = true;\n }\n getOutput() {\n return this.meshNodes;\n }\n visualize() {\n return { rects: [{ center: { x: (this.inputProblem.componentBounds.minX + this.inputProblem.componentBounds.maxX) / 2, y: (this.inputProblem.componentBounds.minY + this.inputProblem.componentBounds.maxY) / 2 }, width: this.inputProblem.componentBounds.maxX - this.inputProblem.componentBounds.minX, height: this.inputProblem.componentBounds.maxY - this.inputProblem.componentBounds.minY, fill: \"rgba(0,0,0,0)\", stroke: \"rgba(30,30,30,0.65)\", label: `component ${this.inputProblem.componentId}` }, ...this.inputProblem.markedComponentObstacles.map((t48) =\u003e ({ center: t48.center, width: t48.width, height: t48.height, fill: \"rgba(255,0,0,0.18)\", stroke: \"rgba(255,0,0,0.52)\", label: `pad ${t48.obstacleId ?? \"obstacle\"}` })), ...this.inputProblem.unmarkedComponentObstacles.map((t48) =\u003e ({ center: t48.center, width: t48.width, height: t48.height, fill: \"rgba(255,140,0,0.14)\", stroke: \"rgba(255,140,0,0.42)\", label: `foreign ${t48.obstacleId ?? \"obstacle\"}` })), ...this.meshNodes.map((t48) =\u003e ({ ...ac(t48, { rectMargin: 0.01 }), fill: t48._containsObstacle ? \"rgba(255,0,0,0.14)\" : t48.capacityMeshNodeId.includes(\"missing\") ? \"rgba(0,200,120,0.18)\" : \"rgba(0,120,255,0.12)\", stroke: t48._containsObstacle ? \"rgba(255,0,0,0.36)\" : t48.capacityMeshNodeId.includes(\"missing\") ? \"rgba(0,200,120,0.52)\" : \"rgba(0,120,255,0.38)\" }))] };\n }\n};\nfunction QW(t48) {\n return t48.capacityMeshNodeId.startsWith(\"bga-gapfill-\");\n}\nfunction tV(t48) {\n return JSON.stringify({ availableZ: [...t48.availableZ].sort((t49, e2) =\u003e t49 - e2), _containsTarget: t48._containsTarget ?? false, _targetConnectionName: t48._targetConnectionName ?? null, _depth: t48._depth ?? null, _strawNode: t48._strawNode ?? false, _strawParentCapacityMeshNodeId: t48._strawParentCapacityMeshNodeId ?? null, _qfpRegionType: t48._qfpRegionType ?? null, _isNarrowQfpPadGap: t48._isNarrowQfpPadGap ?? false, _soicRegionType: t48._soicRegionType ?? null, _offBoardConnectionId: t48._offBoardConnectionId ?? null, _offboardNetName: t48._offboardNetName ?? null, _isVirtualOffboard: t48._isVirtualOffboard ?? false, _containsObstacle: t48._containsObstacle ?? false });\n}\nfunction eV(t48, e2) {\n const n2 = ke(t48);\n for (const o2 of e2) {\n if (!t48.availableZ.some((t49) =\u003e o2.availableZ.includes(t49))) continue;\n const e3 = ke(o2);\n if (ze(n2, e3)) return true;\n }\n return false;\n}\nfunction nV(t48) {\n const e2 = t48[0];\n if (!e2) throw new Error(\"createMergedNode requires at least one source node\");\n let n2 = Number.POSITIVE_INFINITY, o2 = Number.NEGATIVE_INFINITY, i2 = Number.POSITIVE_INFINITY, r2 = Number.NEGATIVE_INFINITY;\n for (const e3 of t48) {\n const t49 = ke(e3);\n n2 = Math.min(n2, t49.minX), o2 = Math.max(o2, t49.maxX), i2 = Math.min(i2, t49.minY), r2 = Math.max(r2, t49.maxY);\n }\n return { ...e2, capacityMeshNodeId: `merge:${t48.map((t49) =\u003e t49.capacityMeshNodeId).join(\":\")}`, center: { x: (n2 + o2) / 2, y: (i2 + r2) / 2 }, width: o2 - n2, height: r2 - i2 };\n}\nfunction oV(t48, e2, n2) {\n return { center: t48.center, width: t48.width, height: t48.height, fill: e2, stroke: e2, label: n2 };\n}\nvar iV = class extends wt {\n constructor(t48) {\n super(), this.inputProblem = t48;\n }\n inputProblem;\n obstacleNodes = [];\n passthroughNodes = [];\n mergedNodes = [];\n pendingGroups = [];\n totalGroupCount = 0;\n processedGroupCount = 0;\n debugFilteredNodes = [];\n debugMergeEvents = [];\n currentGroupKey = null;\n currentRootNodeId = null;\n lastMergedNodeId = null;\n _setup() {\n this.obstacleNodes = this.inputProblem.meshNodes.filter((t49) =\u003e true === t49._containsObstacle), this.passthroughNodes = [], this.mergedNodes = [], this.pendingGroups = [], this.totalGroupCount = 0, this.processedGroupCount = 0, this.debugFilteredNodes = [], this.debugMergeEvents = [], this.currentGroupKey = null, this.currentRootNodeId = null, this.lastMergedNodeId = null;\n const t48 = /* @__PURE__ */ new Map();\n for (const e2 of this.inputProblem.meshNodes) {\n if (true === e2._containsObstacle) {\n this.passthroughNodes.push(e2), this.debugFilteredNodes.push({ type: \"preserved-obstacle\", node: e2, reason: \"contains-obstacle\" });\n continue;\n }\n if (QW(e2)) {\n this.passthroughNodes.push(e2);\n continue;\n }\n if (e2.availableZ.length !== this.inputProblem.layerCount) {\n this.passthroughNodes.push(e2);\n continue;\n }\n let n2 = false;\n for (let t49 = 0; t49 \u003c this.inputProblem.layerCount; t49 += 1) if (!e2.availableZ.includes(t49)) {\n n2 = true;\n break;\n }\n if (n2) {\n this.passthroughNodes.push(e2);\n continue;\n }\n if (eV(e2, this.obstacleNodes)) {\n this.passthroughNodes.push(e2), this.debugFilteredNodes.push({ type: \"preserved-overlap\", node: e2, reason: \"overlaps-obstacle\" });\n continue;\n }\n const o2 = tV(e2), i2 = t48.get(o2);\n i2 ? i2.push(e2) : t48.set(o2, [e2]);\n }\n for (const [e2, n2] of t48.entries()) n2.length \u003c= 1 ? this.passthroughNodes.push(...n2) : this.pendingGroups.push({ groupKey: e2, nodes: n2 });\n this.pendingGroups.sort((t49, e2) =\u003e e2.nodes.length - t49.nodes.length), this.totalGroupCount = this.pendingGroups.length, this.updateStats(\"setup\");\n }\n _step() {\n const t48 = this.pendingGroups.shift();\n if (!t48) return this.currentGroupKey = null, this.currentRootNodeId = null, this.solved = true, void this.updateStats(\"done\");\n const e2 = t48.nodes[0];\n this.currentGroupKey = t48.groupKey, this.currentRootNodeId = e2 ? e2.capacityMeshNodeId : null;\n const n2 = (function(t49) {\n if (!t49.nodes[0]) return { outputNodes: [], mergeEvents: [] };\n let e3 = Number.POSITIVE_INFINITY, n3 = Number.POSITIVE_INFINITY, o3 = Number.POSITIVE_INFINITY, i2 = Number.POSITIVE_INFINITY;\n for (const r3 of t49.nodes) {\n e3 = Math.min(e3, r3.width), n3 = Math.min(n3, r3.height);\n const t50 = ke(r3);\n o3 = Math.min(o3, t50.minX), i2 = Math.min(i2, t50.minY);\n }\n const r2 = /* @__PURE__ */ new Map(), s2 = [];\n for (const a3 of t49.nodes) {\n const t50 = ke(a3), c3 = Math.round((t50.minX - o3) / e3), l3 = Math.round((t50.minY - i2) / n3), h2 = Math.max(1, Math.round(a3.width / e3)), d2 = Math.max(1, Math.round(a3.height / n3));\n for (let t51 = 0; t51 \u003c d2; t51 += 1) for (let e4 = 0; e4 \u003c h2; e4 += 1) r2.set(`${c3 + e4},${l3 + t51}`, a3);\n s2.push({ col: c3, row: l3 });\n }\n s2.sort((t50, e4) =\u003e t50.row - e4.row || t50.col - e4.col);\n const a2 = /* @__PURE__ */ new Set(), c2 = [], l2 = [];\n for (const o4 of s2) {\n const i3 = `${o4.col},${o4.row}`;\n if (a2.has(i3)) continue;\n let s3 = 0;\n for (; ; ) {\n const t50 = `${o4.col + s3},${o4.row}`;\n if (!r2.has(t50)) break;\n if (a2.has(t50)) break;\n s3 += 1;\n }\n let h2 = s3, d2 = 1, u2 = 1, p2 = 1;\n for (let t50 = 1; ; t50 += 1) {\n const i4 = o4.row + t50 - 1;\n let s4 = 0;\n for (; s4 \u003c h2; ) {\n const t51 = `${o4.col + s4},${i4}`;\n if (!r2.has(t51)) break;\n if (a2.has(t51)) break;\n s4 += 1;\n }\n if (0 === s4) break;\n h2 = Math.min(h2, s4);\n for (let o5 = h2; o5 \u003e= 1; o5 -= 1) {\n const i5 = o5 * e3, r3 = t50 * n3, s5 = Math.min(i5, r3);\n if ((s5 \u003c= 1e-6 ? Number.POSITIVE_INFINITY : Math.max(i5, r3) / s5) \u003e 4) continue;\n const a3 = o5 * t50;\n a3 \u003e p2 \u0026\u0026 (p2 = a3, d2 = o5, u2 = t50);\n break;\n }\n }\n const m2 = /* @__PURE__ */ new Map();\n for (let t50 = 0; t50 \u003c u2; t50 += 1) for (let e4 = 0; e4 \u003c d2; e4 += 1) {\n const n4 = `${o4.col + e4},${o4.row + t50}`, i4 = r2.get(n4);\n i4 \u0026\u0026 (a2.add(n4), m2.set(i4.capacityMeshNodeId, i4));\n }\n const g2 = [...m2.values()];\n if (g2.length \u003c= 1) {\n const t50 = g2[0];\n t50 \u0026\u0026 c2.push(t50);\n continue;\n }\n const f2 = nV(g2);\n c2.push(f2), l2.push({ type: \"merge\", groupKey: t49.groupKey, sourceNodes: g2, mergedNode: f2 });\n }\n return { outputNodes: c2, mergeEvents: l2 };\n })(t48);\n this.mergedNodes.push(...n2.outputNodes), this.processedGroupCount += 1, this.debugMergeEvents.push(...n2.mergeEvents);\n const o2 = n2.mergeEvents[n2.mergeEvents.length - 1];\n o2 \u0026\u0026 (this.lastMergedNodeId = o2.mergedNode.capacityMeshNodeId), this.updateStats(n2.mergeEvents.length \u003e 0 ? \"merged-group\" : \"passthrough-group\");\n }\n computeProgress() {\n return 0 === this.totalGroupCount ? 1 : this.processedGroupCount / this.totalGroupCount;\n }\n updateStats(t48) {\n const e2 = new Set(this.debugMergeEvents.map((t49) =\u003e t49.groupKey)), n2 = { lastAction: t48, totalGroupCount: this.totalGroupCount, processedGroupCount: this.processedGroupCount, pendingGroupCount: this.pendingGroups.length, mergedNodeCount: this.mergedNodes.length, passthroughNodeCount: this.passthroughNodes.length, gapFillNodeCount: this.passthroughNodes.filter(QW).length, preservedObstacleNodeCount: this.debugFilteredNodes.filter((t49) =\u003e \"preserved-obstacle\" === t49.type).length, preservedOverlapNodeCount: this.debugFilteredNodes.filter((t49) =\u003e \"preserved-overlap\" === t49.type).length, mergeCount: this.debugMergeEvents.length, mergedGroupCount: e2.size, currentGroupKey: this.currentGroupKey, currentRootNodeId: this.currentRootNodeId, lastMergedNodeId: this.lastMergedNodeId };\n this.stats = n2;\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return [...this.mergedNodes, ...this.passthroughNodes];\n }\n visualize() {\n const t48 = this.getOutput(), e2 = this.currentRootNodeId ? t48.find((t49) =\u003e t49.capacityMeshNodeId === this.currentRootNodeId) ?? null : null, n2 = this.lastMergedNodeId ? t48.find((t49) =\u003e t49.capacityMeshNodeId === this.lastMergedNodeId) ?? null : null;\n return { rects: [...this.debugFilteredNodes.map((t49) =\u003e oV(t49.node, \"preserved-obstacle\" === t49.type ? \"rgba(255,64,64,0.35)\" : \"rgba(255,160,64,0.35)\", t49.reason)), ...this.passthroughNodes.map((t49) =\u003e oV(t49, t49._containsObstacle ? \"rgba(255,0,0,0.35)\" : QW(t49) ? \"rgba(0,120,255,0.18)\" : \"rgba(160,160,160,0.12)\")), ...this.mergedNodes.map((t49) =\u003e oV(t49, \"rgba(120,120,120,0.14)\")), ...e2 ? [oV(e2, \"rgba(255,215,0,0.35)\", \"active-group\")] : [], ...n2 ? [oV(n2, \"rgba(0,200,120,0.28)\", \"merged\")] : []] };\n }\n};\nvar rV = class extends wt {\n constructor(t48) {\n super(), this.inputProblem = t48;\n }\n inputProblem;\n obstacleQueue = [];\n obstacleQueueIndex = 0;\n meshNodes = [];\n _setup() {\n this.obstacleQueue = this.inputProblem.obstacles, this.obstacleQueueIndex = 0, this.meshNodes = [...this.inputProblem.meshNodes];\n }\n _step() {\n if (this.obstacleQueueIndex \u003e= this.obstacleQueue.length) return void (this.solved = true);\n const t48 = this.obstacleQueue[this.obstacleQueueIndex], e2 = t48.layers.map((t49) =\u003e No(t49, this.inputProblem.layerCount)), n2 = [];\n for (const o2 of this.meshNodes) {\n if (o2._containsObstacle) {\n n2.push(o2);\n continue;\n }\n if (!e2.some((t49) =\u003e o2.availableZ.includes(t49))) {\n n2.push(o2);\n continue;\n }\n if (!ze(ke(o2), ke(t48))) {\n n2.push(o2);\n continue;\n }\n if (1 === o2.availableZ.length) continue;\n const i2 = o2.availableZ.filter((t49) =\u003e !e2.includes(t49));\n for (const t49 of i2) {\n const e3 = { ...o2, capacityMeshNodeId: `${o2.capacityMeshNodeId}:z${t49}`, availableZ: [t49], layer: `z${t49}` };\n n2.push(e3);\n }\n }\n this.meshNodes = n2, this.obstacleQueueIndex += 1, this.stats = { obstaclesProcessed: this.obstacleQueueIndex, obstacleCount: this.obstacleQueue.length, meshNodeCount: this.meshNodes.length };\n }\n computeProgress() {\n return 0 === this.obstacleQueue.length ? 1 : this.obstacleQueueIndex / this.obstacleQueue.length;\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return this.meshNodes;\n }\n visualize() {\n const t48 = this.obstacleQueueIndex \u003c this.obstacleQueue.length ? this.obstacleQueue[this.obstacleQueueIndex] ?? null : null, e2 = this.obstacleQueue.slice(0, this.obstacleQueueIndex), n2 = t48 ? this.obstacleQueue.slice(this.obstacleQueueIndex + 1) : [];\n return { rects: [...e2.map((t49) =\u003e ({ center: t49.center, width: t49.width, height: t49.height, fill: \"rgba(160,160,160,0.10)\", stroke: \"rgba(160,160,160,0.35)\", label: `processed ${t49.obstacleId ?? \"obstacle\"}` })), ...t48 ? [{ center: t48.center, width: t48.width, height: t48.height, fill: \"rgba(255,140,0,0.22)\", stroke: \"rgba(255,140,0,0.75)\", label: `active ${t48.obstacleId ?? \"obstacle\"}` }] : [], ...n2.map((t49) =\u003e ({ center: t49.center, width: t49.width, height: t49.height, fill: \"rgba(255,0,0,0.05)\", stroke: \"rgba(255,0,0,0.22)\", label: `pending ${t49.obstacleId ?? \"obstacle\"}` })), ...this.meshNodes.map((t49) =\u003e ({ ...ac(t49, { rectMargin: 0.01 }), fill: t49._containsObstacle ? \"rgba(255,0,0,0.18)\" : \"rgba(0,120,255,0.12)\", stroke: t49._containsObstacle ? \"rgba(255,0,0,0.45)\" : \"rgba(0,120,255,0.45)\" }))] };\n }\n};\nxW.register(class extends Rt {\n constructor(t48) {\n super(t48), this.inputProblem = t48;\n }\n inputProblem;\n static componentKind = \"bga\";\n initialTopologySolver;\n removeMeshNodeOverlappingWithUnmarkedObstacle;\n gapfillDueToNodeRemoval;\n mergeMeshNodes;\n markedComponentObstacles = [];\n unmarkedComponentObstacles = [];\n pipelineDef = [Tt(\"initialTopologySolver\", KW, (t48) =\u003e [{ srj: t48.inputProblem.inputSrj, componentBounds: t48.inputProblem.detectedComponent.bounds, componentId: t48.inputProblem.detectedComponent.componentId, markedComponentObstacles: t48.markedComponentObstacles, unmarkedComponentObstacles: t48.unmarkedComponentObstacles, viaDiameter: t48.inputProblem.viaDiameter }]), Tt(\"removeMeshNodeOverlappingWithUnmarkedObstacle\", rV, (t48) =\u003e [{ meshNodes: t48.initialTopologySolver.getOutput(), obstacles: t48.unmarkedComponentObstacles, layerCount: t48.inputProblem.inputSrj.layerCount }]), Tt(\"gapfillDueToNodeRemoval\", jW, (t48) =\u003e [{ meshNodes: t48.removeMeshNodeOverlappingWithUnmarkedObstacle.getOutput(), unmarkedComponentObstacles: t48.unmarkedComponentObstacles, layerCount: t48.inputProblem.inputSrj.layerCount }]), Tt(\"mergeMeshNodes\", iV, (t48) =\u003e [{ meshNodes: t48.gapfillDueToNodeRemoval.getOutput(), layerCount: t48.inputProblem.inputSrj.layerCount }])];\n _setup() {\n const t48 = this.inputProblem.detectedComponent.bounds, e2 = this.inputProblem.detectedComponent.componentId, n2 = [], o2 = [];\n for (const i2 of this.inputProblem.inputSrj.obstacles) {\n const r2 = ke(i2);\n ze(t48, r2) \u0026\u0026 (i2.componentId !== e2 ? o2.push(i2) : n2.push(i2));\n }\n this.markedComponentObstacles = n2, this.unmarkedComponentObstacles = o2;\n }\n getConstructorParams() {\n return [this.inputProblem];\n }\n getOutput() {\n return { routingRegions: this.mergeMeshNodes?.getOutput() ?? this.gapfillDueToNodeRemoval?.getOutput() ?? this.removeMeshNodeOverlappingWithUnmarkedObstacle?.getOutput() ?? [] };\n }\n initialVisualize() {\n return { rects: [{ center: { x: (this.inputProblem.detectedComponent.bounds.minX + this.inputProblem.detectedComponent.bounds.maxX) / 2, y: (this.inputProblem.detectedComponent.bounds.minY + this.inputProblem.detectedComponent.bounds.maxY) / 2 }, width: this.inputProblem.detectedComponent.bounds.maxX - this.inputProblem.detectedComponent.bounds.minX, height: this.inputProblem.detectedComponent.bounds.maxY - this.inputProblem.detectedComponent.bounds.minY, fill: \"rgba(0,0,0,0)\", stroke: \"rgba(30,30,30,0.65)\", label: `bga ${this.inputProblem.detectedComponent.componentId}` }, ...this.markedComponentObstacles.map((t48) =\u003e ({ center: t48.center, width: t48.width, height: t48.height, fill: \"rgba(255,0,0,0.18)\", stroke: \"rgba(255,0,0,0.52)\", label: `pad ${t48.obstacleId ?? \"obstacle\"}` })), ...this.unmarkedComponentObstacles.map((t48) =\u003e ({ center: t48.center, width: t48.width, height: t48.height, fill: \"rgba(255,140,0,0.14)\", stroke: \"rgba(255,140,0,0.42)\", label: `foreign ${t48.obstacleId ?? \"obstacle\"}` }))] };\n }\n finalVisualize() {\n return { rects: this.getOutput().routingRegions.map((t48) =\u003e ({ ...ac(t48, { rectMargin: 0.01 }), fill: t48._containsObstacle ? \"rgba(255,0,0,0.16)\" : \"rgba(0,120,255,0.12)\", stroke: t48._containsObstacle ? \"rgba(255,0,0,0.36)\" : \"rgba(0,120,255,0.42)\" })) };\n }\n});\nvar sV = 1e-6;\nfunction aV(t48, e2) {\n return t48.__zLayers \u0026\u0026 t48.__zLayers.length \u003e 0 ? wo(t48.__zLayers, e2) : To(t48.layers, e2);\n}\nfunction cV(t48) {\n const e2 = [...t48].sort((t49, e3) =\u003e t49 - e3), n2 = [];\n for (let t49 = 1; t49 \u003c e2.length; t49++) {\n const o3 = e2[t49] - e2[t49 - 1];\n o3 \u003e sV \u0026\u0026 n2.push(o3);\n }\n const o2 = n2.length \u003e 0 ? Math.max(sV, Math.min(...n2) / 4) : 1e-3, i2 = [];\n for (const t49 of e2) {\n const e3 = i2[i2.length - 1];\n (void 0 === e3 || Math.abs(t49 - e3) \u003e o2) \u0026\u0026 i2.push(t49);\n }\n return i2;\n}\nfunction lV(t48) {\n return Array.from({ length: Math.max(0, t48) }, (t49, e2) =\u003e e2);\n}\nvar hV = 1e-6;\nfunction dV(t48) {\n return t48.maxX - t48.minX \u003e hV \u0026\u0026 t48.maxY - t48.minY \u003e hV;\n}\nfunction uV(t48) {\n return (function(t49) {\n const e2 = Math.min(t49.width, t49.height), n2 = Math.max(t49.width, t49.height);\n return e2 \u003c= 0 ? 0 : n2 / e2;\n })(t48) \u003e= 1.5;\n}\nfunction pV(t48, e2) {\n const n2 = [{ side: \"top\", distance: Math.abs(t48.center.y - e2.minY) }, { side: \"right\", distance: Math.abs(e2.maxX - t48.center.x) }, { side: \"bottom\", distance: Math.abs(e2.maxY - t48.center.y) }, { side: \"left\", distance: Math.abs(t48.center.x - e2.minX) }];\n return n2.sort((t49, e3) =\u003e t49.distance - e3.distance), n2[0].side;\n}\nfunction mV(t48, e2) {\n return t48.map((t49, n2) =\u003e ({ key: `pad:${t49.obstacleId ?? n2}`, bounds: Me(t49), regionType: \"pad\", obstacleZ: aV(t49, e2) }));\n}\nfunction gV(t48, e2) {\n return t48.map((t49, n2) =\u003e ({ key: `thermal-pad:${t49.obstacleId ?? n2}`, bounds: Me(t49), regionType: \"pad\", obstacleZ: aV(t49, e2) }));\n}\nfunction fV(t48, e2) {\n return !!dV(t48) \u0026\u0026 Math.min(t48.maxX - t48.minX, t48.maxY - t48.minY) \u003c= e2;\n}\nfunction _V({ side: t48, sideObstacles: e2, bounds: n2, innerBounds: o2, narrowThreshold: i2 }) {\n const r2 = [];\n for (let s2 = 0; s2 \u003c e2.length - 1; s2++) {\n const a2 = Me(e2[s2]), c2 = Me(e2[s2 + 1]);\n let l2;\n l2 = \"top\" === t48 ? { minX: a2.maxX, maxX: c2.minX, minY: n2.minY, maxY: o2.minY } : \"right\" === t48 ? { minX: o2.maxX, maxX: n2.maxX, minY: a2.maxY, maxY: c2.minY } : \"bottom\" === t48 ? { minX: a2.maxX, maxX: c2.minX, minY: o2.maxY, maxY: n2.maxY } : { minX: n2.minX, maxX: o2.minX, minY: a2.maxY, maxY: c2.minY }, r2.push({ key: `${t48}-gap-${s2}`, bounds: l2, regionType: \"pad-gap\", isNarrowPadGap: fV(l2, i2) });\n }\n return r2;\n}\nfunction yV({ side: t48, sideObstacles: e2, thermalPadBounds: n2, narrowThreshold: o2 }) {\n const i2 = [];\n for (let r2 = 0; r2 \u003c e2.length; r2++) {\n const s2 = Me(e2[r2]), a2 = e2[r2 - 1] ? Me(e2[r2 - 1]) : null, c2 = e2[r2 + 1] ? Me(e2[r2 + 1]) : null;\n let l2;\n l2 = \"top\" === t48 ? { minX: a2 ? (a2.maxX + s2.minX) / 2 : s2.minX, maxX: c2 ? (s2.maxX + c2.minX) / 2 : s2.maxX, minY: s2.maxY, maxY: n2.minY } : \"right\" === t48 ? { minX: n2.maxX, maxX: s2.minX, minY: a2 ? (a2.maxY + s2.minY) / 2 : s2.minY, maxY: c2 ? (s2.maxY + c2.minY) / 2 : s2.maxY } : \"bottom\" === t48 ? { minX: a2 ? (a2.maxX + s2.minX) / 2 : s2.minX, maxX: c2 ? (s2.maxX + c2.minX) / 2 : s2.maxX, minY: n2.maxY, maxY: s2.minY } : { minX: s2.maxX, maxX: n2.minX, minY: a2 ? (a2.maxY + s2.minY) / 2 : s2.minY, maxY: c2 ? (s2.maxY + c2.minY) / 2 : s2.maxY }, i2.push({ key: `inner-${t48}-pad-${r2}`, bounds: l2, regionType: \"pad-gap\", isNarrowPadGap: fV(l2, o2) });\n }\n return i2;\n}\nfunction bV({ bounds: t48, innerBounds: e2, sideGroups: n2 }) {\n const o2 = n2.top[0] ? Me(n2.top[0]) : null, i2 = n2.top.at(-1) ? Me(n2.top.at(-1)) : null, r2 = n2.right[0] ? Me(n2.right[0]) : null, s2 = n2.right.at(-1) ? Me(n2.right.at(-1)) : null, a2 = n2.bottom[0] ? Me(n2.bottom[0]) : null, c2 = n2.bottom.at(-1) ? Me(n2.bottom.at(-1)) : null, l2 = n2.left[0] ? Me(n2.left[0]) : null, h2 = n2.left.at(-1) ? Me(n2.left.at(-1)) : null;\n return [{ key: \"corner-nw-outer\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: \"corner-nw-top\", regionType: \"corner\", bounds: { minX: e2.minX, maxX: o2?.minX ?? e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: \"corner-nw-left\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.minY, maxY: l2?.minY ?? e2.minY } }, { key: \"corner-ne-outer\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: t48.minY, maxY: e2.minY } }, { key: \"corner-ne-top\", regionType: \"corner\", bounds: { minX: i2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: t48.minY, maxY: e2.minY } }, { key: \"corner-ne-right\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.minY, maxY: r2?.minY ?? e2.minY } }, { key: \"corner-se-outer\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"corner-se-right\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: s2?.maxY ?? e2.maxY, maxY: e2.maxY } }, { key: \"corner-se-bottom\", regionType: \"corner\", bounds: { minX: c2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"corner-sw-outer\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"corner-sw-bottom\", regionType: \"corner\", bounds: { minX: e2.minX, maxX: a2?.minX ?? e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"corner-sw-left\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: h2?.maxY ?? e2.maxY, maxY: e2.maxY } }];\n}\nfunction xV({ innerBounds: t48, thermalPadBounds: e2, sideGroups: n2 }) {\n const o2 = n2.top[0] ? Me(n2.top[0]) : null, i2 = n2.top.at(-1) ? Me(n2.top.at(-1)) : null, r2 = n2.right[0] ? Me(n2.right[0]) : null, s2 = n2.right.at(-1) ? Me(n2.right.at(-1)) : null, a2 = n2.bottom[0] ? Me(n2.bottom[0]) : null, c2 = n2.bottom.at(-1) ? Me(n2.bottom.at(-1)) : null, l2 = n2.left[0] ? Me(n2.left[0]) : null, h2 = n2.left.at(-1) ? Me(n2.left.at(-1)) : null;\n return [{ key: \"inner-corner-nw-core\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: \"inner-corner-nw-top\", regionType: \"corner\", bounds: { minX: e2.minX, maxX: o2?.minX ?? e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: \"inner-corner-nw-left\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.minY, maxY: l2?.minY ?? e2.minY } }, { key: \"inner-corner-ne-core\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: t48.minY, maxY: e2.minY } }, { key: \"inner-corner-ne-top\", regionType: \"corner\", bounds: { minX: i2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: t48.minY, maxY: e2.minY } }, { key: \"inner-corner-ne-right\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.minY, maxY: r2?.minY ?? e2.minY } }, { key: \"inner-corner-se-core\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"inner-corner-se-right\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: s2?.maxY ?? e2.maxY, maxY: e2.maxY } }, { key: \"inner-corner-se-bottom\", regionType: \"corner\", bounds: { minX: c2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"inner-corner-sw-core\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"inner-corner-sw-bottom\", regionType: \"corner\", bounds: { minX: e2.minX, maxX: a2?.minX ?? e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"inner-corner-sw-left\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: h2?.maxY ?? e2.maxY, maxY: e2.maxY } }];\n}\nxW.register(class extends wt {\n constructor(t48) {\n super(), this.inputProblem = t48;\n }\n inputProblem;\n static componentKind = \"qfp_thermalpad\";\n output = null;\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n if (this.output) return void (this.solved = true);\n const { layerCount: t48, obstacles: e2 } = this.inputProblem.inputSrj, { bounds: n2, componentId: o2 } = this.inputProblem.detectedComponent, i2 = lV(t48), r2 = e2.filter((t49) =\u003e t49.componentId === o2), s2 = r2.length \u003e 0 ? r2 : e2, { padRingObstacles: a2, thermalPadObstacles: c2 } = (function(t49) {\n return { padRingObstacles: t49.filter(uV), thermalPadObstacles: t49.filter((t50) =\u003e !uV(t50)) };\n })(s2), l2 = (function(t49, e3) {\n const n3 = { top: [], right: [], bottom: [], left: [] };\n for (const o3 of t49) n3[pV(o3, e3)].push(o3);\n return n3.top.sort((t50, e4) =\u003e t50.center.x - e4.center.x), n3.bottom.sort((t50, e4) =\u003e t50.center.x - e4.center.x), n3.left.sort((t50, e4) =\u003e t50.center.y - e4.center.y), n3.right.sort((t50, e4) =\u003e t50.center.y - e4.center.y), n3;\n })(a2, n2), h2 = (function({ bounds: t49, sideGroups: e3 }) {\n return { minX: e3.left.length \u003e 0 ? Math.max(...e3.left.map((t50) =\u003e Me(t50).maxX)) : t49.minX, maxX: e3.right.length \u003e 0 ? Math.min(...e3.right.map((t50) =\u003e Me(t50).minX)) : t49.maxX, minY: e3.top.length \u003e 0 ? Math.max(...e3.top.map((t50) =\u003e Me(t50).maxY)) : t49.minY, maxY: e3.bottom.length \u003e 0 ? Math.min(...e3.bottom.map((t50) =\u003e Me(t50).minY)) : t49.maxY };\n })({ bounds: n2, sideGroups: l2 }), d2 = (function(t49) {\n return 0 === t49.length ? null : t49.reduce((t50, e3) =\u003e {\n const n3 = Me(e3);\n return { minX: Math.min(t50.minX, n3.minX), maxX: Math.max(t50.maxX, n3.maxX), minY: Math.min(t50.minY, n3.minY), maxY: Math.max(t50.maxY, n3.maxY) };\n }, Me(t49[0]));\n })(c2);\n if (!d2) return this.failed = true, void (this.error = \"QfpThermalPadTopologyGeneratorSolver requires a thermal pad\");\n const u2 = o2, p2 = this.inputProblem.viaDiameter ?? Do(this.inputProblem.inputSrj).padDiameter, m2 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, g2 = p2 + 2 * m2, f2 = this.inputProblem.inputSrj.minTraceWidth + 2 * m2, _2 = [...mV(a2, t48), ...gV(c2, t48), ..._V({ side: \"top\", sideObstacles: l2.top, bounds: n2, innerBounds: h2, narrowThreshold: f2 }), ..._V({ side: \"right\", sideObstacles: l2.right, bounds: n2, innerBounds: h2, narrowThreshold: f2 }), ..._V({ side: \"bottom\", sideObstacles: l2.bottom, bounds: n2, innerBounds: h2, narrowThreshold: f2 }), ..._V({ side: \"left\", sideObstacles: l2.left, bounds: n2, innerBounds: h2, narrowThreshold: f2 }), ...yV({ side: \"top\", sideObstacles: l2.top, thermalPadBounds: d2, narrowThreshold: f2 }), ...yV({ side: \"right\", sideObstacles: l2.right, thermalPadBounds: d2, narrowThreshold: f2 }), ...yV({ side: \"bottom\", sideObstacles: l2.bottom, thermalPadBounds: d2, narrowThreshold: f2 }), ...yV({ side: \"left\", sideObstacles: l2.left, thermalPadBounds: d2, narrowThreshold: f2 }), ...xV({ innerBounds: h2, thermalPadBounds: d2, sideGroups: l2 }), ...bV({ bounds: n2, innerBounds: h2, sideGroups: l2 })].flatMap((t49) =\u003e (function({ nodeId: t50, bounds: e3, availableZ: n3, multiLayerThreshold: o3, regionType: i3, isNarrowPadGap: r3 = false, obstacleZ: s3 = [] }) {\n if (!dV(e3)) return [];\n const a3 = (function(t51) {\n return { center: { x: (t51.minX + t51.maxX) / 2, y: (t51.minY + t51.maxY) / 2 }, width: t51.maxX - t51.minX, height: t51.maxY - t51.minY };\n })(e3), c3 = Math.min(a3.width, a3.height) \u003e o3, l3 = c3 ? [{ availableZ: n3.filter((t51) =\u003e !s3.includes(t51)), containsObstacle: false }, { availableZ: n3.filter((t51) =\u003e s3.includes(t51)), containsObstacle: true }].filter((t51) =\u003e t51.availableZ.length \u003e 0) : n3.map((t51) =\u003e ({ availableZ: [t51], containsObstacle: s3.includes(t51) }));\n return l3.map((e4) =\u003e ({ capacityMeshNodeId: 1 === l3.length ? t50 : c3 ? `${t50}:${e4.containsObstacle ? \"obstacle\" : \"free\"}` : `${t50}:z${e4.availableZ[0]}`, center: a3.center, width: a3.width, height: a3.height, layer: `z${e4.availableZ.join(\",\")}`, availableZ: e4.availableZ, _qfpRegionType: i3, _isNarrowQfpPadGap: r3, _containsObstacle: e4.containsObstacle }));\n })({ nodeId: `qfp_thermalpad:${u2}:${t49.key}`, bounds: t49.bounds, availableZ: i2, multiLayerThreshold: g2, regionType: t49.regionType, isNarrowPadGap: t49.isNarrowPadGap, obstacleZ: t49.obstacleZ }));\n this.output = { routingRegions: _2 }, this.stats = { componentId: o2, layerCount: t48, viaDiameter: p2, obstacleMargin: m2, multiLayerThreshold: g2, narrowPadGapThreshold: f2, thermalPadCount: c2.length, perimeterPadCount: a2.length, innerCornerRectCount: _2.filter((t49) =\u003e t49.capacityMeshNodeId.includes(\":inner-corner-\")).length, narrowPadGapNodeCount: _2.filter((t49) =\u003e t49._isNarrowQfpPadGap).length, topPadCount: l2.top.length, rightPadCount: l2.right.length, bottomPadCount: l2.bottom.length, leftPadCount: l2.left.length, multiLayerNodeCount: _2.filter((t49) =\u003e t49.availableZ.length \u003e 1).length, totalMeshNodeCount: _2.length }, this.solved = true;\n }\n getOutput() {\n if (!this.output) throw new Error(\"QfpThermalPadTopologyGeneratorSolver has not solved yet\");\n return this.output;\n }\n});\nvar vV = 1e-6;\nfunction SV(t48) {\n return t48.maxX - t48.minX \u003e vV \u0026\u0026 t48.maxY - t48.minY \u003e vV;\n}\nfunction IV(t48, e2) {\n const n2 = [{ side: \"top\", distance: Math.abs(t48.center.y - e2.minY) }, { side: \"right\", distance: Math.abs(e2.maxX - t48.center.x) }, { side: \"bottom\", distance: Math.abs(e2.maxY - t48.center.y) }, { side: \"left\", distance: Math.abs(t48.center.x - e2.minX) }];\n return n2.sort((t49, e3) =\u003e t49.distance - e3.distance), n2[0].side;\n}\nfunction PV(t48, e2) {\n return t48.map((t49, n2) =\u003e ({ key: `pad:${t49.obstacleId ?? n2}`, bounds: Me(t49), regionType: \"pad\", obstacleZ: aV(t49, e2), connectedTo: [...t49.connectedTo] }));\n}\nfunction MV(t48, e2) {\n return !!SV(t48) \u0026\u0026 Math.min(t48.maxX - t48.minX, t48.maxY - t48.minY) \u003c= e2;\n}\nfunction CV({ side: t48, sideObstacles: e2, bounds: n2, centralBounds: o2, narrowThreshold: i2 }) {\n const r2 = [];\n for (let s2 = 0; s2 \u003c e2.length - 1; s2++) {\n const a2 = Me(e2[s2]), c2 = Me(e2[s2 + 1]);\n let l2;\n l2 = \"top\" === t48 ? { minX: a2.maxX, maxX: c2.minX, minY: n2.minY, maxY: o2.minY } : \"right\" === t48 ? { minX: o2.maxX, maxX: n2.maxX, minY: a2.maxY, maxY: c2.minY } : \"bottom\" === t48 ? { minX: a2.maxX, maxX: c2.minX, minY: o2.maxY, maxY: n2.maxY } : { minX: n2.minX, maxX: o2.minX, minY: a2.maxY, maxY: c2.minY }, r2.push({ key: `${t48}-gap-${s2}`, bounds: l2, regionType: \"pad-gap\", isNarrowPadGap: MV(l2, i2) });\n }\n return r2;\n}\nfunction NV({ bounds: t48, centralBounds: e2, sideGroups: n2 }) {\n const o2 = n2.top[0] ? Me(n2.top[0]) : null, i2 = n2.top.at(-1) ? Me(n2.top.at(-1)) : null, r2 = n2.right[0] ? Me(n2.right[0]) : null, s2 = n2.right.at(-1) ? Me(n2.right.at(-1)) : null, a2 = n2.bottom[0] ? Me(n2.bottom[0]) : null, c2 = n2.bottom.at(-1) ? Me(n2.bottom.at(-1)) : null, l2 = n2.left[0] ? Me(n2.left[0]) : null, h2 = n2.left.at(-1) ? Me(n2.left.at(-1)) : null;\n return [{ key: \"corner-nw-outer\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: \"corner-nw-top\", regionType: \"corner\", bounds: { minX: e2.minX, maxX: o2?.minX ?? e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: \"corner-nw-left\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.minY, maxY: l2?.minY ?? e2.minY } }, { key: \"corner-ne-outer\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: t48.minY, maxY: e2.minY } }, { key: \"corner-ne-top\", regionType: \"corner\", bounds: { minX: i2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: t48.minY, maxY: e2.minY } }, { key: \"corner-ne-right\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.minY, maxY: r2?.minY ?? e2.minY } }, { key: \"corner-se-outer\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"corner-se-right\", regionType: \"corner\", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: s2?.maxY ?? e2.maxY, maxY: e2.maxY } }, { key: \"corner-se-bottom\", regionType: \"corner\", bounds: { minX: c2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"corner-sw-outer\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"corner-sw-bottom\", regionType: \"corner\", bounds: { minX: e2.minX, maxX: a2?.minX ?? e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: \"corner-sw-left\", regionType: \"corner\", bounds: { minX: t48.minX, maxX: e2.minX, minY: h2?.maxY ?? e2.maxY, maxY: e2.maxY } }];\n}\nxW.register(class extends wt {\n constructor(t48) {\n super(), this.inputProblem = t48;\n }\n inputProblem;\n static componentKind = \"qfp\";\n output = null;\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n if (this.output) return void (this.solved = true);\n const { layerCount: t48, obstacles: e2 } = this.inputProblem.inputSrj, { bounds: n2, componentId: o2 } = this.inputProblem.detectedComponent, i2 = lV(t48), r2 = e2.filter((t49) =\u003e t49.componentId === o2), s2 = r2.length \u003e 0 ? r2 : e2, a2 = (function(t49, e3) {\n const n3 = { top: [], right: [], bottom: [], left: [] };\n for (const o3 of t49) n3[IV(o3, e3)].push(o3);\n return n3.top.sort((t50, e4) =\u003e t50.center.x - e4.center.x), n3.bottom.sort((t50, e4) =\u003e t50.center.x - e4.center.x), n3.left.sort((t50, e4) =\u003e t50.center.y - e4.center.y), n3.right.sort((t50, e4) =\u003e t50.center.y - e4.center.y), n3;\n })(s2, n2), c2 = (function({ bounds: t49, sideGroups: e3 }) {\n return { minX: e3.left.length \u003e 0 ? Math.max(...e3.left.map((t50) =\u003e Me(t50).maxX)) : t49.minX, maxX: e3.right.length \u003e 0 ? Math.min(...e3.right.map((t50) =\u003e Me(t50).minX)) : t49.maxX, minY: e3.top.length \u003e 0 ? Math.max(...e3.top.map((t50) =\u003e Me(t50).maxY)) : t49.minY, maxY: e3.bottom.length \u003e 0 ? Math.min(...e3.bottom.map((t50) =\u003e Me(t50).minY)) : t49.maxY };\n })({ bounds: n2, sideGroups: a2 }), l2 = o2, h2 = this.inputProblem.viaDiameter ?? Do(this.inputProblem.inputSrj).padDiameter, d2 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, u2 = h2 + 2 * d2, p2 = this.inputProblem.inputSrj.minTraceWidth + 2 * d2, m2 = [{ key: \"center\", bounds: c2, regionType: \"center\" }, ...PV(s2, t48), ...CV({ side: \"top\", sideObstacles: a2.top, bounds: n2, centralBounds: c2, narrowThreshold: p2 }), ...CV({ side: \"right\", sideObstacles: a2.right, bounds: n2, centralBounds: c2, narrowThreshold: p2 }), ...CV({ side: \"bottom\", sideObstacles: a2.bottom, bounds: n2, centralBounds: c2, narrowThreshold: p2 }), ...CV({ side: \"left\", sideObstacles: a2.left, bounds: n2, centralBounds: c2, narrowThreshold: p2 }), ...NV({ bounds: n2, centralBounds: c2, sideGroups: a2 })].flatMap((t49) =\u003e (function({ nodeId: t50, bounds: e3, availableZ: n3, multiLayerThreshold: o3, regionType: i3, isNarrowPadGap: r3 = false, obstacleZ: s3 = [], connectedTo: a3 }) {\n if (!SV(e3)) return [];\n const c3 = (function(t51) {\n return { center: { x: (t51.minX + t51.maxX) / 2, y: (t51.minY + t51.maxY) / 2 }, width: t51.maxX - t51.minX, height: t51.maxY - t51.minY };\n })(e3), l3 = Math.min(c3.width, c3.height) \u003e o3, h3 = l3 ? [{ availableZ: n3.filter((t51) =\u003e !s3.includes(t51)), containsObstacle: false }, { availableZ: n3.filter((t51) =\u003e s3.includes(t51)), containsObstacle: true }].filter((t51) =\u003e t51.availableZ.length \u003e 0) : n3.map((t51) =\u003e ({ availableZ: [t51], containsObstacle: s3.includes(t51) }));\n return h3.map((e4) =\u003e ({ capacityMeshNodeId: 1 === h3.length ? t50 : l3 ? `${t50}:${e4.containsObstacle ? \"obstacle\" : \"free\"}` : `${t50}:z${e4.availableZ[0]}`, center: c3.center, width: c3.width, height: c3.height, layer: `z${e4.availableZ.join(\",\")}`, availableZ: e4.availableZ, _qfpRegionType: i3, _isNarrowQfpPadGap: r3, _containsObstacle: e4.containsObstacle, _connectedTo: e4.containsObstacle ? a3 : void 0 }));\n })({ nodeId: `qfp:${l2}:${t49.key}`, bounds: t49.bounds, availableZ: i2, multiLayerThreshold: u2, regionType: t49.regionType, isNarrowPadGap: t49.isNarrowPadGap, obstacleZ: t49.obstacleZ, connectedTo: t49.connectedTo }));\n this.output = { routingRegions: m2 }, this.stats = { componentId: o2, layerCount: t48, viaDiameter: h2, obstacleMargin: d2, multiLayerThreshold: u2, narrowPadGapThreshold: p2, narrowPadGapNodeCount: m2.filter((t49) =\u003e t49._isNarrowQfpPadGap).length, topPadCount: a2.top.length, rightPadCount: a2.right.length, bottomPadCount: a2.bottom.length, leftPadCount: a2.left.length, multiLayerNodeCount: m2.filter((t49) =\u003e t49.availableZ.length \u003e 1).length, totalMeshNodeCount: m2.length }, this.solved = true;\n }\n getOutput() {\n if (!this.output) throw new Error(\"QfpTopologyGeneratorSolver has not solved yet\");\n return this.output;\n }\n});\nvar wV = 1e-6;\nfunction TV({ nodeId: t48, bounds: e2, availableZ: n2, multiLayerThreshold: o2, regionType: i2, obstacleZ: r2 = [], connectedTo: s2 }) {\n if (!(function(t49) {\n return t49.maxX - t49.minX \u003e wV \u0026\u0026 t49.maxY - t49.minY \u003e wV;\n })(e2)) return [];\n const a2 = (function(t49) {\n return { center: { x: (t49.minX + t49.maxX) / 2, y: (t49.minY + t49.maxY) / 2 }, width: t49.maxX - t49.minX, height: t49.maxY - t49.minY };\n })(e2), c2 = Math.min(a2.width, a2.height) \u003e o2, l2 = c2 ? [{ availableZ: n2.filter((t49) =\u003e !r2.includes(t49)), containsObstacle: false }, { availableZ: n2.filter((t49) =\u003e r2.includes(t49)), containsObstacle: true }].filter((t49) =\u003e t49.availableZ.length \u003e 0) : n2.map((t49) =\u003e ({ availableZ: [t49], containsObstacle: r2.includes(t49) }));\n return l2.map((e3) =\u003e ({ capacityMeshNodeId: 1 === l2.length ? t48 : c2 ? `${t48}:${e3.containsObstacle ? \"obstacle\" : \"free\"}` : `${t48}:z${e3.availableZ[0]}`, center: a2.center, width: a2.width, height: a2.height, layer: `z${e3.availableZ.join(\",\")}`, availableZ: e3.availableZ, _soicRegionType: i2, _containsObstacle: e3.containsObstacle, _connectedTo: e3.containsObstacle ? s2 : void 0 }));\n}\nfunction RV(t48, e2) {\n let n2 = 0, o2 = Number.POSITIVE_INFINITY;\n for (let i2 = 0; i2 \u003c e2.length; i2++) {\n const r2 = Math.abs(t48 - e2[i2]);\n r2 \u003c o2 \u0026\u0026 (n2 = i2, o2 = r2);\n }\n return n2;\n}\nfunction EV(t48, e2) {\n return t48.map((t49, n2) =\u003e ({ key: `pad:${t49.obstacleId ?? n2}`, bounds: Me(t49), regionType: \"pad\", obstacleZ: aV(t49, e2), connectedTo: [...t49.connectedTo] }));\n}\nxW.register(class extends wt {\n constructor(t48) {\n super(), this.inputProblem = t48;\n }\n inputProblem;\n static componentKind = \"soic\";\n output = null;\n getConstructorParams() {\n return [this.inputProblem];\n }\n _step() {\n if (this.output) return void (this.solved = true);\n const { layerCount: t48, obstacles: e2 } = this.inputProblem.inputSrj, { bounds: n2, componentId: o2 } = this.inputProblem.detectedComponent, i2 = lV(t48), r2 = e2.filter((t49) =\u003e t49.componentId === o2), s2 = r2.length \u003e 0 ? r2 : e2, a2 = (function(t49) {\n const e3 = cV(t49.map((t50) =\u003e t50.center.y)).length;\n return 2 === cV(t49.map((t50) =\u003e t50.center.x)).length \u0026\u0026 2 !== e3 ? \"vertical-columns\" : \"horizontal-rows\";\n })(s2), c2 = (function({ obstacles: t49, orientation: e3 }) {\n const n3 = { left: [], right: [], top: [], bottom: [] };\n if (\"vertical-columns\" === e3) {\n const e4 = cV(t49.map((t50) =\u003e t50.center.x));\n for (const o4 of t49) n3[0 === RV(o4.center.x, e4) ? \"left\" : \"right\"].push(o4);\n return n3.left.sort((t50, e5) =\u003e t50.center.y - e5.center.y), n3.right.sort((t50, e5) =\u003e t50.center.y - e5.center.y), n3;\n }\n const o3 = cV(t49.map((t50) =\u003e t50.center.y));\n for (const e4 of t49) n3[0 === RV(e4.center.y, o3) ? \"top\" : \"bottom\"].push(e4);\n return n3.top.sort((t50, e4) =\u003e t50.center.x - e4.center.x), n3.bottom.sort((t50, e4) =\u003e t50.center.x - e4.center.x), n3;\n })({ obstacles: s2, orientation: a2 }), l2 = (function({ bounds: t49, orientation: e3, sideGroups: n3 }) {\n return \"vertical-columns\" === e3 ? { minX: Math.max(...n3.left.map((t50) =\u003e Me(t50).maxX)), maxX: Math.min(...n3.right.map((t50) =\u003e Me(t50).minX)), minY: t49.minY, maxY: t49.maxY } : { minX: t49.minX, maxX: t49.maxX, minY: Math.max(...n3.top.map((t50) =\u003e Me(t50).maxY)), maxY: Math.min(...n3.bottom.map((t50) =\u003e Me(t50).minY)) };\n })({ bounds: n2, orientation: a2, sideGroups: c2 }), h2 = o2, d2 = this.inputProblem.viaDiameter ?? Do(this.inputProblem.inputSrj).padDiameter, u2 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, p2 = 2 * (d2 + u2), m2 = \"vertical-columns\" === a2 ? [\"left\", \"right\"] : [\"top\", \"bottom\"], g2 = [{ key: \"center\", bounds: l2, regionType: \"center\" }, ...EV(s2, t48), ...m2.flatMap((t49) =\u003e (function({ side: t50, sideObstacles: e3, bounds: n3, centralBounds: o3 }) {\n const i3 = [];\n for (let r3 = 0; r3 \u003c e3.length - 1; r3++) {\n const s3 = Me(e3[r3]), a3 = Me(e3[r3 + 1]);\n let c3;\n c3 = \"left\" === t50 ? { minX: n3.minX, maxX: o3.minX, minY: s3.maxY, maxY: a3.minY } : \"right\" === t50 ? { minX: o3.maxX, maxX: n3.maxX, minY: s3.maxY, maxY: a3.minY } : \"top\" === t50 ? { minX: s3.maxX, maxX: a3.minX, minY: n3.minY, maxY: o3.minY } : { minX: s3.maxX, maxX: a3.minX, minY: o3.maxY, maxY: n3.maxY }, i3.push({ key: `${t50}-gap-${r3}`, bounds: c3, regionType: \"pad-gap\" });\n }\n return i3;\n })({ side: t49, sideObstacles: c2[t49], bounds: n2, centralBounds: l2 }))], f2 = g2.flatMap((t49) =\u003e TV({ nodeId: `soic:${h2}:${t49.key}`, bounds: t49.bounds, availableZ: i2, multiLayerThreshold: p2, regionType: t49.regionType, obstacleZ: t49.obstacleZ, connectedTo: t49.connectedTo }));\n this.output = { routingRegions: f2 }, this.stats = { componentId: o2, layerCount: t48, orientation: a2, viaDiameter: d2, obstacleMargin: u2, multiLayerThreshold: p2, firstSidePadCount: c2[m2[0]].length, secondSidePadCount: c2[m2[1]].length, multiLayerNodeCount: f2.filter((t49) =\u003e t49.availableZ.length \u003e 1).length, totalMeshNodeCount: f2.length }, this.solved = true;\n }\n getOutput() {\n if (!this.output) throw new Error(\"SoicTopologyGeneratorSolver has not solved yet\");\n return this.output;\n }\n});\n\n// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/node_modules/graphics-debug/dist/chunk-ZJJUR6DP.js\nvar import_svgson2 = __toESM(require_svgson_umd(), 1);\n\n// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/prepare-buses.ts\nvar FANOUT_BORDER_TARGETS = /* @__PURE__ */ new Set([\n \"left\",\n \"right\",\n \"top\",\n \"bottom\",\n \"top-left\",\n \"top-right\",\n \"bottom-left\",\n \"bottom-right\"\n]);\nvar FANOUT_EDGES = /* @__PURE__ */ new Set([\"left\", \"right\", \"top\", \"bottom\"]);\nvar AVAILABLE_BOUNDARY_REGIONS = {\n top_left: {\n direction: \"up\",\n preferredExit: \"top-left\",\n exitEdge: \"top\"\n },\n top_middle: {\n direction: \"up\",\n preferredExit: \"top\",\n exitEdge: \"top\"\n },\n top_right: {\n direction: \"up\",\n preferredExit: \"top-right\",\n exitEdge: \"top\"\n },\n right_top: {\n direction: \"right\",\n preferredExit: \"top-right\",\n exitEdge: \"right\"\n },\n right_middle: {\n direction: \"right\",\n preferredExit: \"right\",\n exitEdge: \"right\"\n },\n right_bottom: {\n direction: \"right\",\n preferredExit: \"bottom-right\",\n exitEdge: \"right\"\n },\n bottom_right: {\n direction: \"down\",\n preferredExit: \"bottom-right\",\n exitEdge: \"bottom\"\n },\n bottom_middle: {\n direction: \"down\",\n preferredExit: \"bottom\",\n exitEdge: \"bottom\"\n },\n bottom_left: {\n direction: \"down\",\n preferredExit: \"bottom-left\",\n exitEdge: \"bottom\"\n },\n left_bottom: {\n direction: \"left\",\n preferredExit: \"bottom-left\",\n exitEdge: \"left\"\n },\n left_middle: {\n direction: \"left\",\n preferredExit: \"left\",\n exitEdge: \"left\"\n },\n left_top: {\n direction: \"left\",\n preferredExit: \"top-left\",\n exitEdge: \"left\"\n },\n top: {\n direction: \"up\",\n preferredExit: \"top\",\n exitEdge: \"top\"\n },\n right: {\n direction: \"right\",\n preferredExit: \"right\",\n exitEdge: \"right\"\n },\n bottom: {\n direction: \"down\",\n preferredExit: \"bottom\",\n exitEdge: \"bottom\"\n },\n left: {\n direction: \"left\",\n preferredExit: \"left\",\n exitEdge: \"left\"\n }\n};\nfunction uniqueSorted(values) {\n const sortedValues = [...values].sort((a2, b2) =\u003e a2 - b2);\n const result = [];\n for (const value of sortedValues) {\n if (result.length === 0 || Math.abs(result[result.length - 1] - value) \u003e 1e-6) {\n result.push(value);\n }\n }\n return result;\n}\nfunction getPitch(coordinates) {\n let pitch = Number.POSITIVE_INFINITY;\n for (let index2 = 1; index2 \u003c coordinates.length; index2++) {\n const difference = coordinates[index2] - coordinates[index2 - 1];\n if (difference \u003e 1e-6) pitch = Math.min(pitch, difference);\n }\n return pitch;\n}\nfunction getAlignedPitch(obstacles, axis) {\n const perpendicularAxis = axis === \"x\" ? \"y\" : \"x\";\n let pitch = Number.POSITIVE_INFINITY;\n for (let firstIndex = 0; firstIndex \u003c obstacles.length; firstIndex++) {\n const first = obstacles[firstIndex];\n for (let secondIndex = firstIndex + 1; secondIndex \u003c obstacles.length; secondIndex++) {\n const second = obstacles[secondIndex];\n if (Math.abs(\n first.center[perpendicularAxis] - second.center[perpendicularAxis]\n ) \u003e 1e-6) {\n continue;\n }\n const separation = Math.abs(first.center[axis] - second.center[axis]);\n if (separation \u003e 1e-6) pitch = Math.min(pitch, separation);\n }\n }\n return pitch;\n}\nfunction getComponentBounds(obstacles) {\n return {\n minX: Math.min(\n ...obstacles.map((obstacle) =\u003e obstacle.center.x - obstacle.width / 2)\n ),\n maxX: Math.max(\n ...obstacles.map((obstacle) =\u003e obstacle.center.x + obstacle.width / 2)\n ),\n minY: Math.min(\n ...obstacles.map((obstacle) =\u003e obstacle.center.y - obstacle.height / 2)\n ),\n maxY: Math.max(\n ...obstacles.map((obstacle) =\u003e obstacle.center.y + obstacle.height / 2)\n )\n };\n}\nfunction resolveComponentBounds(grid, options) {\n const requestedBounds = options.componentBounds?.[grid.componentId];\n if (!requestedBounds) {\n const inferredMarginX = grid.pitchX * 2.25;\n const inferredMarginY = grid.pitchY * 2.25;\n return {\n minX: grid.bounds.minX - inferredMarginX,\n maxX: grid.bounds.maxX + inferredMarginX,\n minY: grid.bounds.minY - inferredMarginY,\n maxY: grid.bounds.maxY + inferredMarginY\n };\n }\n const values = [\n requestedBounds.minX,\n requestedBounds.maxX,\n requestedBounds.minY,\n requestedBounds.maxY\n ];\n if (values.some((value) =\u003e !Number.isFinite(value)) || requestedBounds.minX \u003e= requestedBounds.maxX || requestedBounds.minY \u003e= requestedBounds.maxY) {\n throw new Error(\n `FanoutSolver: componentBounds for \"${grid.componentId}\" must contain finite, increasing bounds`\n );\n }\n if (requestedBounds.minX \u003e grid.bounds.minX + 1e-6 || requestedBounds.maxX \u003c grid.bounds.maxX - 1e-6 || requestedBounds.minY \u003e grid.bounds.minY + 1e-6 || requestedBounds.maxY \u003c grid.bounds.maxY - 1e-6) {\n throw new Error(\n `FanoutSolver: componentBounds for \"${grid.componentId}\" must contain every component pad`\n );\n }\n return { ...requestedBounds };\n}\nfunction validateSharedBoundary(boundary, componentGrids) {\n const values = [boundary.minX, boundary.maxX, boundary.minY, boundary.maxY];\n if (values.some((value) =\u003e !Number.isFinite(value)) || boundary.minX \u003e= boundary.maxX || boundary.minY \u003e= boundary.maxY) {\n throw new Error(\n \"FanoutSolver: sharedBoundary must contain finite, increasing bounds\"\n );\n }\n for (const grid of componentGrids) {\n if (boundary.minX \u003e grid.bounds.minX + 1e-6 || boundary.maxX \u003c grid.bounds.maxX - 1e-6 || boundary.minY \u003e grid.bounds.minY + 1e-6 || boundary.maxY \u003c grid.bounds.maxY - 1e-6) {\n throw new Error(\n `FanoutSolver: sharedBoundary must contain every pad of component \"${grid.componentId}\"`\n );\n }\n }\n return { ...boundary };\n}\nfunction resolveSharedBoundary(componentGrids, options) {\n if (options.sharedBoundary) {\n return validateSharedBoundary(options.sharedBoundary, componentGrids);\n }\n const componentBounds = componentGrids.map(\n (grid) =\u003e resolveComponentBounds(grid, options)\n );\n const maximumPitch = Math.max(\n ...componentGrids.flatMap((grid) =\u003e [grid.pitchX, grid.pitchY])\n );\n const inferredMargin = maximumPitch * 2.25;\n return validateSharedBoundary(\n {\n minX: Math.min(...componentBounds.map((bounds) =\u003e bounds.minX)) - inferredMargin,\n maxX: Math.max(...componentBounds.map((bounds) =\u003e bounds.maxX)) + inferredMargin,\n minY: Math.min(...componentBounds.map((bounds) =\u003e bounds.minY)) - inferredMargin,\n maxY: Math.max(...componentBounds.map((bounds) =\u003e bounds.maxY)) + inferredMargin\n },\n componentGrids\n );\n}\nfunction findComponentGrids(obstacles) {\n const obstaclesByComponent = /* @__PURE__ */ new Map();\n for (const obstacle of obstacles) {\n if (!obstacle.componentId || obstacle.isCopperPour) continue;\n const componentObstacles = obstaclesByComponent.get(obstacle.componentId) ?? [];\n componentObstacles.push(obstacle);\n obstaclesByComponent.set(obstacle.componentId, componentObstacles);\n }\n const grids = [];\n for (const [componentId, componentObstacles] of obstaclesByComponent) {\n const xCoordinates = uniqueSorted(\n componentObstacles.map((obstacle) =\u003e obstacle.center.x)\n );\n const yCoordinates = uniqueSorted(\n componentObstacles.map((obstacle) =\u003e obstacle.center.y)\n );\n const alignedPitchX = getAlignedPitch(componentObstacles, \"x\");\n const alignedPitchY = getAlignedPitch(componentObstacles, \"y\");\n const coordinatePitchX = getPitch(xCoordinates);\n const coordinatePitchY = getPitch(yCoordinates);\n const fallbackPitch = Math.min(\n ...[\n alignedPitchX,\n alignedPitchY,\n coordinatePitchX,\n coordinatePitchY\n ].filter(Number.isFinite)\n );\n const padSizeFallback = Math.max(\n ...componentObstacles.flatMap((obstacle) =\u003e [\n obstacle.width,\n obstacle.height\n ])\n );\n const resolvedFallback = Number.isFinite(fallbackPitch) ? fallbackPitch : padSizeFallback;\n const pitchX = Number.isFinite(alignedPitchX) ? alignedPitchX : Number.isFinite(coordinatePitchX) ? coordinatePitchX : resolvedFallback;\n const pitchY = Number.isFinite(alignedPitchY) ? alignedPitchY : Number.isFinite(coordinatePitchY) ? coordinatePitchY : resolvedFallback;\n grids.push({\n componentId,\n obstacles: componentObstacles,\n xCoordinates,\n yCoordinates,\n pitchX,\n pitchY,\n bounds: getComponentBounds(componentObstacles)\n });\n }\n return grids;\n}\nfunction getPointLayers(point) {\n return \"layer\" in point ? [point.layer] : point.layers;\n}\nfunction findPointObstacleMatches(params) {\n const { point, connection, componentGrids } = params;\n const pointLayers = getPointLayers(point);\n const matches = [];\n for (const grid of componentGrids) {\n const candidateObstacles = grid.obstacles.filter(\n (obstacle) =\u003e obstacle.layers.some((layer) =\u003e pointLayers.includes(layer))\n ).filter((obstacle) =\u003e pointIsInsideObstacle(point, obstacle, 1e-5)).sort((a2, b2) =\u003e {\n const aDirect = a2.connectedTo.includes(connection.name) || a2.connectedTo.includes(point.pointId ?? \"\") || a2.connectedTo.includes(point.pcb_port_id ?? \"\");\n const bDirect = b2.connectedTo.includes(connection.name) || b2.connectedTo.includes(point.pointId ?? \"\") || b2.connectedTo.includes(point.pcb_port_id ?? \"\");\n if (aDirect !== bDirect) return aDirect ? -1 : 1;\n return a2.width * a2.height - b2.width * b2.height;\n });\n if (candidateObstacles[0]) {\n matches.push({ grid, obstacle: candidateObstacles[0] });\n }\n }\n return matches;\n}\nfunction inferBusId(connection) {\n for (const point of connection.pointsToConnect) {\n if (\"layers\" in point \u0026\u0026 point.busId) return point.busId;\n }\n const nameMatch = /^BUS[_:-]([^_:-]+)(?:[_:-]\\d+)?$/i.exec(connection.name);\n return nameMatch?.[1] ?? null;\n}\nfunction resolvePreferredExit(busId, value) {\n if (value === void 0) return void 0;\n if (!FANOUT_BORDER_TARGETS.has(value)) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" has invalid preferredExit \"${value}\"`\n );\n }\n return value;\n}\nfunction resolveExitEdge(busId, value) {\n if (value === void 0) return void 0;\n if (!FANOUT_EDGES.has(value)) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" has invalid exitEdge \"${value}\"`\n );\n }\n return value;\n}\nfunction resolveExitPosition(busId, value) {\n if (value === void 0) return void 0;\n try {\n return getFanoutExitPositionConfig(value);\n } catch {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" has invalid exitPosition \"${value}\"`\n );\n }\n}\nfunction assertExitPositionFieldMatches(params) {\n const { busId, exitPosition, fieldName, expected, actual, sourceName } = params;\n if (actual === void 0 || actual === expected) return;\n throw new Error(\n `FanoutSolver: bus \"${busId}\" exitPosition \"${exitPosition}\" conflicts with ${sourceName} ${fieldName} \"${actual}\"`\n );\n}\nfunction resolveBusExitFields(params) {\n const { busId, requestedBus, options } = params;\n const exitPosition = requestedBus.exitPosition;\n const exitPositionConfig = resolveExitPosition(busId, exitPosition);\n const busPreferredExit = resolvePreferredExit(\n busId,\n requestedBus.preferredExit\n );\n const optionPreferredExit = resolvePreferredExit(\n busId,\n options.busExitPreferences?.[busId]\n );\n const busExitEdge = resolveExitEdge(busId, requestedBus.exitEdge);\n if (exitPositionConfig \u0026\u0026 exitPosition) {\n for (const [actual, sourceName] of [\n [requestedBus.direction, \"bus\"],\n [options.busDirections?.[busId], \"busDirections\"]\n ]) {\n assertExitPositionFieldMatches({\n busId,\n exitPosition,\n fieldName: \"direction\",\n expected: exitPositionConfig.direction,\n actual,\n sourceName\n });\n }\n for (const [actual, sourceName] of [\n [busPreferredExit, \"bus\"],\n [optionPreferredExit, \"busExitPreferences\"]\n ]) {\n assertExitPositionFieldMatches({\n busId,\n exitPosition,\n fieldName: \"preferredExit\",\n expected: exitPositionConfig.preferredExit,\n actual,\n sourceName\n });\n }\n assertExitPositionFieldMatches({\n busId,\n exitPosition,\n fieldName: \"exitEdge\",\n expected: exitPositionConfig.exitEdge,\n actual: busExitEdge,\n sourceName: \"bus\"\n });\n return {\n exitPosition,\n ...exitPositionConfig.direction ? { direction: exitPositionConfig.direction } : {},\n ...exitPositionConfig.preferredExit ? { preferredExit: exitPositionConfig.preferredExit } : {},\n ...exitPositionConfig.exitEdge ? { exitEdge: exitPositionConfig.exitEdge } : {}\n };\n }\n const direction = options.busDirections?.[busId] ?? requestedBus.direction ?? options.defaultDirection;\n const preferredExit = resolvePreferredExit(\n busId,\n optionPreferredExit ?? busPreferredExit ?? options.defaultPreferredExit\n );\n return {\n ...direction ? { direction } : {},\n ...preferredExit ? { preferredExit } : {},\n ...busExitEdge ? { exitEdge: busExitEdge } : {}\n };\n}\nfunction resolveAllowedLayers(busId, allowedLayers) {\n if (allowedLayers === void 0) return void 0;\n if (allowedLayers.length === 0) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" must allow at least one layer`\n );\n }\n for (const layer of allowedLayers) {\n if (typeof layer !== \"string\" || layer.length === 0) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" has an invalid allowed layer`\n );\n }\n }\n return [...new Set(allowedLayers)];\n}\nfunction resolveMaxLengthSkew(busId, value) {\n if (value === void 0) return void 0;\n if (!Number.isFinite(value) || value \u003c 0) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" maxLengthSkew must be a finite non-negative number`\n );\n }\n return value;\n}\nfunction resolveAvailableBoundaryRegions(value) {\n if (value === void 0) return void 0;\n if (value.length === 0) {\n throw new Error(\n \"FanoutSolver: availableCornersAndSides must contain at least one boundary region\"\n );\n }\n const regions = [];\n const seen = /* @__PURE__ */ new Set();\n for (const input of value) {\n const region = AVAILABLE_BOUNDARY_REGIONS[input];\n if (!region) {\n throw new Error(\n `FanoutSolver: invalid availableCornersAndSides value \"${input}\"`\n );\n }\n const key = `${region.exitEdge}:${region.direction}:${region.preferredExit}`;\n if (seen.has(key)) continue;\n seen.add(key);\n regions.push(region);\n }\n return regions;\n}\nfunction resolveTermination(busId, value) {\n if (value === void 0 || value.type === \"boundary\") {\n return { type: \"boundary\" };\n }\n if (value.type !== \"plane\" || typeof value.layer !== \"string\" || value.layer.length === 0) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" has an invalid termination target`\n );\n }\n return { type: \"plane\", layer: value.layer };\n}\nfunction resolveBusSpecs(srj, options) {\n const requestedBuses = options.buses ?? srj.buses;\n const specsById = /* @__PURE__ */ new Map();\n const claimedConnectionNames = /* @__PURE__ */ new Set();\n const knownConnectionNames = new Set(\n srj.connections.map((connection) =\u003e connection.name)\n );\n for (const requestedBus of requestedBuses ?? []) {\n if (specsById.has(requestedBus.busId)) {\n throw new Error(`FanoutSolver: duplicate bus id \"${requestedBus.busId}\"`);\n }\n for (const connectionName of requestedBus.connectionNames) {\n if (!knownConnectionNames.has(connectionName)) {\n throw new Error(\n `FanoutSolver: bus \"${requestedBus.busId}\" references unknown connection \"${connectionName}\"`\n );\n }\n if (claimedConnectionNames.has(connectionName)) {\n throw new Error(\n `FanoutSolver: connection \"${connectionName}\" belongs to more than one bus`\n );\n }\n claimedConnectionNames.add(connectionName);\n }\n const termination = resolveTermination(\n requestedBus.busId,\n requestedBus.termination\n );\n const resolvedExitFields = resolveBusExitFields({\n busId: requestedBus.busId,\n requestedBus,\n options\n });\n const allowedLayers = resolveAllowedLayers(\n requestedBus.busId,\n requestedBus.allowedLayers\n );\n const maxLengthSkew = resolveMaxLengthSkew(\n requestedBus.busId,\n requestedBus.maxLengthSkew\n );\n if (termination.type === \"plane\" \u0026\u0026 maxLengthSkew !== void 0) {\n throw new Error(\n `FanoutSolver: plane-terminated bus \"${requestedBus.busId}\" cannot specify maxLengthSkew`\n );\n }\n if (termination.type === \"plane\" \u0026\u0026 resolvedExitFields.preferredExit !== void 0) {\n throw new Error(\n `FanoutSolver: plane-terminated bus \"${requestedBus.busId}\" cannot also specify preferredExit`\n );\n }\n specsById.set(requestedBus.busId, {\n ...requestedBus,\n sourceComponentId: requestedBus.sourceComponentId ?? options.sourceComponentId,\n ...resolvedExitFields,\n ...allowedLayers === void 0 ? {} : { allowedLayers },\n ...maxLengthSkew === void 0 ? {} : { maxLengthSkew },\n termination\n });\n }\n for (const connection of srj.connections) {\n if (claimedConnectionNames.has(connection.name)) continue;\n const inferredBusId = inferBusId(connection);\n if (inferredBusId) {\n const existing = specsById.get(inferredBusId);\n if (existing) {\n specsById.set(inferredBusId, {\n ...existing,\n connectionNames: [...existing.connectionNames, connection.name]\n });\n } else {\n specsById.set(inferredBusId, {\n busId: inferredBusId,\n connectionNames: [connection.name],\n direction: options.busDirections?.[inferredBusId] ?? options.defaultDirection,\n sourceComponentId: options.sourceComponentId,\n preferredExit: resolvePreferredExit(\n inferredBusId,\n options.busExitPreferences?.[inferredBusId] ?? options.defaultPreferredExit\n ),\n termination: { type: \"boundary\" }\n });\n }\n } else {\n const singletonBusId = `connection:${connection.name}`;\n specsById.set(singletonBusId, {\n busId: singletonBusId,\n connectionNames: [connection.name],\n sourceComponentId: options.sourceComponentId,\n direction: options.busDirections?.[singletonBusId] ?? options.defaultDirection,\n preferredExit: resolvePreferredExit(\n singletonBusId,\n options.busExitPreferences?.[singletonBusId] ?? options.defaultPreferredExit\n ),\n termination: { type: \"boundary\" }\n });\n }\n }\n return [...specsById.values()];\n}\nfunction chooseSourceGrid(params) {\n const { busSpec, connections, componentGrids } = params;\n const matchCountByComponent = /* @__PURE__ */ new Map();\n for (const connection of connections) {\n const matchedComponents = /* @__PURE__ */ new Set();\n for (const point of connection.pointsToConnect) {\n for (const match of findPointObstacleMatches({\n point,\n connection,\n componentGrids\n })) {\n matchedComponents.add(match.grid.componentId);\n }\n }\n for (const componentId of matchedComponents) {\n matchCountByComponent.set(\n componentId,\n (matchCountByComponent.get(componentId) ?? 0) + 1\n );\n }\n }\n const selectedGrid = [...componentGrids].sort((a2, b2) =\u003e {\n const countDifference = (matchCountByComponent.get(b2.componentId) ?? 0) - (matchCountByComponent.get(a2.componentId) ?? 0);\n if (countDifference !== 0) return countDifference;\n return b2.obstacles.length - a2.obstacles.length;\n })[0];\n const requestedGrid = busSpec.sourceComponentId ? componentGrids.find(\n (grid) =\u003e grid.componentId === busSpec.sourceComponentId\n ) : void 0;\n if (busSpec.sourceComponentId \u0026\u0026 !requestedGrid) {\n throw new Error(\n `FanoutSolver: source component \"${busSpec.sourceComponentId}\" for bus \"${busSpec.busId}\" was not found`\n );\n }\n const sourceGrid = requestedGrid ?? selectedGrid;\n const sourceMatchCount = sourceGrid ? matchCountByComponent.get(sourceGrid.componentId) ?? 0 : 0;\n if (!sourceGrid || sourceMatchCount !== connections.length) {\n throw new Error(\n busSpec.sourceComponentId ? `FanoutSolver: source component \"${busSpec.sourceComponentId}\" is not an endpoint on every connection in bus \"${busSpec.busId}\"` : `FanoutSolver: bus \"${busSpec.busId}\" does not have one component endpoint on every connection`\n );\n }\n return sourceGrid;\n}\nfunction chooseTargetPoint(sourcePoint, connection, sourcePointIndex, termination) {\n const targetCandidates = connection.pointsToConnect.filter(\n (_2, pointIndex) =\u003e pointIndex !== sourcePointIndex\n );\n const targetPoint = targetCandidates.sort(\n (a2, b2) =\u003e distance3(sourcePoint, b2) - distance3(sourcePoint, a2)\n )[0];\n if (!targetPoint \u0026\u0026 termination.type === \"plane\") {\n return sourcePoint;\n }\n if (!targetPoint) {\n throw new Error(\n `FanoutSolver: connection \"${connection.name}\" has no target beyond its BGA pad`\n );\n }\n return targetPoint;\n}\nfunction prepareConnection(params) {\n const {\n connection,\n connectionIndex,\n sourceGrid,\n componentGrids,\n termination,\n exitTargetPoint\n } = params;\n for (let sourcePointIndex = 0; sourcePointIndex \u003c connection.pointsToConnect.length; sourcePointIndex++) {\n const sourcePoint = connection.pointsToConnect[sourcePointIndex];\n const sourceMatch = findPointObstacleMatches({\n point: sourcePoint,\n connection,\n componentGrids\n }).find((match) =\u003e match.grid.componentId === sourceGrid.componentId);\n if (!sourceMatch) continue;\n const sourceLayer = getPointLayers(sourcePoint).find(\n (layer) =\u003e sourceMatch.obstacle.layers.includes(layer)\n );\n if (!sourceLayer) {\n throw new Error(\n `FanoutSolver: connection \"${connection.name}\" has no source layer shared with its BGA pad`\n );\n }\n const targetPoint = chooseTargetPoint(\n sourcePoint,\n connection,\n sourcePointIndex,\n termination\n );\n return {\n connection,\n connectionIndex,\n sourcePoint,\n sourcePointIndex,\n sourceLayer,\n sourceObstacle: sourceMatch.obstacle,\n targetPoint,\n exitTargetPoint: exitTargetPoint ?? {\n x: targetPoint.x,\n y: targetPoint.y\n },\n hasExplicitLayeredExitTarget: exitTargetPoint?.layer !== void 0\n };\n }\n throw new Error(\n `FanoutSolver: connection \"${connection.name}\" does not touch component \"${sourceGrid.componentId}\"`\n );\n}\nfunction inferDirection(busId, connections) {\n let dx2 = 0;\n let dy2 = 0;\n for (const preparedConnection of connections) {\n const exitTargetPoint = preparedConnection.exitTargetPoint ?? preparedConnection.targetPoint;\n dx2 += exitTargetPoint.x - preparedConnection.sourcePoint.x;\n dy2 += exitTargetPoint.y - preparedConnection.sourcePoint.y;\n }\n if (Math.abs(dx2) \u003c 1e-9 \u0026\u0026 Math.abs(dy2) \u003c 1e-9) {\n throw new Error(\n `FanoutSolver: cannot infer an escape direction for bus \"${busId}\"`\n );\n }\n if (Math.abs(dx2) \u003e= Math.abs(dy2)) return dx2 \u003e= 0 ? \"right\" : \"left\";\n return dy2 \u003e= 0 ? \"up\" : \"down\";\n}\nfunction getDirectionsForBorderTarget(target) {\n switch (target) {\n case \"left\":\n return [\"left\"];\n case \"right\":\n return [\"right\"];\n case \"top\":\n return [\"up\"];\n case \"bottom\":\n return [\"down\"];\n case \"top-left\":\n return [\"up\", \"left\"];\n case \"top-right\":\n return [\"up\", \"right\"];\n case \"bottom-left\":\n return [\"down\", \"left\"];\n case \"bottom-right\":\n return [\"down\", \"right\"];\n }\n}\nfunction getAverageSourcePoint(connections) {\n return {\n x: connections.reduce(\n (sum, connection) =\u003e sum + connection.sourcePoint.x,\n 0\n ) / connections.length,\n y: connections.reduce(\n (sum, connection) =\u003e sum + connection.sourcePoint.y,\n 0\n ) / connections.length\n };\n}\nfunction getDistanceToBoundary(source, direction, boundary) {\n switch (direction) {\n case \"left\":\n return source.x - boundary.minX;\n case \"right\":\n return boundary.maxX - source.x;\n case \"up\":\n return boundary.maxY - source.y;\n case \"down\":\n return source.y - boundary.minY;\n }\n}\nfunction getRegionAnchor(region, boundary) {\n if (region.direction === \"up\" || region.direction === \"down\") {\n if (region.preferredExit.endsWith(\"left\")) return boundary.minX;\n if (region.preferredExit.endsWith(\"right\")) return boundary.maxX;\n return (boundary.minX + boundary.maxX) / 2;\n }\n if (region.preferredExit.startsWith(\"top\")) return boundary.maxY;\n if (region.preferredExit.startsWith(\"bottom\")) return boundary.minY;\n return (boundary.minY + boundary.maxY) / 2;\n}\nfunction getRegionSourceCoordinate(source, direction) {\n return direction === \"up\" || direction === \"down\" ? source.x : source.y;\n}\nfunction tryInferDirection(busId, connections) {\n try {\n return inferDirection(busId, connections);\n } catch {\n return void 0;\n }\n}\nfunction resolveAvailableBusExit(params) {\n const {\n busId,\n explicitDirection,\n preferredExit,\n connections,\n sharedBoundary,\n availableRegions\n } = params;\n const compatibleRegions = availableRegions.filter(\n (region) =\u003e (explicitDirection === void 0 || region.direction === explicitDirection) \u0026\u0026 (preferredExit === void 0 || region.preferredExit === preferredExit)\n );\n if (compatibleRegions.length === 0) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" cannot use its requested exit with availableCornersAndSides`\n );\n }\n const inferredDirection = explicitDirection ? void 0 : tryInferDirection(busId, connections);\n const preferredDirectionRegions = inferredDirection ? compatibleRegions.filter(\n (region) =\u003e region.direction === inferredDirection\n ) : [];\n const candidates = preferredDirectionRegions.length \u003e 0 ? preferredDirectionRegions : compatibleRegions;\n const averageSource = getAverageSourcePoint(connections);\n return [...candidates].toSorted(\n (first, second) =\u003e getDistanceToBoundary(averageSource, first.direction, sharedBoundary) - getDistanceToBoundary(\n averageSource,\n second.direction,\n sharedBoundary\n ) || Math.abs(\n getRegionSourceCoordinate(averageSource, first.direction) - getRegionAnchor(first, sharedBoundary)\n ) - Math.abs(\n getRegionSourceCoordinate(averageSource, second.direction) - getRegionAnchor(second, sharedBoundary)\n ) || first.preferredExit.localeCompare(second.preferredExit)\n )[0];\n}\nfunction validateExplicitExitAvailability(params) {\n const { busId, exitEdge, preferredExit, availableRegions } = params;\n const requestedBandSide = getCornerBandSide(exitEdge, preferredExit);\n const hasCompatibleRegion = availableRegions.some(\n (region) =\u003e region.exitEdge === exitEdge \u0026\u0026 getCornerBandSide(region.exitEdge, region.preferredExit) === requestedBandSide\n );\n if (!hasCompatibleRegion) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" cannot use its requested exit with availableCornersAndSides`\n );\n }\n}\nfunction resolveBusDirection(params) {\n const {\n busId,\n explicitDirection,\n preferredExit,\n connections,\n sharedBoundary,\n availableRegions\n } = params;\n if (availableRegions) {\n return resolveAvailableBusExit({\n busId,\n explicitDirection,\n preferredExit,\n connections,\n sharedBoundary,\n availableRegions\n });\n }\n if (!preferredExit) {\n return {\n direction: explicitDirection ?? inferDirection(busId, connections)\n };\n }\n const compatibleDirections = getDirectionsForBorderTarget(preferredExit);\n if (explicitDirection) {\n if (!compatibleDirections.includes(explicitDirection)) {\n throw new Error(\n `FanoutSolver: bus \"${busId}\" direction \"${explicitDirection}\" is incompatible with preferredExit \"${preferredExit}\"`\n );\n }\n return { direction: explicitDirection, preferredExit };\n }\n if (compatibleDirections.length === 1) {\n return { direction: compatibleDirections[0], preferredExit };\n }\n let inferredDirection;\n try {\n inferredDirection = inferDirection(busId, connections);\n } catch {\n inferredDirection = void 0;\n }\n if (inferredDirection \u0026\u0026 compatibleDirections.includes(inferredDirection)) {\n return { direction: inferredDirection, preferredExit };\n }\n const averageSource = getAverageSourcePoint(connections);\n return {\n direction: compatibleDirections.toSorted(\n (first, second) =\u003e getDistanceToBoundary(averageSource, first, sharedBoundary) - getDistanceToBoundary(averageSource, second, sharedBoundary) || first.localeCompare(second)\n )[0],\n preferredExit\n };\n}\nfunction prepareFanoutBuses(srj, options) {\n const componentGrids = findComponentGrids(srj.obstacles);\n if (componentGrids.length === 0 \u0026\u0026 srj.connections.length \u003e 0) {\n throw new Error(\n \"FanoutSolver: no componentId-tagged pad footprint was found\"\n );\n }\n const connectionIndexByName = new Map(\n srj.connections.map((connection, index2) =\u003e [connection.name, index2])\n );\n const resolvedBusInputs = resolveBusSpecs(srj, options).map((busSpec) =\u003e {\n for (const [connectionName, point] of Object.entries(\n busSpec.connectionExitTargets ?? {}\n )) {\n if (!busSpec.connectionNames.includes(connectionName)) {\n throw new Error(\n `FanoutSolver: connectionExitTargets contains connection \"${connectionName}\" outside bus \"${busSpec.busId}\"`\n );\n }\n if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {\n throw new Error(\n `FanoutSolver: connectionExitTargets for connection \"${connectionName}\" must contain finite x and y coordinates`\n );\n }\n }\n const connections = busSpec.connectionNames.map((connectionName) =\u003e {\n const connectionIndex = connectionIndexByName.get(connectionName);\n if (connectionIndex === void 0) {\n throw new Error(\n `FanoutSolver: connection \"${connectionName}\" is missing from the input`\n );\n }\n return srj.connections[connectionIndex];\n });\n const sourceGrid = chooseSourceGrid({\n busSpec,\n connections,\n componentGrids\n });\n const preparedConnections = connections.map(\n (connection) =\u003e prepareConnection({\n connection,\n connectionIndex: connectionIndexByName.get(connection.name),\n sourceGrid,\n componentGrids,\n termination: busSpec.termination ?? { type: \"boundary\" },\n exitTargetPoint: busSpec.connectionExitTargets?.[connection.name]\n })\n );\n return { busSpec, sourceGrid, preparedConnections };\n });\n const sourceGrids = [\n ...new Map(\n resolvedBusInputs.map(({ sourceGrid }) =\u003e [\n sourceGrid.componentId,\n sourceGrid\n ])\n ).values()\n ];\n const sharedBoundary = resolveSharedBoundary(sourceGrids, options);\n const availableRegions = resolveAvailableBoundaryRegions(\n options.availableCornersAndSides\n );\n const buses = [];\n for (const {\n busSpec,\n sourceGrid,\n preparedConnections\n } of resolvedBusInputs) {\n if (busSpec.exitEdge \u0026\u0026 !busSpec.preferredExit) {\n throw new Error(\n `FanoutSolver: bus \"${busSpec.busId}\" exitEdge requires preferredExit`\n );\n }\n if (busSpec.exitEdge \u0026\u0026 busSpec.preferredExit \u0026\u0026 !borderTargetIncludesEdge(busSpec.preferredExit, busSpec.exitEdge)) {\n throw new Error(\n `FanoutSolver: bus \"${busSpec.busId}\" exitEdge \"${busSpec.exitEdge}\" is incompatible with preferredExit \"${busSpec.preferredExit}\"`\n );\n }\n const resolvedExit = resolveBusDirection({\n busId: busSpec.busId,\n explicitDirection: busSpec.direction ?? options.busDirections?.[busSpec.busId],\n preferredExit: busSpec.preferredExit,\n connections: preparedConnections,\n sharedBoundary,\n availableRegions: busSpec.termination?.type === \"plane\" || busSpec.exitEdge ? void 0 : availableRegions\n });\n if (busSpec.termination?.type !== \"plane\" \u0026\u0026 busSpec.exitEdge \u0026\u0026 resolvedExit.preferredExit \u0026\u0026 availableRegions) {\n validateExplicitExitAvailability({\n busId: busSpec.busId,\n exitEdge: busSpec.exitEdge,\n preferredExit: resolvedExit.preferredExit,\n availableRegions\n });\n }\n buses.push({\n busId: busSpec.busId,\n ...busSpec.maxLengthSkew === void 0 ? {} : { maxLengthSkew: busSpec.maxLengthSkew },\n direction: resolvedExit.direction,\n preferredExit: resolvedExit.preferredExit,\n ...busSpec.exitEdge ? { exitEdge: busSpec.exitEdge } : {},\n cornerBandConnectionCount: 0,\n allowedLayers: busSpec.allowedLayers,\n termination: busSpec.termination ?? { type: \"boundary\" },\n connections: preparedConnections,\n componentId: sourceGrid.componentId,\n componentObstacles: sourceGrid.obstacles,\n componentBounds: resolveComponentBounds(sourceGrid, options),\n sharedBoundary,\n xCoordinates: [...sourceGrid.xCoordinates],\n yCoordinates: [...sourceGrid.yCoordinates],\n pitchX: sourceGrid.pitchX,\n pitchY: sourceGrid.pitchY\n });\n }\n const cornerBandConnectionCounts = /* @__PURE__ */ new Map();\n for (const bus of buses) {\n const side = getCornerBandSide(bus.exitEdge, bus.preferredExit);\n if (!bus.exitEdge || !side) continue;\n const key = `${bus.exitEdge}:${side}`;\n cornerBandConnectionCounts.set(\n key,\n (cornerBandConnectionCounts.get(key) ?? 0) + bus.connections.length\n );\n }\n for (const bus of buses) {\n const side = getCornerBandSide(bus.exitEdge, bus.preferredExit);\n if (!bus.exitEdge || !side) continue;\n bus.cornerBandConnectionCount = cornerBandConnectionCounts.get(`${bus.exitEdge}:${side}`) ?? bus.connections.length;\n }\n return buses;\n}\n\n// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/match-angularly-ordered-local-vias.ts\nvar TAU = Math.PI * 2;\n\n// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/route-single-layer-adaptive-exits.ts\nvar FANOUT_FLOW_DEBUG_ENABLED = globalThis.process?.env?.FANOUT_FLOW_DEBUG === \"1\";\n\n// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/runtime-process.ts\nvar getRuntimeProcess = (runtime) =\u003e runtime.process ?? { env: {} };\n\n// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/fanout-solver.ts\nvar process2 = getRuntimeProcess(globalThis);\n\n// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/fit-local-via-grid.ts\nfunction fitLocalViaGrid(coordinates, tolerance) {\n if (coordinates.length \u003c 2) return null;\n const measured = (coordinates.at(-1) - coordinates[0]) / (coordinates.length - 1);\n const pitch = Number(measured.toPrecision(3));\n if (!(pitch \u003e 0) || Math.abs(pitch - measured) \u003e tolerance) return null;\n const measuredOrigin = coordinates.reduce((sum, value, i2) =\u003e sum + value - i2 * pitch, 0) / coordinates.length;\n const quantum = 10 ** (Math.floor(Math.log10(pitch)) - 2);\n const origin = Math.round(measuredOrigin / quantum) * quantum;\n const fitted = coordinates.map((_2, i2) =\u003e origin + i2 * pitch);\n if (fitted.some((value, i2) =\u003e Math.abs(value - coordinates[i2]) \u003e tolerance))\n return null;\n return { coordinates: fitted, pitch };\n}\n\n// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/route-local-signal-dogbones.ts\nfunction routeLocalSignalDogbones(input, options) {\n const connections = structuredClone(input.connections);\n const endpoints = [];\n const virtualConnections = [];\n const buses = [];\n const layers = getCopperLayerNames(input.layerCount);\n for (const [connectionIndex, connection] of connections.entries()) {\n const target = options.targetLayers.get(connection.name);\n if (!target || !layers.includes(target))\n throw Error(`Missing or invalid target layer for ${connection.name}`);\n if (connection.pointsToConnect.length !== 2)\n throw Error(`${connection.name}: two terminals required`);\n for (const [pointIndex, point] of connection.pointsToConnect.entries()) {\n const available = \"layer\" in point ? [point.layer] : point.layers;\n if (available.includes(target)) {\n const { layers: _layers, ...metadata } = point;\n connection.pointsToConnect[pointIndex] = { ...metadata, layer: target };\n continue;\n }\n const sourceObstacle = input.obstacles.find(\n (o2) =\u003e o2.componentId \u0026\u0026 distancePointToObstacle(point, o2) \u003c 1e-8 \u0026\u0026 o2.connectedTo.some(\n (id) =\u003e id === point.pcb_port_id || id === point.pointId || id === connection.name\n )\n );\n if (!sourceObstacle?.componentId)\n throw Error(\n `${connection.name}: local dogbone requires a component pad terminal`\n );\n const name = `dogbone_endpoint_${endpoints.length}`;\n endpoints.push({ connectionIndex, pointIndex });\n virtualConnections.push({\n ...connection,\n name,\n pointsToConnect: [point, connection.pointsToConnect[1 - pointIndex]]\n });\n buses.push({\n busId: name,\n connectionNames: [name],\n sourceComponentId: sourceObstacle.componentId\n });\n }\n }\n if (!endpoints.length)\n return { connections, traces: [] };\n const prepared = prepareFanoutBuses(\n { ...input, connections: virtualConnections, buses: [] },\n { buses }\n );\n for (const bus of prepared) {\n const tolerance = Math.min(...bus.componentObstacles.flatMap((o2) =\u003e [o2.width, o2.height])) / 100;\n const cluster = (values) =\u003e {\n const groups = [];\n for (const value of [...values].sort((a2, b2) =\u003e a2 - b2)) {\n if (groups.length \u0026\u0026 value - groups.at(-1)[0] \u003c tolerance)\n groups.at(-1).push(value);\n else groups.push([value]);\n }\n return groups.map((g2) =\u003e g2.reduce((s2, v2) =\u003e s2 + v2, 0) / g2.length);\n };\n bus.xCoordinates = cluster(bus.xCoordinates);\n bus.yCoordinates = cluster(bus.yCoordinates);\n const pitch = (coordinates, fallback) =\u003e coordinates.length \u003e 1 ? Math.min(...coordinates.slice(1).map((v2, i2) =\u003e v2 - coordinates[i2])) : fallback;\n bus.pitchX = pitch(bus.xCoordinates, bus.pitchX);\n bus.pitchY = pitch(bus.yCoordinates, bus.pitchY);\n const fillMissingRows = (coordinates, step) =\u003e coordinates.flatMap((value, i2) =\u003e {\n if (i2 === coordinates.length - 1) return [value];\n const gap = coordinates[i2 + 1] - value, count = Math.max(1, Math.round(gap / step));\n if (Math.abs(gap / count - step) \u003e tolerance) return [value];\n return Array.from(\n { length: count },\n (_2, j2) =\u003e value + gap * j2 / count\n );\n });\n bus.xCoordinates = fillMissingRows(bus.xCoordinates, bus.pitchX);\n bus.yCoordinates = fillMissingRows(bus.yCoordinates, bus.pitchY);\n const xGrid = fitLocalViaGrid(bus.xCoordinates, tolerance);\n const yGrid = fitLocalViaGrid(bus.yCoordinates, tolerance);\n if (xGrid) {\n bus.xCoordinates = xGrid.coordinates;\n bus.pitchX = xGrid.pitch;\n }\n if (yGrid) {\n bus.yCoordinates = yGrid.coordinates;\n bus.pitchY = yGrid.pitch;\n }\n }\n const blockingSegments = [];\n const blockingVias = [];\n for (const trace of input.traces ?? []) {\n for (const [i2, point] of trace.route.entries()) {\n if (point.route_type === \"via\") {\n blockingVias.push({\n connectionIndex: -1,\n center: point,\n diameter: point.via_diameter ?? options.viaDiameter,\n spanLayers: layers\n });\n const next = trace.route[i2 + 1];\n if (next?.route_type === \"wire\")\n blockingSegments.push({\n connectionIndex: -1,\n segment: {\n start: point,\n end: next,\n layer: next.layer,\n width: next.width\n }\n });\n } else if (point.route_type === \"wire\") {\n const next = trace.route[i2 + 1];\n if (next?.route_type === \"wire\")\n blockingSegments.push({\n connectionIndex: -1,\n segment: {\n start: point,\n end: next,\n layer: point.layer,\n width: point.width\n }\n });\n else if (next?.route_type === \"via\")\n blockingSegments.push({\n connectionIndex: -1,\n segment: {\n start: point,\n end: next,\n layer: point.layer,\n width: point.width\n }\n });\n } else\n throw Error(\"Unsupported fixed copper primitive for local dogbones\");\n }\n }\n const geometryRules = {\n viaDiameter: options.viaDiameter,\n viaHoleDiameter: options.viaHoleDiameter,\n traceWidth: options.traceWidth,\n clearance: options.clearance,\n holeToHoleClearance: options.holeToHoleClearance,\n additionalObstacles: input.obstacles,\n blockingSegments,\n blockingVias\n };\n const candidates = getComponentDogboneViaSiteCandidates(\n prepared,\n geometryRules\n );\n const preferredViaPointsByConnectionIndex = /* @__PURE__ */ new Map();\n for (const connection of prepared.flatMap((b2) =\u003e b2.connections)) {\n const choices = candidates.filter(\n (c2) =\u003e c2.connectionIndex === connection.connectionIndex\n );\n const origin = connection.sourcePoint;\n const rank = (p2) =\u003e Number(p2.x \u003c origin.x) * 2 + Number(p2.y \u003e origin.y) * 2 + Math.hypot(p2.x - origin.x, p2.y - origin.y);\n choices.sort((a2, b2) =\u003e rank(a2.point) - rank(b2.point));\n if (choices[0])\n preferredViaPointsByConnectionIndex.set(\n connection.connectionIndex,\n choices[0].point\n );\n }\n const sites = matchComponentDogboneViaSites(prepared, {\n ...geometryRules,\n preferredViaPointsByConnectionIndex\n });\n if (!sites) throw Error(\"No collision-free local dogbone assignment\");\n const allPrepared = prepared.flatMap((b2) =\u003e b2.connections);\n for (let i2 = 0; i2 \u003c allPrepared.length; i2++)\n for (let j2 = 0; j2 \u003c i2; j2++) {\n const a2 = allPrepared[i2], b2 = allPrepared[j2], p2 = sites.get(a2.connectionIndex), q2 = sites.get(b2.connectionIndex);\n const stubA = {\n start: a2.sourcePoint,\n end: p2,\n layer: a2.sourceLayer,\n width: options.traceWidth\n };\n const stubB = {\n start: b2.sourcePoint,\n end: q2,\n layer: b2.sourceLayer,\n width: options.traceWidth\n };\n const viaSeparation = Math.max(\n options.viaDiameter + options.clearance,\n options.viaHoleDiameter + (options.holeToHoleClearance ?? options.clearance)\n );\n const viaTrace = options.viaDiameter / 2 + options.traceWidth / 2 + options.clearance;\n if (distance3(p2, q2) \u003c viaSeparation - 1e-9 || distancePointToSegment(p2, stubB.start, stubB.end) \u003c viaTrace - 1e-9 || distancePointToSegment(q2, stubA.start, stubA.end) \u003c viaTrace - 1e-9 || a2.sourceLayer === b2.sourceLayer \u0026\u0026 !segmentsAreClear(stubA, stubB, options.clearance))\n throw Error(\"Local dogbones collide between components\");\n }\n const traces = [];\n for (const [endpointIndex, endpoint] of endpoints.entries()) {\n const connection = connections[endpoint.connectionIndex];\n const source = connection.pointsToConnect[endpoint.pointIndex];\n const preparedConnection = prepared.flatMap((b2) =\u003e b2.connections).find((c2) =\u003e c2.connectionIndex === endpointIndex);\n const fromLayer = preparedConnection.sourceLayer;\n const toLayer = options.targetLayers.get(connection.name);\n const site = sites.get(endpointIndex);\n const margin = options.viaDiameter / 2 + (options.boardEdgeClearance ?? 0);\n if (site.x \u003c input.bounds.minX + margin || site.x \u003e input.bounds.maxX - margin || site.y \u003c input.bounds.minY + margin || site.y \u003e input.bounds.maxY - margin)\n throw Error(`${connection.name}: dogbone outside board bounds`);\n const span = getViaSpanLayers({\n fromLayer,\n toLayer,\n layerNames: layers,\n allowBlindAndBuriedVias: options.allowBlindAndBuriedVias ?? false\n });\n traces.push({\n type: \"pcb_trace\",\n pcb_trace_id: `local_dogbone_${connection.name}_${endpoint.pointIndex}`,\n connection_name: connection.name,\n route: [\n {\n route_type: \"wire\",\n x: source.x,\n y: source.y,\n layer: fromLayer,\n width: options.traceWidth\n },\n {\n route_type: \"wire\",\n ...site,\n layer: fromLayer,\n width: options.traceWidth\n },\n {\n route_type: \"via\",\n ...site,\n from_layer: fromLayer,\n to_layer: toLayer,\n layers: span,\n via_diameter: options.viaDiameter,\n via_hole_diameter: options.viaHoleDiameter\n },\n {\n route_type: \"wire\",\n ...site,\n layer: toLayer,\n width: options.traceWidth\n }\n ]\n });\n connection.pointsToConnect[endpoint.pointIndex] = {\n ...site,\n layer: toLayer\n };\n }\n return { connections, traces };\n}\n\n// lib/alternate-signal-dogbones.ts\nfunction routeAlternateSignalDogbones(input, options, attempt) {\n const delta = input.connections.reduce(\n (s2, c2) =\u003e ({\n x: s2.x + c2.pointsToConnect[1].x - c2.pointsToConnect[0].x,\n y: s2.y + c2.pointsToConnect[1].y - c2.pointsToConnect[0].y\n }),\n { x: 0, y: 0 }\n );\n const base = Math.abs(delta.x) \u003e Math.abs(delta.y) ? delta.x \u003e 0 ? 3 : 1 : 0;\n const busNames = new Set(\n (input.buses ?? []).flatMap((b2) =\u003e b2.connectionNames)\n );\n const backward = backwardFacingPackageTerminals({\n ...input,\n connections: input.connections.filter((c2) =\u003e busNames.has(c2.name))\n });\n const order = input.traces?.length ? [0, ...[0, 1, 2, 3].map((i2) =\u003e (base + i2) % 4).filter((i2) =\u003e i2 !== 0)] : [3, 0, 1, 2].map((i2) =\u003e (base + i2) % 4);\n const turns = backward ? (base + attempt) % 4 : order[attempt % 4];\n const rotate2 = (p2, k2) =\u003e {\n let { x: x2, y: y2 } = p2;\n for (let i2 = 0; i2 \u003c k2; i2++) [x2, y2] = [-y2, x2];\n return { ...p2, x: x2, y: y2 };\n };\n const corners = [\n { x: input.bounds.minX, y: input.bounds.minY },\n { x: input.bounds.maxX, y: input.bounds.maxY }\n ].map((p2) =\u003e rotate2(p2, turns));\n const rotated = {\n ...input,\n bounds: {\n minX: Math.min(...corners.map((p2) =\u003e p2.x)),\n maxX: Math.max(...corners.map((p2) =\u003e p2.x)),\n minY: Math.min(...corners.map((p2) =\u003e p2.y)),\n maxY: Math.max(...corners.map((p2) =\u003e p2.y))\n },\n connections: input.connections.map((c2) =\u003e ({\n ...c2,\n pointsToConnect: c2.pointsToConnect.map((p2) =\u003e rotate2(p2, turns))\n })),\n obstacles: input.obstacles.map((o2) =\u003e ({\n ...o2,\n center: rotate2(o2.center, turns),\n ccwRotationDegrees: (o2.ccwRotationDegrees ?? 0) + 90 * turns\n })),\n traces: input.traces?.map((t48) =\u003e ({\n ...t48,\n route: t48.route.map((p2) =\u003e rotate2(p2, turns))\n }))\n };\n const result = routeLocalSignalDogbones(\n rotated,\n options\n );\n return {\n connections: result.connections.map((c2) =\u003e ({\n ...c2,\n pointsToConnect: c2.pointsToConnect.map((p2) =\u003e rotate2(p2, (4 - turns) % 4))\n })),\n traces: result.traces.map((t48) =\u003e ({\n ...t48,\n route: t48.route.map((p2) =\u003e {\n if (!(\"x\" in p2)) throw Error(\"Unexpected dogbone primitive\");\n return rotate2(p2, (4 - turns) % 4);\n })\n }))\n };\n}\n\n// lib/run-bounded-routing.ts\nfunction* runBoundedRouting(generator, limit) {\n let state = generator.next();\n let steps = 0;\n try {\n while (!state.done \u0026\u0026 steps++ \u003c limit) {\n yield;\n state = generator.next();\n }\n return state.done ? state.value : null;\n } finally {\n if (!state.done) generator.return(null);\n }\n}\n\n// lib/repair-bus-dogbones.ts\nfunction signalWidth(input, connection) {\n return input.buses?.find((bus) =\u003e bus.connectionNames.includes(connection.name))?.traceWidth ?? connection.nominalTraceWidth ?? connection.width ?? input.minTraceWidth;\n}\nfunction signalDogboneOptions(input, targetLayers) {\n return {\n targetLayers,\n viaDiameter: input.minViaPadDiameter ?? 0.6,\n viaHoleDiameter: input.minViaHoleDiameter ?? 0.3,\n traceWidth: Math.max(\n input.minTraceWidth,\n ...input.connections.map((c2) =\u003e signalWidth(input, c2))\n ),\n clearance: input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075,\n boardEdgeClearance: input.minBoardEdgeClearance,\n holeToHoleClearance: input.minViaHoleEdgeToViaHoleEdgeClearance,\n allowBlindAndBuriedVias: input.allowBlindAndBuriedVias ?? false\n };\n}\nfunction ownedSignalEscapes(native, traces) {\n return traces.map((trace) =\u003e ({\n ...trace,\n source_trace_id: native.connections.find((c2) =\u003e c2.name === trace.connection_name)?.source_trace_id ?? trace.connection_name\n }));\n}\nfunction* repairBusDogbones(native, laneInput, current, generatedEscapes) {\n let input = structuredClone(laneInput);\n let traces = current;\n let escapes = generatedEscapes;\n const widths = new Map(\n native.connections.map((c2) =\u003e [c2.name, signalWidth(native, c2)])\n );\n const missing = input.connections.filter(\n (c2) =\u003e !traces.some((t48) =\u003e t48.connection_name === c2.name)\n );\n if (!missing.length) return { input, traces, escapes };\n if (missing.length \u003e 3 || missing.some(\n (c2) =\u003e !input.buses?.some((b2) =\u003e b2.connectionNames.includes(c2.name))\n ))\n return null;\n const missingCount = (names) =\u003e missing.filter((c2) =\u003e names.includes(c2.name)).length;\n const buses = (input.buses ?? []).filter((bus) =\u003e missingCount(bus.connectionNames)).sort(\n (a2, b2) =\u003e missingCount(b2.connectionNames) - missingCount(a2.connectionNames)\n );\n for (const bus of buses) {\n const names = new Set(bus.connectionNames);\n const group = native.connections.filter((c2) =\u003e names.has(c2.name));\n const outside = traces.filter((t48) =\u003e !names.has(t48.connection_name));\n const pair = input.differentialPairs?.find(\n (p2) =\u003e p2.connectionNames.every((name) =\u003e names.has(name))\n );\n if (!pair || group.length !== names.size) return null;\n const layer = input.connections.find((c2) =\u003e names.has(c2.name)).pointsToConnect[0].layer;\n const congested = missingCount(bus.connectionNames) \u003e 1;\n const variants = congested ? [1, 0, 3, 5, 2, 4] : [2, 1, 0, 3, 5, 4];\n let solved = false;\n for (let choice = 0; choice \u003c 4 \u0026\u0026 !solved; choice++) {\n const attempt = ((congested ? 1 : 0) + choice) % 4;\n const base = {\n ...native,\n connections: group,\n traces: [\n ...native.traces ?? [],\n ...escapes.filter((t48) =\u003e !names.has(t48.connection_name)),\n ...outside\n ]\n };\n let replacement;\n try {\n replacement = routeAlternateSignalDogbones(\n base,\n signalDogboneOptions(\n base,\n new Map(group.map((c2) =\u003e [c2.name, layer]))\n ),\n attempt\n );\n } catch {\n yield;\n continue;\n }\n const newEscapes = ownedSignalEscapes(native, replacement.traces);\n const local = {\n ...input,\n connections: replacement.connections,\n buses: [bus],\n differentialPairs: [pair],\n traces: [...base.traces, ...newEscapes]\n };\n const fixed = fixedCopper(local);\n const ordinary = local.connections.filter(\n (c2) =\u003e !pair.connectionNames.includes(c2.name)\n );\n for (const variant of variants) {\n const paired = yield* runBoundedRouting(\n routeCoupledPair(local, pair, fixed, {\n copper: [],\n penalty: 0,\n variant\n }),\n 6e3\n );\n if (!paired) continue;\n const generator = negotiateLanes(\n local,\n ordinary,\n fixed,\n paired,\n widths,\n void 0,\n /* @__PURE__ */ new Map(),\n () =\u003e false,\n true\n );\n let state = generator.next();\n let steps = 0;\n let best = 0;\n let completed = null;\n try {\n while (!state.done \u0026\u0026 steps++ \u003c 1e4) {\n if (state.value.length \u003e best) {\n best = state.value.length;\n if (best \u003e= local.connections.length - 1) {\n const closed = yield* runBoundedRouting(\n ejectBlockingLanes(\n { ...local, connections: ordinary },\n state.value.filter(\n (t48) =\u003e !pair.connectionNames.includes(t48.connection_name)\n ),\n [...fixed, ...paired.flatMap(routeCopper)],\n widths,\n /* @__PURE__ */ new Map(),\n { maxSearches: 200 }\n ),\n 2e4\n );\n if (closed) {\n completed = [...paired, ...closed];\n break;\n }\n }\n }\n yield;\n state = generator.next();\n }\n if (state.done) completed = state.value;\n } finally {\n if (!state.done) generator.return(null);\n }\n if (!completed) continue;\n traces = [...outside, ...completed];\n escapes = [\n ...escapes.filter((t48) =\u003e !names.has(t48.connection_name)),\n ...newEscapes\n ];\n input = {\n ...input,\n connections: input.connections.map(\n (c2) =\u003e local.connections.find((next) =\u003e next.name === c2.name) ?? c2\n ),\n traces: [...native.traces ?? [], ...escapes]\n };\n solved = true;\n break;\n }\n }\n if (!solved) return null;\n }\n return traces.length === input.connections.length ? { input, traces, escapes } : null;\n}\n\n// lib/repair-shared-layer-conflicts.ts\nfunction* repairSharedLayerConflicts(input, initial, layers, options = {}) {\n const connections = input.connections, fixed = fixedCopper(input), index2 = new RouteConflictIndex();\n const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;\n const clashes = (routes2) =\u003e {\n const collisions = [];\n for (let a2 = 0; a2 \u003c routes2.length; a2++)\n for (let b2 = 0; b2 \u003c a2; b2++)\n if (routes2[a2].route[0].layer === routes2[b2].route[0].layer \u0026\u0026 index2.firstConflict(\n routes2[a2].route,\n routes2[b2].route,\n (routes2[a2].route[0].width + routes2[b2].route[0].width) / 2 + clearance - 1e-8\n ))\n collisions.push([a2, b2]);\n return collisions;\n };\n function* route(c2, blocked, others) {\n const choices = [];\n for (const layer of layers.get(c2.name) ?? [c2.pointsToConnect[0].layer]) {\n const connection = {\n ...c2,\n pointsToConnect: c2.pointsToConnect.map((p2) =\u003e ({ ...p2, layer }))\n };\n const scene = new VectorScene(input, connection, signalWidth(input, c2), [\n ...fixed,\n ...blocked.flatMap(routeCopper)\n ]);\n const search = new GridVisibilitySearch(\n scene,\n ...connection.pointsToConnect,\n others.flatMap(routeCopper),\n 10,\n void 0,\n {\n maxLength: Math.min(\n maximumCarrierLength(input, c2.name),\n (options.lengthTargets?.get(c2.name) ?? Infinity) - fixedRouteLength(input, c2.name)\n ),\n paretoLength: true,\n checkReachability: true\n }\n );\n let steps = 0;\n try {\n while (!search.solved \u0026\u0026 !search.failed \u0026\u0026 steps++ \u003c 4e3) {\n search.step();\n yield;\n }\n if (search.solved) {\n const trace = {\n type: \"pcb_trace\",\n pcb_trace_id: `bus_lane_${c2.name}`,\n connection_name: c2.name,\n source_trace_id: c2.source_trace_id ?? c2.name,\n route: search.result.map((p2) =\u003e ({\n ...p2,\n route_type: \"wire\",\n layer,\n width: signalWidth(input, c2)\n }))\n };\n const target = options.lengthTargets?.get(c2.name);\n if (target === void 0) choices.push(trace);\n else\n try {\n choices.push(\n tuneSmoothLengths(\n {\n ...input,\n connections: [connection],\n traces: [...input.traces ?? [], ...blocked],\n buses: [],\n differentialPairs: []\n },\n chamferOrdinaryCorners(\n { ...input, connections: [connection] },\n [trace],\n [...fixed, ...blocked.flatMap(routeCopper)],\n 1.5\n ),\n /* @__PURE__ */ new Map([[c2.name, target]]),\n { maxCandidates: 65536, packMeanders: true }\n )[0]\n );\n } catch {\n }\n }\n } finally {\n search.cancel();\n }\n }\n return choices;\n }\n const routes = initial.filter((t48) =\u003e {\n const c2 = connections.find((c3) =\u003e c3.name === t48.connection_name);\n if (!c2 || length(t48.route) \u003e maximumCarrierLength(input, c2.name) + 1e-7)\n return false;\n const target = options.lengthTargets?.get(c2.name);\n if (target !== void 0 \u0026\u0026 Math.abs(length(t48.route) + fixedRouteLength(input, c2.name) - target) \u003e 1e-7)\n return false;\n if (c2.pointsToConnect.some(\n (p2) =\u003e ![t48.route[0], t48.route.at(-1)].some(\n (q2) =\u003e Math.hypot(p2.x - q2.x, p2.y - q2.y) \u003c 1e-7\n )\n ))\n return false;\n const layer = t48.route[0].layer;\n const projected = {\n ...c2,\n pointsToConnect: c2.pointsToConnect.map((p2) =\u003e ({ ...p2, layer }))\n };\n return new VectorScene(\n input,\n projected,\n signalWidth(input, c2),\n fixed\n ).pathVisible(t48.route);\n });\n for (const c2 of connections.filter(\n (c3) =\u003e !routes.some((t48) =\u003e t48.connection_name === c3.name)\n )) {\n const choices = yield* route(c2, [], routes);\n if (!choices.length) {\n options.onBlockedConnection?.(c2.name);\n return null;\n }\n choices.sort(\n (a2, b2) =\u003e clashes([...routes, a2]).length - clashes([...routes, b2]).length || length(a2.route) - length(b2.route)\n );\n routes.push(choices[0]);\n }\n const create = (routes2, constraints, depth) =\u003e ({\n routes: routes2,\n constraints,\n depth,\n collisions: clashes(routes2),\n cost: routes2.reduce((sum, t48) =\u003e sum + length(t48.route), 0)\n });\n const queue = [create(routes, /* @__PURE__ */ new Map(), 0)], seen = /* @__PURE__ */ new Set();\n let best = Infinity;\n const ids = /* @__PURE__ */ new WeakMap();\n let nextId = 0;\n const id = (t48) =\u003e {\n if (!ids.has(t48)) ids.set(t48, nextId++);\n return ids.get(t48);\n };\n for (let nodes = 0; queue.length \u0026\u0026 nodes \u003c (options.maxNodes ?? 2e3); nodes++) {\n queue.sort(\n (a2, b2) =\u003e a2.collisions.length - b2.collisions.length || a2.depth - b2.depth || a2.cost - b2.cost\n );\n const node = queue.shift();\n if (!node.collisions.length) return node.routes;\n if (node.collisions.length \u003c best || nodes % 20 === 0) {\n if (node.collisions.length \u003c best)\n options.onBestCandidate?.(\n node.routes,\n node.collisions.map(([a2, b2]) =\u003e [\n node.routes[a2].connection_name,\n node.routes[b2].connection_name\n ])\n );\n best = Math.min(best, node.collisions.length);\n options.onProgress?.({\n nodes,\n collisions: node.collisions.length,\n queue: queue.length\n });\n }\n const degree = /* @__PURE__ */ new Map();\n for (const pair2 of node.collisions)\n for (const i2 of pair2) degree.set(i2, (degree.get(i2) ?? 0) + 1);\n node.collisions.sort(\n (a2, b2) =\u003e degree.get(a2[0]) + degree.get(a2[1]) - (degree.get(b2[0]) + degree.get(b2[1]))\n );\n const pair = node.collisions[0];\n for (const [change, block] of [pair, [pair[1], pair[0]]]) {\n const name = node.routes[change].connection_name, connection = connections.find((c2) =\u003e c2.name === name);\n const constraints = new Map(node.constraints);\n constraints.set(name, [\n ...constraints.get(name) ?? [],\n node.routes[block]\n ]);\n const signature = connections.map(\n (c2) =\u003e `${c2.name}:${(constraints.get(c2.name) ?? []).map(id).sort((a2, b2) =\u003e a2 - b2).join(\",\")}`\n ).join(\";\");\n if (seen.has(signature)) continue;\n seen.add(signature);\n const others = node.routes.filter((_2, i2) =\u003e i2 !== change);\n for (const choice of yield* route(\n connection,\n constraints.get(name),\n others\n )) {\n const result = node.routes.map((t48, i2) =\u003e i2 === change ? choice : t48);\n queue.push(create(result, constraints, node.depth + 1));\n }\n }\n if (queue.length \u003e 256) {\n queue.sort(\n (a2, b2) =\u003e a2.collisions.length - b2.collisions.length || a2.depth - b2.depth || a2.cost - b2.cost\n );\n queue.length = 256;\n }\n yield;\n }\n return null;\n}\n\n// lib/reserve-bus-package-exits.ts\nfunction reserveBusPackageExits(input, pair) {\n const pairLayer = input.connections.find(\n (c2) =\u003e c2.name === pair.connectionNames[0]\n ).pointsToConnect[0].layer;\n const ownBus = input.buses?.find(\n (bus2) =\u003e pair.connectionNames.some((name) =\u003e bus2.connectionNames.includes(name))\n );\n const related = ownBus ? [ownBus] : (input.buses ?? []).filter(\n (bus2) =\u003e input.connections.some(\n (c2) =\u003e bus2.connectionNames.includes(c2.name) \u0026\u0026 c2.pointsToConnect[0].layer === pairLayer\n )\n );\n if (!related.length) return [];\n const bus = related[0], names = new Set(related.flatMap((bus2) =\u003e bus2.connectionNames)), members = input.connections.filter((c2) =\u003e names.has(c2.name));\n const regions = packageApproachRegions(input, 0), layer = members[0].pointsToConnect[0].layer, width = bus.traceWidth ?? input.minTraceWidth;\n const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;\n const reserve = Math.max(0, members.length - 2) * (width + clearance);\n const faces = /* @__PURE__ */ new Map();\n for (const connection of members)\n for (const point of connection.pointsToConnect) {\n const region = regions.map((region2, index2) =\u003e ({\n box: region2.pads,\n index: index2,\n distance: Math.hypot(\n point.x - (region2.pads.minX + region2.pads.maxX) / 2,\n point.y - (region2.pads.minY + region2.pads.maxY) / 2\n )\n })).sort((a2, b2) =\u003e a2.distance - b2.distance)[0];\n if (!region) continue;\n const { box } = region;\n const edge = [\n { side: \"left\", d: point.x - box.minX, x: -1, y: 0 },\n { side: \"right\", d: box.maxX - point.x, x: 1, y: 0 },\n { side: \"bottom\", d: point.y - box.minY, x: 0, y: -1 },\n { side: \"top\", d: box.maxY - point.y, x: 0, y: 1 }\n ].sort((a2, b2) =\u003e a2.d - b2.d)[0];\n const key = `${region.index}:${edge.side}`;\n let face = faces.get(key);\n if (!face) faces.set(key, face = []);\n face.push({ point, edge, name: connection.name });\n }\n const reservations = [];\n for (const face of faces.values()) {\n const nearest = Math.min(...face.map((member) =\u003e member.edge.d));\n for (const { point, edge, name } of face) {\n if (pair.connectionNames.includes(name) || edge.d \u003e nearest + width / 2)\n continue;\n reservations.push({\n a: point,\n b: { x: point.x + edge.x * reserve, y: point.y + edge.y * reserve },\n radius: width / 2,\n layer,\n owners: [name]\n });\n }\n }\n return reservations;\n}\n\n// lib/plan-shared-pair-corridors.ts\nfunction* planSharedPairCorridors(input, terminalLayers, freshDogbones = false) {\n const pairs = input.differentialPairs ?? [];\n const bounded = input.buses?.some((bus) =\u003e bus.maxLength !== void 0);\n const domains = pairs.map(() =\u003e []);\n const geometry = pairs.map(() =\u003e /* @__PURE__ */ new Set());\n const tried = /* @__PURE__ */ new Set();\n const fixed = fixedCopper(input);\n const conflicts = new RouteConflictIndex();\n const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;\n const scenes = /* @__PURE__ */ new Map();\n let serial = 0;\n const collides = (a2, b2) =\u003e a2.layer === b2.layer \u0026\u0026 a2.traces.some(\n (t48) =\u003e b2.traces.some(\n (r2) =\u003e conflicts.firstConflict(\n t48.route,\n r2.route,\n (t48.route[0].width + r2.route[0].width) / 2 + clearance - 1e-8\n )\n )\n );\n const alternatives = freshDogbones ? [100, 2, 3, 0, 1, 101, 102, 103, 4, 104, 5, 105, 6, 106, 7, 107] : [1, 2, [0, 1], [1, 0], 0, [0, 2], [2, 0], 3, [1, 2], [2, 1], 4, 5, 6, 7];\n for (const variant of alternatives) {\n for (const [index2, pair] of pairs.entries()) {\n const members = pair.connectionNames.map(\n (name) =\u003e input.connections.find((c2) =\u003e c2.name === name)\n );\n const layers = terminalLayers.get(members[0].name)?.filter(\n (layer) =\u003e members.every((c2) =\u003e terminalLayers.get(c2.name)?.includes(layer))\n ) ?? [members[0].pointsToConnect[0].layer];\n for (const layer of layers.filter(\n (layer2) =\u003e !input.allowedLayers || input.allowedLayers.includes(layer2)\n )) {\n const reserved = typeof variant === \"number\" \u0026\u0026 variant \u003e= 100;\n const sceneKey = JSON.stringify([index2, layer, reserved]);\n const local = scenes.get(sceneKey) ?? {\n ...input,\n connections: input.connections.map(\n (c2) =\u003e pair.connectionNames.includes(c2.name) ? {\n ...c2,\n pointsToConnect: c2.pointsToConnect.map((p2) =\u003e ({\n ...p2,\n layer\n }))\n } : c2\n )\n };\n scenes.set(sceneKey, local);\n const search = runBoundedRouting(\n routeCoupledPair(\n local,\n pair,\n reserved ? [...fixed, ...reserveBusPackageExits(local, pair)] : fixed,\n {\n copper: [],\n penalty: 0,\n ...typeof variant === \"number\" ? { variant: reserved ? variant - 100 : variant } : { handoffOffsets: variant }\n }\n ),\n 6e3\n );\n let state = search.next();\n try {\n while (!state.done) {\n yield void 0;\n state = search.next();\n }\n } finally {\n if (!state.done) search.return(null);\n }\n if (!state.value) continue;\n if (bounded \u0026\u0026 state.value.some(\n (trace) =\u003e length(trace.route) \u003e maximumCarrierLength(input, trace.connection_name) + 1e-7\n ))\n continue;\n const key = JSON.stringify(state.value.map((t48) =\u003e t48.route));\n if (geometry[index2].has(key)) continue;\n geometry[index2].add(key);\n domains[index2].push({\n id: serial++,\n layer,\n traces: state.value,\n length: state.value.reduce((sum, t48) =\u003e sum + length(t48.route), 0)\n });\n }\n }\n if (bounded)\n for (const choices of domains) choices.sort((a2, b2) =\u003e a2.length - b2.length);\n const plans = [];\n const visit = (selected, index2) =\u003e {\n if (plans.length \u003e= 256) return;\n if (index2 === domains.length) {\n const key = selected.map((c2) =\u003e c2.id).join(\",\");\n if (!tried.has(key)) plans.push(selected);\n return;\n }\n for (const choice of domains[index2])\n if (!selected.some((other) =\u003e collides(choice, other)))\n visit([...selected, choice], index2 + 1);\n };\n visit([], 0);\n const busNames = new Set(input.buses?.flatMap((bus) =\u003e bus.connectionNames));\n const pairNames = new Set(pairs.flatMap((pair) =\u003e pair.connectionNames));\n const costs = new Map(\n plans.map((plan) =\u003e [\n plan,\n freshDogbones ? input.connections.filter((c2) =\u003e busNames.has(c2.name) \u0026\u0026 !pairNames.has(c2.name)).reduce(\n (sum, c2) =\u003e sum + plan.filter(\n (choice) =\u003e choice.layer === c2.pointsToConnect[0].layer\n ).flatMap((choice) =\u003e choice.traces).filter(\n (trace) =\u003e conflicts.firstConflict(\n c2.pointsToConnect,\n trace.route,\n (trace.route[0].width + input.minTraceWidth) / 2 + clearance - 1e-8\n )\n ).length,\n 0\n ) : 0\n ])\n );\n plans.sort(\n (a2, b2) =\u003e costs.get(a2) - costs.get(b2) || a2.reduce((sum, c2) =\u003e sum + c2.length, 0) - b2.reduce((sum, c2) =\u003e sum + c2.length, 0)\n );\n for (const plan of plans) {\n tried.add(plan.map((c2) =\u003e c2.id).join(\",\"));\n yield plan.flatMap((c2) =\u003e c2.traces);\n }\n }\n}\n\n// lib/reachable-signal-dogbones.ts\nvar near = (a2, b2) =\u003e distance(a2, b2) \u003c 1e-8;\nfunction localSignalSiteCandidates(input, connection, options) {\n const sites = [[], []];\n const single = { ...input, connections: [connection] };\n for (let end = 0; end \u003c 2; end++) {\n const rejected = [];\n for (let attempt = 0; attempt \u003c 8; attempt++) {\n try {\n const generated = routeLocalSignalDogbones(\n {\n ...single,\n obstacles: [...single.obstacles, ...rejected]\n },\n options\n );\n const point = generated.connections[0].pointsToConnect[end];\n if (sites[end].some((site) =\u003e near(site.point, point))) break;\n const escape = ownedSignalEscapes(input, generated.traces).find(\n (trace) =\u003e near(trace.route[0], connection.pointsToConnect[end])\n );\n if (!escape) break;\n sites[end].push({\n point,\n escape,\n copper: fixedCopper({ ...input, obstacles: [], traces: [escape] })\n });\n rejected.push({\n type: \"rect\",\n center: { x: point.x, y: point.y },\n width: 1e-6,\n height: 1e-6,\n layers: getCopperLayerNames(input.layerCount),\n connectedTo: []\n });\n } catch {\n break;\n }\n }\n sites[end].sort((a2, b2) =\u003e a2.point.x - b2.point.x || a2.point.y - b2.point.y);\n }\n return sites;\n}\nfunction* reachableSignalDogbones(input, options, allowedLayers, nearestTerminalAttachments = false) {\n const endpoints = [];\n const fixed = fixedCopper(input);\n for (const [connectionIndex, connection] of input.connections.entries()) {\n const sites = localSignalSiteCandidates(input, connection, options);\n if (sites.some((end) =\u003e !end.length)) return null;\n let best;\n for (const layer of allowedLayers.get(connection.name) ?? []) {\n const supportsLayer = (site) =\u003e site.escape.route.some(\n (point) =\u003e point.route_type === \"via\" \u0026\u0026 point.layers?.includes(layer)\n );\n const starts = sites[0].filter(supportsLayer).map((site) =\u003e ({ ...site.point, layer }));\n const ends = sites[1].filter(supportsLayer).map((site) =\u003e ({ ...site.point, layer }));\n if (!starts.length || !ends.length) continue;\n const local = { ...connection, pointsToConnect: [starts[0], ends[0]] };\n const search = new GridVisibilitySearch(\n new VectorScene(input, local, options.traceWidth, fixed),\n starts[0],\n ends[0],\n [],\n 0,\n void 0,\n { starts, ends, nearestTerminalAttachments, checkReachability: true }\n );\n try {\n let steps = 0;\n while (!search.solved \u0026\u0026 !search.failed \u0026\u0026 steps++ \u003c 4e3) {\n search.step();\n yield;\n }\n if (search.solved) {\n const cost = length(search.result);\n if (!best || cost \u003c best.cost)\n best = { cost, start: search.result[0], end: search.result.at(-1) };\n }\n } finally {\n search.cancel();\n }\n }\n if (!best) return null;\n for (let pointIndex = 0; pointIndex \u003c 2; pointIndex++) {\n const source = connection.pointsToConnect[pointIndex];\n const target = connection.pointsToConnect[1 - pointIndex];\n const preferred = pointIndex ? best.end : best.start;\n const dx2 = target.x - source.x, dy2 = target.y - source.y;\n const outwardRank = (point) =\u003e {\n const displacement = Math.abs(dx2) \u003e= Math.abs(dy2) ? Math.sign(dx2) * (point.x - source.x) : Math.sign(dy2) * (point.y - source.y);\n return displacement \u003e 1e-9 ? 0 : Math.abs(displacement) \u003c= 1e-9 ? 1 : 2;\n };\n sites[pointIndex].sort((a2, b2) =\u003e {\n const difference = distance(source, a2.point) - distance(source, b2.point);\n return Number(!near(a2.point, preferred)) - Number(!near(b2.point, preferred)) || outwardRank(a2.point) - outwardRank(b2.point) || (Math.abs(difference) \u003c 1e-8 ? 0 : difference) || a2.point.x - b2.point.x || a2.point.y - b2.point.y;\n });\n const owners = [connection.name, source.pcb_port_id, source.pointId];\n const pad = input.obstacles.filter(\n (o2) =\u003e o2.componentId \u0026\u0026 o2.connectedTo.some((owner) =\u003e owners.includes(owner))\n ).sort(\n (a2, b2) =\u003e distance(a2.center, source) - distance(b2.center, source)\n )[0];\n if (!pad?.componentId) return null;\n endpoints.push({\n connectionIndex,\n pointIndex,\n component: pad.componentId,\n sites: sites[pointIndex]\n });\n }\n }\n const assigned = /* @__PURE__ */ new Map();\n const compatible = (a2, b2) =\u003e {\n if (a2.copper.some(\n (c2) =\u003e b2.copper.some(\n (d2) =\u003e c2.layer === d2.layer \u0026\u0026 clearanceToCopper(c2.a, c2.b, d2) \u003c c2.radius + options.clearance - 1e-8\n )\n ))\n return false;\n const first = a2.escape.route.find((p2) =\u003e p2.route_type === \"via\");\n const second = b2.escape.route.find((p2) =\u003e p2.route_type === \"via\");\n return distance(first, second) \u003e= options.viaHoleDiameter + (options.holeToHoleClearance ?? options.clearance) - 1e-8;\n };\n let states = 0;\n for (const component of new Set(endpoints.map((end) =\u003e end.component))) {\n const search = (remaining) =\u003e {\n if (++states \u003e 1e5) return false;\n if (!remaining.length) return true;\n const domains = remaining.map((endpoint2) =\u003e ({\n endpoint: endpoint2,\n sites: endpoint2.sites.filter(\n (site) =\u003e [...assigned.values()].every((other) =\u003e compatible(site, other))\n )\n })).sort(\n (a2, b2) =\u003e a2.sites.length - b2.sites.length || a2.endpoint.connectionIndex - b2.endpoint.connectionIndex || a2.endpoint.pointIndex - b2.endpoint.pointIndex\n );\n const { endpoint, sites } = domains[0];\n for (const site of sites) {\n assigned.set(endpoint, site);\n if (search(remaining.filter((end) =\u003e end !== endpoint))) return true;\n assigned.delete(endpoint);\n }\n return false;\n };\n if (!search(endpoints.filter((end) =\u003e end.component === component)))\n return null;\n yield;\n }\n const connections = structuredClone(input.connections);\n const traces = [];\n for (const endpoint of endpoints) {\n const site = assigned.get(endpoint);\n const connection = connections[endpoint.connectionIndex];\n connection.pointsToConnect[endpoint.pointIndex] = {\n ...site.point,\n layer: options.targetLayers.get(connection.name)\n };\n traces.push(site.escape);\n }\n return { connections, traces };\n}\n\n// lib/flexible-signal-state.ts\nfunction signalLayers(input, connection) {\n return (input.allowedLayers ?? getCopperLayerNames(input.layerCount)).filter(\n (layer) =\u003e !connection.pointsToConnect.some((point) =\u003e point.layer === layer) \u0026\u0026 (input.buses ?? []).every(\n (bus) =\u003e !bus.connectionNames.includes(connection.name) || !bus.allowedLayers || bus.allowedLayers.includes(layer)\n )\n );\n}\nfunction signalTrace(input, connection, route, layer) {\n const width = signalWidth(input, connection);\n return {\n type: \"pcb_trace\",\n pcb_trace_id: `bus_lane_${connection.name}`,\n connection_name: connection.name,\n source_trace_id: connection.source_trace_id ?? connection.name,\n route: route.map((point) =\u003e ({\n ...point,\n route_type: \"wire\",\n layer,\n width\n }))\n };\n}\n\n// lib/copper-conflict-index.ts\nvar CopperConflictIndex = class {\n geometry = /* @__PURE__ */ new WeakMap();\n prepare(copper) {\n const cached = this.geometry.get(copper);\n if (cached) return cached;\n const bounds = new Float64Array(copper.length * 4);\n let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;\n for (let i2 = 0; i2 \u003c copper.length; i2++) {\n const c2 = copper[i2], k2 = i2 * 4;\n bounds[k2] = Math.min(c2.a.x, c2.b.x) - c2.radius;\n bounds[k2 + 1] = Math.max(c2.a.x, c2.b.x) + c2.radius;\n bounds[k2 + 2] = Math.min(c2.a.y, c2.b.y) - c2.radius;\n bounds[k2 + 3] = Math.max(c2.a.y, c2.b.y) + c2.radius;\n if (c2.rect) {\n bounds[k2] = Math.min(bounds[k2], c2.rect.minX);\n bounds[k2 + 1] = Math.max(bounds[k2 + 1], c2.rect.maxX);\n bounds[k2 + 2] = Math.min(bounds[k2 + 2], c2.rect.minY);\n bounds[k2 + 3] = Math.max(bounds[k2 + 3], c2.rect.maxY);\n }\n minX = Math.min(minX, bounds[k2]);\n maxX = Math.max(maxX, bounds[k2 + 1]);\n minY = Math.min(minY, bounds[k2 + 2]);\n maxY = Math.max(maxY, bounds[k2 + 3]);\n }\n const geometry = { copper, bounds, minX, maxX, minY, maxY };\n this.geometry.set(copper, geometry);\n return geometry;\n }\n firstConflict(first, second, clearance) {\n const a2 = this.prepare(first), b2 = this.prepare(second);\n if (a2.maxX + clearance \u003c b2.minX || b2.maxX + clearance \u003c a2.minX || a2.maxY + clearance \u003c b2.minY || b2.maxY + clearance \u003c a2.minY)\n return;\n for (let i2 = 0; i2 \u003c first.length; i2++) {\n const c2 = first[i2], ai = i2 * 4;\n for (let j2 = 0; j2 \u003c second.length; j2++) {\n const d2 = second[j2], bj = j2 * 4;\n if (c2.layer !== d2.layer || a2.bounds[ai + 1] + clearance \u003c b2.bounds[bj] || b2.bounds[bj + 1] + clearance \u003c a2.bounds[ai] || a2.bounds[ai + 3] + clearance \u003c b2.bounds[bj + 2] || b2.bounds[bj + 3] + clearance \u003c a2.bounds[ai + 2])\n continue;\n if (clearanceToCopper(c2.a, c2.b, d2) \u003c c2.radius + clearance) return [c2, d2];\n }\n }\n }\n};\n\n// lib/find-signal-site-pocket.ts\nfunction* expandSignalSitePocket(state) {\n const { native, pending, retained, traces } = state;\n const fixed = fixedCopper(pending), conflicts = new RouteConflictIndex(), remove = /* @__PURE__ */ new Set();\n const clearance = native.minTraceToPadEdgeClearance ?? native.defaultObstacleMargin ?? 0.075;\n const probe = function* (connection, hard, local = pending, lanes = traces) {\n const results = [];\n const source = native.connections.find((c2) =\u003e c2.name === connection.name);\n const width = signalWidth(native, source);\n for (const layer of signalLayers(native, source)) {\n const c2 = {\n ...connection,\n pointsToConnect: connection.pointsToConnect.map((p2) =\u003e ({\n ...p2,\n layer\n }))\n };\n const search = new GridVisibilitySearch(\n new VectorScene(local, c2, width, hard),\n c2.pointsToConnect[0],\n c2.pointsToConnect[1],\n lanes.flatMap(routeCopper),\n 100,\n void 0,\n {\n checkReachability: true,\n maxLength: maximumCarrierLength(local, c2.name),\n paretoLength: Number.isFinite(maximumCarrierLength(local, c2.name))\n }\n );\n try {\n let steps = 0;\n while (!search.solved \u0026\u0026 !search.failed \u0026\u0026 steps++ \u003c 3e3) {\n search.step();\n yield;\n }\n if (search.solved)\n results.push({\n layer,\n blockers: lanes.filter(\n (t48) =\u003e t48.route[0].layer === layer \u0026\u0026 conflicts.firstConflict(\n search.result,\n t48.route,\n (width + t48.route[0].width) / 2 + clearance - 1e-8\n )\n )\n });\n } finally {\n search.cancel();\n }\n }\n return results;\n };\n for (const connection of pending.connections.filter(\n (c2) =\u003e !traces.some((t48) =\u003e t48.connection_name === c2.name)\n )) {\n const best = (yield* probe(connection, fixed)).sort(\n (a2, b2) =\u003e a2.blockers.length - b2.blockers.length\n )[0];\n remove.add(connection.name);\n for (const trace of best?.blockers ?? []) remove.add(trace.connection_name);\n }\n const additions = /* @__PURE__ */ new Set(), remaining = traces.filter((t48) =\u003e !remove.has(t48.connection_name));\n for (const connection of pending.connections.filter(\n (c2) =\u003e remove.has(c2.name)\n )) {\n const reduced = {\n ...pending,\n traces: [\n ...native.traces ?? [],\n ...state.escapes.filter((t48) =\u003e !remove.has(t48.connection_name)),\n ...retained\n ]\n };\n const choices = yield* probe(\n connection,\n fixedCopper(reduced),\n reduced,\n remaining\n );\n for (const choice of choices)\n if (choice.blockers.length \u003c= 3)\n for (const trace of choice.blockers)\n additions.add(trace.connection_name);\n const best = choices.sort(\n (a2, b2) =\u003e a2.blockers.length - b2.blockers.length\n )[0];\n for (const trace of best?.blockers ?? [])\n additions.add(trace.connection_name);\n }\n for (const name of additions) remove.add(name);\n return remove;\n}\nfunction* findViaAwareSignalPocket(state) {\n const { native } = state, carriers = [...state.retained, ...state.traces];\n const pairs = new Set(\n native.differentialPairs?.flatMap((p2) =\u003e p2.connectionNames)\n ), remove = /* @__PURE__ */ new Set();\n const clearance = native.minTraceToPadEdgeClearance ?? native.defaultObstacleMargin ?? 0.075;\n const existing = [...state.escapes, ...carriers].map((trace) =\u003e ({\n name: trace.connection_name,\n copper: fixedCopper({ ...native, obstacles: [], traces: [trace] })\n }));\n const conflicts = new CopperConflictIndex();\n const hits = (copper) =\u003e new Set(\n existing.filter(\n (other) =\u003e conflicts.firstConflict(copper, other.copper, clearance - 1e-8)\n ).map((other) =\u003e other.name)\n );\n for (const connection of native.connections.filter(\n (c2) =\u003e !carriers.some((t48) =\u003e t48.connection_name === c2.name)\n )) {\n const layers = signalLayers(native, connection);\n if (!layers.length) return /* @__PURE__ */ new Set();\n const single = { ...native, connections: [connection] };\n const ends = [[], []];\n for (let variant = 0; variant \u003c 4; variant++) {\n try {\n const generated = routeAlternateSignalDogbones(\n single,\n signalDogboneOptions(single, /* @__PURE__ */ new Map([[connection.name, layers[0]]])),\n variant\n );\n for (let end = 0; end \u003c 2; end++) {\n const point = generated.connections[0].pointsToConnect[end];\n if (ends[end].some(\n (site) =\u003e Math.hypot(site.point.x - point.x, site.point.y - point.y) \u003c 1e-6\n ))\n continue;\n const escape = ownedSignalEscapes(native, generated.traces).find(\n (t48) =\u003e Math.hypot(\n t48.route[0].x - connection.pointsToConnect[end].x,\n t48.route[0].y - connection.pointsToConnect[end].y\n ) \u003c 1e-6\n );\n if (escape) ends[end].push({ point, escape });\n }\n } catch {\n }\n yield;\n }\n let best;\n for (const a2 of ends[0])\n for (const b2 of ends[1]) {\n const escapeCopper = fixedCopper({\n ...native,\n obstacles: [],\n traces: [a2.escape, b2.escape]\n }), viaHits = hits(escapeCopper);\n if ([...viaHits].some((name) =\u003e pairs.has(name))) continue;\n const input = {\n ...native,\n connections: [connection],\n traces: [\n ...native.traces ?? [],\n ...state.escapes.filter((t48) =\u003e !viaHits.has(t48.connection_name)),\n ...carriers.filter((t48) =\u003e pairs.has(t48.connection_name))\n ]\n };\n const hard = fixedCopper(input);\n for (const layer of layers) {\n const local = {\n ...connection,\n pointsToConnect: [a2.point, b2.point].map((point) =\u003e ({\n ...point,\n layer\n }))\n };\n const search = new GridVisibilitySearch(\n new VectorScene(\n input,\n local,\n signalWidth(native, connection),\n hard\n ),\n local.pointsToConnect[0],\n local.pointsToConnect[1],\n carriers.filter((t48) =\u003e !pairs.has(t48.connection_name)).flatMap(routeCopper),\n 100,\n void 0,\n {\n checkReachability: true,\n maxLength: maximumCarrierLength(native, connection.name) - length(a2.escape.route) - length(b2.escape.route)\n }\n );\n try {\n let steps = 0;\n while (!search.solved \u0026\u0026 !search.failed \u0026\u0026 steps++ \u003c 4e3) {\n search.step();\n yield;\n }\n if (search.solved) {\n const trace = signalTrace(\n native,\n connection,\n search.result,\n layer\n ), names = hits([...escapeCopper, ...routeCopper(trace)]), cost = names.size * 1e3 + length(trace.route);\n if (![...names].some((name) =\u003e pairs.has(name)) \u0026\u0026 (!best || cost \u003c best.cost))\n best = { cost, names };\n }\n } finally {\n search.cancel();\n }\n }\n }\n remove.add(connection.name);\n for (const name of best?.names ?? []) remove.add(name);\n }\n return remove;\n}\n\n// lib/negotiate-signal-sites.ts\nfunction* negotiateSignalSites(state, remove, stopWithOneRemaining = false) {\n if (!remove.size) return null;\n const { native } = state;\n const all = [...state.retained, ...state.traces];\n const stable = all.filter((trace) =\u003e !remove.has(trace.connection_name));\n const fixedEscapes = state.escapes.filter(\n (trace) =\u003e !remove.has(trace.connection_name)\n );\n const targets = new Map([\n ...state.pending.connections.map((c2) =\u003e [\n c2.name,\n c2.pointsToConnect[0].layer\n ]),\n ...all.map((t48) =\u003e [\n t48.connection_name,\n t48.route[0].layer\n ])\n ]);\n const base = {\n ...native,\n connections: native.connections.filter((c2) =\u003e remove.has(c2.name)),\n traces: [...native.traces ?? [], ...fixedEscapes, ...stable]\n };\n if (!base.connections.length) return null;\n const hard = fixedCopper(base), variants = /* @__PURE__ */ new Map();\n const histories = /* @__PURE__ */ new Map(), projectors = /* @__PURE__ */ new Map();\n const clearance = native.minTraceToPadEdgeClearance ?? native.defaultObstacleMargin ?? 0.075;\n for (const connection of base.connections) {\n const single = { ...base, connections: [connection] }, ends = [[], []];\n for (let variant = 0; variant \u003c 4; variant++) {\n try {\n const generated = routeAlternateSignalDogbones(\n single,\n signalDogboneOptions(single, targets),\n variant\n );\n for (let end = 0; end \u003c 2; end++) {\n const point = generated.connections[0].pointsToConnect[end];\n if (ends[end].some(\n (site) =\u003e Math.hypot(site.point.x - point.x, site.point.y - point.y) \u003c 1e-6\n ))\n continue;\n const escape = ownedSignalEscapes(native, generated.traces).find(\n (t48) =\u003e Math.hypot(\n t48.route[0].x - connection.pointsToConnect[end].x,\n t48.route[0].y - connection.pointsToConnect[end].y\n ) \u003c 1e-6\n );\n if (escape) ends[end].push({ point, escape });\n }\n } catch {\n }\n yield;\n }\n const choices = [];\n for (const a2 of ends[0])\n for (const b2 of ends[1])\n for (const layer of signalLayers(native, connection)) {\n const local = {\n ...connection,\n pointsToConnect: [a2.point, b2.point].map((point) =\u003e ({\n ...point,\n layer\n }))\n };\n const escapes = [a2.escape, b2.escape];\n if (escapes.some(\n (t48) =\u003e !t48.route.some(\n (p2) =\u003e p2.route_type === \"via\" \u0026\u0026 p2.layers?.includes(layer)\n )\n ))\n continue;\n const maxLength = maximumCarrierLength(\n { ...native, traces: [...native.traces ?? [], ...escapes] },\n connection.name\n );\n const escapeCopper = fixedCopper({\n ...base,\n obstacles: [],\n traces: escapes\n });\n const scene = new VectorScene(\n base,\n local,\n signalWidth(native, connection),\n hard\n );\n const search = new GridVisibilitySearch(\n scene,\n local.pointsToConnect[0],\n local.pointsToConnect[1],\n [],\n 0,\n void 0,\n { checkReachability: true, maxLength }\n );\n try {\n let steps = 0;\n while (!search.solved \u0026\u0026 !search.failed \u0026\u0026 steps++ \u003c 3e3) {\n search.step();\n yield;\n }\n if (search.solved)\n choices.push({\n connection: local,\n escapes,\n escapeCopper,\n scene,\n layer,\n length: length(search.result),\n maxLength\n });\n } finally {\n search.cancel();\n }\n }\n choices.sort((a2, b2) =\u003e a2.length - b2.length);\n if (!choices.length) return null;\n variants.set(connection.name, choices);\n }\n const copperConflicts = new CopperConflictIndex();\n const overlap = (a2, b2) =\u003e copperConflicts.firstConflict(a2, b2, clearance - 1e-8);\n const conflicts = new RouteConflictIndex(), pools2 = /* @__PURE__ */ new Map(), signatures = /* @__PURE__ */ new Map(), compatibility = /* @__PURE__ */ new Map();\n let candidateId = 0;\n const compatible = (a2, b2) =\u003e {\n const key = a2.id \u003c b2.id ? `${a2.id},${b2.id}` : `${b2.id},${a2.id}`;\n const cached = compatibility.get(key);\n if (cached !== void 0) return cached;\n const required = (a2.trace.route[0].width + b2.trace.route[0].width) / 2 + clearance;\n const clash = a2.layer === b2.layer \u0026\u0026 conflicts.firstConflict(\n a2.trace.route,\n b2.trace.route,\n required - 1e-8\n ) || overlap(a2.escapeCopper, b2.copper) || overlap(b2.escapeCopper, a2.copper);\n compatibility.set(key, !clash);\n return !clash;\n };\n const addCandidate = (candidate) =\u003e {\n const name = candidate.connection.name, key = JSON.stringify([\n candidate.escapes.map((t48) =\u003e t48.route),\n candidate.trace.route\n ]);\n let seen = signatures.get(name);\n if (!seen) signatures.set(name, seen = /* @__PURE__ */ new Set());\n if (seen.has(key)) return;\n seen.add(key);\n let pool = pools2.get(name);\n if (!pool) pools2.set(name, pool = []);\n pool.push(candidate);\n if (pool.length \u003e 48) pool.splice(8, 1);\n };\n const select = () =\u003e {\n if (base.connections.some((c2) =\u003e !pools2.get(c2.name)?.length)) return;\n let nodes = 0, answer;\n const visit = (selected, domains) =\u003e {\n if (++nodes \u003e 4e3) return;\n if (!domains.length) {\n answer = selected;\n return;\n }\n domains.sort((a2, b2) =\u003e a2.length - b2.length);\n for (const option of domains[0]) {\n const remaining = domains.slice(1).map((domain) =\u003e domain.filter((other) =\u003e compatible(option, other)));\n if (remaining.some((domain) =\u003e !domain.length)) continue;\n visit([...selected, option], remaining);\n if (answer) return;\n }\n };\n visit(\n [],\n base.connections.map((c2) =\u003e [...pools2.get(c2.name)].reverse())\n );\n return answer;\n };\n const routed = /* @__PURE__ */ new Map(), queue = [...base.connections].sort(\n (a2, b2) =\u003e variants.get(a2.name).length - variants.get(b2.name).length\n ), visits = /* @__PURE__ */ new Map();\n const finish = () =\u003e {\n const chosen = [...routed.values()], escapes = [...fixedEscapes, ...chosen.flatMap((option) =\u003e option.escapes)];\n const connections = base.connections.map(\n (c2) =\u003e routed.get(c2.name)?.connection ?? variants.get(c2.name)[0].connection\n );\n return {\n native,\n pending: {\n ...base,\n connections,\n traces: [...native.traces ?? [], ...escapes, ...stable]\n },\n escapes,\n retained: stable,\n traces: chosen.map((option) =\u003e option.trace)\n };\n };\n for (let iteration = 0; queue.length \u0026\u0026 iteration \u003c 1200; iteration++) {\n const connection = queue.shift(), choices = variants.get(connection.name), visit = visits.get(connection.name) ?? 0;\n visits.set(connection.name, visit + 1);\n routed.delete(connection.name);\n const others = [...routed.values()], soft = others.flatMap((option) =\u003e option.copper);\n let best;\n for (let k2 = 0; k2 \u003c Math.min(choices.length, 4); k2++) {\n const option = choices[(visit * 4 + k2) % choices.length], { scene, connection: local, layer } = option;\n if (stopWithOneRemaining \u0026\u0026 best) {\n const [a2, b2] = local.pointsToConnect;\n const forcedHits = others.filter(\n (other) =\u003e overlap(option.escapeCopper, other.copper)\n ).length;\n if (Math.hypot(a2.x - b2.x, a2.y - b2.y) + 100 * forcedHits \u003e best.score + 1e-7)\n continue;\n }\n if (!projectors.has(layer)) {\n const projector = new GridHistoryProjector(scene);\n projectors.set(layer, projector);\n histories.set(layer, new Float32Array(projector.cellCount));\n }\n const search = new GridVisibilitySearch(\n scene,\n local.pointsToConnect[0],\n local.pointsToConnect[1],\n soft,\n 10 + iteration,\n histories.get(layer),\n {\n checkReachability: true,\n maxLength: option.maxLength,\n paretoLength: Number.isFinite(option.maxLength)\n }\n );\n try {\n let steps = 0;\n while (!search.solved \u0026\u0026 !search.failed \u0026\u0026 steps++ \u003c 3e3) {\n search.step();\n yield;\n }\n if (search.solved) {\n const trace = signalTrace(native, connection, search.result, layer), copper = [...option.escapeCopper, ...routeCopper(trace)];\n const hits = others.filter((other) =\u003e overlap(copper, other.copper)), score = length(trace.route) + hits.length * 100;\n const candidate = {\n ...option,\n id: candidateId++,\n trace,\n copper,\n hits,\n score\n };\n if (!stopWithOneRemaining) addCandidate(candidate);\n if (!best || score \u003c best.score) best = candidate;\n }\n } finally {\n search.cancel();\n }\n }\n if (!best) {\n queue.push(connection);\n continue;\n }\n for (const other of best.hits) {\n const hit = overlap(best.copper, other.copper);\n if (hit) {\n const [a2, b2] = hit;\n projectors.get(a2.layer)?.penalizeIntersection(\n histories.get(a2.layer),\n a2.a,\n a2.b,\n b2.a,\n b2.b,\n a2.radius + b2.radius + clearance,\n true\n );\n }\n routed.delete(other.connection.name);\n if (!queue.some((c2) =\u003e c2.name === other.connection.name))\n queue.push(\n base.connections.find((c2) =\u003e c2.name === other.connection.name)\n );\n }\n routed.set(connection.name, best);\n if (stopWithOneRemaining \u0026\u0026 routed.size \u003e= base.connections.length - 1)\n return finish();\n if (!stopWithOneRemaining \u0026\u0026 iteration % 8 === 0 \u0026\u0026 routed.size \u003e= base.connections.length - 3) {\n const selected = select();\n if (selected) {\n for (const option of selected)\n routed.set(option.connection.name, option);\n queue.length = 0;\n }\n }\n yield;\n }\n return routed.size === base.connections.length ? finish() : null;\n}\n\n// lib/route-fresh-shared-buses.ts\nfunction* routeFreshSharedBuses(native, allocation, originalEscapes, terminalLayers, options) {\n const pairNames = new Set(\n native.differentialPairs?.flatMap((pair) =\u003e pair.connectionNames)\n );\n const busNames = new Set(native.buses?.flatMap((bus) =\u003e bus.connectionNames));\n const busLayerLoads = /* @__PURE__ */ new Map();\n for (const bus of allocation.buses ?? []) {\n const occupied = new Set(\n allocation.connections.filter((c2) =\u003e bus.connectionNames.includes(c2.name)).map((c2) =\u003e c2.pointsToConnect[0].layer)\n );\n for (const layer of occupied)\n busLayerLoads.set(layer, (busLayerLoads.get(layer) ?? 0) + 1);\n }\n const sharedTimingLayers = [...busLayerLoads.values()].some(\n (count) =\u003e count \u003e 1\n );\n const pairEscapes = originalEscapes.filter(\n (trace) =\u003e pairNames.has(trace.connection_name)\n );\n const targets = new Map(\n allocation.connections.map((connection) =\u003e [\n connection.name,\n connection.pointsToConnect[0].layer\n ])\n );\n const layers = new Map(\n native.connections.map((connection) =\u003e [\n connection.name,\n signalLayers(native, connection)\n ])\n );\n const direction = native.connections.reduce(\n (sum, c2) =\u003e ({\n x: sum.x + c2.pointsToConnect[1].x - c2.pointsToConnect[0].x,\n y: sum.y + c2.pointsToConnect[1].y - c2.pointsToConnect[0].y\n }),\n { x: 0, y: 0 }\n );\n const nearestAttachments = Math.abs(direction.x) \u003e Math.abs(direction.y);\n for (const paired of planSharedPairCorridors(\n allocation,\n native.buses?.some((bus) =\u003e bus.maxLength !== void 0) ? layers : terminalLayers,\n true\n )) {\n if (!paired) {\n yield;\n continue;\n }\n if (exteriorPairSpacingReports(allocation, paired).some(\n (report) =\u003e busNames.has(report.connectionNames[0]) \u0026\u0026 (report.separatedExteriorLengthMm ?? 0) \u003e 0.05 * length(\n paired.find(\n (trace) =\u003e trace.connection_name === report.connectionNames[0]\n ).route\n )\n ))\n continue;\n const ordinary = {\n ...native,\n connections: native.connections.filter(\n (connection) =\u003e !pairNames.has(connection.name)\n ),\n traces: [...native.traces ?? [], ...pairEscapes, ...paired]\n };\n const generated = yield* reachableSignalDogbones(\n ordinary,\n signalDogboneOptions(ordinary, targets),\n layers,\n nearestAttachments\n );\n if (!generated) continue;\n const escapes = [...pairEscapes, ...generated.traces];\n const pending = {\n ...native,\n connections: generated.connections,\n buses: native.buses?.some((bus) =\u003e bus.maxLength !== void 0) ? native.buses.map((bus) =\u003e ({\n ...bus,\n connectionNames: bus.connectionNames.filter(\n (name) =\u003e generated.connections.some((c2) =\u003e c2.name === name)\n )\n })).filter((bus) =\u003e bus.connectionNames.length) : [],\n differentialPairs: [],\n traces: [...native.traces ?? [], ...escapes, ...paired]\n };\n const widths = new Map(\n pending.connections.map((c2) =\u003e [c2.name, signalWidth(native, c2)])\n );\n const route = negotiateLanes(\n pending,\n pending.connections,\n fixedCopper(pending),\n [],\n widths,\n void 0,\n layers,\n () =\u003e false,\n true,\n true\n );\n let state;\n try {\n let step = route.next(), iterations = 0, lastImprovement = 0, bestCount = 0;\n while (!step.done \u0026\u0026 iterations++ \u003c 3e5) {\n bestCount = Math.max(bestCount, step.value.length);\n if (native.buses?.some((b2) =\u003e b2.maxLength !== void 0) \u0026\u0026 iterations \u003e 6e4 \u0026\u0026 bestCount \u003c pending.connections.length - 3)\n break;\n if (step.value.length \u003e= Math.max(\n 1,\n pending.connections.length - (native.buses?.some((b2) =\u003e b2.maxLength !== void 0) ? 4 : 2)\n ) \u0026\u0026 (!state || step.value.length \u003e state.traces.length)) {\n lastImprovement = iterations;\n state = {\n native,\n pending: structuredClone(pending),\n escapes,\n retained: paired,\n traces: step.value\n };\n }\n if (state \u0026\u0026 !sharedTimingLayers) break;\n if (step.value.length === pending.connections.length) break;\n if (state \u0026\u0026 iterations - lastImprovement \u003e= (native.buses?.some((b2) =\u003e b2.maxLength !== void 0) ? 12e3 : 6e4))\n break;\n yield;\n step = route.next();\n }\n if (step.done \u0026\u0026 step.value)\n state = {\n native,\n pending,\n escapes,\n retained: paired,\n traces: step.value\n };\n } finally {\n route.return(null);\n }\n if (!state) continue;\n if (native.buses?.some((b2) =\u003e b2.maxLength !== void 0) \u0026\u0026 state.traces.length \u003c state.pending.connections.length) {\n const repaired = yield* repairSharedLayerConflicts(\n state.pending,\n state.traces,\n layers,\n { maxNodes: 256 }\n );\n if (repaired) state = { ...state, traces: repaired };\n }\n if (state.retained.length + state.traces.length \u003c native.connections.length) {\n const pocket = yield* expandSignalSitePocket(state);\n state = (yield* negotiateSignalSites(state, pocket, true)) ?? void 0;\n if (!state) continue;\n }\n if (state.retained.length + state.traces.length \u003c native.connections.length) {\n const pocket = yield* findViaAwareSignalPocket(state);\n state = (yield* negotiateSignalSites(state, pocket)) ?? void 0;\n if (!state) continue;\n }\n let traces = [...state.retained, ...state.traces];\n if (traces.length !== native.connections.length) continue;\n const input = {\n ...native,\n connections: native.connections.map((connection) =\u003e {\n const trace = traces.find((t48) =\u003e t48.connection_name === connection.name);\n return {\n ...connection,\n pointsToConnect: [trace.route[0], trace.route.at(-1)]\n };\n }),\n traces: [...native.traces ?? [], ...state.escapes]\n };\n const fixed = fixedCopper(input);\n for (let pass = 0; pass \u003c 3; pass++) {\n for (let index2 = 0; index2 \u003c traces.length; index2++) {\n const trace = traces[index2];\n if (trace.coupledSection) continue;\n const width = trace.route[0].width, layer = trace.route[0].layer;\n const connection = input.connections.find(\n (c2) =\u003e c2.name === trace.connection_name\n );\n traces[index2] = {\n ...trace,\n route: reduceOrdinaryTurns(\n trace.route,\n new VectorScene(input, connection, width, [\n ...fixed,\n ...traces.flatMap(routeCopper)\n ])\n ).map((point) =\u003e ({ ...point, route_type: \"wire\", layer, width }))\n };\n }\n traces = chamferOrdinaryCorners(input, traces);\n yield;\n }\n const matcher = BusLanesSolver.forRefinement(input, traces, options);\n try {\n while (!matcher.solved \u0026\u0026 !matcher.failed) {\n matcher.step();\n yield;\n }\n if (matcher.solved)\n return { input, traces: matcher.traces, escapes: state.escapes };\n } finally {\n if (!matcher.solved \u0026\u0026 !matcher.failed) matcher.tryFinalAcceptance();\n }\n }\n return null;\n}\n\n// lib/is-unrouted-component-pad.ts\nfunction isUnroutedComponentPad(input, connection, point) {\n const owners = new Set(\n [\n connection.name,\n connection.source_trace_id,\n point.pointId,\n point.pcb_port_id\n ].filter((s2) =\u003e !!s2)\n );\n const layers = point.layers ?? [point.layer];\n const pad = input.obstacles.find((o2) =\u003e {\n if (!o2.componentId || !o2.connectedTo.some((id) =\u003e owners.has(id)) || !o2.layers.some((l2) =\u003e layers.includes(l2)))\n return false;\n const angle = -(o2.ccwRotationDegrees ?? 0) * Math.PI / 180;\n const dx2 = point.x - o2.center.x, dy2 = point.y - o2.center.y;\n if (o2.shape === \"circle\") return Math.hypot(dx2, dy2) \u003c= o2.width / 2 + 1e-8;\n const x2 = dx2 * Math.cos(angle) - dy2 * Math.sin(angle), y2 = dx2 * Math.sin(angle) + dy2 * Math.cos(angle);\n return Math.abs(x2) \u003c= o2.width / 2 + 1e-8 \u0026\u0026 Math.abs(y2) \u003c= o2.height / 2 + 1e-8;\n });\n if (!pad) return false;\n return !fixedCopper({ ...input, obstacles: [] }).some(\n (c2) =\u003e layers.includes(c2.layer) \u0026\u0026 c2.owners.some((id) =\u003e owners.has(id)) \u0026\u0026 clearanceToCopper(point, point, c2) \u003c= 1e-8\n );\n}\n\n// lib/rematch-trapped-signal-dogbones.ts\nfunction* reachable(input, connection, fixed, width, layer, end = connection.pointsToConnect[1], bounds) {\n const local = {\n ...connection,\n pointsToConnect: connection.pointsToConnect.map((point, index2) =\u003e ({\n ...index2 ? end : point,\n layer\n }))\n };\n const search = new GridVisibilitySearch(\n new VectorScene(input, local, width, fixed),\n local.pointsToConnect[0],\n local.pointsToConnect[1],\n [],\n 0,\n void 0,\n bounds ? { bounds } : void 0\n );\n try {\n while (!search.solved \u0026\u0026 !search.failed) {\n search.step();\n yield;\n }\n return search.solved;\n } finally {\n if (!search.solved \u0026\u0026 !search.failed) search.cancel();\n }\n}\nfunction componentField(input, source, endpoint) {\n const point = source.pointsToConnect[endpoint];\n const owners = new Set(\n [\n source.name,\n source.source_trace_id,\n point.pcb_port_id,\n point.pointId\n ].filter(Boolean)\n );\n const pad = input.obstacles.filter(\n (obstacle) =\u003e obstacle.componentId \u0026\u0026 obstacle.connectedTo.some((owner) =\u003e owners.has(owner))\n ).sort((a2, b2) =\u003e distance(a2.center, point) - distance(b2.center, point))[0];\n if (!pad) return;\n const pads = input.obstacles.filter(\n (obstacle) =\u003e obstacle.componentId === pad.componentId\n );\n const rectangles = pads.map((obstacle) =\u003e {\n const angle = (obstacle.ccwRotationDegrees ?? 0) * Math.PI / 180;\n return {\n center: obstacle.center,\n width: Math.abs(Math.cos(angle)) * obstacle.width + Math.abs(Math.sin(angle)) * obstacle.height,\n height: Math.abs(Math.sin(angle)) * obstacle.width + Math.abs(Math.cos(angle)) * obstacle.height\n };\n });\n return {\n minX: Math.min(\n ...rectangles.map((obstacle) =\u003e obstacle.center.x - obstacle.width / 2)\n ),\n maxX: Math.max(\n ...rectangles.map((obstacle) =\u003e obstacle.center.x + obstacle.width / 2)\n ),\n minY: Math.min(\n ...rectangles.map((obstacle) =\u003e obstacle.center.y - obstacle.height / 2)\n ),\n maxY: Math.max(\n ...rectangles.map((obstacle) =\u003e obstacle.center.y + obstacle.height / 2)\n )\n };\n}\nfunction* trappedEndpoints(input, source, connection, fixed, width, layers) {\n const result = [];\n const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;\n const margin = 3 * (width + clearance);\n for (const endpoint of [0, 1]) {\n const field = componentField(input, source, endpoint);\n if (!field) continue;\n const point = connection.pointsToConnect[endpoint];\n const edge = width / 2 + (input.minBoardEdgeClearance ?? 0);\n const bounds = {\n minX: Math.max(input.bounds.minX + edge, field.minX - 2 * margin),\n maxX: Math.min(input.bounds.maxX - edge, field.maxX + 2 * margin),\n minY: Math.max(input.bounds.minY + edge, field.minY - 2 * margin),\n maxY: Math.min(input.bounds.maxY - edge, field.maxY + 2 * margin)\n };\n const goals = [\n { ...point, x: Math.max(bounds.minX, field.minX - margin) },\n { ...point, x: Math.min(bounds.maxX, field.maxX + margin) },\n { ...point, y: Math.max(bounds.minY, field.minY - margin) },\n { ...point, y: Math.min(bounds.maxY, field.maxY + margin) }\n ].filter(\n (goal) =\u003e goal.x \u003c field.minX || goal.x \u003e field.maxX || goal.y \u003c field.minY || goal.y \u003e field.maxY\n ).sort((a2, b2) =\u003e distance(point, a2) - distance(point, b2));\n let escaped = false;\n for (const layer of layers) {\n const local = { ...connection, pointsToConnect: [point, point] };\n for (const goal of goals) {\n if (yield* reachable(input, local, fixed, width, layer, goal, bounds)) {\n escaped = true;\n break;\n }\n }\n if (escaped) break;\n }\n if (goals.length \u0026\u0026 !escaped) result.push(endpoint);\n }\n return result;\n}\nfunction* rematchTrappedSignalDogbones(native, pending, completed, escapes, terminalLayers, reachableLayersByConnection) {\n const result = {\n connections: structuredClone(pending.connections),\n escapes: [...escapes]\n };\n const physicalLayers = getCopperLayerNames(native.layerCount);\n for (const [index2, connection] of result.connections.entries()) {\n const source = native.connections.find(\n (original) =\u003e original.name === connection.name\n );\n const owned = result.escapes.filter(\n (trace) =\u003e trace.connection_name === connection.name\n );\n const vias = owned.map(\n (trace) =\u003e trace.route.find((point) =\u003e point.route_type === \"via\")\n );\n if (!source || owned.length !== 2 || vias.some((via) =\u003e !via) || source.pointsToConnect.some(\n (point) =\u003e !isUnroutedComponentPad(native, source, point)\n ))\n continue;\n const layers = (terminalLayers.get(connection.name) ?? [\n connection.pointsToConnect[0].layer\n ]).filter((layer) =\u003e layer !== \"top\" \u0026\u0026 physicalLayers.includes(layer));\n if (!layers.length) continue;\n const width = connection.nominalTraceWidth ?? connection.width ?? native.minTraceWidth;\n const sceneInput = {\n ...pending,\n connections: result.connections,\n traces: [...native.traces ?? [], ...result.escapes, ...completed]\n };\n const fixed = fixedCopper(sceneInput);\n const blockedLayers = [];\n let reachableLayers = 0;\n for (const layer of layers) {\n if (yield* reachable(sceneInput, connection, fixed, width, layer))\n reachableLayers++;\n else blockedLayers.push(layer);\n }\n reachableLayersByConnection?.set(\n connection.name,\n layers.filter((layer) =\u003e !blockedLayers.includes(layer))\n );\n if (reachableLayers \u003e= Math.min(2, layers.length)) continue;\n let shared = false;\n const trapped = yield* trappedEndpoints(\n sceneInput,\n source,\n connection,\n fixed,\n width,\n blockedLayers\n );\n if (!trapped.length \u0026\u0026 reachableLayers === 0) trapped.push(0, 1);\n if (!trapped.length) continue;\n const base = {\n ...native,\n connections: [source],\n traces: [\n ...native.traces ?? [],\n ...result.escapes.filter(\n (trace) =\u003e trace.connection_name !== connection.name\n ),\n ...completed\n ]\n };\n const queue = trapped.map((endpoint) =\u003e [vias[endpoint]]);\n const seen = /* @__PURE__ */ new Set([\n JSON.stringify(connection.pointsToConnect.map(({ x: x2, y: y2 }) =\u003e [x2, y2]))\n ]);\n for (let trial = 0; trial \u003c 16 \u0026\u0026 queue.length; trial++) {\n const excluded = queue.shift();\n const searchInput = {\n ...base,\n obstacles: [\n ...base.obstacles,\n ...excluded.map((point) =\u003e ({\n shape: \"circle\",\n center: { x: point.x, y: point.y },\n width: 1e-6,\n height: 1e-6,\n layers: physicalLayers,\n connectedTo: []\n }))\n ]\n };\n let candidate;\n try {\n candidate = routeLocalSignalDogbones(\n searchInput,\n {\n targetLayers: /* @__PURE__ */ new Map([\n [connection.name, connection.pointsToConnect[0].layer]\n ]),\n viaDiameter: Math.max(\n ...vias.map(\n (via) =\u003e via.via_diameter ?? native.minViaPadDiameter ?? 0.6\n )\n ),\n viaHoleDiameter: Math.max(\n ...vias.map(\n (via) =\u003e via.via_hole_diameter ?? native.minViaHoleDiameter ?? 0.3\n )\n ),\n traceWidth: Math.max(\n ...owned.flatMap(\n (trace) =\u003e trace.route.flatMap(\n (point) =\u003e point.route_type === \"wire\" ? [point.width] : []\n )\n )\n ),\n clearance: native.minTraceToPadEdgeClearance ?? native.defaultObstacleMargin ?? 0.075,\n holeToHoleClearance: native.minViaHoleEdgeToViaHoleEdgeClearance,\n boardEdgeClearance: native.minBoardEdgeClearance,\n allowBlindAndBuriedVias: native.allowBlindAndBuriedVias ?? false\n }\n );\n } catch {\n yield;\n continue;\n }\n yield;\n const replacement = {\n ...connection,\n pointsToConnect: candidate.connections[0].pointsToConnect\n };\n const key = JSON.stringify(\n replacement.pointsToConnect.map(({ x: x2, y: y2 }) =\u003e [x2, y2])\n );\n if (seen.has(key)) continue;\n seen.add(key);\n const traces = candidate.traces.map((trace) =\u003e ({\n ...trace,\n source_trace_id: source.source_trace_id ?? connection.name\n }));\n const candidateInput = {\n ...sceneInput,\n traces: [...base.traces, ...traces]\n };\n const candidateFixed = fixedCopper(candidateInput);\n let candidateReachableLayers = 0;\n const candidateLayers = [];\n for (const layer of layers) {\n if (yield* reachable(\n candidateInput,\n replacement,\n candidateFixed,\n width,\n layer\n )) {\n candidateReachableLayers++;\n candidateLayers.push(layer);\n }\n }\n shared = candidateReachableLayers \u003e reachableLayers;\n if (shared) {\n reachableLayersByConnection?.set(connection.name, candidateLayers);\n result.connections[index2] = replacement;\n result.escapes = [\n ...result.escapes.filter(\n (trace) =\u003e trace.connection_name !== connection.name\n ),\n ...traces\n ];\n break;\n }\n for (const endpoint of yield* trappedEndpoints(\n candidateInput,\n source,\n replacement,\n candidateFixed,\n width,\n blockedLayers\n )) {\n const point = replacement.pointsToConnect[endpoint];\n if (!excluded.some((old) =\u003e distance(old, point) \u003c 1e-8))\n queue.push([...excluded, point]);\n }\n }\n }\n return result;\n}\n\n// lib/route-shared-layer-buses.ts\nfunction* routeSharedLayerBuses(native, allocation, escapes, terminalLayers, options) {\n const busNames = new Set(allocation.buses?.flatMap((b2) =\u003e b2.connectionNames));\n const pairNames = new Set(\n allocation.differentialPairs?.flatMap((p2) =\u003e p2.connectionNames)\n );\n const constrained = /* @__PURE__ */ new Set([...busNames, ...pairNames]);\n const widths = new Map(\n allocation.connections.map((c2) =\u003e [c2.name, signalWidth(allocation, c2)])\n );\n const access = /* @__PURE__ */ new Map();\n const identities = /* @__PURE__ */ new WeakMap();\n let serial = 0;\n const fixed = fixedCopper(allocation);\n const bounded = allocation.buses?.some((bus) =\u003e bus.maxLength !== void 0);\n const availableLayers = bounded ? new Map(native.connections.map((c2) =\u003e [c2.name, signalLayers(native, c2)])) : terminalLayers;\n const plans = planSharedPairCorridors(allocation, availableLayers);\n for (const paired of plans) {\n if (!paired) {\n yield;\n continue;\n }\n const local = structuredClone(allocation);\n for (const c2 of local.connections) {\n const trace = paired.find((t48) =\u003e t48.connection_name === c2.name);\n if (trace)\n for (const p2 of c2.pointsToConnect)\n p2.layer = trace.route[0].layer;\n }\n const busInput = {\n ...local,\n connections: local.connections.filter((c2) =\u003e constrained.has(c2.name))\n };\n const ordinary = busInput.connections.filter((c2) =\u003e !pairNames.has(c2.name));\n let accessible = true;\n const pairedCopper = paired.flatMap(routeCopper);\n const reachableLayers = /* @__PURE__ */ new Map();\n for (const connection of ordinary) {\n const reachableForConnection = [];\n for (const layer of bounded ? availableLayers.get(connection.name) : [connection.pointsToConnect[0].layer]) {\n const key = JSON.stringify([\n connection.name,\n layer,\n paired.filter((t48) =\u003e t48.route[0].layer === layer).map((t48) =\u003e {\n if (!identities.has(t48)) identities.set(t48, serial++);\n return identities.get(t48);\n })\n ]);\n let reachable2 = access.get(key);\n if (reachable2 === void 0) {\n const candidate = {\n ...connection,\n pointsToConnect: connection.pointsToConnect.map((p2) =\u003e ({\n ...p2,\n layer\n }))\n };\n const search = new GridVisibilitySearch(\n new VectorScene(busInput, candidate, widths.get(connection.name), [\n ...fixed,\n ...pairedCopper\n ]),\n candidate.pointsToConnect[0],\n candidate.pointsToConnect[1],\n [],\n 0,\n void 0,\n bounded ? {\n checkReachability: true,\n maxLength: maximumCarrierLength(busInput, connection.name)\n } : void 0\n );\n try {\n let steps2 = 0;\n while (!search.solved \u0026\u0026 !search.failed \u0026\u0026 steps2++ \u003c 4e3) {\n search.step();\n yield;\n }\n if (search.solved || search.failed) {\n reachable2 = search.solved;\n access.set(key, reachable2);\n }\n } finally {\n search.cancel();\n }\n }\n if (reachable2 !== false) reachableForConnection.push(layer);\n }\n if (!reachableForConnection.length) {\n accessible = false;\n break;\n }\n reachableLayers.set(connection.name, reachableForConnection);\n }\n if (!accessible) continue;\n const route = negotiateLanes(\n busInput,\n ordinary,\n fixedCopper(local),\n paired,\n widths,\n void 0,\n bounded ? reachableLayers : /* @__PURE__ */ new Map(),\n () =\u003e !bounded,\n true\n );\n let state = route.next(), steps = 0;\n try {\n while (!state.done \u0026\u0026 steps++ \u003c (bounded ? 3e5 : 16e3)) {\n yield;\n state = route.next();\n }\n } finally {\n if (!state.done) route.return(null);\n }\n if (!state.done || !state.value) continue;\n let matched = state.value;\n let valid = true;\n let jointMatched = false;\n if (bounded) {\n const matcher = BusLanesSolver.forRefinement(busInput, matched, options);\n try {\n while (!matcher.solved \u0026\u0026 !matcher.failed) {\n matcher.step();\n yield;\n }\n if (matcher.solved) {\n matched = matcher.traces;\n jointMatched = true;\n }\n } finally {\n if (!matcher.solved \u0026\u0026 !matcher.failed) matcher.tryFinalAcceptance();\n }\n }\n for (const bus of jointMatched ? [] : local.buses ?? []) {\n const names = new Set(bus.connectionNames);\n const group = {\n ...local,\n connections: local.connections.filter((c2) =\u003e names.has(c2.name)),\n buses: [bus],\n differentialPairs: local.differentialPairs?.filter(\n (p2) =\u003e p2.connectionNames.every((n2) =\u003e names.has(n2))\n ),\n traces: [\n ...local.traces ?? [],\n ...matched.filter((t48) =\u003e !names.has(t48.connection_name))\n ]\n };\n const matcher = BusLanesSolver.forRefinement(\n group,\n matched.filter((t48) =\u003e names.has(t48.connection_name)),\n options\n );\n try {\n while (!matcher.solved \u0026\u0026 !matcher.failed) {\n matcher.step();\n yield;\n }\n if (!matcher.solved) {\n valid = false;\n break;\n }\n matched = [\n ...matched.filter((t48) =\u003e !names.has(t48.connection_name)),\n ...matcher.traces\n ];\n } finally {\n if (!matcher.solved \u0026\u0026 !matcher.failed) matcher.tryFinalAcceptance();\n }\n }\n if (!valid) continue;\n const pending = {\n ...local,\n connections: local.connections.filter((c2) =\u003e !constrained.has(c2.name)),\n buses: [],\n differentialPairs: []\n };\n let rematched = { connections: pending.connections, escapes };\n for (let repair = 0; repair \u003c 2; repair++) {\n if (repair) {\n const reachableLayers2 = new Map(terminalLayers);\n rematched = yield* rematchTrappedSignalDogbones(\n native,\n pending,\n matched,\n escapes,\n terminalLayers,\n reachableLayers2\n );\n if (pending.connections.some(\n (c2) =\u003e reachableLayers2.get(c2.name)?.length === 0\n ) || rematched.escapes.every((trace, i2) =\u003e trace === escapes[i2]))\n break;\n }\n const remainingInput = {\n ...pending,\n connections: rematched.connections,\n traces: [...native.traces ?? [], ...rematched.escapes, ...matched]\n };\n const remaining = new BusLanesSolver(\n remainingInput,\n {\n ...options,\n maxSearchIterations: Math.min(\n options.maxSearchIterations ?? 2e5,\n 2e5\n )\n },\n terminalLayers\n );\n try {\n while (!remaining.solved \u0026\u0026 !remaining.failed) {\n remaining.step();\n yield;\n }\n if (!remaining.solved) continue;\n const traces = [...matched, ...remaining.traces];\n return {\n escapes: rematched.escapes,\n traces,\n input: {\n ...local,\n connections: local.connections.map((c2) =\u003e {\n const t48 = traces.find((t49) =\u003e t49.connection_name === c2.name);\n return {\n ...c2,\n pointsToConnect: [t48.route[0], t48.route.at(-1)]\n };\n }),\n traces: [...native.traces ?? [], ...rematched.escapes]\n }\n };\n } finally {\n if (!remaining.solved \u0026\u0026 !remaining.failed)\n remaining.tryFinalAcceptance();\n }\n }\n }\n return null;\n}\n\n// lib/extend-package-coupling.ts\nvar reverse3 = (t48) =\u003e ({\n ...t48,\n route: t48.route.toReversed(),\n coupledSection: t48.coupledSection ? [\n t48.route.length - 1 - t48.coupledSection[1],\n t48.route.length - 1 - t48.coupledSection[0]\n ] : void 0,\n curvedSegments: t48.curvedSegments?.map((i2) =\u003e t48.route.length - i2)\n});\nvar indexOf = (path, point) =\u003e path.findIndex((p2) =\u003e distance(p2, point) \u003c 1e-7);\nvar preservePoint = (path, point) =\u003e {\n if (indexOf(path, point) \u003e= 0) return path;\n const i2 = path.findIndex(\n (p2, i3) =\u003e i3 \u003e 0 \u0026\u0026 pointSegmentDistanceToPoints(point, path[i3 - 1], p2) \u003c 1e-8\n );\n return i2 \u003c 0 ? path : [...path.slice(0, i2), point, ...path.slice(i2)];\n};\nfunction* extendPackageCoupling(input, original, options = {}) {\n let result = original;\n const fixed = fixedCopper(input);\n const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;\n let budget = 2e3;\n for (const pair of input.differentialPairs ?? []) {\n for (const reversed of [false, true]) {\n for (const side of [0, 1]) {\n if (budget \u003c= 0) return result;\n const nativeRails = pair.connectionNames.map(\n (name) =\u003e result.find((t48) =\u003e t48.connection_name === name)\n );\n if (nativeRails.some((t48) =\u003e !t48?.coupledSection)) continue;\n const rails = nativeRails.map(\n (t48) =\u003e reversed ? reverse3(t48) : t48\n );\n const ref = rails[side], other = rails[1 - side];\n const [rs, re] = ref.coupledSection, [os, oe] = other.coupledSection;\n const width = other.route[0].width, separation = width + (pair.traceGap ?? clearance);\n if (re \u003c 1 || oe \u003c 1 || distance(ref.route[re - 1], ref.route[re]) \u003c 1e-7)\n continue;\n const regions = packageApproachRegions(input, width / 2 + clearance);\n const region = regions.find(\n (r2) =\u003e pointInBox(ref.route.at(-1), r2.copper) \u0026\u0026 pointInBox(other.route.at(-1), r2.copper)\n );\n if (!region || pointInBox(ref.route[re], region.copper)) continue;\n let stop = re + 1;\n while (stop \u003c ref.route.length \u0026\u0026 !pointInBox(ref.route[stop], region.copper))\n stop++;\n if (stop === ref.route.length || ref.curvedSegments?.some((i2) =\u003e i2 \u003e= re \u0026\u0026 i2 \u003c= stop))\n continue;\n const a2 = ref.route[stop - 1], b2 = ref.route[stop];\n let lo = 0, hi = 1;\n for (let i2 = 0; i2 \u003c 40; i2++) {\n const t48 = (lo + hi) / 2;\n if (pointInBox(\n { x: a2.x + (b2.x - a2.x) * t48, y: a2.y + (b2.y - a2.y) * t48 },\n region.copper\n ))\n hi = t48;\n else lo = t48;\n }\n const cut2 = { x: a2.x + (b2.x - a2.x) * hi, y: a2.y + (b2.y - a2.y) * hi };\n const anchor = {\n x: (ref.route[re - 1].x + ref.route[re].x) / 2,\n y: (ref.route[re - 1].y + ref.route[re].y) / 2\n };\n let section = simplify([anchor, ...ref.route.slice(re, stop), cut2]);\n let paths;\n try {\n paths = [separation, -separation].map((d2) =\u003e offsetPath(section, d2));\n } catch {\n continue;\n }\n let path = paths.find(\n (p2) =\u003e pointSegmentDistanceToPoints(\n p2[0],\n other.route[oe - 1],\n other.route[oe]\n ) \u003c 1e-7\n );\n if (!path) continue;\n const localWire = (p2) =\u003e ({\n ...p2,\n route_type: \"wire\",\n width,\n layer: other.route[0].layer\n });\n const localRails = [\n {\n ...ref,\n route: section.map(localWire),\n curvedSegments: [],\n coupledSection: [0, section.length - 1]\n },\n {\n ...other,\n route: path.map(localWire),\n curvedSegments: [],\n coupledSection: [0, path.length - 1]\n }\n ];\n const bevel2 = bevelCoupledCorners(input, [\n ...result.filter(\n (t48) =\u003e !pair.connectionNames.includes(t48.connection_name)\n ),\n ...localRails\n ]);\n section = bevel2.find(\n (t48) =\u003e t48.connection_name === ref.connection_name\n ).route;\n path = bevel2.find(\n (t48) =\u003e t48.connection_name === other.connection_name\n ).route;\n const refRoute = [\n ...ref.route.slice(0, re),\n ...section,\n ...ref.route.slice(stop)\n ].map(localWire);\n const connection = input.connections.find(\n (c2) =\u003e c2.name === other.connection_name\n );\n const scene = new VectorScene(input, connection, width, [\n ...fixed,\n ...result.filter((t48) =\u003e t48.connection_name !== ref.connection_name).flatMap(routeCopper),\n ...routeCopper({ ...ref, route: refRoute })\n ]);\n if (!scene.pathVisible(path)) continue;\n let join = oe + 1;\n while (join \u003c other.route.length \u0026\u0026 !pointInBox(other.route[join], region.copper))\n join++;\n if (join === other.route.length) continue;\n let accepted = false;\n for (; join \u003c other.route.length; join++) {\n if (!pointInBox(other.route[join], region.copper)) continue;\n const search = new GridVisibilitySearch(\n scene,\n path.at(-1),\n other.route[join]\n );\n try {\n let steps = 0;\n while (!search.solved \u0026\u0026 !search.failed \u0026\u0026 steps++ \u003c 256 \u0026\u0026 budget-- \u003e 0) {\n search.step();\n yield;\n }\n if (!search.solved) continue;\n } finally {\n search.cancel();\n }\n const wire = (p2) =\u003e ({\n ...p2,\n route_type: \"wire\",\n layer: other.route[0].layer,\n width\n });\n const next = preservePoint(\n preservePoint(\n simplify([\n ...other.route.slice(0, oe),\n ...path,\n ...reduceOrdinaryTurns(search.result, scene).slice(1),\n ...other.route.slice(join + 1)\n ]).map(wire),\n wire(other.route[os])\n ),\n wire(path.at(-1))\n );\n if (!scene.pathVisible(next) || !tuningPathIsSelfClear(next, width + clearance))\n continue;\n const replacement = [\n {\n ...ref,\n route: refRoute,\n curvedSegments: remapCurvedSegments(ref, refRoute),\n coupledSection: [rs, re + section.length - 1]\n },\n {\n ...other,\n route: next,\n curvedSegments: remapCurvedSegments(other, next),\n coupledSection: [\n indexOf(next, other.route[os]),\n indexOf(next, path.at(-1))\n ]\n }\n ].map((t48) =\u003e reversed ? reverse3(t48) : t48);\n const unchanged = result.filter(\n (t48) =\u003e !pair.connectionNames.includes(t48.connection_name)\n );\n const surrounding = [...fixed, ...unchanged.flatMap(routeCopper)];\n for (const trim of [\n 1.8,\n 1.5,\n 0.75,\n 0.375,\n 0.1875,\n 0.09375,\n 0.046875,\n 0.0234375\n ]) {\n const refinedPair = chamferOrdinaryCorners(\n input,\n result.filter(\n (t48) =\u003e pair.connectionNames.includes(t48.connection_name)\n ).map(\n (t48) =\u003e replacement.find(\n (r2) =\u003e r2.connection_name === t48.connection_name\n )\n ),\n surrounding,\n trim\n );\n const refined = result.map(\n (t48) =\u003e refinedPair.find(\n (r2) =\u003e r2.connection_name === t48.connection_name\n ) ?? t48\n );\n if (!routeAnglesAreConventional(refinedPair) || options.preserveMatching !== false \u0026\u0026 [\n ...busLengthReports(input, refined),\n ...pairLengthReports(input, refined)\n ].some(\n (r2) =\u003e !r2.withinLengthLimit || !r2.aboveMinimumLength || r2.toleranceMm !== null \u0026\u0026 !r2.matched\n ) || sharedPairSpacingReports(input, refined).some((r2) =\u003e !r2.matched))\n continue;\n const copper = [...surrounding, ...refinedPair.flatMap(routeCopper)];\n if (refinedPair.some((t48) =\u003e {\n const w2 = t48.route[0].width;\n return !tuningPathIsSelfClear(t48.route, w2 + clearance) || !new VectorScene(\n input,\n input.connections.find(\n (c2) =\u003e c2.name === t48.connection_name\n ),\n w2,\n copper\n ).pathVisible(t48.route);\n }))\n continue;\n result = refined;\n accepted = true;\n break;\n }\n if (accepted) break;\n }\n }\n }\n }\n return result;\n}\n\n// lib/route-backward-package-buses.ts\nfunction initialPairVariants(input) {\n const busNames = new Set(input.buses?.flatMap((b2) =\u003e b2.connectionNames));\n const groups = independentBusGroups({\n ...input,\n connections: input.connections.filter((c2) =\u003e busNames.has(c2.name))\n });\n return (groups ?? []).map((group) =\u003e {\n const pair = group.differentialPairs?.[0];\n if (!pair) return 0;\n const members = pair.connectionNames.map(\n (name) =\u003e group.connections.find((c2) =\u003e c2.name === name)\n );\n const centers = [0, 1].map((end) =\u003e ({\n x: (members[0].pointsToConnect[end].x + members[1].pointsToConnect[end].x) / 2,\n y: (members[0].pointsToConnect[end].y + members[1].pointsToConnect[end].y) / 2\n }));\n const dx2 = Math.abs(centers[1].x - centers[0].x);\n const dy2 = Math.abs(centers[1].y - centers[0].y);\n const pitch = signalWidth(input, members[0]) + (pair.traceGap ?? input.minTraceToPadEdgeClearance ?? 0.075);\n return Math.min(dx2, dy2) \u003c= 4 * pitch ? 3 : 0;\n });\n}\nfunction* matchRoutes(input, traces, options) {\n const solver = BusLanesSolver.forRefinement(input, traces, options);\n try {\n while (!solver.solved \u0026\u0026 !solver.failed) {\n solver.step();\n yield;\n }\n return solver.solved ? solver.traces : null;\n } finally {\n if (!solver.solved \u0026\u0026 !solver.failed) solver.tryFinalAcceptance();\n }\n}\nfunction* routeBackwardPackageBuses(native, allocation, terminalLayers, options) {\n const targets = new Map(\n allocation.connections.map((c2) =\u003e [c2.name, c2.pointsToConnect[0].layer])\n );\n const alternatives = [0, 2].map(\n (attempt) =\u003e routeAlternateSignalDogbones(\n native,\n signalDogboneOptions(native, targets),\n attempt\n )\n );\n const connections = native.connections.map((c2, i2) =\u003e ({\n ...c2,\n pointsToConnect: [\n alternatives[0].connections[i2].pointsToConnect[0],\n alternatives[1].connections[i2].pointsToConnect[1]\n ]\n }));\n const escapes = ownedSignalEscapes(\n native,\n alternatives.flatMap(\n (alternative, end) =\u003e alternative.traces.filter((trace) =\u003e {\n const connection = native.connections.find(\n (c2) =\u003e c2.name === trace.connection_name\n );\n const point = connection.pointsToConnect[end];\n const start = trace.route[0];\n return start.route_type === \"wire\" \u0026\u0026 Math.hypot(start.x - point.x, start.y - point.y) \u003c 1e-8;\n })\n )\n );\n const fullInput = {\n ...native,\n connections,\n traces: [...native.traces ?? [], ...escapes]\n };\n const standalone = (fullInput.differentialPairs ?? []).filter(\n (pair) =\u003e !fullInput.buses?.some(\n (bus) =\u003e pair.connectionNames.some((name) =\u003e bus.connectionNames.includes(name))\n )\n );\n const heldNames = new Set(standalone.flatMap((p2) =\u003e p2.connectionNames));\n const input = {\n ...fullInput,\n connections: fullInput.connections.filter((c2) =\u003e !heldNames.has(c2.name)),\n differentialPairs: fullInput.differentialPairs?.filter(\n (p2) =\u003e !p2.connectionNames.some((name) =\u003e heldNames.has(name))\n )\n };\n const network = yield* runBoundedRouting(\n preparePairedNetwork(input, terminalLayers, initialPairVariants(input)),\n 6e4\n );\n if (!network) return null;\n const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;\n const regions = packageApproachRegions(\n input,\n Math.max(...network.transforms.map((t48) =\u003e t48.envelope / 2)) + clearance\n );\n const locked = network.transforms.filter(\n (t48) =\u003e regions.some((region) =\u003e pointInBox(t48.center[0], region.copper))\n );\n const dropped = new Set(\n locked.flatMap((t48) =\u003e [\n t48.connection.name,\n ...t48.approaches.map((c2) =\u003e c2.name)\n ])\n );\n const lockedRails = locked.flatMap((t48) =\u003e t48.rails);\n network.local = {\n ...network.local,\n connections: network.local.connections.filter((c2) =\u003e !dropped.has(c2.name)),\n traces: [\n ...(network.local.traces ?? []).filter(\n (t48) =\u003e !locked.some((l2) =\u003e t48.connection_name === l2.connection.name)\n ),\n ...lockedRails\n ],\n buses: network.local.buses?.map((bus) =\u003e ({\n ...bus,\n connectionNames: bus.connectionNames.filter((name) =\u003e !dropped.has(name))\n }))\n };\n network.transforms = network.transforms.filter((t48) =\u003e !locked.includes(t48));\n network.copper = fixedCopper(network.local);\n const generator = negotiateLanes(\n network.local,\n network.local.connections,\n network.copper,\n [],\n network.widths,\n void 0,\n terminalLayers,\n () =\u003e false,\n true\n );\n const originalNames = new Set(input.connections.map((c2) =\u003e c2.name));\n const busNames = new Set(input.buses?.flatMap((b2) =\u003e b2.connectionNames));\n const routeIds = /* @__PURE__ */ new WeakMap();\n const tried = /* @__PURE__ */ new Set();\n let serial = 0;\n let partial = null;\n let state = generator.next();\n let steps = 0;\n try {\n while (!state.done \u0026\u0026 steps++ \u003c 2e5) {\n const current = state.value;\n const missing = network.local.connections.filter(\n (c2) =\u003e !current.some((t48) =\u003e t48.connection_name === c2.name)\n );\n if (missing.length \u003c= 3 \u0026\u0026 missing.every((c2) =\u003e originalNames.has(c2.name) \u0026\u0026 busNames.has(c2.name))) {\n const key = state.value.map((trace) =\u003e {\n if (!routeIds.has(trace)) routeIds.set(trace, serial++);\n return routeIds.get(trace);\n }).join(\",\");\n if (!tried.has(key) \u0026\u0026 tried.size \u003c 24) {\n tried.add(key);\n partial = yield* runBoundedRouting(\n rebuildPairedNetwork(network, [...state.value, ...lockedRails], {\n allowPartial: true\n }),\n 12e3\n );\n if (partial) break;\n }\n }\n yield;\n state = generator.next();\n }\n if (state.done \u0026\u0026 state.value)\n partial = yield* runBoundedRouting(\n rebuildPairedNetwork(network, [...state.value, ...lockedRails]),\n 12e3\n );\n } finally {\n if (!state.done) generator.return(null);\n }\n if (!partial) return null;\n const repaired = yield* repairBusDogbones(native, input, partial, escapes);\n if (!repaired) return null;\n const completeInput = {\n ...fullInput,\n connections: fullInput.connections.map(\n (c2) =\u003e repaired.input.connections.find((next) =\u003e next.name === c2.name) ?? c2\n ),\n traces: repaired.input.traces\n };\n let traces = repaired.traces;\n for (const trace of traces)\n for (const point of completeInput.connections.find(\n (c2) =\u003e c2.name === trace.connection_name\n ).pointsToConnect)\n point.layer = trace.route[0].route_type === \"wire\" ? trace.route[0].layer : point.layer;\n for (const pair of standalone) {\n const members = completeInput.connections.filter(\n (c2) =\u003e pair.connectionNames.includes(c2.name)\n );\n const layers = [\n .../* @__PURE__ */ new Set([\n members[0].pointsToConnect[0].layer,\n ...(terminalLayers.get(members[0].name) ?? []).filter(\n (layer) =\u003e members.every((c2) =\u003e terminalLayers.get(c2.name)?.includes(layer))\n )\n ])\n ].filter((layer) =\u003e layer !== \"top\");\n let paired = null;\n for (const layer of layers) {\n for (const c2 of members)\n for (const point of c2.pointsToConnect) point.layer = layer;\n for (let variant = 0; variant \u003c 6 \u0026\u0026 !paired; variant++)\n paired = yield* runBoundedRouting(\n routeCoupledPair(\n completeInput,\n pair,\n [...fixedCopper(completeInput), ...traces.flatMap(routeCopper)],\n { copper: [], penalty: 0, variant }\n ),\n 12e3\n );\n if (paired) break;\n }\n if (!paired) return null;\n traces = [...traces, ...paired];\n }\n const finished = yield* finishPairedNetwork(\n { ...network, input: completeInput, transforms: [] },\n traces\n );\n if (!finished) return null;\n const matched = yield* matchRoutes(completeInput, finished, options);\n if (!matched) return null;\n const extended = yield* extendPackageCoupling(completeInput, matched, {\n preserveMatching: false\n });\n if (exteriorPairSpacingReports(completeInput, extended).some((r2) =\u003e !r2.matched))\n return null;\n const final = yield* matchRoutes(completeInput, extended, options);\n if (!final || exteriorPairSpacingReports(completeInput, final).some((r2) =\u003e !r2.matched))\n return null;\n const ceilings = new Map(\n busLengthReports(completeInput, matched).map((bus) =\u003e [\n bus.busId,\n Math.max(\n ...bus.lengths.map((length2) =\u003e length2.totalLengthMm ?? Infinity)\n )\n ])\n );\n if (busLengthReports(completeInput, final).some(\n (bus) =\u003e Math.max(\n ...bus.lengths.map((length2) =\u003e length2.totalLengthMm ?? Infinity)\n ) \u003e ceilings.get(bus.busId) + 1e-6\n ))\n return null;\n return { input: completeInput, traces: final, escapes: repaired.escapes };\n}\n\n// lib/shorten-pair-approaches.ts\nfunction shortenPairApproaches(input, traces) {\n const result = [...traces], fixed = fixedCopper(input);\n for (let i2 = 0; i2 \u003c result.length; i2++) {\n const t48 = result[i2];\n if (!t48.coupledSection) continue;\n const [s2, e2] = t48.coupledSection, first = t48.route[0];\n const scene = new VectorScene(\n input,\n input.connections.find((c2) =\u003e c2.name === t48.connection_name),\n first.width,\n [...fixed, ...result.flatMap(routeCopper)]\n );\n const regions = packageApproachRegions(\n input,\n first.width + (input.differentialPairs?.find(\n (p2) =\u003e p2.connectionNames.includes(t48.connection_name)\n )?.traceGap ?? 0.1) / 2 + (input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075)\n );\n const shorten = (start, end) =\u003e {\n const local = regions.find(\n (r2) =\u003e pointInBox(t48.route[start === 0 ? 0 : t48.route.length - 1], r2.copper)\n );\n const externalCurve = (t48.curvedSegments ?? []).some(\n (i3) =\u003e i3 \u003e start \u0026\u0026 i3 \u003c= end \u0026\u0026 (!local || !pointInBox(t48.route[i3 - 1], local.copper) || !pointInBox(t48.route[i3], local.copper))\n );\n return externalCurve ? reduceOrdinaryTurns(t48.route.slice(start, end + 1), scene) : t48.route.slice(start, end + 1);\n };\n const prefix = shorten(0, s2), suffix = shorten(e2, t48.route.length - 1);\n const route = [\n ...prefix.slice(0, -1),\n ...t48.route.slice(s2, e2 + 1),\n ...suffix.slice(1)\n ].map((p2) =\u003e ({\n ...p2,\n route_type: \"wire\",\n layer: first.layer,\n width: first.width\n }));\n result[i2] = {\n ...t48,\n route,\n curvedSegments: remapCurvedSegments(t48, route),\n coupledSection: [prefix.length - 1, prefix.length + e2 - s2 - 1]\n };\n }\n return result;\n}\n\n// lib/bus-lanes-pipeline-solver.ts\nvar BusLanesPipelineSolver = class extends BaseSolver {\n input;\n options;\n phase = \"resolve_layers\";\n traces = [];\n failureCode = null;\n acceptedTraces;\n envelopeOptimization;\n /** Runs only after a complete accepted route exists. A budget interrupt or\n * exception restores that private snapshot, never mutable work-in-progress. */\n *optimizeEnvelope() {\n if (!this.options.smoothTuning) return;\n const before = signalEnvelope(this.acceptedTraces);\n const started = performance.now();\n this.stats = {\n ...this.stats,\n envelopeOptimization: {\n beforeAreaMm2: before.areaMm2,\n afterAreaMm2: before.areaMm2,\n milliseconds: 0\n }\n };\n try {\n for (let pass = 0; pass \u003c 2; pass++) {\n const original = this.acceptedTraces;\n const previousBounds = signalEnvelope(original);\n const view = carrierCompactionView(this.input, original);\n if (!view) return;\n const viaClearance = view.carriers.map(\n (trace) =\u003e createTerminalViaClearanceChecker(view.input, trace)\n );\n const candidate = yield* compactEnvelopeCandidate(\n view.input,\n view.carriers\n );\n if (candidate === view.carriers) return;\n for (const fraction of [1, 0.999, 0.99, 0.95, 0.9, 0.75, 0.5]) {\n const carriers = candidate.map((trace, i2) =\u003e ({\n ...trace,\n route: trace.route.map((point, j2) =\u003e ({\n ...point,\n x: view.carriers[i2].route[j2].x + (point.x - view.carriers[i2].route[j2].x) * fraction,\n y: view.carriers[i2].route[j2].y + (point.y - view.carriers[i2].route[j2].y) * fraction\n }))\n }));\n if (carriers.some((trace, i2) =\u003e !viaClearance[i2](trace.route)))\n continue;\n const complete = view.join(carriers);\n const after = signalEnvelope(complete);\n if (!Number.isFinite(after.areaMm2) || after.areaMm2 \u003e= previousBounds.areaMm2 - 1e-6 || after.minX \u003c previousBounds.minX - 1e-8 || after.maxX \u003e previousBounds.maxX + 1e-8 || after.minY \u003c previousBounds.minY - 1e-8 || after.maxY \u003e previousBounds.maxY + 1e-8)\n continue;\n const validator = BusLanesSolver.forValidation(\n view.input,\n carriers,\n this.options\n );\n try {\n while (!validator.solved \u0026\u0026 !validator.failed) {\n validator.step();\n yield;\n }\n if (!validator.solved || exteriorPairSpacingReports(view.input, carriers).some(\n (r2) =\u003e !r2.matched\n ))\n continue;\n this.acceptedTraces = structuredClone(complete);\n this.stats = {\n ...this.stats,\n envelopeOptimization: {\n beforeAreaMm2: before.areaMm2,\n afterAreaMm2: after.areaMm2,\n milliseconds: performance.now() - started\n }\n };\n break;\n } finally {\n if (!validator.solved \u0026\u0026 !validator.failed)\n validator.tryFinalAcceptance();\n }\n }\n if (this.acceptedTraces === original) break;\n }\n } finally {\n this.stats = {\n ...this.stats,\n envelopeOptimization: {\n ...this.stats.envelopeOptimization,\n milliseconds: performance.now() - started\n }\n };\n }\n }\n finishAccepted(early) {\n const optimization = this.envelopeOptimization;\n this.envelopeOptimization = void 0;\n try {\n optimization?.return();\n } catch (error) {\n this.stats = { ...this.stats, optimizationCleanupError: String(error) };\n }\n this.traces = structuredClone(this.acceptedTraces);\n this.solved = true;\n this.failed = false;\n this.error = null;\n this.failureCode = null;\n this.phase = \"solved\";\n this.progress = 1;\n this.stats = { ...this.stats, optimizationStoppedEarly: early };\n }\n sharedPackages;\n backwardPackages;\n child;\n escapes = [];\n attempt = 0;\n completedLanes = [];\n remainingInput;\n followingInput;\n siteRematch;\n packageCoupling;\n terminalLayers = /* @__PURE__ */ new Map();\n constructor(input, options = {}) {\n super();\n this.input = structuredClone(input);\n this.options = { smoothTuning: true, denseSearch: true, ...options };\n this.MAX_ITERATIONS = (options.maxSearchIterations ?? 2e5) * Math.max(1, input.layerCount);\n }\n getConstructorParams() {\n return [this.input, this.options];\n }\n getOutput() {\n if (!this.solved)\n throw Error(this.error ?? \"Bus lane pipeline is not solved\");\n return {\n ...this.input,\n traces: [...this.input.traces ?? [], ...this.traces]\n };\n }\n tryFinalAcceptance() {\n if (this.solved) return;\n if (this.acceptedTraces) {\n this.finishAccepted(true);\n return;\n }\n this.sharedPackages?.return(null);\n this.sharedPackages = void 0;\n this.backwardPackages?.return(null);\n this.backwardPackages = void 0;\n this.packageCoupling?.return([]);\n this.packageCoupling = void 0;\n this.siteRematch?.return({ connections: [], escapes: [] });\n this.siteRematch = void 0;\n this.child?.tryFinalAcceptance();\n this.failureCode = \"search_budget_exhausted\";\n this.traces = [];\n }\n childOptions(reserveForControls = false) {\n const remaining = Math.max(1, this.MAX_ITERATIONS - this.iterations);\n const reserve = reserveForControls ? Math.min(2e5, Math.floor(remaining / 4)) : 0;\n return {\n ...this.options,\n // Keep the aggregate pipeline budget. Restarting a dense bus at the\n // old per-layer cutoff discards compatible computed alternatives just\n // before they converge. Unconstrained controls retain a work reserve.\n maxSearchIterations: this.options.maxSearchIterations ?? Math.max(1, remaining - reserve)\n };\n }\n *finishPackageCoupling(input, lanes) {\n let refined = yield* extendPackageCoupling(input, lanes);\n if (exteriorPairSpacingReports(input, refined).every((r2) =\u003e r2.matched))\n return refined;\n refined = yield* extendPackageCoupling(\n input,\n shortenPairApproaches(input, refined),\n { preserveMatching: false }\n );\n if (exteriorPairSpacingReports(input, refined).some((r2) =\u003e !r2.matched))\n throw Error(\n \"Pair approaches still separate outside native package fanouts\"\n );\n if (input.buses?.some((b2) =\u003e b2.maxLength !== void 0)) {\n const repaired = yield* rebalancePairEscapes(\n input,\n refined,\n this.escapes,\n this.options\n );\n if (repaired) {\n this.escapes = repaired.escapes;\n return repaired.traces;\n }\n }\n const matcher = BusLanesSolver.forRefinement(input, refined, this.options);\n try {\n while (!matcher.solved \u0026\u0026 !matcher.failed) {\n matcher.step();\n yield;\n }\n if (!matcher.solved)\n throw Error(matcher.error ?? \"Package approach length matching failed\");\n const ceilings = new Map(\n busLengthReports(input, lanes).map((b2) =\u003e [\n b2.busId,\n Math.max(\n ...b2.lengths.map(\n (l2) =\u003e l2.totalLengthMm ?? Number.POSITIVE_INFINITY\n )\n )\n ])\n );\n if (busLengthReports(input, matcher.traces).some(\n (b2) =\u003e Math.max(\n ...b2.lengths.map(\n (l2) =\u003e l2.totalLengthMm ?? Number.POSITIVE_INFINITY\n )\n ) \u003e ceilings.get(b2.busId) + 1e-6\n ))\n throw Error(\"Package refinement increased the bus length target\");\n if (exteriorPairSpacingReports(input, matcher.traces).some(\n (r2) =\u003e !r2.matched\n ))\n throw Error(\"Package approach matching separated the pair\");\n return matcher.traces;\n } finally {\n if (!matcher.solved \u0026\u0026 !matcher.failed) matcher.tryFinalAcceptance();\n }\n }\n prepare() {\n if (this.options.fanout === \"none\") {\n this.child = new BusLanesSolver(this.input, this.options);\n return;\n }\n const physicalLayers = getCopperLayerNames(this.input.layerCount);\n if (this.input.allowedLayers?.some((layer) =\u003e !physicalLayers.includes(layer)))\n throw Error(\"Allowed signal layer is not in the physical stack\");\n const layers = physicalLayers.filter(\n (layer) =\u003e !this.input.allowedLayers || this.input.allowedLayers.includes(layer)\n );\n if (!layers.length) throw Error(\"No allowed signal layers\");\n const names = new Set(this.input.connections.map((c2) =\u003e c2.name));\n for (const bus of this.input.buses ?? [])\n if (bus.connectionNames.some((name) =\u003e !names.has(name)))\n throw Error(\"Unknown bus member\");\n const groups = this.input.connections.map((c2) =\u003e /* @__PURE__ */ new Set([c2.name]));\n for (const members of [\n ...(this.input.differentialPairs ?? []).map((p2) =\u003e p2.connectionNames)\n ]) {\n const related = groups.filter((g2) =\u003e members.some((n2) =\u003e g2.has(n2)));\n if (members.some((n2) =\u003e !related.some((g2) =\u003e g2.has(n2))))\n throw Error(\"Unknown bus or differential pair member\");\n const merged = new Set(related.flatMap((g2) =\u003e [...g2]));\n for (const group of related) groups.splice(groups.indexOf(group), 1);\n groups.push(merged);\n }\n const layerShare = Math.ceil(this.input.connections.length / layers.length);\n const balancedCohorts = this.attempt === 0 \u0026\u0026 (this.input.buses ?? []).every(\n (bus) =\u003e bus.connectionNames.length \u003c= layerShare\n );\n for (const bus of balancedCohorts ? this.input.buses ?? [] : []) {\n const related = groups.filter(\n (group) =\u003e bus.connectionNames.some((name) =\u003e group.has(name))\n );\n const merged = new Set(related.flatMap((group) =\u003e [...group]));\n if (merged.size \u003e layerShare) continue;\n const relatedBuses = (this.input.buses ?? []).filter(\n (candidate) =\u003e candidate.connectionNames.some((name) =\u003e merged.has(name))\n );\n const members = this.input.connections.filter(\n (connection) =\u003e merged.has(connection.name)\n );\n if (!layers.some(\n (layer) =\u003e relatedBuses.every(\n (candidate) =\u003e !candidate.allowedLayers || candidate.allowedLayers.includes(layer)\n ) \u0026\u0026 members.every(\n (connection) =\u003e connection.pointsToConnect.every(\n (point) =\u003e (point.layers ?? [point.layer]).includes(layer) || isUnroutedComponentPad(this.input, connection, point)\n )\n )\n ))\n continue;\n for (const group of related) groups.splice(groups.indexOf(group), 1);\n groups.push(merged);\n }\n groups.sort((a2, b2) =\u003e b2.size - a2.size);\n const load = new Map(layers.map((l2) =\u003e [l2, 0]));\n const targets = /* @__PURE__ */ new Map();\n for (const group of groups) {\n const buses = (this.input.buses ?? []).filter(\n (b2) =\u003e b2.connectionNames.some((n2) =\u003e group.has(n2))\n );\n const members = this.input.connections.filter((c2) =\u003e group.has(c2.name));\n const allowed = layers.filter(\n (layer) =\u003e buses.every(\n (b2) =\u003e !b2.allowedLayers || b2.allowedLayers.includes(layer)\n ) \u0026\u0026 members.every(\n (connection) =\u003e connection.pointsToConnect.every(\n (point) =\u003e (point.layers ?? [point.layer]).includes(layer) || isUnroutedComponentPad(this.input, connection, point)\n )\n )\n );\n if (!allowed.length)\n throw Error(\n \"Bus/pair has no common allowed signal layer; existing fanout handoffs cannot be dogboned again\"\n );\n const preferred = buses.flatMap((b2) =\u003e [b2.preferredLayer, ...b2.preferredLayers ?? []]).filter((l2) =\u003e !!l2);\n const countVias = (l2) =\u003e members.flatMap((c2) =\u003e c2.pointsToConnect).filter((p2) =\u003e !(p2.layers ?? [p2.layer]).includes(l2)).length;\n const rank = (l2) =\u003e preferred.includes(l2) ? preferred.indexOf(l2) : preferred.length;\n const layerCost = new Map(\n allowed.map((layer) =\u003e [\n layer,\n countVias(layer) + this.input.obstacles.filter(\n (o2) =\u003e o2.componentId \u0026\u0026 o2.layers.includes(layer)\n ).length / 8\n ])\n );\n const retryOrder = new Map(\n allowed.map((layer) =\u003e {\n const peers = allowed.filter(\n (other) =\u003e rank(other) === rank(layer) \u0026\u0026 layerCost.get(other) === layerCost.get(layer)\n );\n return [\n layer,\n (peers.indexOf(layer) - this.attempt % peers.length + peers.length) % peers.length\n ];\n })\n );\n allowed.sort((a2, b2) =\u003e {\n const via = layerCost.get(a2) - layerCost.get(b2);\n const crossingCost = (layer) =\u003e {\n const cross4 = (p2, q2, r2) =\u003e (q2.x - p2.x) * (r2.y - p2.y) - (q2.y - p2.y) * (r2.x - p2.x);\n let crossings = 0;\n for (const member of members)\n for (const other of this.input.connections) {\n if (targets.get(other.name) !== layer) continue;\n const [p2, q2] = member.pointsToConnect, [r2, s2] = other.pointsToConnect;\n if (cross4(p2, q2, r2) * cross4(p2, q2, s2) \u003c 0 \u0026\u0026 cross4(r2, s2, p2) * cross4(r2, s2, q2) \u003c 0)\n crossings++;\n }\n return crossings * (this.attempt === 1 ? 0 : 4) + load.get(layer);\n };\n return (group.size \u003e 2 ? rank(a2) - rank(b2) || via || crossingCost(a2) - crossingCost(b2) : via || 4 * (rank(a2) - rank(b2)) + crossingCost(a2) - crossingCost(b2)) || retryOrder.get(a2) - retryOrder.get(b2);\n });\n const target = allowed[0];\n for (const name of group) targets.set(name, target);\n load.set(target, load.get(target) + group.size);\n }\n const widths = this.input.connections.map(\n (c2) =\u003e (this.input.buses ?? []).find((b2) =\u003e b2.connectionNames.includes(c2.name))?.traceWidth ?? c2.nominalTraceWidth ?? c2.width ?? this.input.minTraceWidth\n );\n const result = routeAlternateSignalDogbones(\n this.input,\n {\n targetLayers: targets,\n viaDiameter: this.input.minViaPadDiameter ?? 0.6,\n viaHoleDiameter: this.input.minViaHoleDiameter ?? 0.3,\n traceWidth: Math.max(this.input.minTraceWidth, ...widths),\n clearance: this.input.minTraceToPadEdgeClearance ?? this.input.defaultObstacleMargin ?? 0.075,\n boardEdgeClearance: this.input.minBoardEdgeClearance,\n holeToHoleClearance: this.input.minViaHoleEdgeToViaHoleEdgeClearance,\n allowBlindAndBuriedVias: this.input.allowBlindAndBuriedVias ?? false\n },\n this.attempt\n );\n this.escapes = result.traces.map((t48) =\u003e ({\n ...t48,\n source_trace_id: this.input.connections.find((c2) =\u003e c2.name === t48.connection_name)?.source_trace_id ?? t48.connection_name\n }));\n const terminalLayers = /* @__PURE__ */ new Map();\n for (const connection of this.input.connections) {\n if (groups.some((group) =\u003e group.size \u003e 2 \u0026\u0026 group.has(connection.name)))\n continue;\n const vias = this.escapes.filter((t48) =\u003e t48.connection_name === connection.name).flatMap((t48) =\u003e t48.route.filter((p2) =\u003e p2.route_type === \"via\"));\n if (vias.length !== 2) continue;\n const available = layers.filter(\n (layer) =\u003e (this.input.buses ?? []).every(\n (bus) =\u003e !bus.connectionNames.includes(connection.name) || !bus.allowedLayers || bus.allowedLayers.includes(layer)\n ) \u0026\u0026 vias.every(\n (via) =\u003e layer !== via.from_layer \u0026\u0026 (via.layers ?? physicalLayers.slice(\n Math.min(\n physicalLayers.indexOf(via.from_layer),\n physicalLayers.indexOf(via.to_layer)\n ),\n Math.max(\n physicalLayers.indexOf(via.from_layer),\n physicalLayers.indexOf(via.to_layer)\n ) + 1\n )).includes(layer)\n )\n );\n if (available.length \u003e 1) terminalLayers.set(connection.name, available);\n }\n this.terminalLayers = terminalLayers;\n const laneInput = {\n ...this.input,\n connections: result.connections,\n traces: [...this.input.traces ?? [], ...this.escapes]\n };\n const busNames = new Set(laneInput.buses?.flatMap((b2) =\u003e b2.connectionNames));\n const multilayerBus = (laneInput.buses ?? []).some(\n (bus) =\u003e new Set(\n laneInput.connections.filter(\n (connection) =\u003e bus.connectionNames.includes(connection.name)\n ).map((connection) =\u003e connection.pointsToConnect[0].layer)\n ).size \u003e 1\n );\n const pairsPerLayer = /* @__PURE__ */ new Map();\n for (const pair of laneInput.differentialPairs ?? []) {\n const layer = laneInput.connections.find(\n (c2) =\u003e c2.name === pair.connectionNames[0]\n ).pointsToConnect[0].layer;\n pairsPerLayer.set(layer, (pairsPerLayer.get(layer) ?? 0) + 1);\n }\n const deferStandalonePairs = [...pairsPerLayer.values()].some(\n (count) =\u003e count \u003e 1\n );\n const constrained = /* @__PURE__ */ new Set([\n ...busNames,\n ...(laneInput.differentialPairs ?? []).filter(\n (p2) =\u003e !deferStandalonePairs || p2.connectionNames.some((name) =\u003e busNames.has(name))\n ).flatMap((p2) =\u003e p2.connectionNames)\n ]);\n const matching = laneInput.connections.filter(\n (c2) =\u003e constrained.has(c2.name)\n );\n const remaining = laneInput.connections.filter(\n (c2) =\u003e !constrained.has(c2.name)\n );\n const direction = laneInput.connections.filter((c2) =\u003e busNames.has(c2.name)).reduce(\n (sum, c2) =\u003e ({\n x: sum.x + c2.pointsToConnect[1].x - c2.pointsToConnect[0].x,\n y: sum.y + c2.pointsToConnect[1].y - c2.pointsToConnect[0].y\n }),\n { x: 0, y: 0 }\n );\n if (!multilayerBus \u0026\u0026 this.attempt === 0 \u0026\u0026 deferStandalonePairs \u0026\u0026 (laneInput.buses?.length ?? 0) \u003e 1 \u0026\u0026 this.options.smoothTuning \u0026\u0026 this.options.denseSearch \u0026\u0026 (this.input.buses?.some((bus) =\u003e bus.maxLength !== void 0) || Math.abs(direction.x) \u003e Math.abs(direction.y) || backwardFacingPackageTerminals({\n ...this.input,\n connections: this.input.connections.filter(\n (c2) =\u003e busNames.has(c2.name)\n )\n }))) {\n const freshSites = layers.length === 2 \u0026\u0026 !this.input.allowBlindAndBuriedVias \u0026\u0026 this.escapes.length === 2 * this.input.connections.length \u0026\u0026 backwardFacingPackageTerminals({\n ...this.input,\n connections: this.input.connections.filter(\n (c2) =\u003e busNames.has(c2.name)\n )\n }) \u0026\u0026 this.input.connections.every(\n (c2) =\u003e c2.pointsToConnect.length === 2 \u0026\u0026 c2.pointsToConnect.every(\n (p2) =\u003e isUnroutedComponentPad(this.input, c2, p2)\n )\n );\n this.sharedPackages = (freshSites ? routeFreshSharedBuses : routeSharedLayerBuses)(\n this.input,\n laneInput,\n this.escapes,\n terminalLayers,\n this.childOptions()\n );\n return;\n }\n if (!multilayerBus \u0026\u0026 this.attempt === 0 \u0026\u0026 this.options.smoothTuning \u0026\u0026 this.options.denseSearch \u0026\u0026 Math.abs(direction.y) \u003e= Math.abs(direction.x) \u0026\u0026 backwardFacingPackageTerminals({\n ...this.input,\n connections: this.input.connections.filter((c2) =\u003e busNames.has(c2.name))\n }) \u0026\u0026 this.input.connections.every(\n (c2) =\u003e c2.pointsToConnect.length === 2 \u0026\u0026 c2.pointsToConnect.every(\n (p2) =\u003e isUnroutedComponentPad(this.input, c2, p2)\n )\n )) {\n this.backwardPackages = routeBackwardPackageBuses(\n this.input,\n laneInput,\n terminalLayers,\n this.childOptions()\n );\n return;\n }\n const joint = !multilayerBus \u0026\u0026 (this.attempt \u003e 0 || Math.abs(direction.x) \u003e Math.abs(direction.y)) \u0026\u0026 backwardFacingPackageTerminals({\n ...this.input,\n connections: this.input.connections.filter((c2) =\u003e busNames.has(c2.name))\n });\n if (matching.length \u0026\u0026 remaining.length \u0026\u0026 !joint) {\n this.remainingInput = {\n ...laneInput,\n connections: remaining,\n buses: [],\n differentialPairs: (laneInput.differentialPairs ?? []).filter(\n (p2) =\u003e p2.connectionNames.every((n2) =\u003e !constrained.has(n2))\n )\n };\n if (deferStandalonePairs) {\n const standaloneNames = new Set(\n this.remainingInput.differentialPairs?.flatMap(\n (p2) =\u003e p2.connectionNames\n )\n );\n const standalone = remaining.filter((c2) =\u003e standaloneNames.has(c2.name));\n const controls = remaining.filter((c2) =\u003e !standaloneNames.has(c2.name));\n if (standalone.length \u0026\u0026 controls.length) {\n this.followingInput = {\n ...this.remainingInput,\n connections: controls,\n differentialPairs: []\n };\n this.remainingInput = {\n ...this.remainingInput,\n connections: standalone\n };\n }\n }\n this.child = new BusLanesSolver(\n {\n ...laneInput,\n connections: matching,\n differentialPairs: (laneInput.differentialPairs ?? []).filter(\n (p2) =\u003e p2.connectionNames.every((n2) =\u003e constrained.has(n2))\n )\n },\n this.childOptions(true),\n terminalLayers\n );\n } else\n this.child = new BusLanesSolver(\n laneInput,\n this.childOptions(),\n terminalLayers\n );\n }\n _step() {\n try {\n if (this.envelopeOptimization) {\n const step = this.envelopeOptimization.next();\n if (step.done) this.finishAccepted(false);\n return;\n }\n if (this.siteRematch) {\n const step = this.siteRematch.next();\n this.phase = \"resolve_control_sites\";\n this.stats = { ...this.stats, routingStage: \"control_sites\" };\n if (!step.done) return;\n this.escapes = step.value.escapes;\n this.child = new BusLanesSolver(\n {\n ...this.remainingInput,\n connections: step.value.connections,\n traces: [\n ...this.input.traces ?? [],\n ...this.escapes,\n ...this.completedLanes\n ]\n },\n this.childOptions(),\n this.terminalLayers\n );\n this.remainingInput = void 0;\n this.siteRematch = void 0;\n return;\n }\n if (!this.child \u0026\u0026 !this.backwardPackages \u0026\u0026 !this.sharedPackages)\n this.prepare();\n if (this.sharedPackages) {\n this.phase = \"route_shared_layers\";\n const state = this.sharedPackages.next();\n if (!state.done) return;\n this.sharedPackages = void 0;\n if (!state.value) throw Error(\"Shared-layer bus routing exhausted\");\n this.escapes = state.value.escapes;\n this.child = BusLanesSolver.forValidation(\n state.value.input,\n state.value.traces,\n this.childOptions()\n );\n }\n if (this.backwardPackages) {\n this.phase = \"route_backward_packages\";\n const step = this.backwardPackages.next();\n if (!step.done) return;\n this.backwardPackages = void 0;\n if (!step.value) throw Error(\"Backward package bus routing failed\");\n this.escapes = step.value.escapes;\n this.child = BusLanesSolver.forRefinement(\n step.value.input,\n step.value.traces,\n this.childOptions()\n );\n }\n this.child.step();\n this.phase = `lanes_${this.child.phase}`;\n this.stats = {\n ...this.child.stats,\n layerAttempt: this.attempt,\n dogbones: this.escapes.length,\n routingStage: this.completedLanes.length ? \"remaining_signals\" : this.remainingInput ? \"matched_buses\" : \"all_signals\"\n };\n this.progress = this.child.progress;\n if (this.child.failed)\n throw Error(this.child.error ?? \"Bus lanes failed\");\n if (this.child.solved \u0026\u0026 !this.remainingInput \u0026\u0026 this.followingInput) {\n this.remainingInput = this.followingInput;\n this.followingInput = void 0;\n }\n if (this.child.solved \u0026\u0026 this.remainingInput) {\n this.completedLanes.push(...this.child.traces);\n this.siteRematch = rematchTrappedSignalDogbones(\n this.input,\n this.remainingInput,\n this.completedLanes,\n this.escapes,\n this.terminalLayers\n );\n return;\n }\n if (this.child.solved) {\n const lanes = [...this.completedLanes, ...this.child.traces];\n let refined = lanes;\n if (this.options.smoothTuning \u0026\u0026 this.input.differentialPairs?.length) {\n this.packageCoupling ??= this.finishPackageCoupling(\n {\n ...this.input,\n traces: [...this.input.traces ?? [], ...this.escapes],\n connections: this.input.connections.map((c2) =\u003e {\n const lane = lanes.find((t48) =\u003e t48.connection_name === c2.name);\n return {\n ...c2,\n pointsToConnect: [\n lane.route[0],\n lane.route.at(-1)\n ]\n };\n })\n },\n lanes\n );\n const step = this.packageCoupling.next();\n if (!step.done) {\n this.phase = \"extend_package_coupling\";\n return;\n }\n refined = step.value;\n this.packageCoupling = void 0;\n }\n if (this.options.smoothTuning)\n refined = simplifyMatchedTraces(\n {\n ...this.input,\n traces: [...this.input.traces ?? [], ...this.escapes],\n connections: this.input.connections.map((c2) =\u003e {\n const t48 = refined.find((t49) =\u003e t49.connection_name === c2.name);\n return {\n ...c2,\n pointsToConnect: [\n t48.route[0],\n t48.route.at(-1)\n ]\n };\n })\n },\n refined\n );\n if (this.options.smoothTuning \u0026\u0026 (this.input.allowedLayers?.length ?? this.input.layerCount) === 2)\n refined = compactUnconstrainedLanes(\n {\n ...this.input,\n traces: [...this.input.traces ?? [], ...this.escapes],\n connections: this.input.connections.map((c2) =\u003e {\n const t48 = refined.find((t49) =\u003e t49.connection_name === c2.name);\n return {\n ...c2,\n pointsToConnect: [\n t48.route[0],\n t48.route.at(-1)\n ]\n };\n })\n },\n refined\n );\n this.traces = refined.map((lane) =\u003e {\n const signalLayer = lane.route.find(\n (p2) =\u003e p2.route_type === \"wire\"\n ).layer;\n const escapes = this.escapes.filter((t48) =\u003e t48.connection_name === lane.connection_name).map((t48) =\u003e {\n const via = t48.route.find((p2) =\u003e p2.route_type === \"via\");\n return {\n ...t48,\n route: t48.route.map(\n (p2) =\u003e p2.route_type === \"via\" ? { ...p2, to_layer: signalLayer } : p2.layer === via.to_layer ? { ...p2, layer: signalLayer } : p2\n )\n };\n });\n const near2 = (a2, b2) =\u003e Math.hypot(a2.x - b2.x, a2.y - b2.y) \u003c 1e-8;\n const prefix = escapes.find(\n (t48) =\u003e near2(t48.route.at(-1), lane.route[0])\n );\n const suffix = escapes.find(\n (t48) =\u003e t48 !== prefix \u0026\u0026 near2(t48.route.at(-1), lane.route.at(-1))\n );\n const prefixRoute = prefix?.route, suffixRoute = suffix?.route;\n const reversed = suffixRoute?.toReversed().map(\n (p2) =\u003e p2.route_type === \"via\" ? { ...p2, from_layer: p2.to_layer, to_layer: p2.from_layer } : p2\n ) ?? [];\n const offset = (prefix?.route.length ?? 1) - 1;\n return {\n ...lane,\n coupledSection: lane.coupledSection?.map((i2) =\u003e i2 + offset),\n curvedSegments: lane.curvedSegments?.map((i2) =\u003e i2 + offset),\n route: [\n ...prefixRoute?.slice(0, -1) ?? [],\n ...lane.route,\n ...reversed.slice(1)\n ]\n };\n });\n if (busLengthReports(this.input, this.traces).some(\n (b2) =\u003e !b2.withinLengthLimit || !b2.aboveMinimumLength\n ))\n throw Error(\"Final absolute bus length violation\");\n this.acceptedTraces = structuredClone(this.traces);\n this.phase = \"optimize_envelope\";\n this.envelopeOptimization = this.optimizeEnvelope();\n }\n } catch (error) {\n if (this.acceptedTraces) {\n this.stats = { ...this.stats, optimizationError: String(error) };\n this.finishAccepted(true);\n return;\n }\n this.sharedPackages?.return(null);\n this.sharedPackages = void 0;\n this.backwardPackages?.return(null);\n this.backwardPackages = void 0;\n this.packageCoupling?.return([]);\n this.packageCoupling = void 0;\n this.siteRematch?.return({ connections: [], escapes: [] });\n this.siteRematch = void 0;\n this.attempt++;\n if (this.options.fanout !== \"none\" \u0026\u0026 this.attempt \u003c this.input.layerCount) {\n this.child = void 0;\n this.escapes = [];\n this.completedLanes = [];\n this.remainingInput = void 0;\n this.followingInput = void 0;\n this.phase = \"retry_layers\";\n return;\n }\n this.failureCode = this.child?.failureCode ?? \"local_dogbone_failed\";\n this.error = error instanceof Error ? error.message : String(error);\n this.failed = true;\n this.phase = \"failed\";\n this.traces = [];\n }\n }\n visualize() {\n return this.child?.visualize() ?? { points: [], lines: [] };\n }\n};\nexport {\n BusLanesPipelineSolver,\n BusLanesSolver,\n busLengthReports,\n exteriorPairSpacingReports,\n pairLengthReports\n};\n/*! Bundled license information:\n\nsvgson/dist/svgson.umd.js:\n (*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \u003chttps://feross.org\u003e\n * @license MIT\n *)\n\n@tscircuit/capacity-autorouter/dist/index.js:\n (*! Bundled license information:\n \n is-buffer/index.js:\n (*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \u003chttps://feross.org\u003e\n * @license MIT\n *)\n \n deep-rename-keys/index.js:\n (*!\n * deep-rename-keys \u003chttps://github.com/jonschlinkert/deep-rename-keys\u003e\n *\n * Copyright (c) 2015 Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n *)\n \n @tscircuit/curvy-trace-solver/dist/index.js:\n @tscircuit/find-convex-regions/dist/index.js:\n (*! Bundled license information:\n \n is-buffer/index.js:\n (*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \u003chttps://feross.org\u003e\n * @license MIT\n *)\n \n deep-rename-keys/index.js:\n (*!\n * deep-rename-keys \u003chttps://github.com/jonschlinkert/deep-rename-keys\u003e\n *\n * Copyright (c) 2015 Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n *)\n *)\n \n @tscircuit/hypergraph/dist/index.js:\n (*! Bundled license information:\n \n @tscircuit/find-convex-regions/dist/index.js:\n (*! Bundled license information:\n \n is-buffer/index.js:\n (*!\n * Determine if an object is a Buffer\n *\n * @author Feross Aboukhadijeh \u003chttps://feross.org\u003e\n * @license MIT\n *)\n \n deep-rename-keys/index.js:\n (*!\n * deep-rename-keys \u003chttps://github.com/jonschlinkert/deep-rename-keys\u003e\n *\n * Copyright (c) 2015 Jon Schlinkert, contributors.\n * Licensed under the MIT license.\n *)\n *)\n *)\n *)\n*/\n","content_mimetype":"text/javascript","created_at":"2026-10-05T13:15:28.488Z"}; window.SSR_PACKAGE_RELEASES = [{"package_release_id":"2cf56471-e013-461b-aba1-e755cffaac2c","package_id":"2b60b995-332f-46c6-8360-e30a1b8dee13","version":"0.1.20","github_commit_sha":null,"is_locked":false,"is_latest":false,"ready_to_build":true,"is_pr_preview":false,"created_at":"2026-10-05T18:29:00.470Z","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-0f58dceb4e3a70e5213c5ac53ab26d55","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=2cf56471-e013-461b-aba1-e755cffaac2c\u0026file_path=dist%2Findex%2Fpcb.svg","sch_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=2cf56471-e013-461b-aba1-e755cffaac2c\u0026file_path=dist%2Findex%2Fschematic.svg","cad_preview_image_url":"https://api.tscircuit.com/package_files/view?package_release_id=2cf56471-e013-461b-aba1-e755cffaac2c\u0026file_path=dist%2Findex%2F3d.png","package_release_website_url":null,"display_status":"pending","latest_package_build_id":"dc276ea3-ac51-4a2d-846e-4695464c7986","user_code_job_started_at":"2026-10-05T19:01:30.363Z","user_code_job_completed_at":"2026-10-05T19:06:21.457Z","user_code_job_error":{"message":"Your code failed to build (exit code 1), see build logs for the error details","error_code":"user_code_build_error"},"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=6d353affc0f42669913196262d0d4be7441574f8a6675187f494f1702b9f19ec","ai_review_requested":false,"github_pr_number":null,"github_pr_title":null,"github_branch_name":null},{"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":"design/vendor/bus-lanes-candidate.js"};

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

design/vendor/bus-lanes-candidate.js

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x2) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x2, {
  get: (a2, b2) => (typeof require !== "undefined" ? require : a2)[b2]
}) : x2)(function(x2) {
  if (typeof require !== "undefined") return require.apply(this, arguments);
  throw Error('Dynamic require of "' + x2 + '" is not supported');
});
var __commonJS = (cb2, mod) => function __require2() {
  return mod || (0, cb2[__getOwnPropNames(cb2)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// ../bus-lanes-solver/node_modules/svgson/dist/svgson.umd.js
var require_svgson_umd = __commonJS({
  "../bus-lanes-solver/node_modules/svgson/dist/svgson.umd.js"(exports, module) {
    "use strict";
    (function(global2, factory) {
      typeof exports === "object" && typeof module !== "undefined" ? module.exports = factory() : typeof define === "function" && define.amd ? define(factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, global2.svgson = factory());
    })(exports, (function() {
      "use strict";
      var isBuffer_1 = function(obj) {
        return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer);
      };
      function isBuffer(obj) {
        return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj);
      }
      function isSlowBuffer(obj) {
        return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isBuffer(obj.slice(0, 0));
      }
      var toString = Object.prototype.toString;
      var kindOf = function kindOf2(val) {
        if (typeof val === "undefined") {
          return "undefined";
        }
        if (val === null) {
          return "null";
        }
        if (val === true || val === false || val instanceof Boolean) {
          return "boolean";
        }
        if (typeof val === "string" || val instanceof String) {
          return "string";
        }
        if (typeof val === "number" || val instanceof Number) {
          return "number";
        }
        if (typeof val === "function" || val instanceof Function) {
          return "function";
        }
        if (typeof Array.isArray !== "undefined" && Array.isArray(val)) {
          return "array";
        }
        if (val instanceof RegExp) {
          return "regexp";
        }
        if (val instanceof Date) {
          return "date";
        }
        var type = toString.call(val);
        if (type === "[object RegExp]") {
          return "regexp";
        }
        if (type === "[object Date]") {
          return "date";
        }
        if (type === "[object Arguments]") {
          return "arguments";
        }
        if (type === "[object Error]") {
          return "error";
        }
        if (isBuffer_1(val)) {
          return "buffer";
        }
        if (type === "[object Set]") {
          return "set";
        }
        if (type === "[object WeakSet]") {
          return "weakset";
        }
        if (type === "[object Map]") {
          return "map";
        }
        if (type === "[object WeakMap]") {
          return "weakmap";
        }
        if (type === "[object Symbol]") {
          return "symbol";
        }
        if (type === "[object Int8Array]") {
          return "int8array";
        }
        if (type === "[object Uint8Array]") {
          return "uint8array";
        }
        if (type === "[object Uint8ClampedArray]") {
          return "uint8clampedarray";
        }
        if (type === "[object Int16Array]") {
          return "int16array";
        }
        if (type === "[object Uint16Array]") {
          return "uint16array";
        }
        if (type === "[object Int32Array]") {
          return "int32array";
        }
        if (type === "[object Uint32Array]") {
          return "uint32array";
        }
        if (type === "[object Float32Array]") {
          return "float32array";
        }
        if (type === "[object Float64Array]") {
          return "float64array";
        }
        return "object";
      };
      function createCommonjsModule(fn, module2) {
        return module2 = { exports: {} }, fn(module2, module2.exports), module2.exports;
      }
      var renameKeys = createCommonjsModule(function(module2) {
        (function() {
          function rename(obj, fn) {
            if (typeof fn !== "function") {
              return obj;
            }
            var res = {};
            for (var key in obj) {
              if (Object.prototype.hasOwnProperty.call(obj, key)) {
                res[fn(key, obj[key]) || key] = obj[key];
              }
            }
            return res;
          }
          if (module2.exports) {
            module2.exports = rename;
          } else {
            {
              window.rename = rename;
            }
          }
        })();
      });
      var deepRenameKeys = function renameDeep(obj, cb2) {
        var type = kindOf(obj);
        if (type !== "object" && type !== "array") {
          throw new Error("expected an object");
        }
        var res = [];
        if (type === "object") {
          obj = renameKeys(obj, cb2);
          res = {};
        }
        for (var key in obj) {
          if (obj.hasOwnProperty(key)) {
            var val = obj[key];
            if (kindOf(val) === "object" || kindOf(val) === "array") {
              res[key] = renameDeep(val, cb2);
            } else {
              res[key] = val;
            }
          }
        }
        return res;
      };
      var eventemitter3 = createCommonjsModule(function(module2) {
        var has = Object.prototype.hasOwnProperty, prefix = "~";
        function Events() {
        }
        if (Object.create) {
          Events.prototype = /* @__PURE__ */ Object.create(null);
          if (!new Events().__proto__) prefix = false;
        }
        function EE2(fn, context, once) {
          this.fn = fn;
          this.context = context;
          this.once = once || false;
        }
        function EventEmitter() {
          this._events = new Events();
          this._eventsCount = 0;
        }
        EventEmitter.prototype.eventNames = function eventNames() {
          var names = [], events, name;
          if (this._eventsCount === 0) return names;
          for (name in events = this._events) {
            if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
          }
          if (Object.getOwnPropertySymbols) {
            return names.concat(Object.getOwnPropertySymbols(events));
          }
          return names;
        };
        EventEmitter.prototype.listeners = function listeners(event, exists) {
          var evt = prefix ? prefix + event : event, available = this._events[evt];
          if (exists) return !!available;
          if (!available) return [];
          if (available.fn) return [available.fn];
          for (var i2 = 0, l2 = available.length, ee = new Array(l2); i2 < l2; i2++) {
            ee[i2] = available[i2].fn;
          }
          return ee;
        };
        EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
          var evt = prefix ? prefix + event : event;
          if (!this._events[evt]) return false;
          var listeners = this._events[evt], len = arguments.length, args, i2;
          if (listeners.fn) {
            if (listeners.once) this.removeListener(event, listeners.fn, void 0, true);
            switch (len) {
              case 1:
                return listeners.fn.call(listeners.context), true;
              case 2:
                return listeners.fn.call(listeners.context, a1), true;
              case 3:
                return listeners.fn.call(listeners.context, a1, a2), true;
              case 4:
                return listeners.fn.call(listeners.context, a1, a2, a3), true;
              case 5:
                return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
              case 6:
                return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
            }
            for (i2 = 1, args = new Array(len - 1); i2 < len; i2++) {
              args[i2 - 1] = arguments[i2];
            }
            listeners.fn.apply(listeners.context, args);
          } else {
            var length2 = listeners.length, j2;
            for (i2 = 0; i2 < length2; i2++) {
              if (listeners[i2].once) this.removeListener(event, listeners[i2].fn, void 0, true);
              switch (len) {
                case 1:
                  listeners[i2].fn.call(listeners[i2].context);
                  break;
                case 2:
                  listeners[i2].fn.call(listeners[i2].context, a1);
                  break;
                case 3:
                  listeners[i2].fn.call(listeners[i2].context, a1, a2);
                  break;
                case 4:
                  listeners[i2].fn.call(listeners[i2].context, a1, a2, a3);
                  break;
                default:
                  if (!args) for (j2 = 1, args = new Array(len - 1); j2 < len; j2++) {
                    args[j2 - 1] = arguments[j2];
                  }
                  listeners[i2].fn.apply(listeners[i2].context, args);
              }
            }
          }
          return true;
        };
        EventEmitter.prototype.on = function on(event, fn, context) {
          var listener = new EE2(fn, context || this), evt = prefix ? prefix + event : event;
          if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
          else if (!this._events[evt].fn) this._events[evt].push(listener);
          else this._events[evt] = [this._events[evt], listener];
          return this;
        };
        EventEmitter.prototype.once = function once(event, fn, context) {
          var listener = new EE2(fn, context || this, true), evt = prefix ? prefix + event : event;
          if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
          else if (!this._events[evt].fn) this._events[evt].push(listener);
          else this._events[evt] = [this._events[evt], listener];
          return this;
        };
        EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
          var evt = prefix ? prefix + event : event;
          if (!this._events[evt]) return this;
          if (!fn) {
            if (--this._eventsCount === 0) this._events = new Events();
            else delete this._events[evt];
            return this;
          }
          var listeners = this._events[evt];
          if (listeners.fn) {
            if (listeners.fn === fn && (!once || listeners.once) && (!context || listeners.context === context)) {
              if (--this._eventsCount === 0) this._events = new Events();
              else delete this._events[evt];
            }
          } else {
            for (var i2 = 0, events = [], length2 = listeners.length; i2 < length2; i2++) {
              if (listeners[i2].fn !== fn || once && !listeners[i2].once || context && listeners[i2].context !== context) {
                events.push(listeners[i2]);
              }
            }
            if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
            else if (--this._eventsCount === 0) this._events = new Events();
            else delete this._events[evt];
          }
          return this;
        };
        EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
          var evt;
          if (event) {
            evt = prefix ? prefix + event : event;
            if (this._events[evt]) {
              if (--this._eventsCount === 0) this._events = new Events();
              else delete this._events[evt];
            }
          } else {
            this._events = new Events();
            this._eventsCount = 0;
          }
          return this;
        };
        EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
        EventEmitter.prototype.addListener = EventEmitter.prototype.on;
        EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
          return this;
        };
        EventEmitter.prefixed = prefix;
        EventEmitter.EventEmitter = EventEmitter;
        {
          module2.exports = EventEmitter;
        }
      });
      function _defineProperty(obj, key, value) {
        if (key in obj) {
          Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
        } else {
          obj[key] = value;
        }
        return obj;
      }
      var noop = function noop2() {
      };
      var State = {
        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"
      };
      var Action = {
        lt: "action-lt",
        gt: "action-gt",
        space: "action-space",
        equal: "action-equal",
        quote: "action-quote",
        slash: "action-slash",
        char: "action-char",
        error: "action-error"
      };
      var Type$1 = {
        text: "text",
        openTag: "open-tag",
        closeTag: "close-tag",
        attributeName: "attribute-name",
        attributeValue: "attribute-value"
      };
      var charToAction = {
        " ": Action.space,
        "	": Action.space,
        "\n": Action.space,
        "\r": Action.space,
        "<": Action.lt,
        ">": Action.gt,
        '"': Action.quote,
        "'": Action.quote,
        "=": Action.equal,
        "/": Action.slash
      };
      var getAction = function getAction2(char) {
        return charToAction[char] || Action.char;
      };
      var create$1 = function create2(options) {
        var _State$data, _State$tagBegin, _State$tagName, _State$tagEnd, _State$attributeNameS, _State$attributeName, _State$attributeNameE, _State$attributeValue, _State$attributeValue2, _lexer$stateMachine;
        options = Object.assign({ debug: false }, options);
        var lexer2 = new eventemitter3();
        var state = State.data;
        var data = "";
        var tagName = "";
        var attrName = "";
        var attrValue = "";
        var isClosing = "";
        var openingQuote = "";
        var emit = function emit2(type, value) {
          if (tagName[0] === "?" || tagName[0] === "!") {
            return;
          }
          var event = { type, value };
          if (options.debug) {
            console.log("emit:", event);
          }
          lexer2.emit("data", event);
        };
        lexer2.stateMachine = (_lexer$stateMachine = {}, _defineProperty(_lexer$stateMachine, State.data, (_State$data = {}, _defineProperty(_State$data, Action.lt, function() {
          if (data.trim()) {
            emit(Type$1.text, data);
          }
          tagName = "";
          isClosing = false;
          state = State.tagBegin;
        }), _defineProperty(_State$data, Action.char, function(char) {
          data += char;
        }), _State$data)), _defineProperty(_lexer$stateMachine, State.cdata, _defineProperty({}, Action.char, function(char) {
          data += char;
          if (data.substr(-3) === "]]>") {
            emit(Type$1.text, data.slice(0, -3));
            data = "";
            state = State.data;
          }
        })), _defineProperty(_lexer$stateMachine, State.tagBegin, (_State$tagBegin = {}, _defineProperty(_State$tagBegin, Action.space, noop), _defineProperty(_State$tagBegin, Action.char, function(char) {
          tagName = char;
          state = State.tagName;
        }), _defineProperty(_State$tagBegin, Action.slash, function() {
          tagName = "";
          isClosing = true;
        }), _State$tagBegin)), _defineProperty(_lexer$stateMachine, State.tagName, (_State$tagName = {}, _defineProperty(_State$tagName, Action.space, function() {
          if (isClosing) {
            state = State.tagEnd;
          } else {
            state = State.attributeNameStart;
            emit(Type$1.openTag, tagName);
          }
        }), _defineProperty(_State$tagName, Action.gt, function() {
          if (isClosing) {
            emit(Type$1.closeTag, tagName);
          } else {
            emit(Type$1.openTag, tagName);
          }
          data = "";
          state = State.data;
        }), _defineProperty(_State$tagName, Action.slash, function() {
          state = State.tagEnd;
          emit(Type$1.openTag, tagName);
        }), _defineProperty(_State$tagName, Action.char, function(char) {
          tagName += char;
          if (tagName === "![CDATA[") {
            state = State.cdata;
            data = "";
            tagName = "";
          }
        }), _State$tagName)), _defineProperty(_lexer$stateMachine, State.tagEnd, (_State$tagEnd = {}, _defineProperty(_State$tagEnd, Action.gt, function() {
          emit(Type$1.closeTag, tagName);
          data = "";
          state = State.data;
        }), _defineProperty(_State$tagEnd, Action.char, noop), _State$tagEnd)), _defineProperty(_lexer$stateMachine, State.attributeNameStart, (_State$attributeNameS = {}, _defineProperty(_State$attributeNameS, Action.char, function(char) {
          attrName = char;
          state = State.attributeName;
        }), _defineProperty(_State$attributeNameS, Action.gt, function() {
          data = "";
          state = State.data;
        }), _defineProperty(_State$attributeNameS, Action.space, noop), _defineProperty(_State$attributeNameS, Action.slash, function() {
          isClosing = true;
          state = State.tagEnd;
        }), _State$attributeNameS)), _defineProperty(_lexer$stateMachine, State.attributeName, (_State$attributeName = {}, _defineProperty(_State$attributeName, Action.space, function() {
          state = State.attributeNameEnd;
        }), _defineProperty(_State$attributeName, Action.equal, function() {
          emit(Type$1.attributeName, attrName);
          state = State.attributeValueBegin;
        }), _defineProperty(_State$attributeName, Action.gt, function() {
          attrValue = "";
          emit(Type$1.attributeName, attrName);
          emit(Type$1.attributeValue, attrValue);
          data = "";
          state = State.data;
        }), _defineProperty(_State$attributeName, Action.slash, function() {
          isClosing = true;
          attrValue = "";
          emit(Type$1.attributeName, attrName);
          emit(Type$1.attributeValue, attrValue);
          state = State.tagEnd;
        }), _defineProperty(_State$attributeName, Action.char, function(char) {
          attrName += char;
        }), _State$attributeName)), _defineProperty(_lexer$stateMachine, State.attributeNameEnd, (_State$attributeNameE = {}, _defineProperty(_State$attributeNameE, Action.space, noop), _defineProperty(_State$attributeNameE, Action.equal, function() {
          emit(Type$1.attributeName, attrName);
          state = State.attributeValueBegin;
        }), _defineProperty(_State$attributeNameE, Action.gt, function() {
          attrValue = "";
          emit(Type$1.attributeName, attrName);
          emit(Type$1.attributeValue, attrValue);
          data = "";
          state = State.data;
        }), _defineProperty(_State$attributeNameE, Action.char, function(char) {
          attrValue = "";
          emit(Type$1.attributeName, attrName);
          emit(Type$1.attributeValue, attrValue);
          attrName = char;
          state = State.attributeName;
        }), _State$attributeNameE)), _defineProperty(_lexer$stateMachine, State.attributeValueBegin, (_State$attributeValue = {}, _defineProperty(_State$attributeValue, Action.space, noop), _defineProperty(_State$attributeValue, Action.quote, function(char) {
          openingQuote = char;
          attrValue = "";
          state = State.attributeValue;
        }), _defineProperty(_State$attributeValue, Action.gt, function() {
          attrValue = "";
          emit(Type$1.attributeValue, attrValue);
          data = "";
          state = State.data;
        }), _defineProperty(_State$attributeValue, Action.char, function(char) {
          openingQuote = "";
          attrValue = char;
          state = State.attributeValue;
        }), _State$attributeValue)), _defineProperty(_lexer$stateMachine, State.attributeValue, (_State$attributeValue2 = {}, _defineProperty(_State$attributeValue2, Action.space, function(char) {
          if (openingQuote) {
            attrValue += char;
          } else {
            emit(Type$1.attributeValue, attrValue);
            state = State.attributeNameStart;
          }
        }), _defineProperty(_State$attributeValue2, Action.quote, function(char) {
          if (openingQuote === char) {
            emit(Type$1.attributeValue, attrValue);
            state = State.attributeNameStart;
          } else {
            attrValue += char;
          }
        }), _defineProperty(_State$attributeValue2, Action.gt, function(char) {
          if (openingQuote) {
            attrValue += char;
          } else {
            emit(Type$1.attributeValue, attrValue);
            data = "";
            state = State.data;
          }
        }), _defineProperty(_State$attributeValue2, Action.slash, function(char) {
          if (openingQuote) {
            attrValue += char;
          } else {
            emit(Type$1.attributeValue, attrValue);
            isClosing = true;
            state = State.tagEnd;
          }
        }), _defineProperty(_State$attributeValue2, Action.char, function(char) {
          attrValue += char;
        }), _State$attributeValue2)), _lexer$stateMachine);
        var step = function step2(char) {
          if (options.debug) {
            console.log(state, char);
          }
          var actions = lexer2.stateMachine[state];
          var action = actions[getAction(char)] || actions[Action.error] || actions[Action.char];
          action(char);
        };
        lexer2.write = function(str) {
          var len = str.length;
          for (var i2 = 0; i2 < len; i2++) {
            step(str[i2]);
          }
        };
        return lexer2;
      };
      var lexer = {
        State,
        Action,
        Type: Type$1,
        create: create$1
      };
      var Type = lexer.Type;
      var NodeType = {
        element: "element",
        text: "text"
      };
      var createNode = function createNode2(params) {
        return Object.assign({
          name: "",
          type: NodeType.element,
          value: "",
          parent: null,
          attributes: {},
          children: []
        }, params);
      };
      var create = function create2(options) {
        options = Object.assign({
          stream: false,
          parentNodes: true,
          doneEvent: "done",
          tagPrefix: "tag:",
          emitTopLevelOnly: false,
          debug: false
        }, options);
        var lexer$1 = void 0, rootNode = void 0, current = void 0, attrName = void 0;
        var reader2 = new eventemitter3();
        var handleLexerData = function handleLexerData2(data) {
          switch (data.type) {
            case Type.openTag:
              if (current === null) {
                current = rootNode;
                current.name = data.value;
              } else {
                var node = createNode({
                  name: data.value,
                  parent: current
                });
                current.children.push(node);
                current = node;
              }
              break;
            case Type.closeTag:
              var parent = current.parent;
              if (!options.parentNodes) {
                current.parent = null;
              }
              if (current.name !== data.value) {
                break;
              }
              if (options.stream && parent === rootNode) {
                rootNode.children = [];
                current.parent = null;
              }
              if (!options.emitTopLevelOnly || parent === rootNode) {
                reader2.emit(options.tagPrefix + current.name, current);
                reader2.emit("tag", current.name, current);
              }
              if (current === rootNode) {
                lexer$1.removeAllListeners("data");
                reader2.emit(options.doneEvent, current);
                rootNode = null;
              }
              current = parent;
              break;
            case Type.text:
              if (current) {
                current.children.push(createNode({
                  type: NodeType.text,
                  value: data.value,
                  parent: options.parentNodes ? current : null
                }));
              }
              break;
            case Type.attributeName:
              attrName = data.value;
              current.attributes[attrName] = "";
              break;
            case Type.attributeValue:
              current.attributes[attrName] = data.value;
              break;
          }
        };
        reader2.reset = function() {
          lexer$1 = lexer.create({ debug: options.debug });
          lexer$1.on("data", handleLexerData);
          rootNode = createNode();
          current = null;
          attrName = "";
          reader2.parse = lexer$1.write;
        };
        reader2.reset();
        return reader2;
      };
      var parseSync = function parseSync2(xml, options) {
        options = Object.assign({}, options, { stream: false, tagPrefix: ":" });
        var reader2 = create(options);
        var res = void 0;
        reader2.on("done", function(ast) {
          res = ast;
        });
        reader2.parse(xml);
        return res;
      };
      var reader = {
        parseSync,
        create,
        NodeType
      };
      var reader_1 = reader.parseSync;
      var parseInput = function parseInput2(input) {
        var parsed = reader_1("<root>".concat(input, "</root>"), {
          parentNodes: false
        });
        var isValid = parsed.children && parsed.children.length > 0 && parsed.children.every(function(node) {
          return node.name === "svg";
        });
        if (isValid) {
          return parsed.children.length === 1 ? parsed.children[0] : parsed.children;
        } else {
          throw Error("nothing to parse");
        }
      };
      var camelize = function camelize2(node) {
        return deepRenameKeys(node, function(key) {
          if (!notCamelcase(key)) {
            return toCamelCase(key);
          }
          return key;
        });
      };
      var toCamelCase = function toCamelCase2(prop) {
        return prop.replace(/[-|:]([a-z])/gi, function(all, letter) {
          return letter.toUpperCase();
        });
      };
      var notCamelcase = function notCamelcase2(prop) {
        return /^(data|aria)(-\w+)/.test(prop);
      };
      var escapeText = function escapeText2(text) {
        if (text) {
          var str = String(text);
          return /[&<>]/.test(str) ? "<![CDATA[".concat(str.replace(/]]>/, "]]]]><![CDATA[>"), "]]>") : str;
        }
        return "";
      };
      var escapeAttr = function escapeAttr2(attr) {
        return String(attr).replace(/&/g, "&amp;").replace(/'/g, "&apos;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
      };
      var svgsonSync = function svgsonSync2(input) {
        var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref$transformNode = _ref.transformNode, transformNode = _ref$transformNode === void 0 ? function(node) {
          return node;
        } : _ref$transformNode, _ref$camelcase = _ref.camelcase, camelcase = _ref$camelcase === void 0 ? false : _ref$camelcase;
        var applyFilters = function applyFilters2(input2) {
          var n2;
          n2 = transformNode(input2);
          if (camelcase) {
            n2 = camelize(n2);
          }
          return n2;
        };
        return applyFilters(parseInput(input));
      };
      function svgson() {
        for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
          args[_key] = arguments[_key];
        }
        return new Promise(function(resolve, reject) {
          try {
            var res = svgsonSync.apply(void 0, args);
            resolve(res);
          } catch (e2) {
            reject(e2);
          }
        });
      }
      var stringify3 = function stringify4(_ast) {
        var _ref = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, _ref$transformAttr = _ref.transformAttr, transformAttr = _ref$transformAttr === void 0 ? function(key, value, escape) {
          return "".concat(key, '="').concat(escape(value), '"');
        } : _ref$transformAttr, _ref$transformNode = _ref.transformNode, transformNode = _ref$transformNode === void 0 ? function(node) {
          return node;
        } : _ref$transformNode, _ref$selfClose = _ref.selfClose, selfClose = _ref$selfClose === void 0 ? true : _ref$selfClose;
        if (Array.isArray(_ast)) {
          return _ast.map(function(ast2) {
            return stringify4(ast2, {
              transformAttr,
              selfClose,
              transformNode
            });
          }).join("");
        }
        var ast = transformNode(_ast);
        if (ast.type === "text") {
          return escapeText(ast.value);
        }
        var attributes = "";
        for (var attr in ast.attributes) {
          var attrStr = transformAttr(attr, ast.attributes[attr], escapeAttr, ast.name);
          attributes += attrStr ? " ".concat(attrStr) : "";
        }
        return ast.children && ast.children.length > 0 || !selfClose ? "<".concat(ast.name).concat(attributes, ">").concat(stringify4(ast.children, {
          transformAttr,
          transformNode,
          selfClose
        }), "</").concat(ast.name, ">") : "<".concat(ast.name).concat(attributes, "/>");
      };
      var indexUmd = Object.assign({}, {
        parse: svgson,
        parseSync: svgsonSync,
        stringify: stringify3
      });
      return indexUmd;
    }));
  }
});

// .cache/heap-0.2.7/package/lib/heap.js
var require_heap = __commonJS({
  ".cache/heap-0.2.7/package/lib/heap.js"(exports, module) {
    "use strict";
    (function() {
      var Heap2, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
      floor = Math.floor, min = Math.min;
      defaultCmp = function(x2, y2) {
        if (x2 < y2) {
          return -1;
        }
        if (x2 > y2) {
          return 1;
        }
        return 0;
      };
      insort = function(a2, x2, lo, hi, cmp) {
        var mid;
        if (lo == null) {
          lo = 0;
        }
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (lo < 0) {
          throw new Error("lo must be non-negative");
        }
        if (hi == null) {
          hi = a2.length;
        }
        while (lo < hi) {
          mid = floor((lo + hi) / 2);
          if (cmp(x2, a2[mid]) < 0) {
            hi = mid;
          } else {
            lo = mid + 1;
          }
        }
        return [].splice.apply(a2, [lo, lo - lo].concat(x2)), x2;
      };
      heappush = function(array, item, cmp) {
        if (cmp == null) {
          cmp = defaultCmp;
        }
        array.push(item);
        return _siftdown(array, 0, array.length - 1, cmp);
      };
      heappop = function(array, cmp) {
        var lastelt, returnitem;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        lastelt = array.pop();
        if (array.length) {
          returnitem = array[0];
          array[0] = lastelt;
          _siftup(array, 0, cmp);
        } else {
          returnitem = lastelt;
        }
        return returnitem;
      };
      heapreplace = function(array, item, cmp) {
        var returnitem;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        returnitem = array[0];
        array[0] = item;
        _siftup(array, 0, cmp);
        return returnitem;
      };
      heappushpop = function(array, item, cmp) {
        var _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (array.length && cmp(array[0], item) < 0) {
          _ref = [array[0], item], item = _ref[0], array[0] = _ref[1];
          _siftup(array, 0, cmp);
        }
        return item;
      };
      heapify = function(array, cmp) {
        var i2, _i, _j, _len, _ref, _ref1, _results, _results1;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        _ref1 = (function() {
          _results1 = [];
          for (var _j2 = 0, _ref2 = floor(array.length / 2); 0 <= _ref2 ? _j2 < _ref2 : _j2 > _ref2; 0 <= _ref2 ? _j2++ : _j2--) {
            _results1.push(_j2);
          }
          return _results1;
        }).apply(this).reverse();
        _results = [];
        for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
          i2 = _ref1[_i];
          _results.push(_siftup(array, i2, cmp));
        }
        return _results;
      };
      updateItem = function(array, item, cmp) {
        var pos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        pos = array.indexOf(item);
        if (pos === -1) {
          return;
        }
        _siftdown(array, 0, pos, cmp);
        return _siftup(array, pos, cmp);
      };
      nlargest = function(array, n2, cmp) {
        var elem, result, _i, _len, _ref;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        result = array.slice(0, n2);
        if (!result.length) {
          return result;
        }
        heapify(result, cmp);
        _ref = array.slice(n2);
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          elem = _ref[_i];
          heappushpop(result, elem, cmp);
        }
        return result.sort(cmp).reverse();
      };
      nsmallest = function(array, n2, cmp) {
        var elem, i2, los, result, _i, _j, _len, _ref, _ref1, _results;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        if (n2 * 10 <= array.length) {
          result = array.slice(0, n2).sort(cmp);
          if (!result.length) {
            return result;
          }
          los = result[result.length - 1];
          _ref = array.slice(n2);
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            elem = _ref[_i];
            if (cmp(elem, los) < 0) {
              insort(result, elem, 0, null, cmp);
              result.pop();
              los = result[result.length - 1];
            }
          }
          return result;
        }
        heapify(array, cmp);
        _results = [];
        for (i2 = _j = 0, _ref1 = min(n2, array.length); 0 <= _ref1 ? _j < _ref1 : _j > _ref1; i2 = 0 <= _ref1 ? ++_j : --_j) {
          _results.push(heappop(array, cmp));
        }
        return _results;
      };
      _siftdown = function(array, startpos, pos, cmp) {
        var newitem, parent, parentpos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        newitem = array[pos];
        while (pos > startpos) {
          parentpos = pos - 1 >> 1;
          parent = array[parentpos];
          if (cmp(newitem, parent) < 0) {
            array[pos] = parent;
            pos = parentpos;
            continue;
          }
          break;
        }
        return array[pos] = newitem;
      };
      _siftup = function(array, pos, cmp) {
        var childpos, endpos, newitem, rightpos, startpos;
        if (cmp == null) {
          cmp = defaultCmp;
        }
        endpos = array.length;
        startpos = pos;
        newitem = array[pos];
        childpos = 2 * pos + 1;
        while (childpos < endpos) {
          rightpos = childpos + 1;
          if (rightpos < endpos && !(cmp(array[childpos], array[rightpos]) < 0)) {
            childpos = rightpos;
          }
          array[pos] = array[childpos];
          pos = childpos;
          childpos = 2 * pos + 1;
        }
        array[pos] = newitem;
        return _siftdown(array, startpos, pos, cmp);
      };
      Heap2 = (function() {
        Heap3.push = heappush;
        Heap3.pop = heappop;
        Heap3.replace = heapreplace;
        Heap3.pushpop = heappushpop;
        Heap3.heapify = heapify;
        Heap3.updateItem = updateItem;
        Heap3.nlargest = nlargest;
        Heap3.nsmallest = nsmallest;
        function Heap3(cmp) {
          this.cmp = cmp != null ? cmp : defaultCmp;
          this.nodes = [];
        }
        Heap3.prototype.push = function(x2) {
          return heappush(this.nodes, x2, this.cmp);
        };
        Heap3.prototype.pop = function() {
          return heappop(this.nodes, this.cmp);
        };
        Heap3.prototype.peek = function() {
          return this.nodes[0];
        };
        Heap3.prototype.contains = function(x2) {
          return this.nodes.indexOf(x2) !== -1;
        };
        Heap3.prototype.replace = function(x2) {
          return heapreplace(this.nodes, x2, this.cmp);
        };
        Heap3.prototype.pushpop = function(x2) {
          return heappushpop(this.nodes, x2, this.cmp);
        };
        Heap3.prototype.heapify = function() {
          return heapify(this.nodes, this.cmp);
        };
        Heap3.prototype.updateItem = function(x2) {
          return updateItem(this.nodes, x2, this.cmp);
        };
        Heap3.prototype.clear = function() {
          return this.nodes = [];
        };
        Heap3.prototype.empty = function() {
          return this.nodes.length === 0;
        };
        Heap3.prototype.size = function() {
          return this.nodes.length;
        };
        Heap3.prototype.clone = function() {
          var heap;
          heap = new Heap3();
          heap.nodes = this.nodes.slice(0);
          return heap;
        };
        Heap3.prototype.toArray = function() {
          return this.nodes.slice(0);
        };
        Heap3.prototype.insert = Heap3.prototype.push;
        Heap3.prototype.top = Heap3.prototype.peek;
        Heap3.prototype.front = Heap3.prototype.peek;
        Heap3.prototype.has = Heap3.prototype.contains;
        Heap3.prototype.copy = Heap3.prototype.clone;
        return Heap3;
      })();
      (function(root, factory) {
        if (typeof define === "function" && define.amd) {
          return define([], factory);
        } else if (typeof exports === "object") {
          return module.exports = factory();
        } else {
          return root.Heap = factory();
        }
      })(this, function() {
        return Heap2;
      });
    }).call(exports);
  }
});

// .cache/heap-0.2.7/package/index.js
var require_package = __commonJS({
  ".cache/heap-0.2.7/package/index.js"(exports, module) {
    "use strict";
    module.exports = require_heap();
  }
});

// ../bus-lanes-solver/node_modules/object-hash/dist/object_hash.js
var require_object_hash = __commonJS({
  "../bus-lanes-solver/node_modules/object-hash/dist/object_hash.js"(exports, module) {
    "use strict";
    !(function(e2) {
      var t48;
      "object" == typeof exports ? module.exports = e2() : "function" == typeof define && define.amd ? define(e2) : ("undefined" != typeof window ? t48 = window : "undefined" != typeof global ? t48 = global : "undefined" != typeof self && (t48 = self), t48.objectHash = e2());
    })(function() {
      return (function r2(o2, i2, u2) {
        function s2(n2, e3) {
          if (!i2[n2]) {
            if (!o2[n2]) {
              var t48 = "function" == typeof __require && __require;
              if (!e3 && t48) return t48(n2, true);
              if (a2) return a2(n2, true);
              throw new Error("Cannot find module '" + n2 + "'");
            }
            e3 = i2[n2] = { exports: {} };
            o2[n2][0].call(e3.exports, function(e4) {
              var t49 = o2[n2][1][e4];
              return s2(t49 || e4);
            }, e3, e3.exports, r2, o2, i2, u2);
          }
          return i2[n2].exports;
        }
        for (var a2 = "function" == typeof __require && __require, e2 = 0; e2 < u2.length; e2++) s2(u2[e2]);
        return s2;
      })({ 1: [function(w2, b2, m2) {
        !function(e2, n2, s2, c2, d2, h2, p2, g2, y2) {
          "use strict";
          var r2 = w2("crypto");
          function t48(e3, t49) {
            t49 = u2(e3, t49);
            var n3;
            return void 0 === (n3 = "passthrough" !== t49.algorithm ? r2.createHash(t49.algorithm) : new l2()).write && (n3.write = n3.update, n3.end = n3.update), f2(t49, n3).dispatch(e3), n3.update || n3.end(""), n3.digest ? n3.digest("buffer" === t49.encoding ? void 0 : t49.encoding) : (e3 = n3.read(), "buffer" !== t49.encoding ? e3.toString(t49.encoding) : e3);
          }
          (m2 = b2.exports = t48).sha1 = function(e3) {
            return t48(e3);
          }, m2.keys = function(e3) {
            return t48(e3, { excludeValues: true, algorithm: "sha1", encoding: "hex" });
          }, m2.MD5 = function(e3) {
            return t48(e3, { algorithm: "md5", encoding: "hex" });
          }, m2.keysMD5 = function(e3) {
            return t48(e3, { algorithm: "md5", encoding: "hex", excludeValues: true });
          };
          var o2 = r2.getHashes ? r2.getHashes().slice() : ["sha1", "md5"], i2 = (o2.push("passthrough"), ["buffer", "hex", "binary", "base64"]);
          function u2(e3, t49) {
            var n3 = {};
            if (n3.algorithm = (t49 = t49 || {}).algorithm || "sha1", n3.encoding = t49.encoding || "hex", n3.excludeValues = !!t49.excludeValues, n3.algorithm = n3.algorithm.toLowerCase(), n3.encoding = n3.encoding.toLowerCase(), n3.ignoreUnknown = true === t49.ignoreUnknown, n3.respectType = false !== t49.respectType, n3.respectFunctionNames = false !== t49.respectFunctionNames, n3.respectFunctionProperties = false !== t49.respectFunctionProperties, n3.unorderedArrays = true === t49.unorderedArrays, n3.unorderedSets = false !== t49.unorderedSets, n3.unorderedObjects = false !== t49.unorderedObjects, n3.replacer = t49.replacer || void 0, n3.excludeKeys = t49.excludeKeys || void 0, void 0 === e3) throw new Error("Object argument required.");
            for (var r3 = 0; r3 < o2.length; ++r3) o2[r3].toLowerCase() === n3.algorithm.toLowerCase() && (n3.algorithm = o2[r3]);
            if (-1 === o2.indexOf(n3.algorithm)) throw new Error('Algorithm "' + n3.algorithm + '"  not supported. supported values: ' + o2.join(", "));
            if (-1 === i2.indexOf(n3.encoding) && "passthrough" !== n3.algorithm) throw new Error('Encoding "' + n3.encoding + '"  not supported. supported values: ' + i2.join(", "));
            return n3;
          }
          function a2(e3) {
            if ("function" == typeof e3) return null != /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e3));
          }
          function f2(o3, t49, i3) {
            i3 = i3 || [];
            function u3(e3) {
              return t49.update ? t49.update(e3, "utf8") : t49.write(e3, "utf8");
            }
            return { dispatch: function(e3) {
              return this["_" + (null === (e3 = o3.replacer ? o3.replacer(e3) : e3) ? "null" : typeof e3)](e3);
            }, _object: function(t50) {
              var n3, e3 = Object.prototype.toString.call(t50), r3 = /\[object (.*)\]/i.exec(e3);
              r3 = (r3 = r3 ? r3[1] : "unknown:[" + e3 + "]").toLowerCase();
              if (0 <= (e3 = i3.indexOf(t50))) return this.dispatch("[CIRCULAR:" + e3 + "]");
              if (i3.push(t50), void 0 !== s2 && s2.isBuffer && s2.isBuffer(t50)) return u3("buffer:"), u3(t50);
              if ("object" === r3 || "function" === r3 || "asyncfunction" === r3) return e3 = Object.keys(t50), o3.unorderedObjects && (e3 = e3.sort()), false === o3.respectType || a2(t50) || e3.splice(0, 0, "prototype", "__proto__", "constructor"), o3.excludeKeys && (e3 = e3.filter(function(e4) {
                return !o3.excludeKeys(e4);
              })), u3("object:" + e3.length + ":"), n3 = this, e3.forEach(function(e4) {
                n3.dispatch(e4), u3(":"), o3.excludeValues || n3.dispatch(t50[e4]), u3(",");
              });
              if (!this["_" + r3]) {
                if (o3.ignoreUnknown) return u3("[" + r3 + "]");
                throw new Error('Unknown object type "' + r3 + '"');
              }
              this["_" + r3](t50);
            }, _array: function(e3, t50) {
              t50 = void 0 !== t50 ? t50 : false !== o3.unorderedArrays;
              var n3 = this;
              if (u3("array:" + e3.length + ":"), !t50 || e3.length <= 1) return e3.forEach(function(e4) {
                return n3.dispatch(e4);
              });
              var r3 = [], t50 = e3.map(function(e4) {
                var t51 = new l2(), n4 = i3.slice();
                return f2(o3, t51, n4).dispatch(e4), r3 = r3.concat(n4.slice(i3.length)), t51.read().toString();
              });
              return i3 = i3.concat(r3), t50.sort(), this._array(t50, false);
            }, _date: function(e3) {
              return u3("date:" + e3.toJSON());
            }, _symbol: function(e3) {
              return u3("symbol:" + e3.toString());
            }, _error: function(e3) {
              return u3("error:" + e3.toString());
            }, _boolean: function(e3) {
              return u3("bool:" + e3.toString());
            }, _string: function(e3) {
              u3("string:" + e3.length + ":"), u3(e3.toString());
            }, _function: function(e3) {
              u3("fn:"), a2(e3) ? this.dispatch("[native]") : this.dispatch(e3.toString()), false !== o3.respectFunctionNames && this.dispatch("function-name:" + String(e3.name)), o3.respectFunctionProperties && this._object(e3);
            }, _number: function(e3) {
              return u3("number:" + e3.toString());
            }, _xml: function(e3) {
              return u3("xml:" + e3.toString());
            }, _null: function() {
              return u3("Null");
            }, _undefined: function() {
              return u3("Undefined");
            }, _regexp: function(e3) {
              return u3("regex:" + e3.toString());
            }, _uint8array: function(e3) {
              return u3("uint8array:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _uint8clampedarray: function(e3) {
              return u3("uint8clampedarray:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _int8array: function(e3) {
              return u3("int8array:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _uint16array: function(e3) {
              return u3("uint16array:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _int16array: function(e3) {
              return u3("int16array:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _uint32array: function(e3) {
              return u3("uint32array:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _int32array: function(e3) {
              return u3("int32array:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _float32array: function(e3) {
              return u3("float32array:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _float64array: function(e3) {
              return u3("float64array:"), this.dispatch(Array.prototype.slice.call(e3));
            }, _arraybuffer: function(e3) {
              return u3("arraybuffer:"), this.dispatch(new Uint8Array(e3));
            }, _url: function(e3) {
              return u3("url:" + e3.toString());
            }, _map: function(e3) {
              u3("map:");
              e3 = Array.from(e3);
              return this._array(e3, false !== o3.unorderedSets);
            }, _set: function(e3) {
              u3("set:");
              e3 = Array.from(e3);
              return this._array(e3, false !== o3.unorderedSets);
            }, _file: function(e3) {
              return u3("file:"), this.dispatch([e3.name, e3.size, e3.type, e3.lastModfied]);
            }, _blob: function() {
              if (o3.ignoreUnknown) return u3("[blob]");
              throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n');
            }, _domwindow: function() {
              return u3("domwindow");
            }, _bigint: function(e3) {
              return u3("bigint:" + e3.toString());
            }, _process: function() {
              return u3("process");
            }, _timer: function() {
              return u3("timer");
            }, _pipe: function() {
              return u3("pipe");
            }, _tcp: function() {
              return u3("tcp");
            }, _udp: function() {
              return u3("udp");
            }, _tty: function() {
              return u3("tty");
            }, _statwatcher: function() {
              return u3("statwatcher");
            }, _securecontext: function() {
              return u3("securecontext");
            }, _connection: function() {
              return u3("connection");
            }, _zlib: function() {
              return u3("zlib");
            }, _context: function() {
              return u3("context");
            }, _nodescript: function() {
              return u3("nodescript");
            }, _httpparser: function() {
              return u3("httpparser");
            }, _dataview: function() {
              return u3("dataview");
            }, _signal: function() {
              return u3("signal");
            }, _fsevent: function() {
              return u3("fsevent");
            }, _tlswrap: function() {
              return u3("tlswrap");
            } };
          }
          function l2() {
            return { buf: "", write: function(e3) {
              this.buf += e3;
            }, end: function(e3) {
              this.buf += e3;
            }, read: function() {
              return this.buf;
            } };
          }
          m2.writeToStream = function(e3, t49, n3) {
            return void 0 === n3 && (n3 = t49, t49 = {}), f2(t49 = u2(e3, t49), n3).dispatch(e3);
          };
        }.call(this, w2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, w2("buffer").Buffer, arguments[3], arguments[4], arguments[5], arguments[6], "/fake_9a5aa49d.js", "/");
      }, { buffer: 3, crypto: 5, lYpoI2: 11 }], 2: [function(e2, t48, f2) {
        !function(e3, t49, n2, r2, o2, i2, u2, s2, a2) {
          !(function(e4) {
            "use strict";
            var a3 = "undefined" != typeof Uint8Array ? Uint8Array : Array, t50 = "+".charCodeAt(0), n3 = "/".charCodeAt(0), r3 = "0".charCodeAt(0), o3 = "a".charCodeAt(0), i3 = "A".charCodeAt(0), u3 = "-".charCodeAt(0), s3 = "_".charCodeAt(0);
            function f3(e5) {
              e5 = e5.charCodeAt(0);
              return e5 === t50 || e5 === u3 ? 62 : e5 === n3 || e5 === s3 ? 63 : e5 < r3 ? -1 : e5 < r3 + 10 ? e5 - r3 + 26 + 26 : e5 < i3 + 26 ? e5 - i3 : e5 < o3 + 26 ? e5 - o3 + 26 : void 0;
            }
            e4.toByteArray = function(e5) {
              var t51, n4;
              if (0 < e5.length % 4) throw new Error("Invalid string. Length must be a multiple of 4");
              var r4 = e5.length, r4 = "=" === e5.charAt(r4 - 2) ? 2 : "=" === e5.charAt(r4 - 1) ? 1 : 0, o4 = new a3(3 * e5.length / 4 - r4), i4 = 0 < r4 ? e5.length - 4 : e5.length, u4 = 0;
              function s4(e6) {
                o4[u4++] = e6;
              }
              for (t51 = 0; t51 < i4; t51 += 4, 0) s4((16711680 & (n4 = f3(e5.charAt(t51)) << 18 | f3(e5.charAt(t51 + 1)) << 12 | f3(e5.charAt(t51 + 2)) << 6 | f3(e5.charAt(t51 + 3)))) >> 16), s4((65280 & n4) >> 8), s4(255 & n4);
              return 2 == r4 ? s4(255 & (n4 = f3(e5.charAt(t51)) << 2 | f3(e5.charAt(t51 + 1)) >> 4)) : 1 == r4 && (s4((n4 = f3(e5.charAt(t51)) << 10 | f3(e5.charAt(t51 + 1)) << 4 | f3(e5.charAt(t51 + 2)) >> 2) >> 8 & 255), s4(255 & n4)), o4;
            }, e4.fromByteArray = function(e5) {
              var t51, n4, r4, o4, i4 = e5.length % 3, u4 = "";
              function s4(e6) {
                return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e6);
              }
              for (t51 = 0, r4 = e5.length - i4; t51 < r4; t51 += 3) n4 = (e5[t51] << 16) + (e5[t51 + 1] << 8) + e5[t51 + 2], u4 += s4((o4 = n4) >> 18 & 63) + s4(o4 >> 12 & 63) + s4(o4 >> 6 & 63) + s4(63 & o4);
              switch (i4) {
                case 1:
                  u4 = (u4 += s4((n4 = e5[e5.length - 1]) >> 2)) + s4(n4 << 4 & 63) + "==";
                  break;
                case 2:
                  u4 = (u4 = (u4 += s4((n4 = (e5[e5.length - 2] << 8) + e5[e5.length - 1]) >> 10)) + s4(n4 >> 4 & 63)) + s4(n4 << 2 & 63) + "=";
              }
              return u4;
            };
          })(void 0 === f2 ? this.base64js = {} : f2);
        }.call(this, e2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, e2("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(O2, e2, H2) {
        !function(e3, n2, f2, r2, h2, p2, g2, y2, w2) {
          var a2 = O2("base64-js"), i2 = O2("ieee754");
          function f2(e4, t49, n3) {
            if (!(this instanceof f2)) return new f2(e4, t49, n3);
            var r3, o3, i3, u3, s3 = typeof e4;
            if ("base64" === t49 && "string" == s3) for (e4 = (u3 = e4).trim ? u3.trim() : u3.replace(/^\s+|\s+$/g, ""); e4.length % 4 != 0; ) e4 += "=";
            if ("number" == s3) r3 = j2(e4);
            else if ("string" == s3) r3 = f2.byteLength(e4, t49);
            else {
              if ("object" != s3) throw new Error("First argument needs to be a number, array or string.");
              r3 = j2(e4.length);
            }
            if (f2._useTypedArrays ? o3 = f2._augment(new Uint8Array(r3)) : ((o3 = this).length = r3, o3._isBuffer = true), f2._useTypedArrays && "number" == typeof e4.byteLength) o3._set(e4);
            else if (C2(u3 = e4) || f2.isBuffer(u3) || u3 && "object" == typeof u3 && "number" == typeof u3.length) for (i3 = 0; i3 < r3; i3++) f2.isBuffer(e4) ? o3[i3] = e4.readUInt8(i3) : o3[i3] = e4[i3];
            else if ("string" == s3) o3.write(e4, 0, t49);
            else if ("number" == s3 && !f2._useTypedArrays && !n3) for (i3 = 0; i3 < r3; i3++) o3[i3] = 0;
            return o3;
          }
          function b2(e4, t49, n3, r3) {
            return f2._charsWritten = c2((function(e5) {
              for (var t50 = [], n4 = 0; n4 < e5.length; n4++) t50.push(255 & e5.charCodeAt(n4));
              return t50;
            })(t49), e4, n3, r3);
          }
          function m2(e4, t49, n3, r3) {
            return f2._charsWritten = c2((function(e5) {
              for (var t50, n4, r4 = [], o3 = 0; o3 < e5.length; o3++) n4 = e5.charCodeAt(o3), t50 = n4 >> 8, n4 = n4 % 256, r4.push(n4), r4.push(t50);
              return r4;
            })(t49), e4, n3, r3);
          }
          function v2(e4, t49, n3) {
            var r3 = "";
            n3 = Math.min(e4.length, n3);
            for (var o3 = t49; o3 < n3; o3++) r3 += String.fromCharCode(e4[o3]);
            return r3;
          }
          function o2(e4, t49, n3, r3) {
            r3 || (d2("boolean" == typeof n3, "missing or invalid endian"), d2(null != t49, "missing offset"), d2(t49 + 1 < e4.length, "Trying to read beyond buffer length"));
            var o3, r3 = e4.length;
            if (!(r3 <= t49)) return n3 ? (o3 = e4[t49], t49 + 1 < r3 && (o3 |= e4[t49 + 1] << 8)) : (o3 = e4[t49] << 8, t49 + 1 < r3 && (o3 |= e4[t49 + 1])), o3;
          }
          function u2(e4, t49, n3, r3) {
            r3 || (d2("boolean" == typeof n3, "missing or invalid endian"), d2(null != t49, "missing offset"), d2(t49 + 3 < e4.length, "Trying to read beyond buffer length"));
            var o3, r3 = e4.length;
            if (!(r3 <= t49)) return n3 ? (t49 + 2 < r3 && (o3 = e4[t49 + 2] << 16), t49 + 1 < r3 && (o3 |= e4[t49 + 1] << 8), o3 |= e4[t49], t49 + 3 < r3 && (o3 += e4[t49 + 3] << 24 >>> 0)) : (t49 + 1 < r3 && (o3 = e4[t49 + 1] << 16), t49 + 2 < r3 && (o3 |= e4[t49 + 2] << 8), t49 + 3 < r3 && (o3 |= e4[t49 + 3]), o3 += e4[t49] << 24 >>> 0), o3;
          }
          function _2(e4, t49, n3, r3) {
            if (r3 || (d2("boolean" == typeof n3, "missing or invalid endian"), d2(null != t49, "missing offset"), d2(t49 + 1 < e4.length, "Trying to read beyond buffer length")), !(e4.length <= t49)) return r3 = o2(e4, t49, n3, true), 32768 & r3 ? -1 * (65535 - r3 + 1) : r3;
          }
          function E2(e4, t49, n3, r3) {
            if (r3 || (d2("boolean" == typeof n3, "missing or invalid endian"), d2(null != t49, "missing offset"), d2(t49 + 3 < e4.length, "Trying to read beyond buffer length")), !(e4.length <= t49)) return r3 = u2(e4, t49, n3, true), 2147483648 & r3 ? -1 * (4294967295 - r3 + 1) : r3;
          }
          function I2(e4, t49, n3, r3) {
            return r3 || (d2("boolean" == typeof n3, "missing or invalid endian"), d2(t49 + 3 < e4.length, "Trying to read beyond buffer length")), i2.read(e4, t49, n3, 23, 4);
          }
          function A2(e4, t49, n3, r3) {
            return r3 || (d2("boolean" == typeof n3, "missing or invalid endian"), d2(t49 + 7 < e4.length, "Trying to read beyond buffer length")), i2.read(e4, t49, n3, 52, 8);
          }
          function s2(e4, t49, n3, r3, o3) {
            o3 || (d2(null != t49, "missing value"), d2("boolean" == typeof r3, "missing or invalid endian"), d2(null != n3, "missing offset"), d2(n3 + 1 < e4.length, "trying to write beyond buffer length"), Y2(t49, 65535));
            o3 = e4.length;
            if (!(o3 <= n3)) for (var i3 = 0, u3 = Math.min(o3 - n3, 2); i3 < u3; i3++) e4[n3 + i3] = (t49 & 255 << 8 * (r3 ? i3 : 1 - i3)) >>> 8 * (r3 ? i3 : 1 - i3);
          }
          function l2(e4, t49, n3, r3, o3) {
            o3 || (d2(null != t49, "missing value"), d2("boolean" == typeof r3, "missing or invalid endian"), d2(null != n3, "missing offset"), d2(n3 + 3 < e4.length, "trying to write beyond buffer length"), Y2(t49, 4294967295));
            o3 = e4.length;
            if (!(o3 <= n3)) for (var i3 = 0, u3 = Math.min(o3 - n3, 4); i3 < u3; i3++) e4[n3 + i3] = t49 >>> 8 * (r3 ? i3 : 3 - i3) & 255;
          }
          function B2(e4, t49, n3, r3, o3) {
            o3 || (d2(null != t49, "missing value"), d2("boolean" == typeof r3, "missing or invalid endian"), d2(null != n3, "missing offset"), d2(n3 + 1 < e4.length, "Trying to write beyond buffer length"), F2(t49, 32767, -32768)), e4.length <= n3 || s2(e4, 0 <= t49 ? t49 : 65535 + t49 + 1, n3, r3, o3);
          }
          function L2(e4, t49, n3, r3, o3) {
            o3 || (d2(null != t49, "missing value"), d2("boolean" == typeof r3, "missing or invalid endian"), d2(null != n3, "missing offset"), d2(n3 + 3 < e4.length, "Trying to write beyond buffer length"), F2(t49, 2147483647, -2147483648)), e4.length <= n3 || l2(e4, 0 <= t49 ? t49 : 4294967295 + t49 + 1, n3, r3, o3);
          }
          function U2(e4, t49, n3, r3, o3) {
            o3 || (d2(null != t49, "missing value"), d2("boolean" == typeof r3, "missing or invalid endian"), d2(null != n3, "missing offset"), d2(n3 + 3 < e4.length, "Trying to write beyond buffer length"), D2(t49, 34028234663852886e22, -34028234663852886e22)), e4.length <= n3 || i2.write(e4, t49, n3, r3, 23, 4);
          }
          function x2(e4, t49, n3, r3, o3) {
            o3 || (d2(null != t49, "missing value"), d2("boolean" == typeof r3, "missing or invalid endian"), d2(null != n3, "missing offset"), d2(n3 + 7 < e4.length, "Trying to write beyond buffer length"), D2(t49, 17976931348623157e292, -17976931348623157e292)), e4.length <= n3 || i2.write(e4, t49, n3, r3, 52, 8);
          }
          H2.Buffer = f2, H2.SlowBuffer = f2, H2.INSPECT_MAX_BYTES = 50, f2.poolSize = 8192, f2._useTypedArrays = (function() {
            try {
              var e4 = new ArrayBuffer(0), t49 = new Uint8Array(e4);
              return t49.foo = function() {
                return 42;
              }, 42 === t49.foo() && "function" == typeof t49.subarray;
            } catch (e5) {
              return false;
            }
          })(), f2.isEncoding = function(e4) {
            switch (String(e4).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 true;
              default:
                return false;
            }
          }, f2.isBuffer = function(e4) {
            return !(null == e4 || !e4._isBuffer);
          }, f2.byteLength = function(e4, t49) {
            var n3;
            switch (e4 += "", t49 || "utf8") {
              case "hex":
                n3 = e4.length / 2;
                break;
              case "utf8":
              case "utf-8":
                n3 = T2(e4).length;
                break;
              case "ascii":
              case "binary":
              case "raw":
                n3 = e4.length;
                break;
              case "base64":
                n3 = M2(e4).length;
                break;
              case "ucs2":
              case "ucs-2":
              case "utf16le":
              case "utf-16le":
                n3 = 2 * e4.length;
                break;
              default:
                throw new Error("Unknown encoding");
            }
            return n3;
          }, f2.concat = function(e4, t49) {
            if (d2(C2(e4), "Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."), 0 === e4.length) return new f2(0);
            if (1 === e4.length) return e4[0];
            if ("number" != typeof t49) for (o3 = t49 = 0; o3 < e4.length; o3++) t49 += e4[o3].length;
            for (var n3 = new f2(t49), r3 = 0, o3 = 0; o3 < e4.length; o3++) {
              var i3 = e4[o3];
              i3.copy(n3, r3), r3 += i3.length;
            }
            return n3;
          }, f2.prototype.write = function(e4, t49, n3, r3) {
            isFinite(t49) ? isFinite(n3) || (r3 = n3, n3 = void 0) : (a3 = r3, r3 = t49, t49 = n3, n3 = a3), t49 = Number(t49) || 0;
            var o3, i3, u3, s3, a3 = this.length - t49;
            switch ((!n3 || a3 < (n3 = Number(n3))) && (n3 = a3), r3 = String(r3 || "utf8").toLowerCase()) {
              case "hex":
                o3 = (function(e5, t50, n4, r4) {
                  n4 = Number(n4) || 0;
                  var o4 = e5.length - n4;
                  (!r4 || o4 < (r4 = Number(r4))) && (r4 = o4), d2((o4 = t50.length) % 2 == 0, "Invalid hex string"), o4 / 2 < r4 && (r4 = o4 / 2);
                  for (var i4 = 0; i4 < r4; i4++) {
                    var u4 = parseInt(t50.substr(2 * i4, 2), 16);
                    d2(!isNaN(u4), "Invalid hex string"), e5[n4 + i4] = u4;
                  }
                  return f2._charsWritten = 2 * i4, i4;
                })(this, e4, t49, n3);
                break;
              case "utf8":
              case "utf-8":
                i3 = this, u3 = t49, s3 = n3, o3 = f2._charsWritten = c2(T2(e4), i3, u3, s3);
                break;
              case "ascii":
              case "binary":
                o3 = b2(this, e4, t49, n3);
                break;
              case "base64":
                i3 = this, u3 = t49, s3 = n3, o3 = f2._charsWritten = c2(M2(e4), i3, u3, s3);
                break;
              case "ucs2":
              case "ucs-2":
              case "utf16le":
              case "utf-16le":
                o3 = m2(this, e4, t49, n3);
                break;
              default:
                throw new Error("Unknown encoding");
            }
            return o3;
          }, f2.prototype.toString = function(e4, t49, n3) {
            var r3, o3, i3, u3, s3 = this;
            if (e4 = String(e4 || "utf8").toLowerCase(), t49 = Number(t49) || 0, (n3 = void 0 !== n3 ? Number(n3) : s3.length) === t49) return "";
            switch (e4) {
              case "hex":
                r3 = (function(e5, t50, n4) {
                  var r4 = e5.length;
                  (!t50 || t50 < 0) && (t50 = 0);
                  (!n4 || n4 < 0 || r4 < n4) && (n4 = r4);
                  for (var o4 = "", i4 = t50; i4 < n4; i4++) o4 += k2(e5[i4]);
                  return o4;
                })(s3, t49, n3);
                break;
              case "utf8":
              case "utf-8":
                r3 = (function(e5, t50, n4) {
                  var r4 = "", o4 = "";
                  n4 = Math.min(e5.length, n4);
                  for (var i4 = t50; i4 < n4; i4++) e5[i4] <= 127 ? (r4 += N2(o4) + String.fromCharCode(e5[i4]), o4 = "") : o4 += "%" + e5[i4].toString(16);
                  return r4 + N2(o4);
                })(s3, t49, n3);
                break;
              case "ascii":
              case "binary":
                r3 = v2(s3, t49, n3);
                break;
              case "base64":
                o3 = s3, u3 = n3, r3 = 0 === (i3 = t49) && u3 === o3.length ? a2.fromByteArray(o3) : a2.fromByteArray(o3.slice(i3, u3));
                break;
              case "ucs2":
              case "ucs-2":
              case "utf16le":
              case "utf-16le":
                r3 = (function(e5, t50, n4) {
                  for (var r4 = e5.slice(t50, n4), o4 = "", i4 = 0; i4 < r4.length; i4 += 2) o4 += String.fromCharCode(r4[i4] + 256 * r4[i4 + 1]);
                  return o4;
                })(s3, t49, n3);
                break;
              default:
                throw new Error("Unknown encoding");
            }
            return r3;
          }, f2.prototype.toJSON = function() {
            return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) };
          }, f2.prototype.copy = function(e4, t49, n3, r3) {
            if (t49 = t49 || 0, (r3 = r3 || 0 === r3 ? r3 : this.length) !== (n3 = n3 || 0) && 0 !== e4.length && 0 !== this.length) {
              d2(n3 <= r3, "sourceEnd < sourceStart"), d2(0 <= t49 && t49 < e4.length, "targetStart out of bounds"), d2(0 <= n3 && n3 < this.length, "sourceStart out of bounds"), d2(0 <= r3 && r3 <= this.length, "sourceEnd out of bounds"), r3 > this.length && (r3 = this.length);
              var o3 = (r3 = e4.length - t49 < r3 - n3 ? e4.length - t49 + n3 : r3) - n3;
              if (o3 < 100 || !f2._useTypedArrays) for (var i3 = 0; i3 < o3; i3++) e4[i3 + t49] = this[i3 + n3];
              else e4._set(this.subarray(n3, n3 + o3), t49);
            }
          }, f2.prototype.slice = function(e4, t49) {
            var n3 = this.length;
            if (e4 = S2(e4, n3, 0), t49 = S2(t49, n3, n3), f2._useTypedArrays) return f2._augment(this.subarray(e4, t49));
            for (var r3 = t49 - e4, o3 = new f2(r3, void 0, true), i3 = 0; i3 < r3; i3++) o3[i3] = this[i3 + e4];
            return o3;
          }, f2.prototype.get = function(e4) {
            return console.log(".get() is deprecated. Access using array indexes instead."), this.readUInt8(e4);
          }, f2.prototype.set = function(e4, t49) {
            return console.log(".set() is deprecated. Access using array indexes instead."), this.writeUInt8(e4, t49);
          }, f2.prototype.readUInt8 = function(e4, t49) {
            if (t49 || (d2(null != e4, "missing offset"), d2(e4 < this.length, "Trying to read beyond buffer length")), !(e4 >= this.length)) return this[e4];
          }, f2.prototype.readUInt16LE = function(e4, t49) {
            return o2(this, e4, true, t49);
          }, f2.prototype.readUInt16BE = function(e4, t49) {
            return o2(this, e4, false, t49);
          }, f2.prototype.readUInt32LE = function(e4, t49) {
            return u2(this, e4, true, t49);
          }, f2.prototype.readUInt32BE = function(e4, t49) {
            return u2(this, e4, false, t49);
          }, f2.prototype.readInt8 = function(e4, t49) {
            if (t49 || (d2(null != e4, "missing offset"), d2(e4 < this.length, "Trying to read beyond buffer length")), !(e4 >= this.length)) return 128 & this[e4] ? -1 * (255 - this[e4] + 1) : this[e4];
          }, f2.prototype.readInt16LE = function(e4, t49) {
            return _2(this, e4, true, t49);
          }, f2.prototype.readInt16BE = function(e4, t49) {
            return _2(this, e4, false, t49);
          }, f2.prototype.readInt32LE = function(e4, t49) {
            return E2(this, e4, true, t49);
          }, f2.prototype.readInt32BE = function(e4, t49) {
            return E2(this, e4, false, t49);
          }, f2.prototype.readFloatLE = function(e4, t49) {
            return I2(this, e4, true, t49);
          }, f2.prototype.readFloatBE = function(e4, t49) {
            return I2(this, e4, false, t49);
          }, f2.prototype.readDoubleLE = function(e4, t49) {
            return A2(this, e4, true, t49);
          }, f2.prototype.readDoubleBE = function(e4, t49) {
            return A2(this, e4, false, t49);
          }, f2.prototype.writeUInt8 = function(e4, t49, n3) {
            n3 || (d2(null != e4, "missing value"), d2(null != t49, "missing offset"), d2(t49 < this.length, "trying to write beyond buffer length"), Y2(e4, 255)), t49 >= this.length || (this[t49] = e4);
          }, f2.prototype.writeUInt16LE = function(e4, t49, n3) {
            s2(this, e4, t49, true, n3);
          }, f2.prototype.writeUInt16BE = function(e4, t49, n3) {
            s2(this, e4, t49, false, n3);
          }, f2.prototype.writeUInt32LE = function(e4, t49, n3) {
            l2(this, e4, t49, true, n3);
          }, f2.prototype.writeUInt32BE = function(e4, t49, n3) {
            l2(this, e4, t49, false, n3);
          }, f2.prototype.writeInt8 = function(e4, t49, n3) {
            n3 || (d2(null != e4, "missing value"), d2(null != t49, "missing offset"), d2(t49 < this.length, "Trying to write beyond buffer length"), F2(e4, 127, -128)), t49 >= this.length || (0 <= e4 ? this.writeUInt8(e4, t49, n3) : this.writeUInt8(255 + e4 + 1, t49, n3));
          }, f2.prototype.writeInt16LE = function(e4, t49, n3) {
            B2(this, e4, t49, true, n3);
          }, f2.prototype.writeInt16BE = function(e4, t49, n3) {
            B2(this, e4, t49, false, n3);
          }, f2.prototype.writeInt32LE = function(e4, t49, n3) {
            L2(this, e4, t49, true, n3);
          }, f2.prototype.writeInt32BE = function(e4, t49, n3) {
            L2(this, e4, t49, false, n3);
          }, f2.prototype.writeFloatLE = function(e4, t49, n3) {
            U2(this, e4, t49, true, n3);
          }, f2.prototype.writeFloatBE = function(e4, t49, n3) {
            U2(this, e4, t49, false, n3);
          }, f2.prototype.writeDoubleLE = function(e4, t49, n3) {
            x2(this, e4, t49, true, n3);
          }, f2.prototype.writeDoubleBE = function(e4, t49, n3) {
            x2(this, e4, t49, false, n3);
          }, f2.prototype.fill = function(e4, t49, n3) {
            if (t49 = t49 || 0, n3 = n3 || this.length, d2("number" == typeof (e4 = "string" == typeof (e4 = e4 || 0) ? e4.charCodeAt(0) : e4) && !isNaN(e4), "value is not a number"), d2(t49 <= n3, "end < start"), n3 !== t49 && 0 !== this.length) {
              d2(0 <= t49 && t49 < this.length, "start out of bounds"), d2(0 <= n3 && n3 <= this.length, "end out of bounds");
              for (var r3 = t49; r3 < n3; r3++) this[r3] = e4;
            }
          }, f2.prototype.inspect = function() {
            for (var e4 = [], t49 = this.length, n3 = 0; n3 < t49; n3++) if (e4[n3] = k2(this[n3]), n3 === H2.INSPECT_MAX_BYTES) {
              e4[n3 + 1] = "...";
              break;
            }
            return "<Buffer " + e4.join(" ") + ">";
          }, f2.prototype.toArrayBuffer = function() {
            if ("undefined" == typeof Uint8Array) throw new Error("Buffer.toArrayBuffer not supported in this browser");
            if (f2._useTypedArrays) return new f2(this).buffer;
            for (var e4 = new Uint8Array(this.length), t49 = 0, n3 = e4.length; t49 < n3; t49 += 1) e4[t49] = this[t49];
            return e4.buffer;
          };
          var t48 = f2.prototype;
          function S2(e4, t49, n3) {
            return "number" != typeof e4 ? n3 : t49 <= (e4 = ~~e4) ? t49 : 0 <= e4 || 0 <= (e4 += t49) ? e4 : 0;
          }
          function j2(e4) {
            return (e4 = ~~Math.ceil(+e4)) < 0 ? 0 : e4;
          }
          function C2(e4) {
            return (Array.isArray || function(e5) {
              return "[object Array]" === Object.prototype.toString.call(e5);
            })(e4);
          }
          function k2(e4) {
            return e4 < 16 ? "0" + e4.toString(16) : e4.toString(16);
          }
          function T2(e4) {
            for (var t49 = [], n3 = 0; n3 < e4.length; n3++) {
              var r3 = e4.charCodeAt(n3);
              if (r3 <= 127) t49.push(e4.charCodeAt(n3));
              else for (var o3 = n3, i3 = (55296 <= r3 && r3 <= 57343 && n3++, encodeURIComponent(e4.slice(o3, n3 + 1)).substr(1).split("%")), u3 = 0; u3 < i3.length; u3++) t49.push(parseInt(i3[u3], 16));
            }
            return t49;
          }
          function M2(e4) {
            return a2.toByteArray(e4);
          }
          function c2(e4, t49, n3, r3) {
            for (var o3 = 0; o3 < r3 && !(o3 + n3 >= t49.length || o3 >= e4.length); o3++) t49[o3 + n3] = e4[o3];
            return o3;
          }
          function N2(e4) {
            try {
              return decodeURIComponent(e4);
            } catch (e5) {
              return String.fromCharCode(65533);
            }
          }
          function Y2(e4, t49) {
            d2("number" == typeof e4, "cannot write a non-number as a number"), d2(0 <= e4, "specified a negative value for writing an unsigned value"), d2(e4 <= t49, "value is larger than maximum value for type"), d2(Math.floor(e4) === e4, "value has a fractional component");
          }
          function F2(e4, t49, n3) {
            d2("number" == typeof e4, "cannot write a non-number as a number"), d2(e4 <= t49, "value larger than maximum allowed value"), d2(n3 <= e4, "value smaller than minimum allowed value"), d2(Math.floor(e4) === e4, "value has a fractional component");
          }
          function D2(e4, t49, n3) {
            d2("number" == typeof e4, "cannot write a non-number as a number"), d2(e4 <= t49, "value larger than maximum allowed value"), d2(n3 <= e4, "value smaller than minimum allowed value");
          }
          function d2(e4, t49) {
            if (!e4) throw new Error(t49 || "Failed assertion");
          }
          f2._augment = function(e4) {
            return e4._isBuffer = true, e4._get = e4.get, e4._set = e4.set, e4.get = t48.get, e4.set = t48.set, e4.write = t48.write, e4.toString = t48.toString, e4.toLocaleString = t48.toString, e4.toJSON = t48.toJSON, e4.copy = t48.copy, e4.slice = t48.slice, e4.readUInt8 = t48.readUInt8, e4.readUInt16LE = t48.readUInt16LE, e4.readUInt16BE = t48.readUInt16BE, e4.readUInt32LE = t48.readUInt32LE, e4.readUInt32BE = t48.readUInt32BE, e4.readInt8 = t48.readInt8, e4.readInt16LE = t48.readInt16LE, e4.readInt16BE = t48.readInt16BE, e4.readInt32LE = t48.readInt32LE, e4.readInt32BE = t48.readInt32BE, e4.readFloatLE = t48.readFloatLE, e4.readFloatBE = t48.readFloatBE, e4.readDoubleLE = t48.readDoubleLE, e4.readDoubleBE = t48.readDoubleBE, e4.writeUInt8 = t48.writeUInt8, e4.writeUInt16LE = t48.writeUInt16LE, e4.writeUInt16BE = t48.writeUInt16BE, e4.writeUInt32LE = t48.writeUInt32LE, e4.writeUInt32BE = t48.writeUInt32BE, e4.writeInt8 = t48.writeInt8, e4.writeInt16LE = t48.writeInt16LE, e4.writeInt16BE = t48.writeInt16BE, e4.writeInt32LE = t48.writeInt32LE, e4.writeInt32BE = t48.writeInt32BE, e4.writeFloatLE = t48.writeFloatLE, e4.writeFloatBE = t48.writeFloatBE, e4.writeDoubleLE = t48.writeDoubleLE, e4.writeDoubleBE = t48.writeDoubleBE, e4.fill = t48.fill, e4.inspect = t48.inspect, e4.toArrayBuffer = t48.toArrayBuffer, e4;
          };
        }.call(this, O2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, O2("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(c2, d2, e2) {
        !function(e3, t48, a2, n2, r2, o2, i2, u2, s2) {
          var a2 = c2("buffer").Buffer, f2 = 4, l2 = new a2(f2);
          l2.fill(0);
          d2.exports = { hash: function(e4, t49, n3, r3) {
            for (var o3 = t49((function(e5, t50) {
              e5.length % f2 != 0 && (n4 = e5.length + (f2 - e5.length % f2), e5 = a2.concat([e5, l2], n4));
              for (var n4, r4 = [], o4 = t50 ? e5.readInt32BE : e5.readInt32LE, i4 = 0; i4 < e5.length; i4 += f2) r4.push(o4.call(e5, i4));
              return r4;
            })(e4 = a2.isBuffer(e4) ? e4 : new a2(e4), r3), 8 * e4.length), t49 = r3, i3 = new a2(n3), u3 = t49 ? i3.writeInt32BE : i3.writeInt32LE, s3 = 0; s3 < o3.length; s3++) u3.call(i3, o3[s3], 4 * s3, true);
            return i3;
          } };
        }.call(this, c2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, c2("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(v2, e2, _2) {
        !function(l2, c2, u2, d2, h2, p2, g2, y2, w2) {
          var u2 = v2("buffer").Buffer, e3 = v2("./sha"), t48 = v2("./sha256"), n2 = v2("./rng"), b2 = { sha1: e3, sha256: t48, md5: v2("./md5") }, s2 = 64, a2 = new u2(s2);
          function r2(e4, n3) {
            var r3 = b2[e4 = e4 || "sha1"], o3 = [];
            return r3 || i2("algorithm:", e4, "is not yet supported"), { update: function(e5) {
              return u2.isBuffer(e5) || (e5 = new u2(e5)), o3.push(e5), e5.length, this;
            }, digest: function(e5) {
              var t49 = u2.concat(o3), t49 = n3 ? (function(e6, t50, n4) {
                u2.isBuffer(t50) || (t50 = new u2(t50)), u2.isBuffer(n4) || (n4 = new u2(n4)), t50.length > s2 ? t50 = e6(t50) : t50.length < s2 && (t50 = u2.concat([t50, a2], s2));
                for (var r4 = new u2(s2), o4 = new u2(s2), i3 = 0; i3 < s2; i3++) r4[i3] = 54 ^ t50[i3], o4[i3] = 92 ^ t50[i3];
                return n4 = e6(u2.concat([r4, n4])), e6(u2.concat([o4, n4]));
              })(r3, n3, t49) : r3(t49);
              return o3 = null, e5 ? t49.toString(e5) : t49;
            } };
          }
          function i2() {
            var e4 = [].slice.call(arguments).join(" ");
            throw new Error([e4, "we accept pull requests", "http://github.com/dominictarr/crypto-browserify"].join("\n"));
          }
          a2.fill(0), _2.createHash = function(e4) {
            return r2(e4);
          }, _2.createHmac = r2, _2.randomBytes = function(e4, t49) {
            if (!t49 || !t49.call) return new u2(n2(e4));
            try {
              t49.call(this, void 0, new u2(n2(e4)));
            } catch (e5) {
              t49(e5);
            }
          };
          var o2, f2 = ["createCredentials", "createCipher", "createCipheriv", "createDecipher", "createDecipheriv", "createSign", "createVerify", "createDiffieHellman", "pbkdf2"], m2 = function(e4) {
            _2[e4] = function() {
              i2("sorry,", e4, "is not implemented yet");
            };
          };
          for (o2 in f2) m2(f2[o2], o2);
        }.call(this, v2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, v2("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(w2, b2, e2) {
        !function(e3, r2, o2, i2, u2, a2, f2, l2, y2) {
          var t48 = w2("./helpers");
          function n2(e4, t49) {
            e4[t49 >> 5] |= 128 << t49 % 32, e4[14 + (t49 + 64 >>> 9 << 4)] = t49;
            for (var n3 = 1732584193, r3 = -271733879, o3 = -1732584194, i3 = 271733878, u3 = 0; u3 < e4.length; u3 += 16) {
              var s3 = n3, a3 = r3, f3 = o3, l3 = i3, n3 = c2(n3, r3, o3, i3, e4[u3 + 0], 7, -680876936), i3 = c2(i3, n3, r3, o3, e4[u3 + 1], 12, -389564586), o3 = c2(o3, i3, n3, r3, e4[u3 + 2], 17, 606105819), r3 = c2(r3, o3, i3, n3, e4[u3 + 3], 22, -1044525330);
              n3 = c2(n3, r3, o3, i3, e4[u3 + 4], 7, -176418897), i3 = c2(i3, n3, r3, o3, e4[u3 + 5], 12, 1200080426), o3 = c2(o3, i3, n3, r3, e4[u3 + 6], 17, -1473231341), r3 = c2(r3, o3, i3, n3, e4[u3 + 7], 22, -45705983), n3 = c2(n3, r3, o3, i3, e4[u3 + 8], 7, 1770035416), i3 = c2(i3, n3, r3, o3, e4[u3 + 9], 12, -1958414417), o3 = c2(o3, i3, n3, r3, e4[u3 + 10], 17, -42063), r3 = c2(r3, o3, i3, n3, e4[u3 + 11], 22, -1990404162), n3 = c2(n3, r3, o3, i3, e4[u3 + 12], 7, 1804603682), i3 = c2(i3, n3, r3, o3, e4[u3 + 13], 12, -40341101), o3 = c2(o3, i3, n3, r3, e4[u3 + 14], 17, -1502002290), n3 = d2(n3, r3 = c2(r3, o3, i3, n3, e4[u3 + 15], 22, 1236535329), o3, i3, e4[u3 + 1], 5, -165796510), i3 = d2(i3, n3, r3, o3, e4[u3 + 6], 9, -1069501632), o3 = d2(o3, i3, n3, r3, e4[u3 + 11], 14, 643717713), r3 = d2(r3, o3, i3, n3, e4[u3 + 0], 20, -373897302), n3 = d2(n3, r3, o3, i3, e4[u3 + 5], 5, -701558691), i3 = d2(i3, n3, r3, o3, e4[u3 + 10], 9, 38016083), o3 = d2(o3, i3, n3, r3, e4[u3 + 15], 14, -660478335), r3 = d2(r3, o3, i3, n3, e4[u3 + 4], 20, -405537848), n3 = d2(n3, r3, o3, i3, e4[u3 + 9], 5, 568446438), i3 = d2(i3, n3, r3, o3, e4[u3 + 14], 9, -1019803690), o3 = d2(o3, i3, n3, r3, e4[u3 + 3], 14, -187363961), r3 = d2(r3, o3, i3, n3, e4[u3 + 8], 20, 1163531501), n3 = d2(n3, r3, o3, i3, e4[u3 + 13], 5, -1444681467), i3 = d2(i3, n3, r3, o3, e4[u3 + 2], 9, -51403784), o3 = d2(o3, i3, n3, r3, e4[u3 + 7], 14, 1735328473), n3 = h2(n3, r3 = d2(r3, o3, i3, n3, e4[u3 + 12], 20, -1926607734), o3, i3, e4[u3 + 5], 4, -378558), i3 = h2(i3, n3, r3, o3, e4[u3 + 8], 11, -2022574463), o3 = h2(o3, i3, n3, r3, e4[u3 + 11], 16, 1839030562), r3 = h2(r3, o3, i3, n3, e4[u3 + 14], 23, -35309556), n3 = h2(n3, r3, o3, i3, e4[u3 + 1], 4, -1530992060), i3 = h2(i3, n3, r3, o3, e4[u3 + 4], 11, 1272893353), o3 = h2(o3, i3, n3, r3, e4[u3 + 7], 16, -155497632), r3 = h2(r3, o3, i3, n3, e4[u3 + 10], 23, -1094730640), n3 = h2(n3, r3, o3, i3, e4[u3 + 13], 4, 681279174), i3 = h2(i3, n3, r3, o3, e4[u3 + 0], 11, -358537222), o3 = h2(o3, i3, n3, r3, e4[u3 + 3], 16, -722521979), r3 = h2(r3, o3, i3, n3, e4[u3 + 6], 23, 76029189), n3 = h2(n3, r3, o3, i3, e4[u3 + 9], 4, -640364487), i3 = h2(i3, n3, r3, o3, e4[u3 + 12], 11, -421815835), o3 = h2(o3, i3, n3, r3, e4[u3 + 15], 16, 530742520), n3 = p2(n3, r3 = h2(r3, o3, i3, n3, e4[u3 + 2], 23, -995338651), o3, i3, e4[u3 + 0], 6, -198630844), i3 = p2(i3, n3, r3, o3, e4[u3 + 7], 10, 1126891415), o3 = p2(o3, i3, n3, r3, e4[u3 + 14], 15, -1416354905), r3 = p2(r3, o3, i3, n3, e4[u3 + 5], 21, -57434055), n3 = p2(n3, r3, o3, i3, e4[u3 + 12], 6, 1700485571), i3 = p2(i3, n3, r3, o3, e4[u3 + 3], 10, -1894986606), o3 = p2(o3, i3, n3, r3, e4[u3 + 10], 15, -1051523), r3 = p2(r3, o3, i3, n3, e4[u3 + 1], 21, -2054922799), n3 = p2(n3, r3, o3, i3, e4[u3 + 8], 6, 1873313359), i3 = p2(i3, n3, r3, o3, e4[u3 + 15], 10, -30611744), o3 = p2(o3, i3, n3, r3, e4[u3 + 6], 15, -1560198380), r3 = p2(r3, o3, i3, n3, e4[u3 + 13], 21, 1309151649), n3 = p2(n3, r3, o3, i3, e4[u3 + 4], 6, -145523070), i3 = p2(i3, n3, r3, o3, e4[u3 + 11], 10, -1120210379), o3 = p2(o3, i3, n3, r3, e4[u3 + 2], 15, 718787259), r3 = p2(r3, o3, i3, n3, e4[u3 + 9], 21, -343485551), n3 = g2(n3, s3), r3 = g2(r3, a3), o3 = g2(o3, f3), i3 = g2(i3, l3);
            }
            return Array(n3, r3, o3, i3);
          }
          function s2(e4, t49, n3, r3, o3, i3) {
            return g2((t49 = g2(g2(t49, e4), g2(r3, i3))) << o3 | t49 >>> 32 - o3, n3);
          }
          function c2(e4, t49, n3, r3, o3, i3, u3) {
            return s2(t49 & n3 | ~t49 & r3, e4, t49, o3, i3, u3);
          }
          function d2(e4, t49, n3, r3, o3, i3, u3) {
            return s2(t49 & r3 | n3 & ~r3, e4, t49, o3, i3, u3);
          }
          function h2(e4, t49, n3, r3, o3, i3, u3) {
            return s2(t49 ^ n3 ^ r3, e4, t49, o3, i3, u3);
          }
          function p2(e4, t49, n3, r3, o3, i3, u3) {
            return s2(n3 ^ (t49 | ~r3), e4, t49, o3, i3, u3);
          }
          function g2(e4, t49) {
            var n3 = (65535 & e4) + (65535 & t49);
            return (e4 >> 16) + (t49 >> 16) + (n3 >> 16) << 16 | 65535 & n3;
          }
          b2.exports = function(e4) {
            return t48.hash(e4, n2, 16);
          };
        }.call(this, w2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, w2("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(e2, l2, t48) {
        !function(e3, t49, n2, r2, o2, i2, u2, s2, f2) {
          var a2;
          l2.exports = a2 || function(e4) {
            for (var t50, n3 = new Array(e4), r3 = 0; r3 < e4; r3++) 0 == (3 & r3) && (t50 = 4294967296 * Math.random()), n3[r3] = t50 >>> ((3 & r3) << 3) & 255;
            return n3;
          };
        }.call(this, e2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, e2("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(c2, d2, e2) {
        !function(e3, t48, n2, r2, o2, s2, a2, f2, l2) {
          var i2 = c2("./helpers");
          function u2(l3, c3) {
            l3[c3 >> 5] |= 128 << 24 - c3 % 32, l3[15 + (c3 + 64 >> 9 << 4)] = c3;
            for (var e4, t49, n3, r3 = Array(80), o3 = 1732584193, i3 = -271733879, u3 = -1732584194, s3 = 271733878, d3 = -1009589776, h2 = 0; h2 < l3.length; h2 += 16) {
              for (var p2 = o3, g2 = i3, y2 = u3, w2 = s3, b2 = d3, a3 = 0; a3 < 80; a3++) {
                r3[a3] = a3 < 16 ? l3[h2 + a3] : v2(r3[a3 - 3] ^ r3[a3 - 8] ^ r3[a3 - 14] ^ r3[a3 - 16], 1);
                var f3 = m2(m2(v2(o3, 5), (f3 = i3, t49 = u3, n3 = s3, (e4 = a3) < 20 ? f3 & t49 | ~f3 & n3 : !(e4 < 40) && e4 < 60 ? f3 & t49 | f3 & n3 | t49 & n3 : f3 ^ t49 ^ n3)), m2(m2(d3, r3[a3]), (e4 = a3) < 20 ? 1518500249 : e4 < 40 ? 1859775393 : e4 < 60 ? -1894007588 : -899497514)), d3 = s3, s3 = u3, u3 = v2(i3, 30), i3 = o3, o3 = f3;
              }
              o3 = m2(o3, p2), i3 = m2(i3, g2), u3 = m2(u3, y2), s3 = m2(s3, w2), d3 = m2(d3, b2);
            }
            return Array(o3, i3, u3, s3, d3);
          }
          function m2(e4, t49) {
            var n3 = (65535 & e4) + (65535 & t49);
            return (e4 >> 16) + (t49 >> 16) + (n3 >> 16) << 16 | 65535 & n3;
          }
          function v2(e4, t49) {
            return e4 << t49 | e4 >>> 32 - t49;
          }
          d2.exports = function(e4) {
            return i2.hash(e4, u2, 20, true);
          };
        }.call(this, c2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, c2("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(c2, d2, e2) {
        !function(e3, t48, n2, r2, u2, s2, a2, f2, l2) {
          function b2(e4, t49) {
            var n3 = (65535 & e4) + (65535 & t49);
            return (e4 >> 16) + (t49 >> 16) + (n3 >> 16) << 16 | 65535 & n3;
          }
          function o2(e4, l3) {
            var c3, d3 = 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), t49 = new Array(1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225), n3 = new Array(64);
            e4[l3 >> 5] |= 128 << 24 - l3 % 32, e4[15 + (l3 + 64 >> 9 << 4)] = l3;
            for (var r3, o3, h2 = 0; h2 < e4.length; h2 += 16) {
              for (var i3 = t49[0], u3 = t49[1], s3 = t49[2], p2 = t49[3], a3 = t49[4], g2 = t49[5], y2 = t49[6], w2 = t49[7], f3 = 0; f3 < 64; f3++) n3[f3] = f3 < 16 ? e4[f3 + h2] : b2(b2(b2((o3 = n3[f3 - 2], m2(o3, 17) ^ m2(o3, 19) ^ v2(o3, 10)), n3[f3 - 7]), (o3 = n3[f3 - 15], m2(o3, 7) ^ m2(o3, 18) ^ v2(o3, 3))), n3[f3 - 16]), c3 = b2(b2(b2(b2(w2, m2(o3 = a3, 6) ^ m2(o3, 11) ^ m2(o3, 25)), a3 & g2 ^ ~a3 & y2), d3[f3]), n3[f3]), r3 = b2(m2(r3 = i3, 2) ^ m2(r3, 13) ^ m2(r3, 22), i3 & u3 ^ i3 & s3 ^ u3 & s3), w2 = y2, y2 = g2, g2 = a3, a3 = b2(p2, c3), p2 = s3, s3 = u3, u3 = i3, i3 = b2(c3, r3);
              t49[0] = b2(i3, t49[0]), t49[1] = b2(u3, t49[1]), t49[2] = b2(s3, t49[2]), t49[3] = b2(p2, t49[3]), t49[4] = b2(a3, t49[4]), t49[5] = b2(g2, t49[5]), t49[6] = b2(y2, t49[6]), t49[7] = b2(w2, t49[7]);
            }
            return t49;
          }
          var i2 = c2("./helpers"), m2 = function(e4, t49) {
            return e4 >>> t49 | e4 << 32 - t49;
          }, v2 = function(e4, t49) {
            return e4 >>> t49;
          };
          d2.exports = function(e4) {
            return i2.hash(e4, o2, 32, true);
          };
        }.call(this, c2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, c2("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(e2, t48, f2) {
        !function(e3, t49, n2, r2, o2, i2, u2, s2, a2) {
          f2.read = function(e4, t50, n3, r3, o3) {
            var i3, u3, l2 = 8 * o3 - r3 - 1, c2 = (1 << l2) - 1, d2 = c2 >> 1, s3 = -7, a3 = n3 ? o3 - 1 : 0, f3 = n3 ? -1 : 1, o3 = e4[t50 + a3];
            for (a3 += f3, i3 = o3 & (1 << -s3) - 1, o3 >>= -s3, s3 += l2; 0 < s3; i3 = 256 * i3 + e4[t50 + a3], a3 += f3, s3 -= 8) ;
            for (u3 = i3 & (1 << -s3) - 1, i3 >>= -s3, s3 += r3; 0 < s3; u3 = 256 * u3 + e4[t50 + a3], a3 += f3, s3 -= 8) ;
            if (0 === i3) i3 = 1 - d2;
            else {
              if (i3 === c2) return u3 ? NaN : 1 / 0 * (o3 ? -1 : 1);
              u3 += Math.pow(2, r3), i3 -= d2;
            }
            return (o3 ? -1 : 1) * u3 * Math.pow(2, i3 - r3);
          }, f2.write = function(e4, t50, l2, n3, r3, c2) {
            var o3, i3, u3 = 8 * c2 - r3 - 1, s3 = (1 << u3) - 1, a3 = s3 >> 1, d2 = 23 === r3 ? Math.pow(2, -24) - Math.pow(2, -77) : 0, f3 = n3 ? 0 : c2 - 1, h2 = n3 ? 1 : -1, c2 = t50 < 0 || 0 === t50 && 1 / t50 < 0 ? 1 : 0;
            for (t50 = Math.abs(t50), isNaN(t50) || t50 === 1 / 0 ? (i3 = isNaN(t50) ? 1 : 0, o3 = s3) : (o3 = Math.floor(Math.log(t50) / Math.LN2), t50 * (n3 = Math.pow(2, -o3)) < 1 && (o3--, n3 *= 2), 2 <= (t50 += 1 <= o3 + a3 ? d2 / n3 : d2 * Math.pow(2, 1 - a3)) * n3 && (o3++, n3 /= 2), s3 <= o3 + a3 ? (i3 = 0, o3 = s3) : 1 <= o3 + a3 ? (i3 = (t50 * n3 - 1) * Math.pow(2, r3), o3 += a3) : (i3 = t50 * Math.pow(2, a3 - 1) * Math.pow(2, r3), o3 = 0)); 8 <= r3; e4[l2 + f3] = 255 & i3, f3 += h2, i3 /= 256, r3 -= 8) ;
            for (o3 = o3 << r3 | i3, u3 += r3; 0 < u3; e4[l2 + f3] = 255 & o3, f3 += h2, o3 /= 256, u3 -= 8) ;
            e4[l2 + f3 - h2] |= 128 * c2;
          };
        }.call(this, e2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, e2("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(e2, h2, t48) {
        !function(e3, t49, n2, r2, o2, f2, l2, c2, d2) {
          var i2, u2, s2;
          function a2() {
          }
          (e3 = h2.exports = {}).nextTick = (u2 = "undefined" != typeof window && window.setImmediate, s2 = "undefined" != typeof window && window.postMessage && window.addEventListener, u2 ? function(e4) {
            return window.setImmediate(e4);
          } : s2 ? (i2 = [], window.addEventListener("message", function(e4) {
            var t50 = e4.source;
            t50 !== window && null !== t50 || "process-tick" !== e4.data || (e4.stopPropagation(), 0 < i2.length && i2.shift()());
          }, true), function(e4) {
            i2.push(e4), window.postMessage("process-tick", "*");
          }) : function(e4) {
            setTimeout(e4, 0);
          }), e3.title = "browser", e3.browser = true, e3.env = {}, e3.argv = [], e3.on = a2, e3.addListener = a2, e3.once = a2, e3.off = a2, e3.removeListener = a2, e3.removeAllListeners = a2, e3.emit = a2, e3.binding = function(e4) {
            throw new Error("process.binding is not supported");
          }, e3.cwd = function() {
            return "/";
          }, e3.chdir = function(e4) {
            throw new Error("process.chdir is not supported");
          };
        }.call(this, e2("lYpoI2"), "undefined" != typeof self ? self : "undefined" != typeof window ? window : {}, e2("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);
    });
  }
});

// lib/geometry.ts
function distance(a2, b2) {
  const dx2 = a2.x - b2.x, dy2 = a2.y - b2.y;
  return Math.sqrt(dx2 * dx2 + dy2 * dy2);
}
function pointSegmentDistance(p2, edge) {
  return pointSegmentDistanceToPoints(p2, edge[0], edge[1]);
}
function pointSegmentDistanceToPoints(p2, a2, b2) {
  const dx2 = b2.x - a2.x, dy2 = b2.y - a2.y;
  if (dx2 === 0 && dy2 === 0) return distance(p2, a2);
  const t48 = Math.max(
    0,
    Math.min(
      1,
      ((p2.x - a2.x) * dx2 + (p2.y - a2.y) * dy2) / (dx2 * dx2 + dy2 * dy2 || 1)
    )
  );
  const ex2 = p2.x - a2.x - t48 * dx2, ey2 = p2.y - a2.y - t48 * dy2;
  return Math.sqrt(ex2 * ex2 + ey2 * ey2);
}
var cross = (a2, b2, c2) => (b2.x - a2.x) * (c2.y - a2.y) - (b2.y - a2.y) * (c2.x - a2.x);
function segmentDistance(ab2, cd) {
  const [a2, b2] = ab2, [c2, d2] = cd;
  if (Math.max(a2.x, b2.x) >= Math.min(c2.x, d2.x) && Math.max(c2.x, d2.x) >= Math.min(a2.x, b2.x) && Math.max(a2.y, b2.y) >= Math.min(c2.y, d2.y) && Math.max(c2.y, d2.y) >= Math.min(a2.y, b2.y) && cross(a2, b2, c2) * cross(a2, b2, d2) <= 0 && cross(c2, d2, a2) * cross(c2, d2, b2) <= 0)
    return 0;
  return Math.min(
    pointSegmentDistance(a2, cd),
    pointSegmentDistance(b2, cd),
    pointSegmentDistance(c2, ab2),
    pointSegmentDistance(d2, ab2)
  );
}
var length = (path) => path.slice(1).reduce((sum, p2, i2) => sum + distance(path[i2], p2), 0);
function simplify(path) {
  const result = [];
  for (const [index2, point] of path.entries()) {
    if (result.length && distance(result.at(-1), point) < 1e-12) {
      if (index2 === path.length - 1) result[result.length - 1] = point;
      continue;
    }
    while (result.length > 1) {
      const a2 = result[result.length - 2], b2 = result.at(-1);
      const ux2 = b2.x - a2.x, uy2 = b2.y - a2.y;
      const vx2 = point.x - b2.x, vy2 = point.y - b2.y;
      const scale2 = Math.hypot(ux2, uy2) * Math.hypot(vx2, vy2);
      if (ux2 * vx2 + uy2 * vy2 <= 0 || Math.abs(ux2 * vy2 - uy2 * vx2) > scale2 * 1e-8 || pointSegmentDistance(b2, [a2, point]) > 1e-10)
        break;
      result.pop();
    }
    result.push(point);
  }
  return result;
}

// lib/route-lengths.ts
function fixedRouteLength(input, name) {
  const connection = input.connections.find((c2) => c2.name === name);
  return (input.traces ?? []).filter(
    (t48) => t48.connection_name === name || t48.source_trace_id === (connection?.source_trace_id ?? name)
  ).reduce((sum, t48) => sum + length(t48.route), 0);
}
function busLengthReports(input, traces) {
  return (input.buses ?? []).map((bus) => {
    const lengths = bus.connectionNames.map((name) => {
      const route = traces.find((t48) => t48.connection_name === name);
      return {
        name,
        carrierLengthMm: route ? length(route.route) : null,
        fixedLengthMm: fixedRouteLength(input, name),
        totalLengthMm: route ? length(route.route) + fixedRouteLength(input, name) : null
      };
    });
    const complete = lengths.every((l2) => l2.totalLengthMm !== null);
    const values = lengths.map((l2) => l2.totalLengthMm ?? 0);
    const skewMm = complete && values.length ? Math.max(...values) - Math.min(...values) : null;
    return {
      busId: bus.busId,
      minLengthMm: bus.minLength ?? null,
      aboveMinimumLength: bus.minLength === void 0 ? true : complete && values.every((value) => value >= bus.minLength - 1e-7),
      maxLengthMm: bus.maxLength ?? null,
      withinLengthLimit: bus.maxLength === void 0 ? true : complete && values.every((value) => value <= bus.maxLength + 1e-7),
      toleranceMm: bus.maxLengthSkew ?? null,
      skewMm,
      matched: bus.maxLengthSkew !== void 0 && skewMm !== null && skewMm <= bus.maxLengthSkew + 1e-7,
      lengths
    };
  });
}
function lengthConstraints(input) {
  return [
    ...(input.buses ?? []).filter((b2) => b2.maxLengthSkew !== void 0).map((b2) => ({
      names: b2.connectionNames,
      tolerance: b2.maxLengthSkew
    })),
    ...(input.differentialPairs ?? []).map((p2) => ({
      names: p2.connectionNames,
      tolerance: p2.lengthTolerance
    }))
  ];
}
function minimumLengthTargets(input, traces) {
  const targets = new Map(
    traces.map((t48) => [
      t48.connection_name,
      length(t48.route) + fixedRouteLength(input, t48.connection_name)
    ])
  );
  for (const bus of input.buses ?? [])
    if (bus.minLength !== void 0) {
      for (const name of bus.connectionNames)
        if (targets.has(name))
          targets.set(name, Math.max(targets.get(name), bus.minLength));
    }
  const constraints = lengthConstraints(input);
  for (let pass = 0; pass < targets.size; pass++) {
    let changed = false;
    for (const { names, tolerance } of constraints) {
      const floor = Math.max(...names.map((n2) => targets.get(n2))) - tolerance;
      for (const name of names)
        if (targets.get(name) < floor - 1e-9) {
          targets.set(name, floor);
          changed = true;
        }
    }
    if (!changed) break;
  }
  return targets;
}
function pairLengthReports(input, traces) {
  return busLengthReports(
    {
      ...input,
      buses: (input.differentialPairs ?? []).map((p2, i2) => ({
        busId: `pair_${i2}`,
        connectionNames: p2.connectionNames,
        maxLengthSkew: p2.lengthTolerance
      }))
    },
    traces
  );
}
function maximumCarrierLength(input, name) {
  return Math.min(
    Infinity,
    ...(input.buses ?? []).filter(
      (bus) => bus.connectionNames.includes(name) && bus.maxLength !== void 0
    ).map((bus) => bus.maxLength - fixedRouteLength(input, name))
  );
}
function assertLengthTargets(input, targets) {
  for (const bus of input.buses ?? [])
    if (bus.maxLength !== void 0 && bus.connectionNames.some(
      (name) => (targets.get(name) ?? Infinity) > bus.maxLength + 1e-7
    ))
      throw Error(
        `${bus.busId}: matching would exceed maximum length ${bus.maxLength} mm`
      );
}

// lib/tuning-bank-demands.ts
function highDemandPairedLanes(input, traces) {
  const busNames = new Set(input.buses?.flatMap((bus) => bus.connectionNames));
  const targets = minimumLengthTargets(input, traces);
  const result = /* @__PURE__ */ new Set();
  for (const pair of input.differentialPairs ?? []) {
    if (pair.connectionNames.some((name) => {
      const trace = traces.find((t48) => t48.connection_name === name);
      if (!trace?.coupledSection || !busNames.has(name)) return false;
      const [start, end] = trace.coupledSection;
      let longest = 0;
      for (let i2 = start + 1; i2 <= end; i2++)
        longest = Math.max(
          longest,
          distance(trace.route[i2 - 1], trace.route[i2])
        );
      const deficit = (targets.get(name) ?? 0) - length(trace.route) - fixedRouteLength(input, name);
      return deficit > longest / 2;
    }))
      for (const name of pair.connectionNames) result.add(name);
  }
  return result;
}

// lib/align-coupled-section-boundaries.ts
function alignStarts(traces) {
  if (traces.some((trace) => !trace.coupledSection)) return traces;
  const starts = traces.map((trace) => trace.coupledSection[0]);
  const points = traces.map(
    (trace, side) => trace.route[starts[side]]
  );
  const next = traces.map(
    (trace, side) => trace.route[starts[side] + 1]
  );
  if (points.some((point) => point?.route_type !== "wire") || next.some((point) => point?.route_type !== "wire") || points.some((point) => point.layer !== points[0].layer) || next.some((point) => point.layer !== points[0].layer) || traces.some(
    (trace, side) => trace.curvedSegments?.includes(starts[side] + 1)
  ))
    return traces;
  const runs = points.map((point, side) => {
    const span = distance(point, next[side]);
    return {
      span,
      x: (next[side].x - point.x) / span,
      y: (next[side].y - point.y) / span
    };
  });
  if (runs.some((run) => run.span < 1e-8) || distance(runs[0], runs[1]) > 1e-7)
    return traces;
  const direction = runs[0];
  const project = (point) => point.x * direction.x + point.y * direction.y;
  const common = Math.max(...points.map(project));
  if (points.some(
    (point, side) => common - project(point) > runs[side].span + 1e-8
  ))
    return traces;
  return traces.map((trace, side) => {
    const index2 = starts[side];
    const advance = common - project(points[side]);
    if (advance < 1e-8) return trace;
    if (Math.abs(advance - runs[side].span) < 1e-8) {
      if (index2 + 1 >= trace.coupledSection[1]) return trace;
      return { ...trace, coupledSection: [index2 + 1, trace.coupledSection[1]] };
    }
    const point = {
      ...points[side],
      x: points[side].x + direction.x * advance,
      y: points[side].y + direction.y * advance
    };
    return {
      ...trace,
      route: [
        ...trace.route.slice(0, index2 + 1),
        point,
        ...trace.route.slice(index2 + 1)
      ],
      coupledSection: [index2 + 1, trace.coupledSection[1] + 1],
      curvedSegments: trace.curvedSegments?.map(
        (curve) => curve > index2 ? curve + 1 : curve
      )
    };
  });
}
function reverse(trace) {
  const count = trace.route.length;
  return {
    ...trace,
    route: trace.route.toReversed(),
    coupledSection: trace.coupledSection && [
      count - 1 - trace.coupledSection[1],
      count - 1 - trace.coupledSection[0]
    ],
    curvedSegments: trace.curvedSegments?.map((curve) => count - curve).sort((a2, b2) => a2 - b2)
  };
}
function alignCoupledSectionBoundaries(input, traces) {
  const result = [...traces];
  for (const pair of input.differentialPairs ?? []) {
    const indices = pair.connectionNames.map(
      (name) => result.findIndex((trace) => trace.connection_name === name)
    );
    const rails = indices.map((index2) => result[index2]);
    if (rails.some((trace) => !trace?.coupledSection)) continue;
    const aligned = alignStarts(alignStarts(rails).map(reverse)).map(reverse);
    indices.forEach((index2, side) => {
      result[index2] = aligned[side];
    });
  }
  return result;
}

// lib/package-approach-regions.ts
var pointInBox = (p2, box) => p2.x >= box.minX && p2.x <= box.maxX && p2.y >= box.minY && p2.y <= box.maxY;
function packageApproachRegions(input, margin) {
  const pads = input.obstacles.filter((o2) => o2.componentId);
  const regions = /* @__PURE__ */ new Map();
  const include = (box, p2, x2, y2 = x2) => {
    box.minX = Math.min(box.minX, p2.x - x2);
    box.maxX = Math.max(box.maxX, p2.x + x2);
    box.minY = Math.min(box.minY, p2.y - y2);
    box.maxY = Math.max(box.maxY, p2.y + y2);
  };
  for (const pad of pads) {
    let region = regions.get(pad.componentId);
    if (!region) {
      const box = {
        minX: Infinity,
        maxX: -Infinity,
        minY: Infinity,
        maxY: -Infinity
      };
      region = { pads: box, copper: { ...box } };
      regions.set(pad.componentId, region);
    }
    const angle = (pad.ccwRotationDegrees ?? 0) * Math.PI / 180;
    include(
      region.pads,
      pad.center,
      (Math.abs(Math.cos(angle)) * pad.width + Math.abs(Math.sin(angle)) * pad.height) / 2,
      (Math.abs(Math.sin(angle)) * pad.width + Math.abs(Math.cos(angle)) * pad.height) / 2
    );
  }
  for (const region of regions.values()) region.copper = { ...region.pads };
  for (const trace of input.traces ?? []) {
    const vias = trace.route.filter((p2) => p2.route_type === "via");
    if (vias.length !== 1 || !trace.route.length) continue;
    const first = trace.route[0];
    const owner = pads.find((p2) => distance(p2.center, first) < 1e-4);
    if (!owner) continue;
    const region = regions.get(owner.componentId);
    const via = vias[0];
    const radius = (via.via_diameter ?? input.minViaPadDiameter ?? 0.6) / 2;
    const angle = (owner.ccwRotationDegrees ?? 0) * Math.PI / 180;
    const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
    const reachX = (Math.abs(Math.cos(angle)) * owner.width + Math.abs(Math.sin(angle)) * owner.height) / 2 + radius + clearance;
    const reachY = (Math.abs(Math.sin(angle)) * owner.width + Math.abs(Math.cos(angle)) * owner.height) / 2 + radius + clearance;
    const peripheralGuard = 1e-3;
    if (Math.abs(via.x - first.x) > reachX + peripheralGuard + 1e-4 || Math.abs(via.y - first.y) > reachY + peripheralGuard + 1e-4)
      continue;
    include(
      region.copper,
      via,
      (via.via_diameter ?? input.minViaPadDiameter ?? 0.6) / 2
    );
  }
  for (const region of regions.values()) {
    region.copper.minX -= margin;
    region.copper.maxX += margin;
    region.copper.minY -= margin;
    region.copper.maxY += margin;
  }
  return [...regions.values()];
}

// lib/terminal-via-clearance.ts
function createTerminalViaClearanceChecker(input, trace, options = {}) {
  const width = trace.route[0].width;
  const vias = (input.traces ?? []).filter((fixed) => fixed.connection_name === trace.connection_name).flatMap(
    (fixed) => fixed.route.filter((point) => point.route_type === "via")
  ).map((via) => ({
    via,
    reach: ((via.via_diameter ?? input.minViaPadDiameter ?? 0.6) + width) / 2
  }));
  if (!vias.length) return (_path) => true;
  const original = trace.route.filter((point) => point.route_type === "wire");
  const same = (a2, b2) => Math.abs(a2.x - b2.x) < 1e-8 && Math.abs(a2.y - b2.y) < 1e-8;
  return (path) => {
    let prefix = 0, suffix = 0;
    while (prefix < Math.min(path.length, original.length) && same(path[prefix], original[prefix]))
      prefix++;
    while (suffix < Math.min(path.length, original.length) && same(
      path[path.length - 1 - suffix],
      original[original.length - 1 - suffix]
    ))
      suffix++;
    for (const { via, reach } of vias) {
      const atStart = same(via, path[0]);
      if (!atStart && !same(via, path.at(-1))) continue;
      let along2 = 0;
      for (let step = 1; step < path.length; step++) {
        const i2 = atStart ? step : path.length - step;
        const a2 = path[atStart ? i2 - 1 : i2];
        const b2 = path[atStart ? i2 : i2 - 1];
        const unchanged = options.preserveExistingApproach !== false && (atStart ? i2 < prefix : i2 >= path.length - suffix + 1);
        if (!unchanged && along2 > reach + 1e-9 && Math.min(a2.x, b2.x) <= via.x + reach && Math.max(a2.x, b2.x) >= via.x - reach && Math.min(a2.y, b2.y) <= via.y + reach && Math.max(a2.y, b2.y) >= via.y - reach && pointSegmentDistanceToPoints(via, a2, b2) <= reach + 1e-9)
          return false;
        if (along2 <= reach + 1e-9) along2 += distance(a2, b2);
      }
    }
    return true;
  };
}

// lib/copper-index.ts
var CopperIndex = class {
  root;
  constructor(copper) {
    const entries = copper.map((c2) => ({
      copper: c2,
      ...c2.rect ?? {
        minX: Math.min(c2.a.x, c2.b.x) - c2.radius,
        maxX: Math.max(c2.a.x, c2.b.x) + c2.radius,
        minY: Math.min(c2.a.y, c2.b.y) - c2.radius,
        maxY: Math.max(c2.a.y, c2.b.y) + c2.radius
      }
    }));
    const swap = (a2, b2) => {
      const value = entries[a2];
      entries[a2] = entries[b2];
      entries[b2] = value;
    };
    const partition = (start, end, middle, x2) => {
      const key = (entry) => x2 ? entry.minX + entry.maxX : entry.minY + entry.maxY;
      while (end - start > 1) {
        const a2 = key(entries[start]), b2 = key(entries[start + end >> 1]), c2 = key(entries[end - 1]);
        const pivot2 = a2 < b2 ? b2 < c2 ? b2 : Math.max(a2, c2) : a2 < c2 ? a2 : Math.max(b2, c2);
        let lower = start, upper = end, i2 = start;
        while (i2 < upper) {
          const value = key(entries[i2]);
          if (value < pivot2) swap(lower++, i2++);
          else if (value > pivot2) swap(i2, --upper);
          else i2++;
        }
        if (middle < lower) end = lower;
        else if (middle >= upper) start = upper;
        else return;
      }
    };
    const build = (start, end) => {
      const box = {
        minX: Infinity,
        maxX: -Infinity,
        minY: Infinity,
        maxY: -Infinity
      };
      for (let i2 = start; i2 < end; i2++) {
        const e2 = entries[i2];
        box.minX = Math.min(box.minX, e2.minX);
        box.maxX = Math.max(box.maxX, e2.maxX);
        box.minY = Math.min(box.minY, e2.minY);
        box.maxY = Math.max(box.maxY, e2.maxY);
      }
      if (end - start <= 8)
        return { ...box, entries: entries.slice(start, end) };
      const x2 = box.maxX - box.minX >= box.maxY - box.minY;
      const middle = start + end >> 1;
      partition(start, end, middle, x2);
      return { ...box, left: build(start, middle), right: build(middle, end) };
    };
    if (entries.length) this.root = build(0, entries.length);
  }
  /** Exact nearest-copper distance using bounding boxes only to prune. A
   * point inside a box has no useful signed-distance lower bound. queryRadius
   * expands the queried point when the predicate subtracts its radius too. */
  distanceToPoint(point, distanceOf, queryRadius = 0) {
    let nearest = Infinity;
    const lowerBound = (box) => {
      const dx2 = Math.max(box.minX - point.x, 0, point.x - box.maxX);
      const dy2 = Math.max(box.minY - point.y, 0, point.y - box.maxY);
      return dx2 || dy2 ? Math.hypot(dx2, dy2) - queryRadius : -Infinity;
    };
    const visit = (node, bound) => {
      if (bound >= nearest) return;
      if (node.entries) {
        for (const entry of node.entries)
          if (lowerBound(entry) < nearest)
            nearest = Math.min(nearest, distanceOf(entry.copper));
        return;
      }
      const left = lowerBound(node.left), right = lowerBound(node.right);
      if (left <= right) {
        visit(node.left, left);
        visit(node.right, right);
      } else {
        visit(node.right, right);
        visit(node.left, left);
      }
    };
    if (this.root) visit(this.root, lowerBound(this.root));
    return nearest;
  }
  some(box, predicate) {
    const visit = (node) => {
      if (node.minX > box.maxX || node.maxX < box.minX || node.minY > box.maxY || node.maxY < box.minY)
        return false;
      if (node.entries) {
        for (const e2 of node.entries) {
          if (e2.minX > box.maxX || e2.maxX < box.minX || e2.minY > box.maxY || e2.maxY < box.minY)
            continue;
          if (predicate(e2.copper)) return true;
        }
        return false;
      }
      return visit(node.left) || visit(node.right);
    };
    return this.root ? visit(this.root) : false;
  }
};

// lib/vector-scene.ts
function fixedCopper(input) {
  const result = [];
  for (const o2 of input.obstacles) {
    const angle = (o2.ccwRotationDegrees ?? 0) * Math.PI / 180;
    const width = Math.abs(Math.cos(angle)) * o2.width + Math.abs(Math.sin(angle)) * o2.height;
    const height = Math.abs(Math.sin(angle)) * o2.width + Math.abs(Math.cos(angle)) * o2.height;
    for (const layer of o2.layers)
      result.push({
        a: o2.center,
        b: o2.center,
        radius: o2.shape === "circle" ? o2.width / 2 : 0,
        layer,
        owners: o2.connectedTo,
        rect: o2.shape === "circle" ? void 0 : {
          minX: o2.center.x - width / 2,
          maxX: o2.center.x + width / 2,
          minY: o2.center.y - height / 2,
          maxY: o2.center.y + height / 2
        }
      });
  }
  const layers = Array.from(
    { length: input.layerCount },
    (_2, i2) => i2 === 0 ? "top" : i2 === input.layerCount - 1 ? "bottom" : `inner${i2}`
  );
  for (const t48 of input.traces ?? [])
    for (let i2 = 0; i2 < t48.route.length; i2++) {
      const p2 = t48.route[i2], q2 = t48.route[i2 + 1], owners = [t48.connection_name ?? "", t48.source_trace_id ?? ""];
      if (p2.route_type === "via") {
        const a2 = layers.indexOf(p2.from_layer), b2 = layers.indexOf(p2.to_layer);
        for (const layer of p2.layers ?? layers.slice(Math.min(a2, b2), Math.max(a2, b2) + 1))
          result.push({
            a: p2,
            b: p2,
            radius: (p2.via_diameter ?? 0.3) / 2,
            layer,
            owners
          });
      } else if (q2?.route_type === "wire") {
        if (p2.layer !== q2.layer)
          throw Error("Fixed trace changes layer without a via");
        result.push({ a: p2, b: q2, radius: p2.width / 2, layer: p2.layer, owners });
      }
      if (q2 && p2.route_type !== q2.route_type && distance(p2, q2) > 1e-10) {
        const wire = p2.route_type === "wire" ? p2 : q2;
        result.push({
          a: p2,
          b: q2,
          radius: wire.width / 2,
          layer: wire.layer,
          owners
        });
      }
    }
  return result;
}
function routeCopper(t48) {
  return t48.route.slice(1).map((p2, i2) => ({
    a: t48.route[i2],
    b: p2,
    radius: p2.width / 2,
    layer: p2.layer,
    owners: [t48.connection_name ?? ""]
  }));
}
var intersectsRect = (a2, b2, r2) => {
  let t0 = 0, t1 = 1;
  for (const [origin, delta, min, max] of [
    [a2.x, b2.x - a2.x, r2.minX, r2.maxX],
    [a2.y, b2.y - a2.y, r2.minY, r2.maxY]
  ]) {
    if (Math.abs(delta) < 1e-12) {
      if (origin < min || origin > max) return false;
      continue;
    }
    let lo = (min - origin) / delta, hi = (max - origin) / delta;
    if (lo > hi) [lo, hi] = [hi, lo];
    t0 = Math.max(t0, lo);
    t1 = Math.min(t1, hi);
    if (t0 > t1) return false;
  }
  return true;
};
function clearanceToCopper(a2, b2, c2) {
  if (!c2.rect) {
    if (a2.x === b2.x && a2.y === b2.y) {
      if (c2.a.x === c2.b.x && c2.a.y === c2.b.y) return distance(a2, c2.a) - c2.radius;
      return pointSegmentDistance(a2, [c2.a, c2.b]) - c2.radius;
    }
    if (c2.a.x === c2.b.x && c2.a.y === c2.b.y)
      return pointSegmentDistance(c2.a, [a2, b2]) - c2.radius;
    return segmentDistance([a2, b2], [c2.a, c2.b]) - c2.radius;
  }
  const r2 = c2.rect;
  if (intersectsRect(a2, b2, r2)) return 0;
  const corners = [
    { x: r2.minX, y: r2.minY },
    { x: r2.maxX, y: r2.minY },
    { x: r2.maxX, y: r2.maxY },
    { x: r2.minX, y: r2.maxY }
  ];
  return Math.min(
    ...corners.map(
      (p2, i2) => segmentDistance([a2, b2], [p2, corners[(i2 + 1) % 4]])
    )
  );
}
function copperTooClose(a2, b2, c2, margin) {
  if (c2.rect) return clearanceToCopper(a2, b2, c2) < margin;
  const u2 = c2.a, v2 = c2.b, radius = c2.radius;
  if (u2.x === v2.x && u2.y === v2.y)
    return pointSegmentDistanceToPoints(u2, a2, b2) - radius < margin;
  if (a2.x === b2.x && a2.y === b2.y)
    return pointSegmentDistanceToPoints(a2, u2, v2) - radius < margin;
  if (Math.max(a2.x, b2.x) >= Math.min(u2.x, v2.x) && Math.max(u2.x, v2.x) >= Math.min(a2.x, b2.x) && Math.max(a2.y, b2.y) >= Math.min(u2.y, v2.y) && Math.max(u2.y, v2.y) >= Math.min(a2.y, b2.y) && ((b2.x - a2.x) * (u2.y - a2.y) - (b2.y - a2.y) * (u2.x - a2.x)) * ((b2.x - a2.x) * (v2.y - a2.y) - (b2.y - a2.y) * (v2.x - a2.x)) <= 0 && ((v2.x - u2.x) * (a2.y - u2.y) - (v2.y - u2.y) * (a2.x - u2.x)) * ((v2.x - u2.x) * (b2.y - u2.y) - (v2.y - u2.y) * (b2.x - u2.x)) <= 0)
    return -radius < margin;
  return pointSegmentDistanceToPoints(a2, u2, v2) - radius < margin || pointSegmentDistanceToPoints(b2, u2, v2) - radius < margin || pointSegmentDistanceToPoints(u2, a2, b2) - radius < margin || pointSegmentDistanceToPoints(v2, a2, b2) - radius < margin;
}
function prepareCopper(copper) {
  const dx2 = copper.b.x - copper.a.x, dy2 = copper.b.y - copper.a.y;
  return {
    copper,
    ax: copper.a.x,
    ay: copper.a.y,
    bx: copper.b.x,
    by: copper.b.y,
    dx: dx2,
    dy: dy2,
    denominator: dx2 * dx2 + dy2 * dy2
  };
}
function pointPreparedSegmentDistance(px2, py2, ax2, ay2, dx2, dy2, denominator) {
  const ex2 = px2 - ax2, ey2 = py2 - ay2;
  if (dx2 === 0 && dy2 === 0) return Math.sqrt(ex2 * ex2 + ey2 * ey2);
  const t48 = Math.max(0, Math.min(1, (ex2 * dx2 + ey2 * dy2) / (denominator || 1)));
  const rx2 = ex2 - t48 * dx2, ry2 = ey2 - t48 * dy2;
  return Math.sqrt(rx2 * rx2 + ry2 * ry2);
}
function copperTooClosePrepared(ax2, ay2, bx2, by2, dx2, dy2, denominator, c2, margin) {
  const radius = c2.copper.radius;
  if (c2.copper.rect)
    return copperTooClose({ x: ax2, y: ay2 }, { x: bx2, y: by2 }, c2.copper, margin);
  if (c2.dx === 0 && c2.dy === 0)
    return pointPreparedSegmentDistance(c2.ax, c2.ay, ax2, ay2, dx2, dy2, denominator) - radius < margin;
  if (dx2 === 0 && dy2 === 0)
    return pointPreparedSegmentDistance(
      ax2,
      ay2,
      c2.ax,
      c2.ay,
      c2.dx,
      c2.dy,
      c2.denominator
    ) - radius < margin;
  if (Math.max(ax2, bx2) >= Math.min(c2.ax, c2.bx) && Math.max(c2.ax, c2.bx) >= Math.min(ax2, bx2) && Math.max(ay2, by2) >= Math.min(c2.ay, c2.by) && Math.max(c2.ay, c2.by) >= Math.min(ay2, by2) && (dx2 * (c2.ay - ay2) - dy2 * (c2.ax - ax2)) * (dx2 * (c2.by - ay2) - dy2 * (c2.bx - ax2)) <= 0 && (c2.dx * (ay2 - c2.ay) - c2.dy * (ax2 - c2.ax)) * (c2.dx * (by2 - c2.ay) - c2.dy * (bx2 - c2.ax)) <= 0)
    return -radius < margin;
  return pointPreparedSegmentDistance(
    ax2,
    ay2,
    c2.ax,
    c2.ay,
    c2.dx,
    c2.dy,
    c2.denominator
  ) - radius < margin || pointPreparedSegmentDistance(
    bx2,
    by2,
    c2.ax,
    c2.ay,
    c2.dx,
    c2.dy,
    c2.denominator
  ) - radius < margin || pointPreparedSegmentDistance(c2.ax, c2.ay, ax2, ay2, dx2, dy2, denominator) - radius < margin || pointPreparedSegmentDistance(c2.bx, c2.by, ax2, ay2, dx2, dy2, denominator) - radius < margin;
}
var VectorScene = class {
  constructor(input, connection, width, all) {
    this.input = input;
    this.connection = connection;
    this.width = width;
    this.owners = new Set(
      [
        connection.name,
        connection.source_trace_id,
        ...connection.pointsToConnect.flatMap((p2) => [
          p2.pointId,
          p2.pcb_port_id
        ])
      ].filter((s2) => !!s2)
    );
    this.copper = all.filter(
      (c2) => c2.layer === connection.pointsToConnect[0].layer && !c2.owners.some((n2) => this.owners.has(n2))
    );
    this.margin = width / 2 + (input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075);
  }
  input;
  connection;
  width;
  visibleCalls = 0;
  copperIndex;
  copper;
  owners;
  margin;
  visible(a2, b2) {
    const m2 = this.width / 2 + (this.input.minBoardEdgeClearance ?? 0), r2 = this.input.bounds;
    if ([a2, b2].some(
      (p2) => p2.x < r2.minX + m2 - 1e-9 || p2.x > r2.maxX - m2 + 1e-9 || p2.y < r2.minY + m2 - 1e-9 || p2.y > r2.maxY - m2 + 1e-9
    ))
      return false;
    const minX = Math.min(a2.x, b2.x) - this.margin, maxX = Math.max(a2.x, b2.x) + this.margin, minY = Math.min(a2.y, b2.y) - this.margin, maxY = Math.max(a2.y, b2.y) + this.margin;
    if (++this.visibleCalls === 16)
      this.copperIndex = new CopperIndex(this.copper);
    if (this.copperIndex)
      return !this.copperIndex.some(
        { minX, maxX, minY, maxY },
        (c2) => copperTooClose(a2, b2, c2, this.margin - 1e-8)
      );
    for (const c2 of this.copper) {
      const r3 = c2.rect ?? {
        minX: Math.min(c2.a.x, c2.b.x) - c2.radius,
        maxX: Math.max(c2.a.x, c2.b.x) + c2.radius,
        minY: Math.min(c2.a.y, c2.b.y) - c2.radius,
        maxY: Math.max(c2.a.y, c2.b.y) + c2.radius
      };
      if (r3.minX > maxX || r3.maxX < minX || r3.minY > maxY || r3.maxY < minY)
        continue;
      if (copperTooClose(a2, b2, c2, this.margin - 1e-8)) return false;
    }
    return true;
  }
  pathVisible(path) {
    return path.slice(1).every((b2, i2) => this.visible(path[i2], b2));
  }
  /** Vertices of circumscribed octagonal Minkowski offsets. Their edges are
   * horizontal, vertical or 45 degrees, including circular vias and trace caps. */
  vertices() {
    const result = [], k2 = Math.SQRT2 - 1, epsilon = 1e-5;
    for (const c2 of this.copper) {
      if (c2.rect) {
        const r2 = c2.rect, m2 = this.margin + epsilon;
        result.push(
          { x: r2.minX - m2, y: r2.minY - m2 },
          { x: r2.minX - m2, y: r2.maxY + m2 },
          { x: r2.maxX + m2, y: r2.minY - m2 },
          { x: r2.maxX + m2, y: r2.maxY + m2 }
        );
      } else {
        const r2 = c2.radius + this.margin + epsilon;
        for (const p2 of distance(c2.a, c2.b) < 1e-9 ? [c2.a] : [c2.a, c2.b])
          for (const [x2, y2] of [
            [1, k2],
            [k2, 1],
            [-k2, 1],
            [-1, k2],
            [-1, -k2],
            [-k2, -1],
            [k2, -1],
            [1, -k2]
          ])
            result.push({ x: p2.x + x2 * r2, y: p2.y + y2 * r2 });
      }
    }
    const seen = /* @__PURE__ */ new Set();
    return result.filter((p2) => {
      const key = `${p2.x.toFixed(9)},${p2.y.toFixed(9)}`;
      if (seen.has(key)) return false;
      seen.add(key);
      return this.visible(p2, p2);
    });
  }
};

// lib/length-tuning.ts
function tuneLengths(input, traces, targets) {
  const fixed = fixedCopper(input);
  function* candidates(t48, scene) {
    const connection = input.connections.find(
      (c2) => c2.name === t48.connection_name
    );
    const terminalViaCopperIsClear = t48.coupledSection ? (_path) => true : createTerminalViaClearanceChecker(input, t48);
    const width = t48.route[0].width;
    const fixedLength = fixedRouteLength(input, connection.name);
    const delta = targets.get(connection.name) - length(t48.route) - fixedLength;
    if (delta < 1e-8) {
      yield t48;
      return;
    }
    const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
    const returnSpacing = Math.max(width + clearance, 3 * width);
    const pitch = 2 * (returnSpacing + 2 * width);
    const segments = t48.route.slice(1).map((p2, i2) => ({ i: i2, span: distance(t48.route[i2], p2) })).sort((a2, b2) => b2.span - a2.span);
    for (const { i: i2 } of segments) {
      const a2 = t48.route[i2], b2 = t48.route[i2 + 1], span = distance(a2, b2);
      if (span < 0.01) continue;
      const ux2 = (b2.x - a2.x) / span, uy2 = (b2.y - a2.y) / span;
      const maximumTeeth = Math.floor(span * 0.9 / pitch);
      const preferredTeeth = Math.min(
        maximumTeeth,
        Math.max(2, Math.ceil(delta / (12 * width)))
      );
      const counts = Array.from({ length: maximumTeeth }, (_2, i3) => i3 + 1).sort(
        (a3, b3) => Math.abs(a3 - preferredTeeth) - Math.abs(b3 - preferredTeeth) || b3 - a3
      );
      for (const teeth of counts) {
        for (const fraction of [0.9, 0.65, 0.4]) {
          const w2 = span * fraction / teeth;
          if (w2 < pitch) continue;
          const c2 = Math.min(
            delta / (2 * teeth),
            w2 / 10,
            (w2 / 2 - returnSpacing) / 2
          );
          const h2 = delta / (2 * teeth) + 2 * c2 * (2 - Math.SQRT2);
          for (const phase of [0.5, 0, 1])
            for (const side of [1, -1]) {
              const at2 = (x2, y2) => ({
                x: a2.x + ux2 * x2 - uy2 * y2 * side,
                y: a2.y + uy2 * x2 + ux2 * y2 * side
              });
              const bump = [at2(0, 0)];
              for (let tooth = 0; tooth < teeth; tooth++) {
                const offset = span * (1 - fraction) * (0.05 + 0.9 * phase) + tooth * w2, gap = w2 * 0.5;
                bump.push(
                  ...[
                    [offset, 0],
                    [offset + c2, c2],
                    [offset + c2, h2 - c2],
                    [offset + 2 * c2, h2],
                    [offset + gap - 2 * c2, h2],
                    [offset + gap - c2, h2 - c2],
                    [offset + gap - c2, c2],
                    [offset + gap, 0]
                  ].map(([x2, y2]) => at2(x2, y2))
                );
              }
              bump.push(at2(span, 0));
              if (!scene.pathVisible(bump)) continue;
              const next = simplify([
                ...t48.route.slice(0, i2),
                ...bump,
                ...t48.route.slice(i2 + 2)
              ]);
              if (Math.abs(
                length(next) + fixedLength - targets.get(connection.name)
              ) > 1e-6)
                continue;
              if (!terminalViaCopperIsClear(next) || !tuningPathIsSelfClear(next, returnSpacing))
                continue;
              yield {
                ...t48,
                route: next.map((p2) => ({
                  ...p2,
                  route_type: "wire",
                  layer: connection.pointsToConnect[0].layer,
                  width
                }))
              };
            }
        }
      }
    }
  }
  const result = [...traces];
  const pending = new Set(traces.map((_2, i2) => i2));
  let changed = true;
  while (pending.size && changed) {
    changed = false;
    for (const index2 of pending) {
      const connection = input.connections.find(
        (c2) => c2.name === traces[index2].connection_name
      );
      const scene = new VectorScene(
        input,
        connection,
        traces[index2].route[0].width,
        [...fixed, ...result.flatMap(routeCopper)]
      );
      const next = candidates(traces[index2], scene).next().value;
      if (!next) continue;
      result[index2] = next;
      pending.delete(index2);
      changed = true;
    }
  }
  if (pending.size)
    throw Error(
      `Insufficient tuning clearance for ${[...pending].map((i2) => traces[i2].connection_name).join(", ")}`
    );
  return result;
}
function tuningPathIsSelfClear(path, required) {
  const cumulative = [0];
  const turning = [0];
  const unsafeBends = [0];
  for (let i2 = 1; i2 < path.length - 1; i2++) {
    const a2 = { x: path[i2].x - path[i2 - 1].x, y: path[i2].y - path[i2 - 1].y };
    const b2 = { x: path[i2 + 1].x - path[i2].x, y: path[i2 + 1].y - path[i2].y };
    const angle = Math.abs(
      Math.atan2(a2.x * b2.y - a2.y * b2.x, a2.x * b2.x + a2.y * b2.y)
    );
    const cross4 = Math.abs(a2.x * b2.y - a2.y * b2.x);
    const radius = cross4 < 1e-12 ? Infinity : Math.hypot(a2.x, a2.y) * Math.hypot(b2.x, b2.y) * distance(path[i2 - 1], path[i2 + 1]) / (2 * cross4);
    turning.push(turning[i2 - 1] + angle);
    unsafeBends.push(
      unsafeBends[i2 - 1] + Number(angle > Math.PI / 8 + 1e-8 || radius < required / 2 - 1e-8)
    );
  }
  for (let i2 = 1; i2 < path.length; i2++)
    cumulative.push(cumulative[i2 - 1] + distance(path[i2 - 1], path[i2]));
  for (let i2 = 0; i2 < path.length - 1; i2++)
    for (let j2 = i2 + 2; j2 < path.length - 1; j2++) {
      const a2 = path[i2], b2 = path[i2 + 1], c2 = path[j2], d2 = path[j2 + 1];
      const padding = Math.max(required, 1e-9);
      if (Math.max(a2.x, b2.x) + padding < Math.min(c2.x, d2.x) || Math.max(c2.x, d2.x) + padding < Math.min(a2.x, b2.x) || Math.max(a2.y, b2.y) + padding < Math.min(c2.y, d2.y) || Math.max(c2.y, d2.y) + padding < Math.min(a2.y, b2.y))
        continue;
      const separation = segmentDistance([a2, b2], [c2, d2]);
      if (separation < 1e-9 && cumulative[j2] - cumulative[i2 + 1] > 1e-8)
        return false;
      if (cumulative[j2] - cumulative[i2 + 1] <= Math.PI * required + 1e-8 && (turning[j2] - turning[i2] <= Math.PI / 2 + 1e-8 || turning[j2] - turning[i2] <= Math.PI + 1e-8 && unsafeBends[j2] === unsafeBends[i2]))
        continue;
      if (separation >= required - 1e-8) continue;
      let sx2 = 0, sy2 = 0;
      for (let k2 = i2; k2 <= j2; k2++) {
        const dx2 = path[k2 + 1].x - path[k2].x, dy2 = path[k2 + 1].y - path[k2].y;
        if (Math.abs(dx2) > 1e-8) {
          if (sx2 && sx2 !== Math.sign(dx2)) return false;
          sx2 = Math.sign(dx2);
        }
        if (Math.abs(dy2) > 1e-8) {
          if (sy2 && sy2 !== Math.sign(dy2)) return false;
          sy2 = Math.sign(dy2);
        }
      }
    }
  return true;
}

// lib/chamfer-ordinary-corners.ts
function chamferOrdinaryCorners(input, traces, fixed = fixedCopper(input), maxTrimInTraceWidths = 1.5) {
  if (!Number.isFinite(maxTrimInTraceWidths) || maxTrimInTraceWidths <= 0)
    throw Error("Corner trim must be a positive finite number of trace widths");
  const result = traces.map((t48) => ({ ...t48, route: [...t48.route] }));
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  for (const [traceIndex, trace] of result.entries()) {
    if (trace.route.some((p2) => p2.route_type !== "wire")) continue;
    const connection = input.connections.find(
      (c2) => c2.name === trace.connection_name
    );
    if (!connection) continue;
    const otherCopper = fixedCopper({
      ...input,
      obstacles: [],
      traces: result.filter((_2, i2) => i2 !== traceIndex)
    });
    const scenes = /* @__PURE__ */ new Map();
    for (let i2 = 1; i2 < trace.route.length - 1; i2++) {
      const [a2, b2, c2] = trace.route.slice(i2 - 1, i2 + 2);
      if (a2.route_type !== "wire" || b2.route_type !== "wire" || c2.route_type !== "wire" || a2.layer !== b2.layer || b2.layer !== c2.layer || trace.curvedSegments?.some((index2) => index2 === i2 || index2 === i2 + 1) || trace.coupledSection && i2 > trace.coupledSection[0] && i2 < trace.coupledSection[1])
        continue;
      const before = distance(a2, b2), after = distance(b2, c2);
      if (before < 1e-8 || after < 1e-8) continue;
      const u2 = { x: (b2.x - a2.x) / before, y: (b2.y - a2.y) / before }, v2 = { x: (c2.x - b2.x) / after, y: (c2.y - b2.y) / after };
      const octilinear = (p2) => Math.min(Math.abs(p2.x), Math.abs(p2.y)) < 1e-8 || Math.abs(Math.abs(p2.x) - Math.abs(p2.y)) < 1e-8;
      const dot2 = u2.x * v2.x + u2.y * v2.y;
      const acute = Math.abs(dot2 + Math.SQRT1_2) < 1e-8;
      if (!octilinear(u2) || !octilinear(v2) || Math.abs(dot2) > 1e-8 && !acute)
        continue;
      const key = `${b2.layer}/${b2.width}`;
      let scene = scenes.get(key);
      if (!scene) {
        scene = new VectorScene(
          input,
          {
            ...connection,
            pointsToConnect: connection.pointsToConnect.map((p2) => ({
              ...p2,
              layer: b2.layer
            }))
          },
          b2.width,
          [...fixed, ...otherCopper]
        );
        scenes.set(key, scene);
      }
      const maximumTrim = Math.min(
        maxTrimInTraceWidths * b2.width,
        before / 2,
        after / 2
      );
      for (let attempt = 0; attempt < 8; attempt++) {
        const trim = maximumTrim / 2 ** attempt;
        if (trim < 1e-6) break;
        const start = { ...b2, x: b2.x - u2.x * trim, y: b2.y - u2.y * trim };
        const end = { ...b2, x: b2.x + v2.x * trim, y: b2.y + v2.y * trim };
        const turn = Math.sign(u2.x * v2.y - u2.y * v2.x);
        const bevel2 = (Math.SQRT2 - 1) * trim;
        const middle = {
          ...b2,
          x: start.x + (u2.x - turn * u2.y) * Math.SQRT1_2 * bevel2,
          y: start.y + (u2.y + turn * u2.x) * Math.SQRT1_2 * bevel2
        };
        const inserted = acute ? [start, middle, end] : [start, end];
        const added = inserted.length - 1;
        const route = [
          ...trace.route.slice(0, i2),
          ...inserted,
          ...trace.route.slice(i2 + 1)
        ];
        if (!scene.pathVisible(route) || !tuningPathIsSelfClear(route, b2.width + clearance) && tuningPathIsSelfClear(trace.route, b2.width + clearance))
          continue;
        trace.route = route;
        trace.curvedSegments = trace.curvedSegments?.map(
          (index2) => index2 > i2 ? index2 + added : index2
        );
        trace.coupledSection = trace.coupledSection?.map(
          (index2, boundary) => index2 > i2 || index2 === i2 && boundary === 0 ? index2 + added : index2
        );
        i2 += added;
        break;
      }
    }
  }
  return result;
}

// lib/route-angle-validation.ts
function routeAnglesAreConventional(traces) {
  return traces.every((trace) => {
    let previous;
    let direction;
    for (const point of trace.route) {
      if (point.route_type !== "wire") {
        previous = direction = void 0;
        continue;
      }
      if (!previous || previous.layer !== point.layer) {
        previous = point;
        direction = void 0;
        continue;
      }
      const span = distance(previous, point);
      if (span < 1e-8) continue;
      const next = {
        x: (point.x - previous.x) / span,
        y: (point.y - previous.y) / span
      };
      if (direction && direction.x * next.x + direction.y * next.y < Math.cos(45.2 * Math.PI / 180))
        return false;
      previous = point;
      direction = next;
    }
    return true;
  });
}

// lib/shared-pair-spacing.ts
function sharedPairSpacingReports(input, traces) {
  return (input.differentialPairs ?? []).map((pair) => {
    const rails = pair.connectionNames.map(
      (name) => traces.find(
        (t48) => t48.connection_name === name || t48.source_trace_id === name
      )
    );
    const paths = rails.map(
      (t48) => t48?.coupledSection ? t48.route.slice(t48.coupledSection[0], t48.coupledSection[1] + 1) : []
    );
    const valid = rails.every(
      (t48) => t48?.coupledSection?.length === 2 && t48.coupledSection.every(Number.isInteger) && t48.coupledSection[0] >= 0 && t48.coupledSection[1] < t48.route.length && t48.coupledSection[0] < t48.coupledSection[1]
    ) && paths.every(
      (path) => path.length >= 2 && path.every(
        (p2) => p2.route_type === "wire" && Number.isFinite(p2.x) && Number.isFinite(p2.y) && Number.isFinite(p2.width) && p2.width > 0
      )
    ) && paths.flat().every((p2) => p2.layer === paths[0][0]?.layer);
    const required = pair.traceGap !== void 0 || pair.maxUncoupledLength !== void 0;
    const gap = pair.traceGap ?? input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
    const base = {
      connectionNames: pair.connectionNames,
      requestedGapMm: pair.traceGap ?? null
    };
    if (!valid)
      return {
        ...base,
        sharedSectionPresent: false,
        minEdgeGapMm: null,
        maxEdgeGapMm: null,
        maxSamplingErrorMm: null,
        sharedCopperMm: null,
        maxAllowedEdgeGapMm: null,
        matched: !required
      };
    const widths = paths.map((path) => path[0].width);
    if (paths.some(
      (path, side) => path.some((p2) => Math.abs(p2.width - widths[side]) > 1e-8)
    ))
      return {
        ...base,
        sharedSectionPresent: false,
        minEdgeGapMm: null,
        maxEdgeGapMm: null,
        maxSamplingErrorMm: null,
        sharedCopperMm: null,
        maxAllowedEdgeGapMm: null,
        matched: !required
      };
    const halfWidths = (widths[0] + widths[1]) / 2;
    const maxAllowedEdgeGapMm = (halfWidths + gap) / Math.cos(Math.PI / 8) - halfWidths + 2e-3;
    let min = Infinity, max = -Infinity, maxSamplingErrorMm = 0;
    const sharedCopperMm = [0, 0];
    for (let side = 0; side < 2; side++) {
      const path = paths[side], mate = rails[1 - side].route;
      const segments = mate.slice(1).flatMap((v2, index3) => {
        const u2 = mate[index3];
        return u2.route_type === "wire" && v2.route_type === "wire" && u2.layer === path[0].layer && v2.layer === path[0].layer ? [{ a: u2, b: v2, radius: u2.width / 2, layer: u2.layer, owners: [] }] : [];
      });
      const index2 = new CopperIndex(segments);
      for (let i2 = 1; i2 < path.length; i2++) {
        const a2 = path[i2 - 1], b2 = path[i2], span = distance(a2, b2);
        const steps = Math.max(1, Math.ceil(span / 2e-3));
        sharedCopperMm[side] += span;
        maxSamplingErrorMm = Math.max(maxSamplingErrorMm, span / (2 * steps));
        for (let j2 = 0; j2 < steps; j2++) {
          const fraction = (j2 + 0.5) / steps;
          const p2 = {
            x: a2.x + (b2.x - a2.x) * fraction,
            y: a2.y + (b2.y - a2.y) * fraction
          };
          const separation = index2.distanceToPoint(
            p2,
            (segment) => pointSegmentDistanceToPoints(p2, segment.a, segment.b) - segment.radius
          ) - a2.width / 2;
          min = Math.min(min, separation);
          max = Math.max(max, separation);
        }
      }
    }
    return {
      ...base,
      sharedSectionPresent: true,
      minEdgeGapMm: min,
      maxEdgeGapMm: max,
      maxSamplingErrorMm,
      sharedCopperMm,
      maxAllowedEdgeGapMm,
      matched: !required || sharedCopperMm.every((n2) => n2 > 0) && max + maxSamplingErrorMm <= maxAllowedEdgeGapMm
    };
  });
}

// lib/folded-tuning.ts
function foldedPairedLobes(a2, b2, spacing, deficit, folds, side, minRadius) {
  const span = distance(a2, b2), radius = minRadius + spacing / 2;
  if (!Number.isFinite(span + spacing + deficit + minRadius) || spacing < 0 || side !== 1 && side !== -1 || minRadius <= 0 || deficit <= 0 || !Number.isInteger(folds) || folds < 1 || folds > 64 || span < 6 * radius)
    return null;
  const height = (4 * folds + 2) * radius;
  const ux2 = (b2.x - a2.x) / span, uy2 = (b2.y - a2.y) / span;
  const generate = (reach2) => {
    const vertices = [
      { x: 0, y: 0 },
      { x: radius, y: 0 },
      { x: radius, y: height },
      { x: reach2, y: height }
    ];
    for (let i2 = 1; i2 <= 2 * folds; i2++) {
      const x2 = i2 % 2 ? 3 * radius : reach2;
      const y2 = height - 2 * radius * i2;
      vertices.push({ x: vertices.at(-1).x, y: y2 }, { x: x2, y: y2 });
    }
    vertices.push({ x: reach2, y: 0 }, { x: span, y: 0 });
    const rails = [[], []];
    const emit = (x2, y2, tx2, ty2) => {
      for (let k2 = 0; k2 < (spacing ? 2 : 1); k2++) {
        const offset = (k2 === 0 ? 1 : -1) * spacing / 2;
        const px2 = x2 - side * ty2 * offset, py2 = side * y2 + tx2 * offset;
        const p2 = { x: a2.x + ux2 * px2 - uy2 * py2, y: a2.y + uy2 * px2 + ux2 * py2 };
        if (!rails[k2].length || distance(rails[k2].at(-1), p2) > 1e-10)
          rails[k2].push(p2);
      }
    };
    emit(0, 0, 1, 0);
    for (let i2 = 1; i2 < vertices.length - 1; i2++) {
      const p2 = vertices[i2 - 1], q2 = vertices[i2], s2 = vertices[i2 + 1];
      const d1 = distance(p2, q2), d2 = distance(q2, s2);
      const u2 = { x: (q2.x - p2.x) / d1, y: (q2.y - p2.y) / d1 }, v2 = { x: (s2.x - q2.x) / d2, y: (s2.y - q2.y) / d2 };
      const start = { x: q2.x - u2.x * radius, y: q2.y - u2.y * radius };
      const center = { x: start.x + v2.x * radius, y: start.y + v2.y * radius };
      const turn = u2.x * v2.y - u2.y * v2.x;
      const angle = Math.atan2(start.y - center.y, start.x - center.x);
      for (let j2 = 0; j2 <= 18; j2++) {
        const theta = angle + turn * Math.PI / 2 * j2 / 18;
        emit(
          center.x + radius * Math.cos(theta),
          center.y + radius * Math.sin(theta),
          -turn * Math.sin(theta),
          turn * Math.cos(theta)
        );
      }
    }
    emit(span, 0, 1, 0);
    if (!spacing) rails[1] = rails[0];
    return rails;
  };
  const minimumReach = 5 * radius, maximumReach = span - radius;
  const arcCorrection = 4 * (folds + 1) * radius * (36 * Math.sin(Math.PI / 72) - 2);
  const addition = 2 * height + 4 * folds * radius + arcCorrection;
  if (addition > deficit + 1e-8) return null;
  const reach = minimumReach + (deficit - addition) / (2 * folds);
  if (reach > maximumReach + 1e-8) return null;
  return generate(Math.min(reach, maximumReach));
}
function foldedTuningLobes(a2, b2, deficit, folds, side, minRadius) {
  return foldedPairedLobes(a2, b2, 0, deficit, folds, side, minRadius)?.[0] ?? null;
}

// lib/smooth-tuning.ts
function smoothTuningLobes(a2, b2, deficit, lobes, side, minRadius) {
  const span = distance(a2, b2), period = span / lobes;
  if (span <= 0 || deficit <= 0 || lobes < 1) return null;
  const ux2 = (b2.x - a2.x) / span, uy2 = (b2.y - a2.y) / span;
  const maxHeight = period * period / (2 * Math.PI * Math.PI * minRadius);
  const samples = Math.max(
    48,
    Math.ceil(period / Math.max(5e-3, minRadius / 6))
  );
  const positions = [], raised = [];
  for (let l2 = 0; l2 < lobes; l2++)
    for (let j2 = 0; j2 < samples; j2++) {
      positions.push(period * (l2 + j2 / samples));
      raised.push(1 - Math.cos(2 * Math.PI * j2 / samples));
    }
  const generate = (height) => {
    const points = [];
    for (let i2 = 0; i2 < positions.length; i2++) {
      const x2 = positions[i2], y2 = side * height * raised[i2] / 2;
      points.push({ x: a2.x + ux2 * x2 - uy2 * y2, y: a2.y + uy2 * x2 + ux2 * y2 });
    }
    points.push(b2);
    return points;
  };
  const emittedLength = (height) => {
    let total = 0, lastX = 0, lastY = 0;
    for (let i2 = 0; i2 < positions.length; i2++) {
      const localX = positions[i2], localY = side * height * raised[i2] / 2;
      const x2 = a2.x + ux2 * localX - uy2 * localY, y2 = a2.y + uy2 * localX + ux2 * localY;
      if (i2 > 0) {
        const dx2 = lastX - x2, dy2 = lastY - y2;
        total += Math.sqrt(dx2 * dx2 + dy2 * dy2);
      }
      lastX = x2;
      lastY = y2;
    }
    if (positions.length) {
      const dx2 = lastX - b2.x, dy2 = lastY - b2.y;
      total += Math.sqrt(dx2 * dx2 + dy2 * dy2);
    }
    return total;
  };
  let lo = 0, hi = Math.min(maxHeight, deficit + span);
  if (emittedLength(hi) - span < deficit) return null;
  for (let i2 = 0; i2 < 40; i2++) {
    const mid = (lo + hi) / 2;
    if (emittedLength(mid) - span < deficit) lo = mid;
    else hi = mid;
  }
  return generate((lo + hi) / 2);
}
function smoothPairedLobes(a2, b2, spacing, deficit, lobes, side, minRadius) {
  const span = distance(a2, b2), period = span / lobes;
  if (span <= 0 || deficit <= 0) return null;
  const ux2 = (b2.x - a2.x) / span, uy2 = (b2.y - a2.y) / span;
  const maxHeight = period * period / (2 * Math.PI * Math.PI * (minRadius + spacing / 2));
  const samples = Math.max(
    64,
    Math.ceil(period / Math.max(5e-3, minRadius / 6))
  );
  const positions = [], raised = [], slopes = [];
  for (let k2 = 0; k2 <= samples * lobes; k2++) {
    const phase = 2 * Math.PI * k2 / samples;
    positions.push(k2 * span / (samples * lobes));
    raised.push(1 - Math.cos(phase));
    slopes.push(Math.sin(phase));
  }
  const generate = (height) => {
    const rails = [[], []];
    for (let k2 = 0; k2 < positions.length; k2++) {
      const x2 = positions[k2], y2 = side * height * raised[k2] / 2, slope = side * height * Math.PI / period * slopes[k2];
      const norm = Math.hypot(1, slope);
      for (let i2 = 0; i2 < 2; i2++) {
        const offset = (i2 === 0 ? 1 : -1) * spacing / 2;
        const lx2 = x2 - offset * slope / norm, ly2 = y2 + offset / norm;
        rails[i2].push({
          x: a2.x + ux2 * lx2 - uy2 * ly2,
          y: a2.y + uy2 * lx2 + ux2 * ly2
        });
      }
    }
    return rails;
  };
  const addition = (height) => {
    const total = [0, 0], lastX = [0, 0], lastY = [0, 0];
    for (let k2 = 0; k2 < positions.length; k2++) {
      const centerX = positions[k2], centerY = side * height * raised[k2] / 2, slope = side * height * Math.PI / period * slopes[k2];
      const norm = Math.hypot(1, slope);
      for (let i2 = 0; i2 < 2; i2++) {
        const offset = (i2 === 0 ? 1 : -1) * spacing / 2;
        const lx2 = centerX - offset * slope / norm, ly2 = centerY + offset / norm;
        const x2 = a2.x + ux2 * lx2 - uy2 * ly2, y2 = a2.y + uy2 * lx2 + ux2 * ly2;
        if (k2 > 0) {
          const dx2 = lastX[i2] - x2, dy2 = lastY[i2] - y2;
          total[i2] += Math.sqrt(dx2 * dx2 + dy2 * dy2);
        }
        lastX[i2] = x2;
        lastY[i2] = y2;
      }
    }
    return Math.min(total[0] - span, total[1] - span);
  };
  let lo = 0, hi = Math.min(maxHeight, deficit + span);
  if (addition(hi) < deficit) return null;
  for (let i2 = 0; i2 < 40; i2++) {
    const mid = (lo + hi) / 2;
    if (addition(mid) < deficit) lo = mid;
    else hi = mid;
  }
  return generate((lo + hi) / 2);
}
function roundedPairedLobes(a2, b2, spacing, deficit, lobes, side, minRadius) {
  const span = distance(a2, b2), period = span / lobes, radius = minRadius + spacing / 2;
  if (deficit <= 0 || lobes < 1 || period < 4 * radius) return null;
  const ux2 = (b2.x - a2.x) / span, uy2 = (b2.y - a2.y) / span;
  const samples = Math.max(
    18,
    Math.ceil(Math.PI * radius / (2 * Math.max(5e-3, minRadius / 6)))
  );
  const railCount = spacing === 0 ? 1 : 2;
  const templates = [];
  for (let l2 = 0; l2 < lobes; l2++)
    for (const [cx2, raised, start, end] of [
      [0, 0, -Math.PI / 2, 0],
      [2 * radius, 1, Math.PI, Math.PI / 2],
      [period - 2 * radius, 1, Math.PI / 2, 0],
      [period, 0, Math.PI, Math.PI * 1.5]
    ])
      for (let i2 = 0; i2 <= samples; i2++) {
        const angle = start + (end - start) * i2 / samples, direction = Math.sign(end - start);
        const x2 = l2 * period + cx2 + radius * Math.cos(angle);
        const tx2 = -Math.sin(angle) * direction, ty2 = side * Math.cos(angle) * direction;
        for (let k2 = 0; k2 < railCount; k2++) {
          const offset = (k2 === 0 ? 1 : -1) * spacing / 2;
          templates.push({
            px: x2 - ty2 * offset,
            sin: radius * Math.sin(angle),
            offsetY: tx2 * offset,
            raised: !!raised,
            rail: k2
          });
        }
      }
  const generate = (height2) => {
    const rails = [[], []];
    for (const t48 of templates) {
      const cy2 = t48.raised ? height2 - radius : radius;
      const py2 = side * (cy2 + t48.sin) + t48.offsetY;
      const point = {
        x: a2.x + ux2 * t48.px - uy2 * py2,
        y: a2.y + uy2 * t48.px + ux2 * py2
      };
      const rail = rails[t48.rail];
      if (!rail.length || distance(rail.at(-1), point) > 1e-10)
        rail.push(point);
    }
    if (railCount === 1) rails[1] = rails[0];
    return rails;
  };
  const railTemplates = [
    templates.filter((t48) => t48.rail === 0),
    templates.filter((t48) => t48.rail === 1)
  ];
  const added = (height2) => {
    let shortest = Infinity;
    for (let k2 = 0; k2 < railCount; k2++) {
      let lastX = 0, lastY = 0, total = 0, first = true;
      for (const t48 of railTemplates[k2]) {
        const cy2 = t48.raised ? height2 - radius : radius;
        const py2 = side * (cy2 + t48.sin) + t48.offsetY;
        const x2 = a2.x + ux2 * t48.px - uy2 * py2;
        const y2 = a2.y + uy2 * t48.px + ux2 * py2;
        const dx2 = lastX - x2, dy2 = lastY - y2;
        const d2 = Math.sqrt(dx2 * dx2 + dy2 * dy2);
        if (first || d2 > 1e-10) {
          if (!first) total += d2;
          lastX = x2;
          lastY = y2;
          first = false;
        }
      }
      shortest = Math.min(shortest, total - span);
    }
    return shortest;
  };
  const minimumHeight = 2 * radius;
  const minimumAddition = added(minimumHeight);
  if (minimumAddition > deficit + 1e-8) return null;
  let height = minimumHeight + Math.max(0, deficit - minimumAddition) / (2 * lobes);
  height = Math.max(
    minimumHeight,
    height + (deficit - added(height)) / (2 * lobes)
  );
  return generate(height);
}
function roundedTuningLobes(a2, b2, deficit, lobes, side, minRadius) {
  return roundedPairedLobes(a2, b2, 0, deficit, lobes, side, minRadius)?.[0] ?? null;
}

// lib/smooth-length-tuning.ts
var IncompleteLengthTuningError = class extends Error {
  constructor(traces, unfinished) {
    super(`Insufficient tuning clearance for ${unfinished.join(", ")}`);
    this.traces = traces;
    this.unfinished = unfinished;
  }
  traces;
  unfinished;
};
function tuneSmoothLengths(input, traces, targets, options = {}) {
  let attempted = 0;
  let allowFolded = false;
  const fixed = fixedCopper(input);
  function* candidates(t48, scene, fractionOfDeficit = 1) {
    const connection = input.connections.find(
      (c2) => c2.name === t48.connection_name
    );
    const terminalViaCopperIsClear = t48.coupledSection ? (_path) => true : createTerminalViaClearanceChecker(input, t48);
    const width = t48.route[0].width;
    const fixedLength = fixedRouteLength(input, connection.name);
    const currentLength = length(t48.route) + fixedLength;
    const delta = (targets.get(connection.name) - currentLength) * fractionOfDeficit;
    if (delta < 1e-8) {
      yield t48;
      return;
    }
    const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
    const pair = input.differentialPairs?.find(
      (p2) => p2.connectionNames.includes(t48.connection_name)
    );
    const regions = pair && options.packageOnlyPairTuning ? packageApproachRegions(
      input,
      width + (pair.traceGap ?? clearance) / 2 + clearance
    ) : [];
    const returnSpacing = width + clearance;
    const pitch = 4 * Math.max(width * 1.2, clearance);
    const segments = t48.route.slice(1).map((p2, i2) => {
      const a2 = t48.route[i2], span = distance(a2, p2);
      const midpoint = { x: (a2.x + p2.x) / 2, y: (a2.y + p2.y) / 2 };
      const normal = span > 1e-8 ? { x: -(p2.y - a2.y) / span, y: (p2.x - a2.x) / span } : { x: 0, y: 0 };
      const height = 2 * Math.max(width * 1.2, clearance);
      const openSides = [-1, 1].filter(
        (side) => scene.visible(midpoint, {
          x: midpoint.x + side * normal.x * height,
          y: midpoint.y + side * normal.y * height
        })
      ).length;
      return { i: i2, span, openSides };
    }).sort((a2, b2) => b2.openSides - a2.openSides || b2.span - a2.span);
    const folded = allowFolded;
    let attemptedFolded = 0;
    for (const compact of folded ? [false] : [false, true])
      for (const { i: i2 } of segments) {
        if (t48.curvedSegments?.includes(i2 + 1)) continue;
        if (t48.coupledSection && i2 >= t48.coupledSection[0] && i2 < t48.coupledSection[1])
          continue;
        const a2 = t48.route[i2], b2 = t48.route[i2 + 1], span = distance(a2, b2);
        if (span < 0.01) continue;
        const ux2 = (b2.x - a2.x) / span, uy2 = (b2.y - a2.y) / span;
        const maximumTeeth = Math.floor(span * 0.9 / pitch);
        const preferredTeeth = Math.min(
          maximumTeeth,
          options.packMeanders ? maximumTeeth : Math.max(2, Math.ceil(delta / (12 * width)))
        );
        const counts = Array.from(
          { length: maximumTeeth },
          (_2, i3) => i3 + 1
        ).sort(
          (a3, b3) => Math.abs(a3 - preferredTeeth) - Math.abs(b3 - preferredTeeth) || b3 - a3
        );
        function* placements() {
          if (folded) {
            for (const teeth of [1, 2, 3])
              for (const fraction of [0.9, 0.65, 0.4])
                for (const position of [0.5, 0, 1])
                  yield { teeth, fraction, position };
            return;
          }
          for (const teeth of counts) {
            if (!compact) {
              for (const fraction of [0.9, 0.65, 0.4])
                for (const phase of [0.5, 0, 1])
                  yield {
                    teeth,
                    fraction,
                    position: 0.05 + 0.9 * phase
                  };
            } else {
              for (const fraction of [0.9, 0.65, 0.4])
                for (const position of [0, 1])
                  yield { teeth, fraction, position };
              for (const fraction of [0.25, 0.15, 0.1])
                for (const position of [0.5, 0.05, 0.95, 0, 1])
                  yield { teeth, fraction, position };
            }
          }
        }
        for (const { teeth, fraction, position } of placements()) {
          const w2 = span * fraction / teeth;
          if (!folded && w2 < pitch) continue;
          for (const side of [1, -1])
            for (const createLobes of folded ? [foldedTuningLobes] : [roundedTuningLobes, smoothTuningLobes]) {
              const offset = span * (1 - fraction) * position;
              const start = { x: a2.x + ux2 * offset, y: a2.y + uy2 * offset };
              const end = {
                x: start.x + ux2 * span * fraction,
                y: start.y + uy2 * span * fraction
              };
              if (folded) {
                if (++attemptedFolded > Math.min(1024, options.maxCandidates ?? 1024))
                  return;
              }
              if (!folded && ++attempted > (options.maxCandidates ?? Infinity)) {
                if (options.packMeanders) return;
                throw Error("Smooth tuning candidate budget exhausted");
              }
              const lobes = createLobes(
                start,
                end,
                delta,
                teeth,
                side,
                Math.max(width * 1.2, clearance)
              );
              if (!lobes || regions.length && !regions.some(
                (r2) => lobes.every((p2) => pointInBox(p2, r2.copper))
              ))
                continue;
              const bump = [a2, ...lobes, b2];
              if (!scene.pathVisible(bump)) continue;
              const next = (t48.coupledSection ? (points) => points : simplify)([...t48.route.slice(0, i2), ...bump, ...t48.route.slice(i2 + 2)]);
              if (Math.abs(length(next) + fixedLength - (currentLength + delta)) > 1e-6)
                continue;
              if (!terminalViaCopperIsClear(next) || !tuningPathIsSelfClear(next, returnSpacing))
                continue;
              const candidate = {
                ...t48,
                coupledSection: t48.coupledSection ? t48.coupledSection.map(
                  (v2) => v2 > i2 ? v2 + next.length - t48.route.length : v2
                ) : void 0,
                curvedSegments: next.slice(1).flatMap((p2, i3) => {
                  const dx2 = Math.abs(p2.x - next[i3].x), dy2 = Math.abs(p2.y - next[i3].y);
                  return Math.min(dx2, dy2) > 1e-8 && Math.abs(dx2 - dy2) > 1e-8 ? [i3 + 1] : [];
                }),
                route: next.map((p2) => ({
                  ...p2,
                  route_type: "wire",
                  layer: connection.pointsToConnect[0].layer,
                  width
                }))
              };
              if (routeAnglesAreConventional([candidate])) yield candidate;
            }
        }
      }
  }
  const result = [...traces];
  const deficits = traces.map(
    (trace) => targets.get(trace.connection_name) - length(trace.route) - fixedRouteLength(input, trace.connection_name)
  );
  const pending = new Set(
    traces.map((_2, i2) => i2).sort((a2, b2) => {
      const order = options.priorityConnectionNames ?? [];
      const rank = (index2) => {
        const n2 = order.indexOf(traces[index2].connection_name);
        return n2 < 0 ? Infinity : n2;
      };
      return rank(a2) - rank(b2) || deficits[b2] - deficits[a2];
    })
  );
  const partialBanks = /* @__PURE__ */ new Map();
  let allowPartial = false;
  let changed = true;
  while (pending.size && changed) {
    changed = false;
    for (const index2 of pending) {
      const connection = input.connections.find(
        (c2) => c2.name === traces[index2].connection_name
      );
      const scene = new VectorScene(
        input,
        connection,
        result[index2].route[0].width,
        [...fixed, ...result.flatMap(routeCopper)]
      );
      let next = candidates(result[index2], scene).next().value;
      if (!next && allowPartial && (partialBanks.get(index2) ?? 0) < 8) {
        for (const fraction of [0.5, 0.25]) {
          next = candidates(result[index2], scene, fraction).next().value;
          if (next) {
            partialBanks.set(index2, (partialBanks.get(index2) ?? 0) + 1);
            break;
          }
        }
      }
      if (!next) continue;
      result[index2] = next;
      if (length(next.route) + fixedRouteLength(input, connection.name) >= targets.get(connection.name) - 1e-8)
        pending.delete(index2);
      changed = true;
    }
    if (!changed && !allowPartial) {
      allowPartial = true;
      changed = true;
    } else if (!changed && !allowFolded && options.packMeanders) {
      allowFolded = true;
      allowPartial = false;
      for (const index2 of pending) result[index2] = traces[index2];
      partialBanks.clear();
      changed = true;
    }
  }
  if (pending.size)
    throw new IncompleteLengthTuningError(
      result,
      [...pending].map((i2) => traces[i2].connection_name)
    );
  return result;
}

// lib/extend-coupled-section.ts
function extendCoupledSectionEnds(traces) {
  if (traces.length !== 2 || traces.some((t48) => !t48.coupledSection))
    return traces;
  const ends = traces.map((t48) => t48.coupledSection[1]);
  const points = traces.map((t48, i2) => t48.route[ends[i2]]);
  const directions = traces.map((t48, i2) => {
    const a2 = t48.route[ends[i2] - 1], b2 = points[i2], d2 = distance(a2, b2);
    return { x: (b2.x - a2.x) / d2, y: (b2.y - a2.y) / d2 };
  });
  if (distance(directions[0], directions[1]) > 1e-7) return traces;
  const direction = directions[0];
  const spans = traces.map((t48, i2) => {
    let span = 0;
    for (let k2 = ends[i2] + 1; k2 < t48.route.length; k2++) {
      const p2 = t48.route[k2], dx2 = p2.x - points[i2].x, dy2 = p2.y - points[i2].y;
      const along2 = dx2 * direction.x + dy2 * direction.y;
      if (Math.abs(dx2 * direction.y - dy2 * direction.x) > 1e-8 || along2 < span)
        break;
      span = along2;
    }
    return span;
  });
  const advance = Math.min(...spans);
  if (advance < 1e-8) return traces;
  return traces.map((t48, i2) => {
    const endpoint = {
      ...points[i2],
      x: points[i2].x + direction.x * advance,
      y: points[i2].y + direction.y * advance
    };
    let tail = ends[i2] + 1;
    while (tail < t48.route.length) {
      const dx2 = t48.route[tail].x - points[i2].x, dy2 = t48.route[tail].y - points[i2].y;
      if (Math.abs(dx2 * direction.y - dy2 * direction.x) > 1e-8 || dx2 * direction.x + dy2 * direction.y > advance + 1e-8)
        break;
      tail++;
    }
    return {
      ...t48,
      curvedSegments: t48.curvedSegments?.filter((n2) => n2 <= ends[i2] || n2 >= tail).map((n2) => n2 >= tail ? n2 - (tail - ends[i2] - 1) : n2),
      route: [...t48.route.slice(0, ends[i2]), endpoint, ...t48.route.slice(tail)]
    };
  });
}

// lib/coupled-pair-cache.ts
var requestCaches = /* @__PURE__ */ new WeakMap();
function coupledPairCache(input, fixed) {
  const scene = JSON.stringify([input, fixed]);
  let cache = requestCaches.get(input);
  if (!cache || cache.scene !== scene) {
    cache = { scene, alternatives: /* @__PURE__ */ new Map() };
    requestCaches.set(input, cache);
  }
  return {
    get(key) {
      const alternative = cache.alternatives.get(key);
      return alternative ? structuredClone(alternative) : void 0;
    },
    set(key, alternative) {
      if (cache.alternatives.size >= 512)
        cache.alternatives.delete(cache.alternatives.keys().next().value);
      cache.alternatives.set(key, structuredClone(alternative));
    }
  };
}

// lib/min-heap.ts
var MinHeap = class {
  entries = [];
  sequence = 0;
  get length() {
    return this.entries.length;
  }
  values() {
    return this.entries.map((e2) => e2.value);
  }
  before(a2, b2) {
    return a2.value.f < b2.value.f || a2.value.f === b2.value.f && a2.sequence < b2.sequence;
  }
  push(value) {
    const entry = { value, sequence: this.sequence++ };
    let i2 = this.entries.length;
    this.entries.push(entry);
    while (i2 > 0) {
      const parent = i2 - 1 >> 1;
      if (!this.before(entry, this.entries[parent])) break;
      this.entries[i2] = this.entries[parent];
      i2 = parent;
    }
    this.entries[i2] = entry;
  }
  pop() {
    const first = this.entries[0], last = this.entries.pop();
    if (this.entries.length) {
      let i2 = 0;
      while (i2 * 2 + 1 < this.entries.length) {
        let child = i2 * 2 + 1;
        if (child + 1 < this.entries.length && this.before(this.entries[child + 1], this.entries[child]))
          child++;
        if (!this.before(this.entries[child], last)) break;
        this.entries[i2] = this.entries[child];
        i2 = child;
      }
      this.entries[i2] = last;
    }
    return first.value;
  }
};

// lib/vector-visibility.ts
function connectors(a2, b2) {
  const dx2 = b2.x - a2.x, dy2 = b2.y - a2.y, sx2 = Math.sign(dx2), sy2 = Math.sign(dy2), d2 = Math.min(Math.abs(dx2), Math.abs(dy2));
  if (Math.min(Math.abs(dx2), Math.abs(dy2)) < 1e-10 || Math.abs(Math.abs(dx2) - Math.abs(dy2)) < 1e-10)
    return [[a2, b2]];
  const lead = (Math.max(Math.abs(dx2), Math.abs(dy2)) - d2) / 2;
  const centered = Math.abs(dx2) > Math.abs(dy2) ? [a2, { x: a2.x + sx2 * lead, y: a2.y }, { x: b2.x - sx2 * lead, y: b2.y }, b2] : [a2, { x: a2.x, y: a2.y + sy2 * lead }, { x: b2.x, y: b2.y - sy2 * lead }, b2];
  return [
    centered,
    [a2, { x: a2.x + sx2 * d2, y: a2.y + sy2 * d2 }, b2],
    [a2, { x: b2.x - sx2 * d2, y: b2.y - sy2 * d2 }, b2],
    [a2, { x: a2.x, y: b2.y }, b2],
    [a2, { x: b2.x, y: a2.y }, b2]
  ];
}
var VectorVisibilitySearch = class {
  constructor(scene, start, end) {
    this.scene = scene;
    this.start = start;
    this.end = end;
    this.vertices = [start, end];
    this.open.push({ id: 0, g: 0, f: distance(start, end) });
    this.best.set(0, 0);
  }
  scene;
  start;
  end;
  vertices;
  open = new MinHeap();
  best = /* @__PURE__ */ new Map();
  expanded = 0;
  failed = false;
  solved = false;
  result = [];
  geometryLoaded = false;
  current;
  visibleEdges = [];
  step() {
    if (!this.geometryLoaded) {
      this.geometryLoaded = true;
      const lowerBound = Math.max(
        Math.abs(this.end.x - this.start.x),
        Math.abs(this.end.y - this.start.y)
      ) + (Math.SQRT2 - 1) * Math.min(
        Math.abs(this.end.x - this.start.x),
        Math.abs(this.end.y - this.start.y)
      );
      for (const path of connectors(this.start, this.end)) {
        if (length(path) > lowerBound + 1e-9 || !this.scene.pathVisible(path))
          continue;
        this.visibleEdges = [path];
        this.result = simplify(path);
        this.solved = true;
        this.expanded = 1;
        return;
      }
      this.vertices.push(...this.scene.vertices());
    }
    if (!this.open.length) {
      this.failed = true;
      return;
    }
    const cur = this.open.pop();
    if (cur.g > (this.best.get(cur.id) ?? Infinity) + 1e-9) return;
    this.current = cur;
    this.expanded++;
    this.visibleEdges = [];
    if (cur.id === 1) {
      const edges = [];
      for (let c2 = cur; c2?.parent; c2 = c2.parent)
        edges.push(c2.edge);
      this.result = simplify([
        this.start,
        ...edges.reverse().flatMap((p2) => p2.slice(1))
      ]);
      this.solved = true;
      return;
    }
    const from = this.vertices[cur.id];
    for (let id = 1; id < this.vertices.length; id++) {
      if (id === cur.id) continue;
      const to = this.vertices[id], lower = cur.g + distance(from, to);
      if (lower >= (this.best.get(id) ?? Infinity) - 1e-9) continue;
      const candidates = connectors(from, to).sort(
        (a2, b2) => length(a2) - length(b2)
      );
      for (const path of candidates) {
        const g2 = cur.g + length(path);
        if (g2 >= (this.best.get(id) ?? Infinity) - 1e-9) continue;
        if (!this.scene.pathVisible(path)) continue;
        this.best.set(id, g2);
        this.open.push({
          id,
          g: g2,
          f: g2 + distance(to, this.end),
          parent: cur,
          edge: path
        });
        if (this.visibleEdges.length < 100) this.visibleEdges.push(path);
        break;
      }
    }
  }
  currentPath() {
    const edges = [];
    for (let c2 = this.current; c2?.parent; c2 = c2.parent) edges.push(c2.edge);
    return [this.start, ...edges.reverse().flatMap((e2) => e2.slice(1))];
  }
};

// lib/reduce-ordinary-turns.ts
function reduceOrdinaryTurns(path, scene) {
  let result = simplify(path);
  for (let pass = 0; pass < 12; pass++) {
    let changed = false;
    for (let i2 = 0; i2 < result.length - 2; i2++) {
      for (let j2 = result.length - 1; j2 > i2 + 1; j2--) {
        const old = length(result.slice(i2, j2 + 1));
        const candidates = connectors(result[i2], result[j2]).sort(
          (a2, b2) => length(a2) - length(b2) || a2.length - b2.length
        );
        let accepted = false;
        for (const replacement of candidates) {
          if (length(replacement) > old + 1e-8 || replacement.length >= j2 - i2 + 1 && length(replacement) >= old - 1e-8 || !scene.pathVisible(replacement))
            continue;
          const candidate = simplify([
            ...result.slice(0, i2),
            ...replacement,
            ...result.slice(j2 + 1)
          ]);
          const required = scene.width / 2 + scene.margin;
          if (!tuningPathIsSelfClear(candidate, required) && tuningPathIsSelfClear(result, required))
            continue;
          result = candidate;
          changed = true;
          accepted = true;
          break;
        }
        if (accepted) break;
      }
    }
    if (!changed) break;
  }
  return tuningPathIsSelfClear(result, scene.width / 2 + scene.margin) ? result : path;
}

// lib/length-search-frontier.ts
var LengthSearchFrontier = class {
  labels = /* @__PURE__ */ new Map();
  heap = [];
  sequence = 0;
  get length() {
    return this.heap.length;
  }
  clear() {
    this.labels.clear();
    this.heap.length = 0;
    this.sequence = 0;
  }
  dominated(node, cost, travelled) {
    return this.labels.get(node)?.some(
      (label) => label.cost <= cost + 1e-10 && label.travelled <= travelled + 1e-10
    ) ?? false;
  }
  add(node, cost, travelled, heuristic, parent, rootPath) {
    if (this.dominated(node, cost, travelled)) return;
    const previous = this.labels.get(node) ?? [];
    const retained = previous.filter((label2) => {
      if (cost <= label2.cost + 1e-10 && travelled <= label2.travelled + 1e-10) {
        label2.active = false;
        return false;
      }
      return true;
    });
    const label = {
      node,
      cost,
      travelled,
      priority: cost + heuristic,
      sequence: this.sequence++,
      parent,
      rootPath,
      active: true
    };
    retained.push(label);
    this.labels.set(node, retained);
    let i2 = this.heap.length;
    this.heap.push(label);
    while (i2 > 0) {
      const parentIndex = i2 - 1 >> 1;
      if (!this.before(label, this.heap[parentIndex])) break;
      this.heap[i2] = this.heap[parentIndex];
      i2 = parentIndex;
    }
    this.heap[i2] = label;
  }
  before(a2, b2) {
    return a2.priority < b2.priority || a2.priority === b2.priority && (a2.cost > b2.cost || a2.cost === b2.cost && a2.sequence < b2.sequence);
  }
  pop() {
    while (this.heap.length) {
      const result = this.heap[0], last = this.heap.pop();
      if (this.heap.length) {
        let i2 = 0;
        while (2 * i2 + 1 < this.heap.length) {
          let next = 2 * i2 + 1;
          if (next + 1 < this.heap.length && this.before(this.heap[next + 1], this.heap[next]))
            next++;
          if (!this.before(this.heap[next], last)) break;
          this.heap[i2] = this.heap[next];
          i2 = next;
        }
        this.heap[i2] = last;
      }
      if (result.active) return result;
    }
  }
};

// lib/grid-components.ts
var GridComponents = class {
  constructor(blocked, width) {
    this.width = width;
    const starts = [0], ends = [0], parents = [0], rows = [1];
    const root = (id) => {
      while (parents[id] !== id) {
        parents[id] = parents[parents[id]];
        id = parents[id];
      }
      return id;
    };
    let previousFirst = 1, previousEnd = 1;
    for (let base = 0; base < blocked.length; base += width) {
      const rowEnd = Math.min(base + width, blocked.length), first = parents.length;
      const row = blocked.subarray(base, rowEnd);
      let position = base, previous = previousFirst;
      while (position < rowEnd) {
        const offset = row.indexOf(0, position - base);
        if (offset < 0) break;
        const start = base + offset;
        const stop = row.indexOf(1, offset);
        const end = stop < 0 ? rowEnd : base + stop;
        const id = parents.length;
        starts.push(start);
        ends.push(end);
        parents.push(id);
        while (previous < previousEnd && ends[previous] + width < start)
          previous++;
        for (let other = previous; other < previousEnd && starts[other] + width <= end; other++) {
          const a2 = root(id), b2 = root(other);
          if (a2 !== b2) parents[Math.max(a2, b2)] = Math.min(a2, b2);
        }
        position = end;
      }
      previousFirst = first;
      previousEnd = parents.length;
      rows.push(previousEnd);
    }
    this.starts = Uint32Array.from(starts);
    this.ends = Uint32Array.from(ends);
    this.roots = Uint32Array.from(parents.map((_2, id) => root(id)));
    this.rows = Uint32Array.from(rows);
  }
  width;
  starts;
  ends;
  roots;
  rows;
  get storageBytes() {
    return this.starts.byteLength + this.ends.byteLength + this.roots.byteLength + this.rows.byteLength;
  }
  at(cell) {
    const row = Math.floor(cell / this.width);
    let lo = this.rows[row], hi = this.rows[row + 1];
    while (lo < hi) {
      const middle = lo + hi >>> 1;
      if (cell < this.starts[middle]) hi = middle;
      else if (cell >= this.ends[middle]) lo = middle + 1;
      else return this.roots[middle];
    }
    return 0;
  }
};

// lib/grid-heap.ts
var GridHeap = class {
  ids = new Int32Array(1024);
  costs = new Float64Array(1024);
  priorities = new Float64Array(1024);
  sequences = new Float64Array(1024);
  size = 0;
  positions;
  constructor(cellCount) {
    this.positions = new Int32Array(cellCount);
  }
  sequence = 0;
  id = 0;
  g = 0;
  get length() {
    return this.size;
  }
  get storageBytes() {
    return this.positions.byteLength + this.ids.byteLength + this.costs.byteLength + this.priorities.byteLength + this.sequences.byteLength;
  }
  clear() {
    for (let i2 = 0; i2 < this.size; i2++) this.positions[this.ids[i2]] = 0;
    this.size = 0;
    this.sequence = 0;
    this.id = 0;
    this.g = 0;
  }
  push(id, g2, f2) {
    const seq = this.sequence++;
    const previous = this.positions[id];
    if (previous && (f2 > this.priorities[previous - 1] || f2 === this.priorities[previous - 1] && g2 <= this.costs[previous - 1])) {
      this.sink(previous - 1, id, g2, f2, seq);
      return;
    }
    let i2 = previous ? previous - 1 : this.size++;
    if (i2 === this.ids.length) {
      const ids2 = new Int32Array(i2 * 2), costs2 = new Float64Array(i2 * 2), priorities2 = new Float64Array(i2 * 2), sequences2 = new Float64Array(i2 * 2);
      ids2.set(this.ids);
      costs2.set(this.costs);
      priorities2.set(this.priorities);
      sequences2.set(this.sequences);
      this.ids = ids2;
      this.costs = costs2;
      this.priorities = priorities2;
      this.sequences = sequences2;
    }
    const { ids, positions, costs, priorities, sequences } = this;
    while (i2 > 0) {
      const p2 = i2 - 1 >> 2;
      const pf = priorities[p2];
      if (f2 > pf || f2 === pf && (g2 < costs[p2] || g2 === costs[p2] && seq >= sequences[p2]))
        break;
      ids[i2] = ids[p2];
      positions[ids[i2]] = i2 + 1;
      costs[i2] = costs[p2];
      priorities[i2] = pf;
      sequences[i2] = sequences[p2];
      i2 = p2;
    }
    ids[i2] = id;
    positions[id] = i2 + 1;
    costs[i2] = g2;
    priorities[i2] = f2;
    sequences[i2] = seq;
  }
  pop() {
    const { ids, positions, costs, priorities, sequences } = this;
    this.id = ids[0];
    this.g = costs[0];
    positions[this.id] = 0;
    const n2 = --this.size;
    const id = ids[n2], g2 = costs[n2], f2 = priorities[n2], seq = sequences[n2];
    if (!n2) return;
    this.sink(0, id, g2, f2, seq);
  }
  sink(i2, id, g2, f2, seq) {
    const n2 = this.size;
    const start = i2;
    const { ids, costs, priorities, sequences, positions } = this;
    while (i2 * 4 + 1 < n2) {
      let child = i2 * 4 + 1;
      let cf = priorities[child], cg = costs[child], cs = sequences[child];
      const end = Math.min(child + 4, n2);
      for (let other = child + 1; other < end; other++) {
        const of = priorities[other];
        if (of < cf || of === cf && (costs[other] > cg || costs[other] === cg && sequences[other] < cs)) {
          child = other;
          cf = of;
          cg = costs[other];
          cs = sequences[other];
        }
      }
      ids[i2] = ids[child];
      positions[ids[i2]] = i2 + 1;
      costs[i2] = cg;
      priorities[i2] = cf;
      sequences[i2] = cs;
      i2 = child;
    }
    while (i2 > start) {
      const p2 = i2 - 1 >> 2;
      const pf = priorities[p2];
      if (f2 > pf || f2 === pf && (g2 < costs[p2] || g2 === costs[p2] && seq >= sequences[p2]))
        break;
      ids[i2] = ids[p2];
      positions[ids[i2]] = i2 + 1;
      costs[i2] = costs[p2];
      priorities[i2] = pf;
      sequences[i2] = sequences[p2];
      i2 = p2;
    }
    ids[i2] = id;
    positions[id] = i2 + 1;
    costs[i2] = g2;
    priorities[i2] = f2;
    sequences[i2] = seq;
  }
};

// lib/grid-scratch.ts
var maxScratchBytes = 64 * 1024 * 1024;
var pools = /* @__PURE__ */ new WeakMap();
function storageBytes(scratch) {
  return scratch.best.byteLength + scratch.parent.byteLength + (scratch.travel?.byteLength ?? 0) + scratch.heap.storageBytes;
}
var GridScratchPool = class {
  available = /* @__PURE__ */ new Map();
  retained = /* @__PURE__ */ new Map();
  bytes = 0;
  acquire(cellCount, withTravel) {
    const bucket = this.available.get(cellCount);
    const scratch = bucket?.pop() ?? {
      cellCount,
      best: new Float64Array(cellCount),
      parent: new Int32Array(cellCount),
      heap: new GridHeap(cellCount)
    };
    if (bucket && !bucket.length) this.available.delete(cellCount);
    const retainedBytes = this.retained.get(scratch);
    if (retainedBytes !== void 0) {
      this.bytes -= retainedBytes;
      this.retained.delete(scratch);
    }
    scratch.best.fill(Infinity);
    if (withTravel && !scratch.travel)
      scratch.travel = new Float64Array(cellCount);
    let active = true;
    return {
      scratch,
      release: () => {
        if (!active) return;
        active = false;
        this.retain(scratch);
      }
    };
  }
  retain(scratch) {
    scratch.heap.clear();
    const bytes = storageBytes(scratch);
    if (bytes > maxScratchBytes) return;
    while (this.bytes + bytes > maxScratchBytes) {
      const oldest = this.retained.keys().next().value;
      this.bytes -= this.retained.get(oldest);
      this.retained.delete(oldest);
      const bucket2 = this.available.get(oldest.cellCount);
      bucket2.splice(bucket2.indexOf(oldest), 1);
      if (!bucket2.length) this.available.delete(oldest.cellCount);
    }
    const bucket = this.available.get(scratch.cellCount) ?? [];
    bucket.push(scratch);
    this.available.set(scratch.cellCount, bucket);
    this.retained.set(scratch, bytes);
    this.bytes += bytes;
  }
};
function acquireGridScratch(input, cellCount, withTravel) {
  let pool = pools.get(input);
  if (!pool) pools.set(input, pool = new GridScratchPool());
  return pool.acquire(cellCount, withTravel);
}

// lib/grid-visibility.ts
var CopperBuckets = class {
  dense;
  sparse;
  storageBytes;
  minX;
  minY;
  maxX;
  maxY;
  width;
  constructor(bounds) {
    this.minX = Math.floor(bounds.minX);
    this.minY = Math.floor(bounds.minY);
    this.maxX = Math.ceil(bounds.maxX) + 1;
    this.maxY = Math.ceil(bounds.maxY) + 1;
    this.width = this.maxX - this.minX + 1;
    const cells = this.width * (this.maxY - this.minY + 1);
    if (cells <= 65536) {
      this.dense = new Array(cells);
      this.storageBytes = cells * 8;
    } else {
      this.sparse = /* @__PURE__ */ new Map();
      this.storageBytes = 0;
    }
  }
  add(x2, y2, entry) {
    if (x2 < this.minX || x2 > this.maxX || y2 < this.minY || y2 > this.maxY) return;
    const key = x2 - this.minX + (y2 - this.minY) * this.width;
    let bucket = this.dense ? this.dense[key] : this.sparse.get(key);
    if (!bucket) {
      bucket = [];
      if (this.dense) this.dense[key] = bucket;
      else this.sparse.set(key, bucket);
    }
    if (bucket[bucket.length - 1] !== entry) bucket.push(entry);
  }
  addCopper(entry, margin) {
    const c2 = entry.copper;
    const box = (minX, maxX, minY, maxY) => {
      for (let x2 = Math.floor(minX); x2 <= Math.floor(maxX); x2++)
        for (let y2 = Math.floor(minY); y2 <= Math.floor(maxY); y2++)
          this.add(x2, y2, entry);
    };
    if (c2.rect) {
      box(entry.minX, entry.maxX, entry.minY, entry.maxY);
      return;
    }
    const dx2 = c2.b.x - c2.a.x, dy2 = c2.b.y - c2.a.y;
    const steps = Math.max(1, Math.ceil(Math.max(Math.abs(dx2), Math.abs(dy2))));
    const rx2 = c2.radius + margin + Math.abs(dx2) / (2 * steps) + 1e-9;
    const ry2 = c2.radius + margin + Math.abs(dy2) / (2 * steps) + 1e-9;
    for (let i2 = 0; i2 <= steps; i2++) {
      const x2 = c2.a.x + dx2 * i2 / steps, y2 = c2.a.y + dy2 * i2 / steps;
      box(x2 - rx2, x2 + rx2, y2 - ry2, y2 + ry2);
    }
  }
  get(x2, y2) {
    if (x2 < this.minX || x2 > this.maxX || y2 < this.minY || y2 > this.maxY)
      return void 0;
    const key = x2 - this.minX + (y2 - this.minY) * this.width;
    return this.dense ? this.dense[key] : this.sparse.get(key);
  }
  *values() {
    if (this.dense) {
      for (const bucket of this.dense) if (bucket) yield bucket;
    } else yield* this.sparse.values();
  }
};
var softGrids = /* @__PURE__ */ new WeakMap();
var maxSoftGridBytes = 16 * 1024 * 1024;
var emptyEdgeBytes = new Uint8Array(0);
var hardGrids = /* @__PURE__ */ new WeakMap();
var maxHardGridBytes = 64 * 1024 * 1024;
function copperEntry(copper, margin) {
  const r2 = copper.rect ?? {
    minX: Math.min(copper.a.x, copper.b.x) - copper.radius,
    maxX: Math.max(copper.a.x, copper.b.x) + copper.radius,
    minY: Math.min(copper.a.y, copper.b.y) - copper.radius,
    maxY: Math.max(copper.a.y, copper.b.y) + copper.radius
  };
  return {
    ...prepareCopper({
      ...copper,
      a: { ...copper.a },
      b: { ...copper.b },
      rect: copper.rect ? { ...copper.rect } : void 0
    }),
    minX: r2.minX - margin,
    maxX: r2.maxX + margin,
    minY: r2.minY - margin,
    maxY: r2.maxY + margin
  };
}
function routingBounds(scene, step) {
  const input = scene.input, board = input.bounds;
  const layer = scene.connection.pointsToConnect[0].layer;
  const copper = fixedCopper(input).filter((c2) => c2.layer === layer);
  const points = input.connections.flatMap((c2) => c2.pointsToConnect);
  for (const c2 of copper) {
    if (c2.rect)
      points.push(
        { x: c2.rect.minX, y: c2.rect.minY, layer },
        { x: c2.rect.maxX, y: c2.rect.maxY, layer }
      );
    else
      points.push(
        {
          x: Math.min(c2.a.x, c2.b.x) - c2.radius,
          y: Math.min(c2.a.y, c2.b.y) - c2.radius,
          layer
        },
        {
          x: Math.max(c2.a.x, c2.b.x) + c2.radius,
          y: Math.max(c2.a.y, c2.b.y) + c2.radius,
          layer
        }
      );
  }
  const minX = Math.min(...points.map((p2) => p2.x)), maxX = Math.max(...points.map((p2) => p2.x));
  const minY = Math.min(...points.map((p2) => p2.y)), maxY = Math.max(...points.map((p2) => p2.y));
  const pitch = input.minTraceWidth + (input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075);
  const margin = Math.max(
    2,
    input.connections.length * pitch,
    Math.min(maxX - minX, maxY - minY) / 2
  );
  const lo = (n2, origin) => origin + Math.floor((n2 - origin) / step) * step;
  const hi = (n2, origin) => origin + Math.ceil((n2 - origin) / step) * step;
  return {
    minX: Math.max(board.minX, lo(minX - margin, board.minX)),
    maxX: Math.min(board.maxX, hi(maxX + margin, board.minX)),
    minY: Math.max(board.minY, lo(minY - margin, board.minY)),
    maxY: Math.min(board.maxY, hi(maxY + margin, board.minY))
  };
}
var GridHistoryProjector = class {
  constructor(scene, grid) {
    this.scene = scene;
    this.packageGrid = scene.input.obstacles.some((o2) => o2.componentId);
    this.stepSize = Math.max(
      0.01,
      grid?.step ?? scene.input.minTraceWidth / (this.packageGrid ? 2 : 1)
    );
    const b2 = grid?.bounds ?? (this.packageGrid ? routingBounds(scene, this.stepSize) : scene.input.bounds);
    this.gridBounds = b2;
    this.origin = { x: b2.minX, y: b2.minY };
    this.nx = Math.ceil((b2.maxX - b2.minX) / this.stepSize) + 1;
    this.ny = Math.ceil((b2.maxY - b2.minY) / this.stepSize) + 1;
    this.xs = Float64Array.from(
      { length: this.nx },
      (_2, x2) => this.origin.x + x2 * this.stepSize
    );
    this.ys = Float64Array.from(
      { length: this.ny },
      (_2, y2) => this.origin.y + y2 * this.stepSize
    );
    if (this.cellCount > 8e6)
      throw Error("Dense grid search budget exceeded");
  }
  scene;
  packageGrid;
  gridBounds;
  nx;
  ny;
  stepSize;
  origin;
  xs;
  ys;
  get cellCount() {
    return this.nx * this.ny;
  }
  penalizeIntersection(history, a2, b2, c2, d2, radius, wholeSegments = false) {
    const touched = /* @__PURE__ */ new Set();
    const testedBoth = /* @__PURE__ */ new Set();
    for (const [start, end] of [
      [a2, b2],
      [c2, d2]
    ]) {
      const tested = wholeSegments ? /* @__PURE__ */ new Set() : testedBoth;
      const samples = Math.max(
        1,
        Math.ceil(distance(start, end) / this.stepSize)
      );
      for (let i2 = 0; i2 <= samples; i2++) {
        const p2 = {
          x: start.x + (end.x - start.x) * i2 / samples,
          y: start.y + (end.y - start.y) * i2 / samples
        };
        const cx2 = Math.round((p2.x - this.origin.x) / this.stepSize), cy2 = Math.round((p2.y - this.origin.y) / this.stepSize), n2 = Math.ceil(radius / this.stepSize);
        for (let dy2 = -n2; dy2 <= n2; dy2++)
          for (let dx2 = -n2; dx2 <= n2; dx2++) {
            if (cx2 + dx2 < 0 || cx2 + dx2 >= this.nx || cy2 + dy2 < 0 || cy2 + dy2 >= this.ny)
              continue;
            const id = cx2 + dx2 + (cy2 + dy2) * this.nx;
            if (touched.has(id) || tested.has(id)) continue;
            tested.add(id);
            const point = this.point(id);
            if (segmentDistance([point, point], [start, end]) > radius) continue;
            if (!wholeSegments && (segmentDistance([point, point], [a2, b2]) > radius || segmentDistance([point, point], [c2, d2]) > radius))
              continue;
            touched.add(id);
          }
      }
    }
    for (const id of touched) history[id] += wholeSegments ? 0.3 : 1;
  }
  point(id) {
    return {
      x: this.xs[id % this.nx],
      y: this.ys[Math.floor(id / this.nx)]
    };
  }
};
var GridVisibilitySearch = class extends GridHistoryProjector {
  constructor(scene, start, end, softCopper = [], penalty = 4, history, grid) {
    super(scene, grid);
    this.start = start;
    this.end = end;
    this.penalty = penalty;
    this.history = history;
    const b2 = this.gridBounds;
    this.softMargin = scene.margin;
    this.hasSoftCopper = softCopper.some(
      (c2) => c2.layer === scene.connection.pointsToConnect[0].layer
    );
    this.copperBuckets = new CopperBuckets(b2);
    this.neighbors = [];
    for (let dy2 = -1; dy2 <= 1; dy2++)
      for (let dx2 = -1; dx2 <= 1; dx2++) {
        if (!(dx2 || dy2)) continue;
        const direction = (dy2 + 1) * 3 + dx2 + 1;
        const index2 = direction > 4 ? direction - 1 : direction;
        this.neighbors.push({
          dx: dx2,
          dy: dy2,
          offset: dx2 + dy2 * this.nx,
          cost: dx2 && dy2 ? Math.SQRT2 : 1,
          bit: 1 << index2,
          reverse: 1 << 7 - index2
        });
      }
    const ends = grid?.ends ?? [end];
    this.goalBounds = {
      minX: Math.min(...ends.map((p2) => p2.x)),
      maxX: Math.max(...ends.map((p2) => p2.x)),
      minY: Math.min(...ends.map((p2) => p2.y)),
      maxY: Math.max(...ends.map((p2) => p2.y))
    };
    this.hx = this.xs.map(
      (x2) => Math.max(this.goalBounds.minX - x2, x2 - this.goalBounds.maxX, 0) / this.stepSize
    );
    this.hy = this.ys.map(
      (y2) => Math.max(this.goalBounds.minY - y2, y2 - this.goalBounds.maxY, 0) / this.stepSize
    );
    const n2 = this.nx * this.ny;
    const grids = hardGrids.get(scene.input) ?? /* @__PURE__ */ new Map();
    hardGrids.set(scene.input, grids);
    const gridKey = JSON.stringify([
      b2.minX,
      b2.minY,
      b2.maxX,
      b2.maxY,
      this.nx,
      this.ny,
      this.stepSize,
      scene.margin,
      scene.width,
      scene.input.minBoardEdgeClearance,
      scene.input.bounds,
      scene.copper.map((c2) => [c2.a.x, c2.a.y, c2.b.x, c2.b.y, c2.radius, c2.rect])
    ]);
    let cachedGrid = grids.get(gridKey);
    const attachments = cachedGrid?.attachments ?? /* @__PURE__ */ new Map();
    if (cachedGrid) {
      grids.delete(gridKey);
      grids.set(gridKey, cachedGrid);
    }
    this.blocked = cachedGrid?.blocked ?? new Uint8Array(n2);
    this.hardEdgeKnown = cachedGrid?.edgeKnown ?? new Uint8Array(n2);
    this.hardEdgeBlocked = cachedGrid?.edgeBlocked ?? new Uint8Array(n2);
    if (cachedGrid) this.copperBuckets = cachedGrid.buckets;
    this.maxLength = grid?.maxLength ?? Infinity;
    if (grid?.paretoLength && Number.isFinite(this.maxLength))
      this.lengthFrontier = new LengthSearchFrontier();
    let componentIndex = cachedGrid?.components;
    if (!cachedGrid) {
      const testedBy = new Uint32Array(n2);
      let copperStamp = 0;
      const markBox = (minX, maxX, minY, maxY, entry) => {
        const copper = entry.copper;
        const loX = Math.max(0, Math.floor((minX - b2.minX) / this.stepSize));
        const hiX = Math.min(
          this.nx - 1,
          Math.ceil((maxX - b2.minX) / this.stepSize)
        );
        const loY = Math.max(0, Math.floor((minY - b2.minY) / this.stepSize));
        const hiY = Math.min(
          this.ny - 1,
          Math.ceil((maxY - b2.minY) / this.stepSize)
        );
        const circle = !copper.rect && copper.a.x === copper.b.x && copper.a.y === copper.b.y;
        const threshold = scene.margin - 1e-8;
        for (let y2 = loY; y2 <= hiY; y2++) {
          const py2 = this.ys[y2], dy2 = py2 - copper.a.y;
          const row = y2 * this.nx;
          for (let x2 = loX; x2 <= hiX; x2++) {
            const id = x2 + row;
            if (this.blocked[id] || testedBy[id] === copperStamp) continue;
            testedBy[id] = copperStamp;
            if (circle) {
              const dx2 = this.xs[x2] - copper.a.x;
              if (Math.sqrt(dx2 * dx2 + dy2 * dy2) - copper.radius < threshold)
                this.blocked[id] = 1;
            } else {
              if (copperTooClosePrepared(
                this.xs[x2],
                py2,
                this.xs[x2],
                py2,
                0,
                0,
                0,
                entry,
                threshold
              ))
                this.blocked[id] = 1;
            }
          }
        }
      };
      for (const copper of scene.copper) {
        copperStamp++;
        const entry = copperEntry(copper, scene.margin);
        const r2 = scene.margin + copper.radius;
        this.copperBuckets.addCopper(entry, scene.margin);
        if (copper.rect) {
          const q2 = copper.rect;
          markBox(q2.minX - r2, q2.maxX + r2, q2.minY - r2, q2.maxY + r2, entry);
          continue;
        }
        const span = distance(copper.a, copper.b), steps = Math.max(1, Math.ceil(span / this.stepSize));
        for (let i2 = 0; i2 <= steps; i2++) {
          const p2 = {
            x: copper.a.x + (copper.b.x - copper.a.x) * i2 / steps,
            y: copper.a.y + (copper.b.y - copper.a.y) * i2 / steps
          };
          markBox(p2.x - r2, p2.x + r2, p2.y - r2, p2.y + r2, entry);
        }
      }
      componentIndex = grid?.checkReachability ? new GridComponents(this.blocked, this.nx) : void 0;
      const bytes = (componentIndex?.storageBytes ?? 0) + n2 * 3 + this.copperBuckets.storageBytes + gridKey.length * 2 + [...this.copperBuckets.values()].reduce(
        (sum, bucket) => sum + bucket.length * 8 + 64,
        0
      ) + scene.copper.length * 136;
      if (bytes <= maxHardGridBytes) {
        let retained = [...grids.values()].reduce(
          (sum, value) => sum + value.bytes,
          0
        );
        while (retained + bytes > maxHardGridBytes && grids.size) {
          const oldest = grids.keys().next().value;
          retained -= grids.get(oldest).bytes;
          grids.delete(oldest);
        }
        cachedGrid = {
          attachments,
          blocked: this.blocked,
          edgeKnown: this.hardEdgeKnown,
          edgeBlocked: this.hardEdgeBlocked,
          buckets: this.copperBuckets,
          bytes,
          components: componentIndex
        };
        grids.set(gridKey, cachedGrid);
      }
    }
    if (grid?.checkReachability && !componentIndex) {
      componentIndex = new GridComponents(this.blocked, this.nx);
      if (cachedGrid) {
        cachedGrid.components = componentIndex;
        cachedGrid.bytes += componentIndex.storageBytes;
        let retained = [...grids.values()].reduce(
          (sum, value) => sum + value.bytes,
          0
        );
        while (retained > maxHardGridBytes && grids.size) {
          const oldest = grids.keys().next().value;
          retained -= grids.get(oldest).bytes;
          grids.delete(oldest);
        }
      }
    }
    if (this.hasSoftCopper) {
      this.softBuckets = new CopperBuckets(b2);
      const softKey = JSON.stringify([
        b2.minX,
        b2.minY,
        b2.maxX,
        b2.maxY,
        this.nx,
        this.ny,
        this.stepSize,
        this.softMargin,
        scene.connection.pointsToConnect[0].layer
      ]);
      const softMemo = softGrids.get(scene.input) ?? /* @__PURE__ */ new Map();
      softGrids.set(scene.input, softMemo);
      const previous = softMemo.get(softKey);
      const softEntries = /* @__PURE__ */ new Map();
      for (const copper of softCopper) {
        if (copper.layer !== scene.connection.pointsToConnect[0].layer) continue;
        const key = JSON.stringify([
          copper.a.x,
          copper.a.y,
          copper.b.x,
          copper.b.y,
          copper.radius,
          copper.rect
        ]);
        const entry = previous?.copper.get(key) ?? copperEntry(copper, this.softMargin);
        this.softBuckets.addCopper(entry, this.softMargin);
        softEntries.set(key, entry);
      }
      const softBytes = n2 * 2 + softKey.length * 2 + [...softEntries.keys()].reduce(
        (sum, key) => sum + key.length * 2 + 136,
        0
      );
      const reusable = previous && !previous.lease.active && softBytes <= maxSoftGridBytes ? previous : void 0;
      this.softEdgeKnown = reusable?.edgeKnown ?? new Uint8Array(n2);
      this.softEdgeBlocked = reusable?.edgeBlocked ?? new Uint8Array(n2);
      if (reusable) {
        const invalidateBox = (minX, maxX, minY, maxY) => {
          const loX = Math.max(0, Math.floor((minX - b2.minX) / this.stepSize));
          const hiX = Math.min(
            this.nx - 1,
            Math.ceil((maxX - b2.minX) / this.stepSize)
          );
          const loY = Math.max(0, Math.floor((minY - b2.minY) / this.stepSize));
          const hiY = Math.min(
            this.ny - 1,
            Math.ceil((maxY - b2.minY) / this.stepSize)
          );
          if (hiX < loX) return;
          for (let y2 = loY; y2 <= hiY; y2++) {
            const offset = y2 * this.nx;
            this.softEdgeKnown.fill(0, offset + loX, offset + hiX + 1);
            this.softEdgeBlocked.fill(0, offset + loX, offset + hiX + 1);
          }
        };
        const invalidate = (entry) => {
          const halo = this.stepSize + 1e-9;
          if (entry.copper.rect) {
            invalidateBox(
              entry.minX - halo,
              entry.maxX + halo,
              entry.minY - halo,
              entry.maxY + halo
            );
            return;
          }
          const radius = entry.copper.radius + this.softMargin + halo;
          const loY = Math.max(
            0,
            Math.floor(
              (Math.min(entry.ay, entry.by) - radius - b2.minY) / this.stepSize
            )
          );
          const hiY = Math.min(
            this.ny - 1,
            Math.ceil(
              (Math.max(entry.ay, entry.by) + radius - b2.minY) / this.stepSize
            )
          );
          for (let y2 = loY; y2 <= hiY; y2++) {
            let lo = 0, hi = 1;
            if (entry.dy === 0) {
              if (Math.abs(this.ys[y2] - entry.ay) > radius) continue;
            } else {
              const t0 = (this.ys[y2] - radius - entry.ay) / entry.dy, t1 = (this.ys[y2] + radius - entry.ay) / entry.dy;
              lo = Math.max(0, Math.min(t0, t1));
              hi = Math.min(1, Math.max(t0, t1));
              if (lo > hi) continue;
            }
            const x0 = entry.ax + entry.dx * lo, x1 = entry.ax + entry.dx * hi;
            const loX = Math.max(
              0,
              Math.floor((Math.min(x0, x1) - radius - b2.minX) / this.stepSize)
            );
            const hiX = Math.min(
              this.nx - 1,
              Math.ceil((Math.max(x0, x1) + radius - b2.minX) / this.stepSize)
            );
            if (hiX < loX) continue;
            const offset = y2 * this.nx;
            this.softEdgeKnown.fill(0, offset + loX, offset + hiX + 1);
            this.softEdgeBlocked.fill(0, offset + loX, offset + hiX + 1);
          }
        };
        for (const [key, entry] of reusable.copper)
          if (!softEntries.has(key)) invalidate(entry);
        for (const [key, entry] of softEntries)
          if (!reusable.copper.has(key)) invalidate(entry);
      }
      if (softBytes <= maxSoftGridBytes) {
        if (previous) softMemo.delete(softKey);
        let retained = [...softMemo.values()].reduce(
          (sum, grid2) => sum + grid2.bytes,
          0
        );
        while (retained + softBytes > maxSoftGridBytes && softMemo.size) {
          const oldest = softMemo.keys().next().value;
          retained -= softMemo.get(oldest).bytes;
          softMemo.delete(oldest);
        }
        this.softMemoLease = { active: true };
        softMemo.set(softKey, {
          edgeKnown: this.softEdgeKnown,
          edgeBlocked: this.softEdgeBlocked,
          copper: softEntries,
          lease: this.softMemoLease,
          bytes: softBytes
        });
      }
    }
    const attach = (p2) => {
      const key = JSON.stringify(p2);
      if (attachments.has(key)) return structuredClone(attachments.get(key));
      const x2 = Math.round((p2.x - b2.minX) / this.stepSize), y2 = Math.round((p2.y - b2.minY) / this.stepSize);
      const candidates = [];
      for (let dy2 = -4; dy2 <= 4; dy2++)
        for (let dx2 = -4; dx2 <= 4; dx2++) {
          if (x2 + dx2 < 0 || x2 + dx2 >= this.nx || y2 + dy2 < 0 || y2 + dy2 >= this.ny)
            continue;
          const id = x2 + dx2 + (y2 + dy2) * this.nx;
          if (this.blocked[id]) continue;
          for (const path of connectors(p2, this.point(id)))
            if (scene.pathVisible(path)) {
              candidates.push({ id, path });
              break;
            }
        }
      const result = candidates.sort((a3, b3) => length(a3.path) - length(b3.path) || a3.id - b3.id).slice(0, 8);
      if (attachments.size >= 128)
        attachments.delete(attachments.keys().next().value);
      attachments.set(key, structuredClone(result));
      return result;
    };
    const distinct = (items) => {
      const unique = /* @__PURE__ */ new Map();
      for (const a3 of items.sort((a4, b3) => length(a4.path) - length(b3.path)))
        if (!unique.has(a3.id)) unique.set(a3.id, a3);
      return [...unique.values()];
    };
    this.startAttachments = grid?.starts ? distinct(
      grid.starts.flatMap(
        (point) => grid.nearestTerminalAttachments ? attach(point).slice(0, 1) : attach(point)
      )
    ) : attach(start);
    this.endAttachments = grid?.ends ? distinct(
      ends.flatMap(
        (point) => grid.nearestTerminalAttachments ? attach(point).slice(0, 1) : attach(point)
      )
    ) : attach(end);
    const a2 = this.startAttachments[0], z2 = this.endAttachments[0];
    if (!a2 || !z2) {
      this.failed = true;
      if (this.softMemoLease) this.softMemoLease.active = false;
      return;
    }
    const components = componentIndex;
    const sameComponent = (starts, ends2) => starts.some(
      (start2) => ends2.some(
        (end2) => components.at(start2.id) !== 0 && components.at(start2.id) === components.at(end2.id)
      )
    );
    let forceAlternativeAttachments = false;
    if (grid?.checkReachability && !sameComponent([a2], [z2])) {
      if (!sameComponent(this.startAttachments, this.endAttachments)) {
        this.failed = true;
        if (this.softMemoLease) this.softMemoLease.active = false;
        return;
      }
      forceAlternativeAttachments = true;
    }
    this.scratchLease = acquireGridScratch(
      scene.input,
      n2,
      Number.isFinite(this.maxLength)
    );
    const scratch = this.scratchLease.scratch;
    this.heap = scratch.heap;
    this.best = scratch.best;
    this.parent = scratch.parent;
    this.travel = Number.isFinite(this.maxLength) ? scratch.travel : void 0;
    this.startPath = a2.path;
    this.endPath = z2.path.toReversed();
    this.goal = z2.id;
    this.best[a2.id] = 0;
    this.parent[a2.id] = -1;
    if (this.travel) this.travel[a2.id] = length(a2.path);
    if (this.lengthFrontier)
      this.lengthFrontier.add(
        a2.id,
        0,
        length(a2.path),
        this.heuristic(start),
        void 0,
        a2.path
      );
    else this.heap.push(a2.id, 0, this.heuristic(start));
    if (forceAlternativeAttachments || grid?.allTerminalAttachments || grid?.starts || grid?.ends)
      this.retryAttachments();
  }
  start;
  end;
  penalty;
  history;
  expanded = 0;
  failed = false;
  solved = false;
  result = [];
  heap;
  lengthFrontier;
  scratchLease;
  neighbors;
  travel;
  maxLength = Infinity;
  best;
  parent;
  blocked;
  softMargin;
  softBuckets;
  hasSoftCopper;
  softEdgeKnown = emptyEdgeBytes;
  softMemoLease;
  softEdgeBlocked = emptyEdgeBytes;
  hardEdgeKnown;
  hardEdgeBlocked;
  copperBuckets;
  goal = -1;
  startPath = [];
  endPath = [];
  startAttachments = [];
  endAttachments = [];
  alternateAttachments = false;
  rootPaths = /* @__PURE__ */ new Map();
  goalPaths = /* @__PURE__ */ new Map();
  attachmentResult;
  goalBounds;
  hx;
  hy;
  retryAttachments() {
    if (this.alternateAttachments || this.startAttachments.length <= 1 && this.endAttachments.length <= 1)
      return false;
    this.alternateAttachments = true;
    this.heap.clear();
    this.lengthFrontier?.clear();
    this.best.fill(Infinity);
    for (const attachment of this.startAttachments) {
      const travelled = length(attachment.path);
      if (travelled > this.maxLength + 1e-8) continue;
      const cost = travelled / this.stepSize;
      this.best[attachment.id] = cost;
      this.parent[attachment.id] = -1;
      if (this.travel) this.travel[attachment.id] = travelled;
      this.rootPaths.set(attachment.id, attachment.path);
      if (this.lengthFrontier)
        this.lengthFrontier.add(
          attachment.id,
          cost,
          travelled,
          this.heuristic(this.point(attachment.id)),
          void 0,
          attachment.path
        );
      else
        this.heap.push(
          attachment.id,
          cost,
          cost + this.heuristic(this.point(attachment.id))
        );
    }
    for (const attachment of this.endAttachments)
      this.goalPaths.set(attachment.id, attachment.path.toReversed());
    return true;
  }
  pathTo(id, endPath, label) {
    if (label) {
      const path2 = [];
      let root2 = label;
      for (let current = label; current; current = current.parent) {
        root2 = current;
        path2.push(this.point(current.node));
      }
      return simplify([
        ...root2.rootPath,
        ...path2.reverse().slice(1),
        ...endPath.slice(1)
      ]);
    }
    const path = [];
    let root = id;
    for (let current = id; current >= 0; current = this.parent[current]) {
      root = current;
      path.push(this.point(current));
    }
    return simplify([
      ...this.alternateAttachments ? this.rootPaths.get(root) : this.startPath,
      ...path.reverse().slice(1),
      ...endPath.slice(1)
    ]);
  }
  finish(path) {
    this.result = path;
    this.solved = true;
    if (this.softMemoLease) this.softMemoLease.active = false;
    this.scratchLease?.release();
    this.lengthFrontier?.clear();
  }
  edgeClear(fromX, fromY, toX, toY, buckets, margin = this.scene.margin) {
    if (!buckets) return true;
    const minX = Math.min(fromX, toX), maxX = Math.max(fromX, toX);
    const minY = Math.min(fromY, toY), maxY = Math.max(fromY, toY);
    const dx2 = toX - fromX, dy2 = toY - fromY, denominator = dx2 * dx2 + dy2 * dy2;
    const threshold = margin - 1e-8;
    const endX = Math.floor(maxX), endY = Math.floor(maxY);
    for (let x2 = Math.floor(minX); x2 <= endX; x2++) {
      for (let y2 = Math.floor(minY); y2 <= endY; y2++) {
        const bucket = buckets.get(x2, y2);
        if (!bucket) continue;
        for (let i2 = 0; i2 < bucket.length; i2++) {
          const entry = bucket[i2];
          if (entry.minX > maxX || entry.maxX < minX || entry.minY > maxY || entry.maxY < minY)
            continue;
          if (copperTooClosePrepared(
            fromX,
            fromY,
            toX,
            toY,
            dx2,
            dy2,
            denominator,
            entry,
            threshold
          ))
            return false;
        }
      }
    }
    return true;
  }
  heuristic(point) {
    const dx2 = Math.max(
      this.goalBounds.minX - point.x,
      point.x - this.goalBounds.maxX,
      0
    ) / this.stepSize;
    const dy2 = Math.max(
      this.goalBounds.minY - point.y,
      point.y - this.goalBounds.maxY,
      0
    ) / this.stepSize;
    return Math.max(dx2, dy2) + (Math.SQRT2 - 1) * Math.min(dx2, dy2);
  }
  /** Stop an abandoned search before handing its memo to the next search.
   * Completed route results remain readable and unchanged. */
  cancel() {
    if (!this.solved) this.failed = true;
    if (this.softMemoLease) this.softMemoLease.active = false;
    this.scratchLease?.release();
    this.lengthFrontier?.clear();
  }
  step() {
    const {
      heap,
      lengthFrontier,
      best,
      parent,
      blocked,
      nx: nx2,
      ny: ny2,
      xs,
      ys,
      hx: hx2,
      hy: hy2,
      history,
      travel,
      stepSize,
      maxLength,
      penalty,
      hasSoftCopper,
      softEdgeKnown,
      softEdgeBlocked,
      hardEdgeKnown,
      hardEdgeBlocked,
      softBuckets,
      copperBuckets,
      softMargin
    } = this;
    const bounds = this.scene.input.bounds;
    const edge = this.scene.width / 2 + (this.scene.input.minBoardEdgeClearance ?? 0);
    const minX = bounds.minX + edge, maxX = bounds.maxX - edge;
    const minY = bounds.minY + edge, maxY = bounds.maxY - edge;
    for (let batch = 0; batch < 500 && !this.failed && !this.solved; batch++) {
      if (!(lengthFrontier?.length ?? heap.length)) {
        if (this.attachmentResult) {
          this.finish(this.attachmentResult.path);
          return;
        }
        if (this.retryAttachments()) continue;
        this.failed = true;
        if (this.softMemoLease) this.softMemoLease.active = false;
        this.scratchLease?.release();
        this.lengthFrontier?.clear();
        return;
      }
      const currentLabel = lengthFrontier?.pop();
      if (lengthFrontier && !currentLabel) continue;
      if (!lengthFrontier) heap.pop();
      const curId = currentLabel?.node ?? heap.id, curG = currentLabel?.cost ?? heap.g;
      if (!lengthFrontier && curG !== best[curId]) continue;
      this.expanded++;
      if (this.attachmentResult && curG + this.heuristic(this.point(curId)) >= this.attachmentResult.score) {
        this.finish(this.attachmentResult.path);
        return;
      }
      const endPath = this.alternateAttachments ? this.goalPaths.get(curId) : curId === this.goal ? this.endPath : void 0;
      if (endPath) {
        const result = this.pathTo(curId, endPath, currentLabel);
        if (length(result) > maxLength + 1e-8 || !this.scene.pathVisible(result)) {
          if (!this.alternateAttachments && !lengthFrontier) {
            if (this.retryAttachments()) continue;
            this.failed = true;
            if (this.softMemoLease) this.softMemoLease.active = false;
            this.scratchLease?.release();
            this.lengthFrontier?.clear();
            return;
          }
        } else if (this.alternateAttachments) {
          const score = curG + length(endPath) / stepSize;
          if (!this.attachmentResult || score < this.attachmentResult.score)
            this.attachmentResult = { score, path: result };
        } else {
          this.finish(result);
          return;
        }
      }
      const x2 = curId % nx2, y2 = Math.floor(curId / nx2);
      for (const { dx: dx2, dy: dy2, offset, cost, bit, reverse: reverse4 } of this.neighbors) {
        if (x2 + dx2 < 0 || x2 + dx2 >= nx2 || y2 + dy2 < 0 || y2 + dy2 >= ny2) continue;
        const id = curId + offset;
        if (blocked[id]) continue;
        const minimumG = curG + cost + 0 + (history?.[id] ?? 0);
        if (!lengthFrontier && penalty >= 0 && minimumG >= best[id] - 1e-10)
          continue;
        const goalDx = hx2[x2 + dx2], goalDy = hy2[y2 + dy2];
        const heuristic = Math.max(goalDx, goalDy) + (Math.SQRT2 - 1) * Math.min(goalDx, goalDy);
        const travelled = (currentLabel?.travelled ?? travel?.[curId] ?? 0) + cost * stepSize;
        if (travel && travelled + heuristic * stepSize > maxLength + 1e-8)
          continue;
        if (lengthFrontier && penalty >= 0 && lengthFrontier.dominated(id, minimumG, travelled))
          continue;
        const px2 = xs[x2 + dx2], py2 = ys[y2 + dy2];
        if (px2 < minX || px2 > maxX || py2 < minY || py2 > maxY) continue;
        let softCost = 0;
        if (hasSoftCopper) {
          if (!(softEdgeKnown[curId] & bit)) {
            softEdgeKnown[curId] |= bit;
            softEdgeKnown[id] |= reverse4;
            if (!this.edgeClear(xs[x2], ys[y2], px2, py2, softBuckets, softMargin)) {
              softEdgeBlocked[curId] |= bit;
              softEdgeBlocked[id] |= reverse4;
            }
          }
          softCost = softEdgeBlocked[curId] & bit ? penalty : 0;
        }
        const g2 = curG + cost + softCost + (history?.[id] ?? 0);
        if (lengthFrontier ? lengthFrontier.dominated(id, g2, travelled) : g2 >= best[id] - 1e-10)
          continue;
        if (!(hardEdgeKnown[curId] & bit)) {
          hardEdgeKnown[curId] |= bit;
          hardEdgeKnown[id] |= reverse4;
          if (!this.edgeClear(xs[x2], ys[y2], px2, py2, copperBuckets)) {
            hardEdgeBlocked[curId] |= bit;
            hardEdgeBlocked[id] |= reverse4;
          }
        }
        if (hardEdgeBlocked[curId] & bit) continue;
        if (lengthFrontier)
          lengthFrontier.add(id, g2, travelled, heuristic, currentLabel);
        else {
          best[id] = g2;
          if (travel) travel[id] = travelled;
          parent[id] = curId;
          heap.push(id, g2, g2 + heuristic);
        }
      }
    }
  }
};

// lib/coupled-pair-routing.ts
function offsetPath(path, offset) {
  const normals = path.slice(1).map((b2, i2) => {
    const a2 = path[i2], d2 = distance(a2, b2);
    return { x: -(b2.y - a2.y) / d2, y: (b2.x - a2.x) / d2 };
  });
  return path.map((p2, i2) => {
    const a2 = normals[Math.max(0, i2 - 1)], b2 = normals[Math.min(normals.length - 1, i2)];
    const denominator = 1 + a2.x * b2.x + a2.y * b2.y;
    if (denominator < 1e-5) throw Error("Pair centerline reverses direction");
    return {
      x: p2.x + offset * (a2.x + b2.x) / denominator,
      y: p2.y + offset * (a2.y + b2.y) / denominator
    };
  });
}
function* routeCoupledPair(input, pair, fixed, negotiation) {
  const members = pair.connectionNames.map(
    (n2) => input.connections.find((c2) => c2.name === n2)
  );
  if (members.some((c2) => !c2 || c2.pointsToConnect.length !== 2))
    throw Error("Pair requires two two-terminal connections");
  const widths = members.map(
    (c2) => (input.buses ?? []).find((b2) => b2.connectionNames.includes(c2.name))?.traceWidth ?? c2.nominalTraceWidth ?? c2.width ?? input.minTraceWidth
  );
  if (Math.abs(widths[0] - widths[1]) > 1e-8)
    throw Error("Coupled pair requires equal trace widths");
  const width = widths[0], gap = pair.traceGap ?? input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const fixedLengths = members.map(
    (member) => fixedRouteLength(input, member.name)
  );
  const inside = (point, polygon) => {
    let inside2 = false;
    for (let i2 = 0, j2 = polygon.length - 1; i2 < polygon.length; j2 = i2++) {
      const a2 = polygon[i2], b2 = polygon[j2];
      if (a2.y > point.y !== b2.y > point.y && point.x < (b2.x - a2.x) * (point.y - a2.y) / (b2.y - a2.y) + a2.x)
        inside2 = !inside2;
    }
    return inside2;
  };
  const layer = members[0].pointsToConnect[0].layer;
  if (members.some((c2) => c2.pointsToConnect.some((p2) => p2.layer !== layer)))
    throw Error("Pair requires a common signal layer");
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  if (gap < clearance - 1e-8) throw Error("Pair gap is below trace clearance");
  const centers = [0, 1].map((i2) => ({
    x: (members[0].pointsToConnect[i2].x + members[1].pointsToConnect[i2].x) / 2,
    y: (members[0].pointsToConnect[i2].y + members[1].pointsToConnect[i2].y) / 2
  }));
  const vertical = Math.abs(centers[1].y - centers[0].y) >= Math.abs(centers[1].x - centers[0].x);
  const axis = vertical ? "y" : "x", crossAxis = vertical ? "x" : "y";
  const sign = Math.sign(centers[1][axis] - centers[0][axis]) || 1;
  const originalPads = members.map(
    (c2) => (input.obstacles ?? []).filter(
      (o2) => o2.componentId && o2.connectedTo.includes(c2.name)
    )
  );
  const pairInBus = (input.buses ?? []).some(
    (b2) => pair.connectionNames.some((n2) => b2.connectionNames.includes(n2))
  );
  const handoffChoices = centers.map((p2, i2) => {
    const pads = originalPads.flat().filter(
      (o2) => Math.abs(o2.center[axis] - p2[axis]) < Math.abs(centers[1][axis] - centers[0][axis]) / 2
    );
    const ids = new Set(pads.map((o2) => o2.componentId));
    const field = input.obstacles.filter(
      (o2) => o2.componentId && ids.has(o2.componentId)
    );
    const s2 = i2 === 0 ? sign : -sign;
    const edge = field.length ? s2 > 0 ? Math.max(
      ...field.map(
        (o2) => o2.center[axis] + (vertical ? o2.height : o2.width) / 2
      )
    ) : Math.min(
      ...field.map(
        (o2) => o2.center[axis] - (vertical ? o2.height : o2.width) / 2
      )
    ) : p2[axis];
    const margin = 2 * width + gap + clearance;
    const front = { ...p2, [axis]: edge + s2 * margin };
    if (!field.length) return [front];
    const left = Math.min(...field.map((o2) => o2.center.x - o2.width / 2)) - margin;
    const right = Math.max(...field.map((o2) => o2.center.x + o2.width / 2)) + margin;
    const bottom = Math.min(...field.map((o2) => o2.center.y - o2.height / 2)) - margin;
    const top = Math.max(...field.map((o2) => o2.center.y + o2.height / 2)) + margin;
    const openFront = pairInBus ? front : i2 === 0 ? {
      ...front,
      [axis]: front[axis] + s2 * Math.max(
        4 * width,
        distance(
          members[0].pointsToConnect[i2],
          members[1].pointsToConnect[i2]
        )
      )
    } : {
      ...front,
      [crossAxis]: vertical ? (left + right) / 2 : (top + bottom) / 2
    };
    return [
      openFront,
      front,
      { x: left, y: p2.y },
      { x: right, y: p2.y },
      { x: p2.x, y: bottom },
      { x: p2.x, y: top }
    ];
  });
  const sharingBuses = (input.buses ?? []).filter(
    (bus) => input.connections.some(
      (c2) => bus.connectionNames.includes(c2.name) && c2.pointsToConnect[0].layer === layer
    )
  );
  if (!pairInBus && sharingBuses.length) {
    const field = input.obstacles.filter((o2) => o2.componentId);
    if (field.length) {
      const reserve = Math.max(...sharingBuses.map((bus) => bus.connectionNames.length)) * (width + clearance);
      const extent = (o2) => {
        const angle = (o2.ccwRotationDegrees ?? 0) * Math.PI / 180;
        return (vertical ? Math.abs(Math.cos(angle)) * o2.width + Math.abs(Math.sin(angle)) * o2.height : Math.abs(Math.sin(angle)) * o2.width + Math.abs(Math.cos(angle)) * o2.height) / 2;
      };
      const low = Math.min(...field.map((o2) => o2.center[crossAxis] - extent(o2))) - reserve - width - gap - clearance;
      const high = Math.max(...field.map((o2) => o2.center[crossAxis] + extent(o2))) + reserve + width + gap + clearance;
      for (let end = 0; end < 2; end++)
        handoffChoices[end].push(
          { ...centers[end], [crossAxis]: low },
          { ...centers[end], [crossAxis]: high }
        );
    }
  }
  const busNames = new Set(
    (input.buses ?? []).filter(
      (b2) => pair.connectionNames.some((n2) => b2.connectionNames.includes(n2))
    ).flatMap((b2) => b2.connectionNames)
  );
  const busMembers = input.connections.filter((c2) => busNames.has(c2.name));
  if (busMembers.length > 2 && originalPads.some((p2) => p2.length)) {
    const reserve = busMembers.length * (width + clearance);
    const crossDelta = centers[1][crossAxis] - centers[0][crossAxis];
    const side = Math.abs(crossDelta) < 1e-8 ? sign : Math.sign(crossDelta);
    const positions = busMembers.flatMap(
      (c2) => c2.pointsToConnect.map((p2) => p2[crossAxis])
    );
    const outer = (side > 0 ? Math.max(...positions) : Math.min(...positions)) + side * (reserve + 2 * width + gap + clearance);
    for (let end = 0; end < 2; end++) {
      const front = handoffChoices[end][0];
      handoffChoices[end].unshift({
        ...handoffChoices[end][0],
        [axis]: handoffChoices[end][0][axis] + (end === 0 ? sign : -sign) * reserve,
        [crossAxis]: outer
      });
      if (end === 0)
        handoffChoices[end].unshift({
          ...front,
          [axis]: front[axis] + sign * reserve / 2
        });
    }
  }
  for (let end = 0; end < 2; end++) {
    handoffChoices[end] = handoffChoices[end].filter(
      (point, index2, choices) => choices.findIndex((other) => distance(point, other) < 1e-8) === index2
    );
    const cost = (point) => 2 * distance(point, centers[end]) + distance(point, centers[1 - end]);
    handoffChoices[end].sort((a2, b2) => cost(a2) - cost(b2));
  }
  const variant = negotiation?.variant ?? 0;
  const sourceOffset = variant % handoffChoices[0].length;
  const offsets = negotiation?.handoffOffsets ?? [
    sourceOffset,
    sourceOffset + Math.floor(variant / handoffChoices[0].length)
  ];
  for (let end = 0; end < 2; end++) {
    const offset = offsets[end] % handoffChoices[end].length;
    handoffChoices[end] = [
      ...handoffChoices[end].slice(offset),
      ...handoffChoices[end].slice(0, offset)
    ];
  }
  const names = new Set(
    members.flatMap((c2) => [c2.name, c2.source_trace_id ?? c2.name])
  );
  const corridorCopper = fixed.filter(
    (c2) => !c2.owners.some((n2) => names.has(n2))
  );
  const envelope = 2 * width + gap;
  const makeTrace = (c2, points, keepVertices = false) => ({
    type: "pcb_trace",
    pcb_trace_id: `bus_lane_${c2.name}`,
    connection_name: c2.name,
    source_trace_id: c2.source_trace_id ?? c2.name,
    route: (keepVertices ? points : simplify(points)).map((p2) => ({
      ...p2,
      route_type: "wire",
      layer,
      width
    }))
  });
  let best = null, bestScore = Infinity, viable = 0;
  const reachability = /* @__PURE__ */ new Map();
  const fine = originalPads.some((pads) => pads.length > 0);
  const approachChoices = (fine ? [width / 2, width / 10] : [void 0]).flatMap(
    (approachStep) => handoffChoices[0].map((point) => ({ point, approachStep }))
  );
  const cached = negotiation && !negotiation.copper.length && !negotiation.penalty && !negotiation.history ? coupledPairCache(input, fixed) : void 0;
  for (const { point: first, approachStep } of approachChoices)
    for (const second of handoffChoices[1])
      candidates: for (const shift of [0, -1, 1, -2, 2]) {
        const ends = [first, second].map((p2) => ({
          ...p2,
          [crossAxis]: p2[crossAxis] + shift * envelope
        }));
        const key = JSON.stringify([
          pair,
          layer,
          width,
          gap,
          approachStep,
          ends
        ]);
        const remembered = cached?.get(key);
        if (remembered) {
          if (remembered.traces && remembered.score < bestScore) {
            bestScore = remembered.score;
            best = remembered.traces;
          }
          if (remembered.hasMatchedAlternative) return best;
          if (remembered.countsAttempt && best && ++viable >= 4) return best;
          continue;
        }
        let handoffBest = null, handoffScore = Infinity;
        const virtual = {
          name: "pair_corridor",
          pointsToConnect: ends.map((p2) => ({ ...p2, layer }))
        };
        const scene = new VectorScene(input, virtual, envelope, corridorCopper);
        const visibleScene = negotiation ? new VectorScene(input, virtual, envelope, [
          ...corridorCopper,
          ...negotiation.copper
        ]) : scene;
        const direct = connectors(ends[0], ends[1]).find(
          (p2) => visibleScene.pathVisible(p2)
        );
        const centerSearch = direct ? {
          solved: true,
          failed: false,
          expanded: 0,
          result: direct,
          step() {
          }
        } : fine || input.connections.length > 12 ? new GridVisibilitySearch(
          scene,
          ends[0],
          ends[1],
          negotiation?.copper,
          negotiation?.penalty,
          negotiation?.history
        ) : new VectorVisibilitySearch(scene, ends[0], ends[1]);
        try {
          while (!centerSearch.solved && !centerSearch.failed && centerSearch.expanded < (centerSearch instanceof GridVisibilitySearch ? 5e5 : 1e3)) {
            centerSearch.step();
            yield;
          }
        } finally {
          if (centerSearch instanceof GridVisibilitySearch)
            centerSearch.cancel();
        }
        if (!centerSearch.solved) {
          cached?.set(key, {
            traces: null,
            score: Infinity,
            hasMatchedAlternative: false,
            countsAttempt: false
          });
          continue;
        }
        const centerPath = reduceOrdinaryTurns(
          centerSearch.result,
          visibleScene
        );
        if (centerPath.length < 2 || centerPath.some((point, i2) => {
          if (!i2) return false;
          const previous = centerPath[i2 - 1], span = distance(previous, point);
          if (span < 1e-8) return true;
          if (i2 < 2) return false;
          const before = centerPath[i2 - 2], oldSpan = distance(before, previous);
          const dot2 = ((previous.x - before.x) * (point.x - previous.x) + (previous.y - before.y) * (point.y - previous.y)) / (oldSpan * span);
          return 1 + dot2 < 1e-5;
        })) {
          cached?.set(key, {
            traces: null,
            score: Infinity,
            hasMatchedAlternative: false,
            countsAttempt: false
          });
          continue;
        }
        const rails = [
          offsetPath(centerPath, (width + gap) / 2),
          offsetPath(centerPath, -(width + gap) / 2)
        ];
        const flips = [false, true].sort((a2, b2) => {
          const cost = (flip) => members.reduce((sum, c2, i2) => {
            const rail = rails[flip ? 1 - i2 : i2];
            return sum + distance(c2.pointsToConnect[0], rail[0]) + distance(c2.pointsToConnect[1], rail.at(-1));
          }, 0);
          return cost(a2) - cost(b2);
        });
        for (const flip of flips) {
          const ordered = flip ? rails.toReversed() : rails;
          const main = members.map((c2, i2) => makeTrace(c2, ordered[i2]));
          for (const escapeOrders of [
            [
              [0, 1],
              [0, 1]
            ],
            [
              [0, 1],
              [1, 0]
            ],
            [
              [1, 0],
              [0, 1]
            ],
            [
              [1, 0],
              [1, 0]
            ]
          ]) {
            const escapes = [[], []];
            let failed = false;
            for (let end = 0; end < 2; end++)
              for (const i2 of escapeOrders[end]) {
                const c2 = members[i2], target = ordered[i2][end === 0 ? 0 : ordered[i2].length - 1], source = c2.pointsToConnect[end];
                const escapeInput = input;
                const ownRail = end === 0 ? ordered[i2] : ordered[i2].toReversed();
                let skip = 4 * width;
                const tail = [];
                for (let k2 = 1; k2 < ownRail.length; k2++) {
                  const a2 = ownRail[k2 - 1], b2 = ownRail[k2], d2 = distance(a2, b2);
                  if (skip >= d2) {
                    skip -= d2;
                    continue;
                  }
                  tail.push({
                    a: {
                      x: a2.x + (b2.x - a2.x) * skip / d2,
                      y: a2.y + (b2.y - a2.y) * skip / d2
                    },
                    b: b2,
                    radius: width / 2,
                    layer,
                    owners: ["reserved_pair_tail"]
                  });
                  skip = 0;
                }
                const escapeScene = new VectorScene(escapeInput, c2, width, [
                  ...fixed,
                  ...tail,
                  ...main.flatMap(routeCopper),
                  ...escapes.flat().flatMap(routeCopper)
                ]);
                const visibleEscapeScene = negotiation ? new VectorScene(escapeInput, c2, width, [
                  ...fixed,
                  ...tail,
                  ...main.flatMap(routeCopper),
                  ...escapes.flat().flatMap(routeCopper),
                  ...negotiation.copper
                ]) : escapeScene;
                const directEscape = connectors(source, target).find(
                  (p2) => visibleEscapeScene.pathVisible(p2)
                );
                const padding = 30 * width;
                const localBounds = {
                  minX: Math.max(
                    input.bounds.minX,
                    Math.min(source.x, target.x) - padding
                  ),
                  maxX: Math.min(
                    input.bounds.maxX,
                    Math.max(source.x, target.x) + padding
                  ),
                  minY: Math.max(
                    input.bounds.minY,
                    Math.min(source.y, target.y) - padding
                  ),
                  maxY: Math.min(
                    input.bounds.maxY,
                    Math.max(source.y, target.y) + padding
                  )
                };
                const search = directEscape ? {
                  solved: true,
                  failed: false,
                  expanded: 0,
                  result: directEscape,
                  step() {
                  }
                } : new GridVisibilitySearch(
                  escapeScene,
                  source,
                  target,
                  negotiation?.copper,
                  negotiation?.penalty,
                  fine ? void 0 : negotiation?.history,
                  fine ? { step: approachStep, bounds: localBounds } : void 0
                );
                try {
                  while (!search.solved && !search.failed && search.expanded < 5e5) {
                    search.step();
                    yield;
                  }
                } finally {
                  if (search instanceof GridVisibilitySearch) search.cancel();
                }
                if (!search.solved) {
                  failed = true;
                  break;
                }
                escapes[i2][end] = makeTrace(
                  c2,
                  reduceOrdinaryTurns(search.result, visibleEscapeScene)
                );
              }
            if (failed) continue;
            let traces = extendCoupledSectionEnds(
              members.map((c2, i2) => ({
                ...makeTrace(
                  c2,
                  [
                    ...escapes[i2][0].route,
                    ...ordered[i2].slice(1),
                    ...escapes[i2][1].route.toReversed().slice(1)
                  ],
                  true
                ),
                coupledSection: [
                  escapes[i2][0].route.length - 1,
                  escapes[i2][0].route.length + ordered[i2].length - 2
                ]
              }))
            );
            if (!traces.every(
              (t48, i2) => new VectorScene(input, members[i2], width, [
                ...fixed,
                ...traces.flatMap(routeCopper)
              ]).pathVisible(t48.route)
            ))
              continue;
            const pairInput = {
              ...input,
              connections: members,
              buses: [],
              differentialPairs: [pair]
            };
            let finished;
            for (const trim of [1.5, 0.75, 0.375, 0.1875]) {
              const shaped = chamferOrdinaryCorners(
                pairInput,
                traces,
                fixed,
                trim
              );
              if (!routeAnglesAreConventional(shaped) || sharedPairSpacingReports(pairInput, shaped).some(
                (p2) => !p2.matched
              ))
                continue;
              if (shaped.some(
                (trace) => length(trace.route) > maximumCarrierLength(input, trace.connection_name) + 1e-7
              ))
                continue;
              try {
                let tuned = tuneSmoothLengths(
                  pairInput,
                  shaped,
                  minimumLengthTargets(pairInput, shaped),
                  { maxCandidates: 512 }
                );
                const regions = packageApproachRegions(
                  pairInput,
                  width + gap / 2 + clearance
                );
                const dogboneCounts = /* @__PURE__ */ new Map();
                for (const t48 of pairInput.traces ?? [])
                  dogboneCounts.set(
                    t48.connection_name,
                    (dogboneCounts.get(t48.connection_name) ?? 0) + 1
                  );
                const freshSignalEscapes = (pairInput.traces?.length ?? 0) > 0 && [...dogboneCounts.values()].every((n2) => n2 === 2) && pairInput.traces.every(
                  (t48) => t48.route.filter((p2) => p2.route_type === "via").length === 1
                );
                if (freshSignalEscapes && regions.length && tuned.some(
                  (t48) => t48.curvedSegments?.some(
                    (i2) => !regions.some(
                      (r2) => pointInBox(t48.route[i2 - 1], r2.copper) && pointInBox(t48.route[i2], r2.copper)
                    )
                  )
                )) {
                  tuned = tuneSmoothLengths(
                    pairInput,
                    shaped,
                    minimumLengthTargets(pairInput, shaped),
                    { maxCandidates: 512, packageOnlyPairTuning: true }
                  );
                }
                if (routeAnglesAreConventional(tuned) && sharedPairSpacingReports(pairInput, tuned).every(
                  (p2) => p2.matched
                )) {
                  finished = tuned;
                  break;
                }
              } catch {
              }
            }
            if (!finished) continue;
            traces = finished;
            const polygon = [
              ...traces[0].route,
              ...traces[1].route.toReversed()
            ];
            const enclosed = input.connections.filter(
              (c2) => !pair.connectionNames.includes(c2.name) && c2.pointsToConnect.some(
                (p2) => p2.layer === layer && inside(p2, polygon)
              )
            );
            let trapsTerminal = false;
            const skew = Math.abs(
              length(traces[0].route) + fixedLengths[0] - length(traces[1].route) - fixedLengths[1]
            );
            let candidateScore = negotiation ? skew + 0.05 * traces.reduce((sum, t48) => sum + length(t48.route), 0) : traces.reduce((sum, t48) => sum + length(t48.route), 0);
            const pending = (negotiation ? enclosed : input.connections).filter(
              (c2) => !pair.connectionNames.includes(c2.name) && c2.pointsToConnect[0].layer === layer
            );
            const corridorKey = pending.length ? JSON.stringify(traces.map((trace) => trace.route)) : "";
            for (const other of pending) {
              const key2 = `${other.name}:${corridorKey}`;
              let result = reachability.get(key2);
              if (!result) {
                const otherWidth = (input.buses ?? []).find(
                  (b2) => b2.connectionNames.includes(other.name)
                )?.traceWidth ?? other.nominalTraceWidth ?? other.width ?? input.minTraceWidth;
                const otherScene = new VectorScene(input, other, otherWidth, [
                  ...fixed,
                  ...traces.flatMap(routeCopper)
                ]);
                const attachments = connectors(
                  other.pointsToConnect[0],
                  other.pointsToConnect[1]
                );
                const shortest = length(attachments[0]);
                const direct2 = attachments.find(
                  (path) => length(path) <= shortest + 1e-8 && otherScene.pathVisible(path)
                );
                const check = direct2 ? {
                  solved: true,
                  failed: false,
                  expanded: 0,
                  result: direct2,
                  step() {
                  },
                  cancel() {
                  }
                } : new GridVisibilitySearch(
                  otherScene,
                  other.pointsToConnect[0],
                  other.pointsToConnect[1]
                );
                try {
                  while (!check.solved && !check.failed && check.expanded < 5e5) {
                    check.step();
                    yield;
                  }
                } finally {
                  check.cancel();
                }
                result = {
                  reachable: check.solved,
                  length: check.solved ? length(check.result) : Infinity
                };
                reachability.set(key2, result);
              }
              if (!result.reachable) {
                trapsTerminal = true;
                break;
              }
              candidateScore += negotiation ? 0.05 * Math.max(
                0,
                result.length - length(
                  connectors(
                    other.pointsToConnect[0],
                    other.pointsToConnect[1]
                  )[0]
                )
              ) : result.length;
            }
            if (!trapsTerminal && traces.every(
              (t48) => tuningPathIsSelfClear(t48.route, width + clearance)
            )) {
              if (candidateScore < handoffScore) {
                handoffScore = candidateScore;
                handoffBest = traces;
              }
              if (candidateScore < bestScore) {
                bestScore = candidateScore;
                best = traces;
              }
              if (negotiation && skew <= pair.lengthTolerance) {
                cached?.set(key, {
                  traces: handoffBest,
                  score: handoffScore,
                  hasMatchedAlternative: true,
                  countsAttempt: true
                });
                return best;
              }
              if (!negotiation && ++viable >= 2) return best;
              if (!negotiation) continue candidates;
            }
          }
        }
        cached?.set(key, {
          traces: handoffBest,
          score: handoffScore,
          hasMatchedAlternative: false,
          countsAttempt: true
        });
        if (negotiation && best && ++viable >= 4) return best;
      }
  return best;
}

// lib/backward-facing-package-terminals.ts
function backwardFacingPackageTerminals(input) {
  const fields = /* @__PURE__ */ new Map();
  const pads = input.obstacles.filter((pad) => pad.componentId);
  const physicalPorts = /* @__PURE__ */ new Map();
  for (const pad of pads) {
    const port = pad.circuitJsonMetadata?.pcb_port_id;
    if (port) physicalPorts.set(port, pad.componentId);
    const angle = (pad.ccwRotationDegrees ?? 0) * Math.PI / 180;
    const width = Math.abs(Math.cos(angle)) * pad.width + Math.abs(Math.sin(angle)) * pad.height;
    const height = Math.abs(Math.sin(angle)) * pad.width + Math.abs(Math.cos(angle)) * pad.height;
    const field = fields.get(pad.componentId) ?? {
      left: Infinity,
      right: -Infinity,
      bottom: Infinity,
      top: -Infinity
    };
    field.left = Math.min(field.left, pad.center.x - width / 2);
    field.right = Math.max(field.right, pad.center.x + width / 2);
    field.bottom = Math.min(field.bottom, pad.center.y - height / 2);
    field.top = Math.max(field.top, pad.center.y + height / 2);
    fields.set(pad.componentId, field);
  }
  const centers = new Map(
    [...fields].map(([id, field]) => [
      id,
      { x: (field.left + field.right) / 2, y: (field.bottom + field.top) / 2 }
    ])
  );
  const groups = /* @__PURE__ */ new Map();
  for (const connection of input.connections) {
    if (connection.pointsToConnect.length !== 2) continue;
    const components = connection.pointsToConnect.map((terminal) => {
      const physicalOwner = terminal.pcb_port_id ? physicalPorts.get(terminal.pcb_port_id) : void 0;
      if (physicalOwner) return physicalOwner;
      const owners = new Set(
        [
          connection.name,
          connection.source_trace_id,
          terminal.pointId,
          terminal.pcb_port_id
        ].filter((owner) => !!owner)
      );
      return pads.filter((pad) => pad.connectedTo.some((owner) => owners.has(owner))).sort(
        (a2, b2) => distance(terminal, a2.center) - distance(terminal, b2.center)
      )[0]?.componentId;
    });
    for (const [index2, source] of components.entries()) {
      const remote = components[1 - index2];
      if (!source || !remote || source === remote) continue;
      const key = JSON.stringify([source, remote]);
      const group = groups.get(key) ?? { source, remote, points: [] };
      group.points.push(connection.pointsToConnect[index2]);
      groups.set(key, group);
    }
  }
  return [...groups.values()].some((group) => {
    const center = centers.get(group.source), remote = centers.get(group.remote);
    const centroid = {
      x: group.points.reduce((sum, point) => sum + point.x, 0) / group.points.length,
      y: group.points.reduce((sum, point) => sum + point.y, 0) / group.points.length
    };
    return (centroid.x - center.x) * (remote.x - center.x) + (centroid.y - center.y) * (remote.y - center.y) < -1e-9;
  });
}

// lib/repair-grid-jogs.ts
function* repairGridJogs(input, traces, fixed) {
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  for (const trace of traces) {
    const width = trace.route[0].width;
    if (tuningPathIsSelfClear(trace.route, width + clearance)) continue;
    if (trace.coupledSection) return false;
    const connection = input.connections.find(
      (c2) => c2.name === trace.connection_name
    );
    const scene = new VectorScene(input, connection, width, [
      ...fixed,
      ...traces.flatMap(routeCopper)
    ]);
    const margin = width * 10;
    const bounds = {
      minX: Math.max(
        input.bounds.minX,
        Math.min(...trace.route.map((p2) => p2.x)) - margin
      ),
      maxX: Math.min(
        input.bounds.maxX,
        Math.max(...trace.route.map((p2) => p2.x)) + margin
      ),
      minY: Math.max(
        input.bounds.minY,
        Math.min(...trace.route.map((p2) => p2.y)) - margin
      ),
      maxY: Math.min(
        input.bounds.maxY,
        Math.max(...trace.route.map((p2) => p2.y)) + margin
      )
    };
    let repaired = false;
    for (const step of [width / 4, width / 5]) {
      for (const reverse4 of [false, true]) {
        const ends = reverse4 ? connection.pointsToConnect.toReversed() : connection.pointsToConnect;
        const search = new GridVisibilitySearch(
          scene,
          ends[0],
          ends[1],
          [],
          0,
          void 0,
          { step, bounds }
        );
        try {
          while (!search.failed && !search.solved) {
            search.step();
            yield;
          }
          if (!search.solved) continue;
          const path = reduceOrdinaryTurns(
            reverse4 ? search.result.toReversed() : search.result,
            scene
          );
          if (!tuningPathIsSelfClear(path, width + clearance)) continue;
          trace.route = path.map((p2) => ({
            ...p2,
            route_type: "wire",
            layer: connection.pointsToConnect[0].layer,
            width
          }));
          repaired = true;
          break;
        } finally {
          search.cancel();
        }
      }
      if (repaired) break;
    }
    if (!repaired) return false;
  }
  return true;
}

// lib/refine-route-candidates.ts
function* refineRouteCandidates(input, fixed, widths, candidates, units, matchingGroups, terminalLayers) {
  const seen = /* @__PURE__ */ new Map();
  let steps = 0;
  for (let round = 0; round < 24 && steps < 2e4; round++) {
    const result = candidates.select(units, matchingGroups);
    if (result) return result;
    const core = candidates.unresolvedUnits(units);
    if (!core?.length) return null;
    const key = core.join("\0"), visit = seen.get(key) ?? 0;
    seen.set(key, visit + 1);
    let added = 0;
    for (const name of [...core].sort(
      (a2, b2) => Number(
        input.differentialPairs?.some((p2) => p2.connectionNames.includes(a2))
      ) - Number(
        input.differentialPairs?.some((p2) => p2.connectionNames.includes(b2))
      )
    )) {
      const pair = input.differentialPairs?.find(
        (p2) => p2.connectionNames.includes(name)
      );
      if (pair) {
        if (added || visit < 1) continue;
        for (let trial = 0; trial < 4 && steps < 2e4; trial++) {
          const conditional = candidates.conditionalRoutes(
            core.filter((n2) => n2 !== name),
            trial === 0 ? -1 : visit * 4 + trial,
            trial % 2 === 0 ? units.filter((n2) => n2 !== name) : []
          );
          if (!conditional) continue;
          const generator = routeCoupledPair(
            input,
            pair,
            [...fixed, ...conditional.flatMap(routeCopper)],
            { copper: [], penalty: 0, variant: visit }
          );
          let step = generator.next(), localSteps = 0;
          try {
            while (!step.done && steps < 2e4 && localSteps < 2e3) {
              steps++;
              localSteps++;
              yield;
              step = generator.next();
            }
          } finally {
            if (!step.done) generator.return(null);
          }
          if (step.done && step.value) {
            const before = candidates.revisionNumber;
            candidates.add(name, step.value);
            added += Number(candidates.revisionNumber !== before);
          }
        }
        continue;
      }
      const original = input.connections.find((c2) => c2.name === name);
      const bus = input.buses?.some((b2) => b2.connectionNames.includes(name));
      const layers = bus ? [original.pointsToConnect[0].layer] : terminalLayers.get(name) ?? [original.pointsToConnect[0].layer];
      const others = core.filter((n2) => n2 !== name);
      for (let trial = 0; trial < 12 && steps < 2e4; trial++) {
        const conditional = candidates.conditionalRoutes(
          others,
          trial === 0 ? -1 : visit * 12 + trial,
          trial % 2 === 0 ? units.filter((n2) => n2 !== name) : []
        );
        if (!conditional) continue;
        for (const layer of layers) {
          const connection = {
            ...original,
            pointsToConnect: original.pointsToConnect.map((p2) => ({
              ...p2,
              layer
            }))
          }, width = widths.get(name) ?? input.minTraceWidth;
          const scene = new VectorScene(input, connection, width, [
            ...fixed,
            ...conditional.flatMap(routeCopper)
          ]);
          const search = new GridVisibilitySearch(
            scene,
            connection.pointsToConnect[0],
            connection.pointsToConnect[1]
          );
          try {
            while (!search.solved && !search.failed && search.expanded < 5e5 && steps < 2e4) {
              search.step();
              steps++;
              yield;
            }
          } finally {
            search.cancel();
          }
          if (!search.solved) continue;
          const points = reduceOrdinaryTurns(search.result, scene);
          if (!tuningPathIsSelfClear(points, width / 2 + scene.margin)) continue;
          const before = candidates.revisionNumber;
          candidates.add(name, [
            {
              type: "pcb_trace",
              pcb_trace_id: `bus_lane_${name}`,
              connection_name: name,
              source_trace_id: original.source_trace_id ?? name,
              route: points.map((p2) => ({
                ...p2,
                route_type: "wire",
                layer,
                width
              }))
            }
          ]);
          added += Number(candidates.revisionNumber !== before);
        }
      }
    }
    if (!added && visit > 5) return null;
  }
  return candidates.select(units, matchingGroups);
}

// lib/route-via-waypoint.ts
function* routeViaWaypoint(scene, waypoint, soft, penalty, history, maxLength) {
  const [start, end] = scene.connection.pointsToConnect;
  const first = new GridVisibilitySearch(
    scene,
    start,
    waypoint,
    soft,
    penalty,
    history,
    { maxLength: maxLength - distance(waypoint, end) }
  );
  try {
    while (!first.solved && !first.failed) {
      first.step();
      yield;
    }
  } finally {
    first.cancel();
  }
  if (!first.solved) return null;
  const firstPath = reduceOrdinaryTurns(first.result, scene);
  const prefix = [];
  let remaining = length(firstPath) - scene.width - scene.margin - 1e-7;
  for (let i2 = 1; i2 < firstPath.length && remaining > 0; i2++) {
    const a2 = firstPath[i2 - 1], b2 = firstPath[i2], span = distance(a2, b2), fraction = Math.min(1, remaining / span);
    prefix.push({
      a: a2,
      b: { x: a2.x + (b2.x - a2.x) * fraction, y: a2.y + (b2.y - a2.y) * fraction },
      radius: scene.width / 2,
      layer: start.layer,
      owners: ["waypoint_prefix"]
    });
    remaining -= span;
  }
  const secondScene = new VectorScene(
    scene.input,
    scene.connection,
    scene.width,
    [...scene.copper, ...prefix]
  );
  const second = new GridVisibilitySearch(
    secondScene,
    waypoint,
    end,
    soft,
    penalty,
    history,
    { maxLength: maxLength - length(firstPath) }
  );
  try {
    while (!second.solved && !second.failed) {
      second.step();
      yield;
    }
  } finally {
    second.cancel();
  }
  if (!second.solved) return null;
  const secondPath = reduceOrdinaryTurns(second.result, secondScene);
  const path = simplify([...firstPath, ...secondPath.slice(1)]);
  if (length(path) > maxLength + 1e-8 || !tuningPathIsSelfClear(path, scene.width / 2 + scene.margin))
    return null;
  return path;
}

// lib/pending-lane-certificates.ts
var certificates = /* @__PURE__ */ new WeakMap();
function* pendingLaneCertificates(input, connections, fixed, widths) {
  const key = JSON.stringify([
    input.bounds,
    input.layerCount,
    input.minTraceWidth,
    input.obstacles,
    input.traces,
    input.connections.map((c2) => c2.pointsToConnect),
    input.minBoardEdgeClearance,
    input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075,
    fixed,
    connections.map((c2) => [
      c2.name,
      c2.source_trace_id,
      c2.pointsToConnect,
      widths.get(c2.name)
    ])
  ]);
  const cache = certificates.get(input) ?? /* @__PURE__ */ new Map();
  certificates.set(input, cache);
  const cached = cache.get(key);
  if (cached) return structuredClone(cached);
  const result = [];
  for (const connection of connections) {
    const width = widths.get(connection.name);
    const search = new GridVisibilitySearch(
      new VectorScene(input, connection, width, fixed),
      connection.pointsToConnect[0],
      connection.pointsToConnect[1]
    );
    try {
      while (!search.solved && !search.failed) {
        search.step();
        yield;
      }
      if (search.solved)
        result.push({
          type: "pcb_trace",
          pcb_trace_id: `certificate_${connection.name}`,
          connection_name: connection.name,
          route: search.result.map((point) => ({
            ...point,
            route_type: "wire",
            layer: connection.pointsToConnect[0].layer,
            width
          }))
        });
    } finally {
      if (!search.solved && !search.failed) search.cancel();
    }
  }
  if (cache.size >= 8) cache.delete(cache.keys().next().value);
  cache.set(key, structuredClone(result));
  return result;
}

// lib/route-conflict-index.ts
var RouteConflictIndex = class {
  geometry = /* @__PURE__ */ new WeakMap();
  conflicts = /* @__PURE__ */ new WeakMap();
  getGeometry(route) {
    const cached = this.geometry.get(route);
    if (cached) return cached;
    const edges = [];
    const bounds = new Float64Array(Math.max(0, route.length - 1) * 4);
    let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
    for (let i2 = 1; i2 < route.length; i2++) {
      const a2 = route[i2 - 1], b2 = route[i2], offset = (i2 - 1) * 4;
      edges.push([a2, b2]);
      bounds[offset] = Math.min(a2.x, b2.x);
      bounds[offset + 1] = Math.max(a2.x, b2.x);
      bounds[offset + 2] = Math.min(a2.y, b2.y);
      bounds[offset + 3] = Math.max(a2.y, b2.y);
      minX = Math.min(minX, bounds[offset]);
      maxX = Math.max(maxX, bounds[offset + 1]);
      minY = Math.min(minY, bounds[offset + 2]);
      maxY = Math.max(maxY, bounds[offset + 3]);
    }
    const result = { edges, bounds, minX, maxX, minY, maxY };
    this.geometry.set(route, result);
    return result;
  }
  firstConflict(first, second, required) {
    let row = this.conflicts.get(first);
    const cached = row?.get(second);
    if (cached?.required === required) return cached.result;
    if (!row) {
      row = /* @__PURE__ */ new WeakMap();
      this.conflicts.set(first, row);
    }
    const a2 = this.getGeometry(first), b2 = this.getGeometry(second);
    let result = null;
    if (a2.maxX + required >= b2.minX && b2.maxX + required >= a2.minX && a2.maxY + required >= b2.minY && b2.maxY + required >= a2.minY) {
      conflict: for (let i2 = 0; i2 < a2.edges.length; i2++) {
        const ai = i2 * 4;
        for (let j2 = 0; j2 < b2.edges.length; j2++) {
          const bj = j2 * 4;
          if (a2.bounds[ai + 1] + required < b2.bounds[bj] || b2.bounds[bj + 1] + required < a2.bounds[ai] || a2.bounds[ai + 3] + required < b2.bounds[bj + 2] || b2.bounds[bj + 3] + required < a2.bounds[ai + 2])
            continue;
          if (segmentDistance(a2.edges[i2], b2.edges[j2]) < required) {
            result = [i2 + 1, j2 + 1];
            break conflict;
          }
        }
      }
    }
    row.set(second, { required, result });
    return result;
  }
};

// lib/select-route-candidates.ts
var CandidateConflicts = class {
  bits = new Uint8Array(0);
  sparse = /* @__PURE__ */ new Map();
  get(id) {
    if (id >= 4096) return this.sparse.get(id);
    const value = this.bits[id];
    return value ? value === 2 : void 0;
  }
  set(id, value) {
    if (id >= 4096) {
      this.sparse.set(id, value);
      return;
    }
    if (id >= this.bits.length) {
      const next = new Uint8Array(
        Math.max(16, 2 ** Math.ceil(Math.log2(id + 1)))
      );
      next.set(this.bits);
      this.bits = next;
    }
    this.bits[id] = value ? 2 : 1;
  }
  keys() {
    return this.sparse.keys();
  }
  delete(id) {
    this.sparse.delete(id);
  }
};
var RouteCandidatePool = class {
  constructor(clearance, limit = 120) {
    this.clearance = clearance;
    this.limit = limit;
  }
  clearance;
  limit;
  pools = /* @__PURE__ */ new Map();
  nextId = 0;
  additions = 0;
  assignments = /* @__PURE__ */ new Map();
  routeConflicts = new RouteConflictIndex();
  signatures = /* @__PURE__ */ new Map();
  routeSignatures = /* @__PURE__ */ new WeakMap();
  revision = 0;
  selection;
  add(unit, traces) {
    const pool = this.pools.get(unit) ?? [];
    let signatures = this.signatures.get(unit);
    if (!signatures) {
      signatures = /* @__PURE__ */ new Set();
      this.signatures.set(unit, signatures);
    }
    const signature = `[${traces.map((trace) => {
      let value = this.routeSignatures.get(trace.route);
      if (value === void 0) {
        value = JSON.stringify(trace.route);
        this.routeSignatures.set(trace.route, value);
      }
      return value;
    }).join(",")}]`;
    if (signatures.has(signature)) return;
    const lengths = traces.map((trace) => length(trace.route));
    const candidate = {
      traces,
      key: signature,
      length: lengths.reduce((sum, value) => sum + value, 0),
      peak: Math.max(...lengths),
      layers: [...new Set(traces.map((t48) => t48.route[0].layer))],
      singleLayer: traces.every(
        (t48) => t48.route[0].layer === traces[0].route[0].layer
      ) ? traces[0].route[0].layer : void 0,
      conflicts: new CandidateConflicts(),
      id: this.nextId++
    };
    pool.push(candidate);
    signatures.add(signature);
    if (pool.length > this.limit) signatures.delete(pool.shift().key);
    this.pools.set(unit, pool);
    this.additions++;
    this.revision++;
  }
  transformUnit(unit, transform2) {
    const alternatives = this.pools.get(unit) ?? [];
    this.pools.delete(unit);
    this.signatures.delete(unit);
    this.revision++;
    for (const candidate of alternatives) {
      const traces = transform2(candidate.traces);
      if (traces) this.add(unit, traces);
    }
  }
  hasEveryUnit(units) {
    return units.every((unit) => !!this.pools.get(unit)?.length);
  }
  /** Small unresolved domain set for generating fresh conditional routes.
   * A bounded search failure is a refinement hint, not an impossibility proof. */
  unresolvedUnits(units) {
    if (this.compatible(
      units.map((n2) => this.pools.get(n2) ?? []),
      5e5
    ))
      return null;
    let subset = units.slice();
    for (const unit of units) {
      const remaining = subset.filter((n2) => n2 !== unit);
      if (!this.compatible(
        remaining.map((n2) => this.pools.get(n2) ?? []),
        5e5
      ))
        subset = remaining;
    }
    return subset;
  }
  conditionalRoutes(units, trial, completion = []) {
    if (!units.length) return [];
    const pivot2 = trial % units.length, index2 = Math.floor(trial / units.length);
    const domains = units.map((n2, i2) => {
      const pool = this.pools.get(n2) ?? [];
      return trial < 0 || i2 !== pivot2 || !pool.length ? pool : [pool[index2 % pool.length]];
    });
    let selected = this.compatible(domains, 5e5);
    if (!selected) return null;
    const extended = selected.map((candidate) => [candidate]);
    for (const unit of completion) {
      if (units.includes(unit)) continue;
      const domain = this.pools.get(unit) ?? [];
      const next = this.compatible([...extended, domain]);
      if (!next) continue;
      extended.push(domain);
      selected = next;
    }
    return selected.flatMap((candidate) => candidate.traces);
  }
  get revisionNumber() {
    return this.revision;
  }
  collides(a2, b2) {
    if (a2.singleLayer !== void 0 && b2.singleLayer !== void 0 && a2.singleLayer !== b2.singleLayer)
      return false;
    const low = a2.id < b2.id ? a2 : b2;
    const high = Math.max(a2.id, b2.id);
    const row = low.conflicts;
    const cached = row.get(high);
    if (cached !== void 0) return cached;
    if (!a2.layers.some((layer) => b2.layers.includes(layer))) {
      row.set(high, false);
      return false;
    }
    for (const first of a2.traces)
      for (const second of b2.traces) {
        if (first.route[0].layer !== second.route[0].layer)
          continue;
        const required = (first.route[0].width + second.route[0].width) / 2 + this.clearance - 1e-8;
        if (this.routeConflicts.firstConflict(first.route, second.route, required)) {
          row.set(high, true);
          return true;
        }
      }
    row.set(high, false);
    return false;
  }
  compatible(domains, searchBudget = 5e4) {
    const key = `${searchBudget}:` + domains.map((domain) => domain.map((c2) => c2.id).join(",")).join(";");
    if (this.assignments.has(key)) return this.assignments.get(key);
    const result = this.computeCompatible(domains, searchBudget);
    if (this.assignments.size >= 128)
      this.assignments.delete(this.assignments.keys().next().value);
    this.assignments.set(key, result);
    return result;
  }
  computeCompatible(domains, searchBudget) {
    if (domains.some((domain) => !domain.length)) return null;
    const layers = domains.map(
      (domain) => new Set(domain.flatMap((candidate) => candidate.layers))
    );
    const pending = new Set(domains.map((_2, i2) => i2));
    const components = [];
    while (pending.size) {
      const component = [pending.values().next().value];
      pending.delete(component[0]);
      for (let j2 = 0; j2 < component.length; j2++)
        for (const i2 of pending) {
          if (![...layers[i2]].some((layer) => layers[component[j2]].has(layer)))
            continue;
          pending.delete(i2);
          component.push(i2);
        }
      components.push(component);
    }
    if (components.length > 1) {
      const combined = [];
      for (const component of components) {
        const result = this.compatible(
          component.map((i2) => domains[i2]),
          searchBudget
        );
        if (!result) return null;
        component.forEach((index2, i2) => {
          combined[index2] = result[i2];
        });
      }
      return combined;
    }
    const selected = domains.map(() => void 0);
    const visit = (remaining) => {
      if (--searchBudget < 0) return null;
      let next = -1;
      for (let i2 = 0; i2 < remaining.length; i2++) {
        if (selected[i2]) continue;
        if (!remaining[i2].length) return null;
        if (next < 0 || remaining[i2].length < remaining[next].length) next = i2;
      }
      if (next < 0) return selected;
      for (const candidate of remaining[next]) {
        selected[next] = candidate;
        const filtered = remaining.map(
          (domain, i2) => selected[i2] ? domain : domain.filter((other) => !this.collides(candidate, other))
        );
        const result = visit(filtered);
        if (result) return result.slice();
        selected[next] = void 0;
        if (searchBudget < 0) break;
      }
      return null;
    };
    return visit(
      domains.map((domain) => [...domain].sort((a2, b2) => a2.length - b2.length))
    );
  }
  pruneConflicts() {
    const active = new Set(
      [...this.pools.values()].flat().map((candidate) => candidate.id)
    );
    for (const pool of this.pools.values())
      for (const candidate of pool)
        for (const other of candidate.conflicts.keys())
          if (!active.has(other)) candidate.conflicts.delete(other);
    this.additions = 0;
  }
  select(units, matchingGroups = []) {
    const key = JSON.stringify([units, matchingGroups]);
    if (this.selection?.revision === this.revision && this.selection.key === key)
      return this.selection.result?.slice() ?? null;
    const result = this.computeSelection(units, matchingGroups);
    this.selection = { revision: this.revision, key, result };
    return result?.slice() ?? null;
  }
  computeSelection(units, matchingGroups) {
    if (this.additions >= 100) this.pruneConflicts();
    let domains = units.map((unit) => this.pools.get(unit) ?? []);
    let best = this.compatible(domains);
    if (!best) return null;
    const peak = (candidate) => candidate.peak;
    for (const group of [units, ...matchingGroups]) {
      const indices = new Set(
        group.map((name) => units.indexOf(name)).filter((i2) => i2 >= 0)
      );
      if (!indices.size) continue;
      let ceiling = Math.max(...best.filter((_2, i2) => indices.has(i2)).map(peak));
      const levels = [
        ...new Set(
          domains.flatMap(
            (domain, i2) => indices.has(i2) ? domain.map(peak) : []
          )
        )
      ].filter((n2) => n2 < ceiling).sort((a2, b2) => a2 - b2);
      let lo = 0, hi = levels.length - 1;
      while (lo <= hi) {
        const mid = lo + hi >> 1;
        const choice = this.compatible(
          domains.map(
            (domain, i2) => indices.has(i2) ? domain.filter((c2) => peak(c2) <= levels[mid]) : domain
          )
        );
        if (choice) {
          best = choice;
          ceiling = levels[mid];
          hi = mid - 1;
        } else lo = mid + 1;
      }
      domains = domains.map(
        (domain, i2) => indices.has(i2) ? domain.filter((c2) => peak(c2) <= ceiling) : domain
      );
    }
    return best.flatMap((c2) => c2.traces);
  }
};

// lib/repair-lane-closures.ts
function* permutations(names) {
  if (!names.length) yield [];
  else
    for (let i2 = 0; i2 < names.length; i2++)
      for (const rest of permutations(names.filter((_2, j2) => i2 !== j2)))
        yield [names[i2], ...rest];
}
function* repairOrders(names) {
  if (names.length <= 4) {
    yield* permutations(names);
    return;
  }
  const seen = /* @__PURE__ */ new Set();
  for (const order of permutations(names))
    for (let start = 0; start < order.length; start++) {
      const rotated = [...order.slice(start), ...order.slice(0, start)];
      const key = JSON.stringify(rotated);
      if (seen.has(key)) continue;
      seen.add(key);
      yield rotated;
      if (seen.size === 24) return;
    }
}
function* repairLaneClosures(input, connections, fixed, current, widths, options = {}) {
  const byName = new Map(connections.map((c2) => [c2.name, c2]));
  const width = (name) => widths.get(name) ?? byName.get(name)?.width ?? byName.get(name)?.nominalTraceWidth ?? input.minTraceWidth;
  const valid = (trace) => {
    const c2 = byName.get(trace.connection_name ?? "");
    return !!c2 && c2.pointsToConnect.length === 2 && trace.route.length >= 2 && trace.route.every(
      (p2) => p2.route_type === "wire" && Number.isFinite(p2.x) && Number.isFinite(p2.y) && p2.layer === c2.pointsToConnect[0].layer && Number.isFinite(p2.width) && p2.width > 0 && Math.abs(p2.width - width(c2.name)) < 1e-12
    ) && distance(trace.route[0], c2.pointsToConnect[0]) <= 1e-8 && distance(trace.route.at(-1), c2.pointsToConnect[1]) <= 1e-8;
  };
  if (current.some((t48) => !valid(t48))) return null;
  const paired = new Set(
    (input.differentialPairs ?? []).flatMap((p2) => p2.connectionNames)
  );
  const missing = connections.filter(
    (c2) => !current.some((t48) => t48.connection_name === c2.name)
  );
  if (!missing.length || missing.some(
    (c2) => paired.has(c2.name) || c2.pointsToConnect.length !== 2 || c2.pointsToConnect[0].layer !== c2.pointsToConnect[1].layer
  ))
    return null;
  const groups = /* @__PURE__ */ new Map();
  for (const c2 of missing) {
    const layer = c2.pointsToConnect[0].layer;
    const group = groups.get(layer) ?? [];
    group.push(c2);
    groups.set(layer, group);
  }
  if ([...groups.values()].some((group) => group.length > 2)) return null;
  let working = current.slice();
  const budget = { searches: 0, searchSteps: 0, candidates: 0 };
  for (const layer of groups.keys()) {
    const group = connections.filter(
      (c2) => c2.pointsToConnect[0].layer === layer
    );
    const names = new Set(group.map((c2) => c2.name));
    const other = working.filter((t48) => !names.has(t48.connection_name));
    const repaired = yield* repairLayer(
      input,
      group,
      [...fixed, ...other.flatMap(routeCopper)],
      working.filter((t48) => names.has(t48.connection_name)),
      widths,
      options,
      budget
    );
    if (!repaired) return null;
    working = [...other, ...repaired];
  }
  if (working.length !== connections.length || new Set(working.map((t48) => t48.connection_name)).size !== connections.length)
    return null;
  for (const trace of working) {
    if (!valid(trace)) return null;
    const c2 = byName.get(trace.connection_name);
    const scene = new VectorScene(input, c2, width(c2.name), [
      ...fixed,
      ...working.filter((t48) => t48 !== trace).flatMap(routeCopper)
    ]);
    if (!scene.pathVisible(trace.route) || !(options.deferRetainedSelfClearance && current.some((t48) => t48.route === trace.route)) && !tuningPathIsSelfClear(
      trace.route,
      width(c2.name) + (input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075)
    ))
      return null;
  }
  return working;
}
function* repairLayer(input, connections, fixed, current, widths, options, budget) {
  const maxSubset = Math.min(5, options.maxSubsetSize ?? 4);
  const maxSearches = options.maxSearches ?? 1200;
  const maxSteps = options.maxSearchSteps ?? 18e4;
  const domainLimit = options.maxCandidatesPerLane ?? 80;
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const byName = new Map(connections.map((c2) => [c2.name, c2]));
  const pairedNames = new Set(
    (input.differentialPairs ?? []).flatMap((p2) => p2.connectionNames)
  );
  const ordinary = (c2) => !pairedNames.has(c2.name) && c2.pointsToConnect.length === 2 && c2.pointsToConnect[0].layer === c2.pointsToConnect[1].layer;
  const width = (name) => widths.get(name) ?? byName.get(name)?.width ?? byName.get(name)?.nominalTraceWidth ?? input.minTraceWidth;
  const validCarrier = (trace) => {
    const c2 = byName.get(trace.connection_name ?? "");
    return !!c2 && c2.pointsToConnect.length === 2 && trace.route.length >= 2 && trace.route.every(
      (p2) => p2.route_type === "wire" && Number.isFinite(p2.x) && Number.isFinite(p2.y) && p2.layer === c2.pointsToConnect[0].layer && Number.isFinite(p2.width) && p2.width > 0 && Math.abs(p2.width - width(c2.name)) < 1e-12
    ) && distance(trace.route[0], c2.pointsToConnect[0]) <= 1e-8 && distance(trace.route.at(-1), c2.pointsToConnect[1]) <= 1e-8;
  };
  if (current.some((trace) => !validCarrier(trace))) return null;
  const existingNames = new Set(current.map((t48) => t48.connection_name));
  const missing = connections.filter((c2) => !existingNames.has(c2.name));
  if (!missing.length || missing.length > 2 || missing.length > maxSubset || missing.some((c2) => !ordinary(c2)))
    return null;
  const copperCache = /* @__PURE__ */ new WeakMap();
  const copper = (t48) => {
    let result = copperCache.get(t48);
    if (!result) {
      result = routeCopper(t48);
      copperCache.set(t48, result);
    }
    return result;
  };
  const makeTrace = (name, path) => ({
    type: "pcb_trace",
    pcb_trace_id: `lane_closure_repair_${name}`,
    connection_name: name,
    source_trace_id: byName.get(name).source_trace_id,
    route: path.map((p2) => ({
      ...p2,
      route_type: "wire",
      layer: byName.get(name).pointsToConnect[0].layer,
      width: width(name)
    }))
  });
  const replaceable = (trace) => {
    const c2 = byName.get(trace.connection_name ?? "");
    return !!c2 && ordinary(c2) && !trace.coupledSection && !trace.curvedSegments?.length && trace.route.every((p2) => p2.route_type === "wire");
  };
  const normalized = current;
  const subset = missing.map((c2) => c2.name);
  let additions = 0;
  const exhausted = () => budget.searches >= maxSearches || budget.searchSteps >= maxSteps;
  const report = () => options.onProgress?.({
    searches: budget.searches,
    searchSteps: budget.searchSteps,
    subset: [...subset],
    candidates: budget.candidates
  });
  const globalLengthLimit = 2 * Math.max(
    ...connections.map(
      (c2) => distance(c2.pointsToConnect[0], c2.pointsToConnect[1])
    )
  );
  const searchResults = /* @__PURE__ */ new Map();
  function* search(name, hard, reverse4 = false) {
    if (exhausted()) return null;
    const key = JSON.stringify([
      name,
      reverse4,
      byName.get(name).pointsToConnect,
      width(name),
      hard.map((t48) => [t48.connection_name, t48.route])
    ]);
    if (searchResults.has(key)) return searchResults.get(key);
    const remember = (result) => {
      if (searchResults.size >= 256)
        searchResults.delete(searchResults.keys().next().value);
      searchResults.set(key, result);
      return result;
    };
    budget.searches++;
    report();
    const connection = byName.get(name);
    const scene = new VectorScene(input, connection, width(name), [
      ...fixed,
      ...hard.flatMap(copper)
    ]);
    const solver = new GridVisibilitySearch(
      scene,
      connection.pointsToConnect[reverse4 ? 1 : 0],
      connection.pointsToConnect[reverse4 ? 0 : 1],
      [],
      0,
      void 0,
      { maxLength: options.maxLengths?.get(name) ?? globalLengthLimit }
    );
    let attemptSteps = 0;
    try {
      while (attemptSteps < (options.maxSearchStepsPerAttempt ?? 500) && !solver.solved && !solver.failed && budget.searchSteps < maxSteps) {
        solver.step();
        attemptSteps++;
        budget.searchSteps++;
        yield;
      }
      if (!solver.solved) return remember(null);
      const raw = reverse4 ? solver.result.toReversed() : solver.result;
      const path = reduceOrdinaryTurns(raw, scene);
      if (!scene.pathVisible(path) || !tuningPathIsSelfClear(path, width(name) + clearance))
        return remember(null);
      return remember(makeTrace(name, path));
    } finally {
      solver.cancel();
      report();
    }
  }
  const initialWitnesses = /* @__PURE__ */ new Map();
  const witnesses = /* @__PURE__ */ new Map();
  for (const c2 of missing) {
    const direct = yield* search(c2.name, normalized);
    if (direct) initialWitnesses.set(c2.name, [direct]);
    else
      for (const trace of normalized) {
        if (!replaceable(trace) || trace.route[0].layer !== c2.pointsToConnect[0].layer)
          continue;
        const opened = yield* search(
          c2.name,
          normalized.filter((t48) => t48 !== trace)
        );
        if (!opened) continue;
        witnesses.set(
          trace.connection_name,
          (witnesses.get(trace.connection_name) ?? 0) + 1
        );
        initialWitnesses.set(c2.name, [
          ...initialWitnesses.get(c2.name) ?? [],
          opened
        ]);
      }
  }
  function* combinations(items, count, start = 0, prefix = []) {
    if (!count) {
      yield prefix;
      return;
    }
    for (let i2 = start; i2 <= items.length - count; i2++)
      yield* combinations(items, count - 1, i2 + 1, [...prefix, items[i2]]);
  }
  for (const connection of missing) {
    if (initialWitnesses.has(connection.name)) continue;
    const donors = normalized.filter(
      (t48) => replaceable(t48) && t48.route[0].layer === connection.pointsToConnect[0].layer
    );
    let found = false;
    for (let count = 2; count <= maxSubset - missing.length && !found; count++)
      for (const removed of combinations(donors, count)) {
        if (exhausted()) break;
        const opened = yield* search(
          connection.name,
          normalized.filter((t48) => !removed.includes(t48))
        );
        if (!opened) continue;
        for (const trace of removed)
          witnesses.set(
            trace.connection_name,
            (witnesses.get(trace.connection_name) ?? 0) + 1
          );
        initialWitnesses.set(connection.name, [opened]);
        found = true;
        break;
      }
  }
  for (const [name] of [...witnesses].sort((a2, b2) => b2[1] - a2[1])) {
    if (subset.length >= Math.min(4, maxSubset)) break;
    subset.push(name);
  }
  if (exhausted()) return null;
  function* expandSubset() {
    const remaining = normalized.filter(
      (t48) => !subset.includes(t48.connection_name)
    );
    const scores = /* @__PURE__ */ new Map();
    for (const anchor of missing.map((c2) => c2.name)) {
      const baseline = yield* search(anchor, remaining);
      if (!baseline) continue;
      for (const target of subset.filter((n2) => n2 !== anchor)) {
        if (yield* search(target, [...remaining, baseline])) continue;
        for (const trace of remaining) {
          if (!replaceable(trace) || trace.route[0].layer !== byName.get(target).pointsToConnect[0].layer)
            continue;
          if (!(yield* search(target, [
            ...remaining.filter((t48) => t48 !== trace),
            baseline
          ])))
            continue;
          const targets = scores.get(trace.connection_name) ?? /* @__PURE__ */ new Set();
          targets.add(target);
          scores.set(trace.connection_name, targets);
        }
      }
    }
    const witness = [...scores].sort((a2, b2) => b2[1].size - a2[1].size)[0]?.[0];
    if (witness) return witness;
    for (const anchor of missing) {
      const relaxed = yield* search(
        anchor.name,
        normalized.filter((t48) => !replaceable(t48))
      );
      if (!relaxed) continue;
      const blocker = remaining.find(
        (trace) => replaceable(trace) && !new VectorScene(input, anchor, width(anchor.name), [
          ...fixed,
          ...copper(trace)
        ]).pathVisible(relaxed.route)
      );
      if (blocker) return blocker.connection_name;
    }
    return null;
  }
  const seeds = [...normalized, ...[...initialWitnesses.values()].flat()];
  for (; ; ) {
    const remaining = normalized.filter(
      (t48) => !subset.includes(t48.connection_name)
    );
    const hardBase = [...fixed, ...remaining.flatMap(copper)];
    const pool = new RouteCandidatePool(clearance, domainLimit);
    const candidateMap = /* @__PURE__ */ new Map();
    const signatures = /* @__PURE__ */ new Map();
    const add = (trace) => {
      const name = trace.connection_name;
      if (!validCarrier(trace)) return false;
      const scene = new VectorScene(
        input,
        byName.get(name),
        width(name),
        hardBase
      );
      if (!scene.pathVisible(trace.route) || !(options.deferRetainedSelfClearance && current.some((t48) => t48.route === trace.route)) && !tuningPathIsSelfClear(trace.route, width(name) + clearance))
        return false;
      const key = JSON.stringify(trace.route), seen = signatures.get(name) ?? /* @__PURE__ */ new Set();
      if (seen.has(key)) return false;
      const domain = candidateMap.get(name) ?? [];
      domain.push(trace);
      seen.add(key);
      if (domain.length > domainLimit)
        seen.delete(JSON.stringify(domain.shift().route));
      candidateMap.set(name, domain);
      signatures.set(name, seen);
      pool.add(name, [trace]);
      additions++;
      budget.candidates++;
      return true;
    };
    const complete = () => {
      const selected2 = pool.select(subset, [subset]);
      if (!selected2) return null;
      const all = [...remaining, ...selected2];
      if (all.length !== connections.length || new Set(all.map((t48) => t48.connection_name)).size !== connections.length)
        return null;
      for (const trace of all) {
        const c2 = byName.get(trace.connection_name);
        if (!c2 || !validCarrier(trace)) return null;
        const scene = new VectorScene(input, c2, width(c2.name), [
          ...fixed,
          ...all.filter((t48) => t48 !== trace).flatMap(copper)
        ]);
        if (!scene.pathVisible(trace.route) || !(options.deferRetainedSelfClearance && current.some((t48) => t48.route === trace.route)) && !tuningPathIsSelfClear(trace.route, width(c2.name) + clearance))
          return null;
      }
      return all;
    };
    for (const trace of seeds)
      if (subset.includes(trace.connection_name)) add(trace);
    for (const name of subset) {
      const baseline = yield* search(name, remaining);
      if (baseline) add(baseline);
    }
    let selected = complete();
    if (selected) return selected;
    for (const order of repairOrders(subset)) {
      const prefix = [];
      for (const name of order) {
        const trace = yield* search(name, [...remaining, ...prefix]);
        if (!trace) break;
        prefix.push(trace);
        add(trace);
        selected = complete();
        if (selected) return selected;
      }
      if (exhausted()) return null;
    }
    const domainFor = (name, limit) => {
      const domain = candidateMap.get(name) ?? [];
      const shortest = [...domain].sort(
        (a2, b2) => length(a2.route) - length(b2.route)
      );
      return domain.length <= limit ? shortest : [
        .../* @__PURE__ */ new Set([
          domain[0],
          ...shortest.slice(0, limit / 2 - 1),
          ...domain.slice(-limit / 2)
        ])
      ];
    };
    function* conditionals(cheap = false, jointOnly = false) {
      const limit = cheap ? Math.min(8, domainLimit) : domainLimit;
      for (let pass = 0; pass < (jointOnly ? 0 : cheap ? 1 : options.maxConditionalPasses ?? 4); pass++) {
        const before = additions;
        const snapshot = new Map(
          subset.map((name) => [name, domainFor(name, limit)])
        );
        for (const pending of subset)
          for (const remote of subset.filter((n2) => n2 !== pending))
            for (const partner of snapshot.get(remote)) {
              const trace = yield* search(pending, [...remaining, partner]);
              if (trace) add(trace);
              const result = complete();
              if (result) return result;
              if (exhausted()) return null;
            }
        if (additions === before) break;
      }
      for (const pending of subset) {
        const remotes = subset.filter((name) => name !== pending);
        const snapshot = new Map(
          remotes.map((name) => [name, domainFor(name, limit)])
        );
        for (const forced of remotes)
          for (const option of snapshot.get(forced)) {
            const conditional = new RouteCandidatePool(clearance, domainLimit);
            for (const remote of remotes)
              for (const candidate of remote === forced ? [option] : snapshot.get(remote))
                conditional.add(remote, [candidate]);
            const partners = conditional.select(remotes, [remotes]);
            if (!partners) continue;
            const trace = yield* search(pending, [...remaining, ...partners]);
            if (trace) add(trace);
            const result = complete();
            if (result) return result;
            if (exhausted()) return null;
          }
      }
      return null;
    }
    selected = yield* conditionals(true);
    if (selected || exhausted()) return selected;
    if (subset.length < maxSubset) {
      const next = yield* expandSubset();
      if (exhausted()) return null;
      if (next) {
        seeds.push(...[...candidateMap.values()].flat());
        subset.push(next);
        continue;
      }
    }
    const points = connections.flatMap((c2) => c2.pointsToConnect);
    const halo = (width(missing[0].name) + clearance) * 2;
    const pads = input.obstacles.filter((o2) => o2.componentId);
    let seededAt = additions;
    for (const fraction of [0.1, 0.3, 0.5, 0.7, 0.9])
      for (let channelIndex = 0; channelIndex < 11; channelIndex++)
        for (const name of subset) {
          if (exhausted()) return null;
          budget.searches++;
          const c2 = byName.get(name), [start, end] = c2.pointsToConnect;
          const localVertical = Math.abs(end.y - start.y) >= Math.abs(end.x - start.x);
          const localCross = (point) => localVertical ? point.x : point.y;
          const localLow = Math.min(...points.map(localCross)) - halo;
          const localHigh = Math.max(...points.map(localCross)) + halo;
          const localChannels = Array.from(
            { length: 9 },
            (_2, i2) => localLow + (localHigh - localLow) * i2 / 8
          );
          if (pads.length)
            localChannels.push(
              Math.min(
                ...pads.map(
                  (p2) => localCross(p2.center) - (localVertical ? p2.width : p2.height) / 2
                )
              ) - halo,
              Math.max(
                ...pads.map(
                  (p2) => localCross(p2.center) + (localVertical ? p2.width : p2.height) / 2
                )
              ) + halo
            );
          const channel = localChannels[channelIndex % localChannels.length];
          const waypoint = localVertical ? { x: channel, y: start.y + (end.y - start.y) * fraction } : { x: start.x + (end.x - start.x) * fraction, y: channel };
          const scene = new VectorScene(input, c2, width(name), hardBase);
          const generator = routeViaWaypoint(
            scene,
            waypoint,
            [],
            0,
            void 0,
            options.maxLengths?.get(name) ?? globalLengthLimit
          );
          let next = generator.next();
          try {
            while (!next.done && budget.searchSteps < maxSteps) {
              budget.searchSteps++;
              yield;
              next = generator.next();
            }
          } finally {
            if (!next.done) generator.return(null);
          }
          if (next.done && next.value) add(makeTrace(name, next.value));
          selected = complete();
          if (selected) return selected;
          if (additions - seededAt >= 12) {
            selected = yield* conditionals(true, true);
            if (selected || exhausted()) return selected;
            seededAt = additions;
          }
        }
    return yield* conditionals();
  }
}

// lib/negotiate-lanes.ts
function* negotiateLanes(input, connections, fixed, paired, widths, reportProgress, terminalLayers = /* @__PURE__ */ new Map(), enableTerminalReservations = () => true, deferRetainedSelfClearance = false, checkReachability = false) {
  const flexibleTerminals = connections.some(
    (connection) => (terminalLayers.get(connection.name)?.length ?? 1) > 1
  );
  const routed = /* @__PURE__ */ new Map();
  const histories = /* @__PURE__ */ new Map();
  const searches = /* @__PURE__ */ new Map();
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const pairs = (input.differentialPairs ?? []).filter(
    (p2) => (p2.traceGap !== void 0 || p2.maxUncoupledLength !== void 0) && p2.connectionNames.every((n2) => connections.some((c2) => c2.name === n2))
  );
  const pairedNames = new Set(pairs.flatMap((p2) => p2.connectionNames));
  const units = [
    ...pairs.map((pair) => ({
      pair,
      connections: pair.connectionNames.map(
        (n2) => connections.find((c2) => c2.name === n2)
      )
    })),
    ...connections.filter((c2) => !pairedNames.has(c2.name)).map((c2) => ({ pair: void 0, connections: [c2] }))
  ].sort(
    (a2, b2) => Number(!a2.pair) - Number(!b2.pair) || length(a2.connections[0].pointsToConnect) - length(b2.connections[0].pointsToConnect)
  );
  const limits = /* @__PURE__ */ new Map();
  const ceilings = /* @__PURE__ */ new Map();
  for (const bus of input.buses ?? []) {
    const members = connections.filter(
      (c2) => bus.connectionNames.includes(c2.name)
    );
    const limit = (
      // Reserve one percent of the compact search envelope for length tuning.
      1.5 * 0.99 * Math.max(...members.map((c2) => length(c2.pointsToConnect)))
    );
    for (const member of members) {
      const hardLimit = maximumCarrierLength(input, member.name);
      limits.set(member.name, Math.min(limit, hardLimit));
      ceilings.set(member.name, Math.min(limit * 4 / 3, hardLimit));
    }
  }
  const candidates = new RouteCandidatePool(clearance, 240);
  const conflicts = new RouteConflictIndex();
  const unitNames = units.map((unit) => unit.connections[0].name);
  const matchingGroups = [
    ...(input.buses ?? []).map(
      (bus) => units.filter(
        (unit) => unit.connections.some((c2) => bus.connectionNames.includes(c2.name))
      ).map((unit) => unit.connections[0].name)
    ),
    ...units.filter(
      (unit) => !unit.connections.some(
        (c2) => (input.buses ?? []).some(
          (bus) => bus.connectionNames.includes(c2.name)
        )
      )
    ).map((unit) => [unit.connections[0].name])
  ];
  const copperCache = /* @__PURE__ */ new WeakMap();
  const getCopper = (trace) => {
    let copper = copperCache.get(trace);
    if (!copper) {
      copper = routeCopper(trace);
      copperCache.set(trace, copper);
    }
    return copper;
  };
  const pairedCopper = paired.flatMap(getCopper);
  const visits = /* @__PURE__ */ new Map();
  const queue = [...units];
  let bestCount = 0, lastProgress = 0, pairRefresh = 0, closureAttempts = 0, refinementAttempts = 0, lastClosureRepair = -Infinity;
  routing: for (let iteration = 0; iteration < 12e3 && queue.length; iteration++) {
    const pass = Math.floor(iteration / Math.max(1, connections.length / 4));
    const congestionPenalty = 10 + pass * 4;
    if (iteration - lastProgress >= units.length * 8) {
      for (const [name, limit] of limits) {
        const ceiling = ceilings.get(name);
        if (limit < ceiling) limits.set(name, Math.min(ceiling, limit * 1.025));
      }
      const waitingLayers = new Set(
        queue.flatMap(
          (unit) => unit.connections.map((c2) => c2.pointsToConnect[0].layer)
        )
      );
      const coupled = units.filter(
        (unit) => unit.pair && waitingLayers.has(unit.connections[0].pointsToConnect[0].layer)
      );
      if (coupled.length) {
        const unit = coupled[pairRefresh++ % coupled.length];
        const queued = queue.indexOf(unit);
        if (queued >= 0) queue.splice(queued, 1);
        queue.unshift(unit);
      }
      lastProgress = iteration;
    }
    const currentUnit = queue.shift();
    const sweep = [currentUnit];
    for (const unit of sweep) {
      const connection = unit.connections[0];
      const visit = (visits.get(connection.name) ?? 0) + 1;
      visits.set(connection.name, visit);
      const previous = unit.connections.flatMap(
        (c2) => routed.has(c2.name) ? [routed.get(c2.name)] : []
      );
      for (const c2 of unit.connections) routed.delete(c2.name);
      const available = terminalLayers.get(connection.name)?.filter(
        (layer2) => unit.connections.every(
          (c2) => terminalLayers.get(c2.name)?.includes(layer2)
        )
      ) ?? [connection.pointsToConnect[0].layer];
      const projected = previous.length ? previous : unit.connections.map((c2) => ({
        connection_name: c2.name,
        route: c2.pointsToConnect
      }));
      const layerCost = (layer2) => {
        let cost = layer2 === connection.pointsToConnect[0].layer ? 0 : 0.25;
        for (const other of routed.values()) {
          if (other.route[0].layer !== layer2) continue;
          const hit = projected.some(
            (trace) => conflicts.firstConflict(
              trace.route,
              other.route,
              (widths.get(trace.connection_name) + other.route[0].width) / 2 + clearance - 1e-8
            )
          );
          if (hit) cost++;
        }
        return cost;
      };
      if (available.length > 1) {
        const layerCosts = new Map(
          available.map((layer2) => [layer2, layerCost(layer2)])
        );
        available.sort((a2, b2) => layerCosts.get(a2) - layerCosts.get(b2));
      }
      const chosenLayer = available[0];
      for (const c2 of unit.connections)
        for (const point of c2.pointsToConnect) point.layer = chosenLayer;
      const width = widths.get(connection.name), layer = connection.pointsToConnect[0].layer;
      routed.delete(connection.name);
      const routedLanes = [...routed.values()];
      const progressRoutes = [...paired, ...routedLanes];
      const routedCopper = routedLanes.flatMap(getCopper);
      const sceneCopper = [
        ...fixed,
        ...pairedCopper,
        ...!unit.pair ? routedLanes.filter((t48) => pairedNames.has(t48.connection_name)).flatMap(getCopper) : []
      ];
      const scene = new VectorScene(input, connection, width, sceneCopper);
      if (unit.pair) {
        const projector = new GridHistoryProjector(scene);
        if (!histories.has(layer))
          histories.set(layer, new Float32Array(projector.cellCount));
        searches.set(layer, projector);
        const generator = routeCoupledPair(input, unit.pair, fixed, {
          copper: [],
          penalty: 0,
          variant: visit - 1
        });
        let step = generator.next();
        try {
          while (!step.done) {
            yield routedLanes;
            step = generator.next();
          }
        } finally {
          if (!step.done) step = generator.return(null);
        }
        if (!step.value) {
          if (previous.length !== unit.connections.length) return null;
          for (const trace of previous) {
            routed.set(trace.connection_name, trace);
            const c2 = unit.connections.find(
              (c3) => c3.name === trace.connection_name
            );
            for (const point of c2.pointsToConnect)
              point.layer = trace.route[0].layer;
          }
          continue;
        }
        candidates.add(connection.name, step.value);
        for (const trace of step.value)
          routed.set(trace.connection_name, trace);
        continue;
      }
      let pendingCopper = [];
      let certificatePaths = [];
      if (input.buses?.length && iteration >= units.length * 4 && enableTerminalReservations()) {
        const generator = pendingLaneCertificates(
          input,
          connections.filter((c2) => !pairedNames.has(c2.name)),
          sceneCopper,
          widths
        );
        let step = generator.next();
        try {
          while (!step.done) {
            yield progressRoutes;
            step = generator.next();
          }
        } finally {
          if (!step.done) generator.return([]);
        }
        const paths = step.value;
        certificatePaths = paths;
        pendingCopper = paths.filter(
          (t48) => t48.connection_name !== connection.name && !routed.has(t48.connection_name)
        ).flatMap(getCopper);
      }
      const search = new GridVisibilitySearch(
        scene,
        connection.pointsToConnect[0],
        connection.pointsToConnect[1],
        [...routedCopper, ...pendingCopper],
        congestionPenalty,
        histories.get(layer),
        {
          maxLength: limits.get(connection.name),
          paretoLength: Number.isFinite(
            maximumCarrierLength(input, connection.name)
          ),
          checkReachability
        }
      );
      if (!histories.has(layer))
        histories.set(layer, new Float32Array(search.cellCount));
      searches.set(layer, search);
      let bestChoice;
      for (const candidateLayer of available) {
        for (const point of connection.pointsToConnect)
          point.layer = candidateLayer;
        const candidateScene = candidateLayer === layer ? scene : new VectorScene(input, connection, width, sceneCopper);
        let candidateSearch = candidateLayer === layer ? search : new GridVisibilitySearch(
          candidateScene,
          connection.pointsToConnect[0],
          connection.pointsToConnect[1],
          [...routedCopper, ...pendingCopper],
          congestionPenalty,
          histories.get(candidateLayer),
          {
            maxLength: limits.get(connection.name),
            paretoLength: Number.isFinite(
              maximumCarrierLength(input, connection.name)
            ),
            checkReachability
          }
        );
        if (!histories.has(candidateLayer))
          histories.set(
            candidateLayer,
            new Float32Array(candidateSearch.cellCount)
          );
        searches.set(candidateLayer, candidateSearch);
        try {
          while (!candidateSearch.solved && !candidateSearch.failed) {
            candidateSearch.step();
            yield progressRoutes;
          }
        } finally {
          if (!candidateSearch.solved && !candidateSearch.failed)
            candidateSearch.cancel();
        }
        if (!candidateSearch.solved && limits.has(connection.name)) {
          candidateSearch = new GridVisibilitySearch(
            candidateScene,
            connection.pointsToConnect[0],
            connection.pointsToConnect[1],
            [],
            0,
            void 0,
            {
              checkReachability,
              maxLength: maximumCarrierLength(input, connection.name)
            }
          );
          try {
            while (!candidateSearch.solved && !candidateSearch.failed) {
              candidateSearch.step();
              yield progressRoutes;
            }
          } finally {
            if (!candidateSearch.solved && !candidateSearch.failed)
              candidateSearch.cancel();
          }
          if (candidateSearch.solved && length(candidateSearch.result) > limits.get(connection.name)) {
            const bus = input.buses.find(
              (b2) => b2.connectionNames.includes(connection.name)
            );
            for (const name of bus.connectionNames)
              limits.set(
                name,
                Math.min(
                  length(candidateSearch.result) * 1.05,
                  maximumCarrierLength(input, name)
                )
              );
          }
        }
        if (!candidateSearch.solved) continue;
        const paths = [candidateSearch.result];
        if (visit > 1 && visit % 2 === 0 && limits.has(connection.name)) {
          const [a2, b2] = connection.pointsToConnect;
          const vertical = Math.abs(b2.y - a2.y) >= Math.abs(b2.x - a2.x);
          const coordinates = [
            ...connections.flatMap((c2) => c2.pointsToConnect),
            ...input.obstacles.filter((o2) => o2.componentId).flatMap((o2) => [
              {
                x: o2.center.x - o2.width / 2 - 0.6,
                y: o2.center.y - o2.height / 2 - 0.6
              },
              {
                x: o2.center.x + o2.width / 2 + 0.6,
                y: o2.center.y + o2.height / 2 + 0.6
              }
            ]),
            ...[...routed.values()].filter((t48) => t48.coupledSection).flatMap((t48) => t48.route)
          ].map((p2) => vertical ? p2.x : p2.y);
          const low = Math.min(...coordinates) - (width + clearance) * 2;
          const high = Math.max(...coordinates) + (width + clearance) * 2;
          const trial = Math.floor(visit / 2) - 1;
          const cross4 = low + (high - low) * (trial * 5 % 9) / 8;
          const along2 = [-0.15, 0.2, 0.5, 0.8, 1.15, 0.35, 0.65, 0.1, 0.9][trial % 9];
          let waypoint = vertical ? { x: cross4, y: a2.y + (b2.y - a2.y) * along2 } : { x: a2.x + (b2.x - a2.x) * along2, y: cross4 };
          const generator = routeViaWaypoint(
            candidateScene,
            waypoint,
            routedCopper,
            congestionPenalty,
            histories.get(candidateLayer),
            limits.get(connection.name)
          );
          let step = generator.next();
          try {
            while (!step.done) {
              yield progressRoutes;
              step = generator.next();
            }
          } finally {
            if (!step.done) generator.return(null);
          }
          if (step.value) paths.push(step.value);
        }
        for (const path of paths) {
          if (length(path) > maximumCarrierLength(input, connection.name) + 1e-7)
            continue;
          let hits = 0;
          for (const other of routed.values()) {
            if (other.route[0].layer !== candidateLayer) continue;
            const hit = conflicts.firstConflict(
              path,
              other.route,
              (width + other.route[0].width) / 2 + clearance - 1e-8
            );
            if (hit) hits++;
          }
          const score = length(path) + hits * length(connection.pointsToConnect);
          const choice = {
            score,
            trace: {
              type: "pcb_trace",
              pcb_trace_id: `bus_lane_${connection.name}`,
              connection_name: connection.name,
              source_trace_id: connection.source_trace_id ?? connection.name,
              route: path.map((p2) => ({
                ...p2,
                route_type: "wire",
                layer: candidateLayer,
                width
              }))
            }
          };
          candidates.add(connection.name, [choice.trace]);
          if (!bestChoice || score < bestChoice.score) bestChoice = choice;
        }
      }
      if (!bestChoice) {
        if (!certificatePaths.length) return null;
        for (const trace of previous) {
          routed.set(trace.connection_name, trace);
          const restored = unit.connections.find(
            (c2) => c2.name === trace.connection_name
          );
          for (const point of restored.pointsToConnect)
            point.layer = trace.route[0].layer;
        }
        queue.push(unit);
        reportProgress?.(iteration + 1, connections.length - routed.size);
        yield [...paired, ...routed.values()];
        continue routing;
      }
      for (const point of connection.pointsToConnect)
        point.layer = bestChoice.trace.route[0].layer;
      candidates.add(connection.name, [bestChoice.trace]);
      routed.set(connection.name, bestChoice.trace);
    }
    const selected = candidates.select(unitNames, matchingGroups);
    if (selected) {
      routed.clear();
      for (const trace of selected) {
        routed.set(trace.connection_name, trace);
        const connection = connections.find(
          (c2) => c2.name === trace.connection_name
        );
        for (const point of connection.pointsToConnect)
          point.layer = trace.route[0].layer;
      }
    }
    const pending = /* @__PURE__ */ new Set();
    const lanes = [...routed.values()];
    for (let a2 = 0; a2 < lanes.length; a2++)
      for (let b2 = 0; b2 < a2; b2++) {
        const first = lanes[a2], second = lanes[b2];
        const layer = first.route[0].layer;
        if (layer !== second.route[0].layer) continue;
        const required = (first.route[0].width + second.route[0].width) / 2 + clearance;
        const conflict = conflicts.firstConflict(
          first.route,
          second.route,
          required - 1e-8
        );
        if (conflict) {
          const [i2, j2] = conflict;
          pending.add(first.connection_name);
          pending.add(second.connection_name);
          searches.get(layer).penalizeIntersection(
            histories.get(layer),
            first.route[i2 - 1],
            first.route[i2],
            second.route[j2 - 1],
            second.route[j2],
            required * 1.25,
            true
          );
        }
      }
    if (pending.size) {
      for (const unit of units) {
        if (unit === currentUnit || !unit.connections.some((c2) => pending.has(c2.name)))
          continue;
        for (const c2 of unit.connections) routed.delete(c2.name);
        if (!queue.includes(unit)) queue.push(unit);
      }
    }
    if (routed.size > bestCount) {
      bestCount = routed.size;
      lastProgress = iteration;
    }
    let missing = connections.length - routed.size;
    if (missing > 0 && missing <= 3 && !flexibleTerminals && closureAttempts < 6 && iteration >= units.length * 2 && iteration - lastClosureRepair >= units.length * 4 && connections.every((c2) => routed.has(c2.name) || !pairedNames.has(c2.name))) {
      closureAttempts++;
      lastClosureRepair = iteration;
      const generator = repairLaneClosures(
        input,
        connections,
        [...fixed, ...pairedCopper],
        [...routed.values()],
        widths,
        {
          deferRetainedSelfClearance,
          maxSubsetSize: 5,
          maxSearches: 64,
          maxSearchSteps: 6e3,
          maxLengths: ceilings
        }
      );
      let step = generator.next();
      try {
        while (!step.done) {
          yield [...paired, ...routed.values()];
          step = generator.next();
        }
      } finally {
        if (!step.done) generator.return(null);
      }
      if (step.value) {
        routed.clear();
        for (const trace of step.value)
          routed.set(trace.connection_name, trace);
        missing = 0;
      }
    }
    if (missing > 0 && missing <= 3 && !flexibleTerminals && refinementAttempts < 2 && iteration >= units.length * (input.buses?.length ? 8 + refinementAttempts * 4 : 2 + refinementAttempts * 2) && candidates.hasEveryUnit(unitNames)) {
      refinementAttempts++;
      const generator = refineRouteCandidates(
        input,
        [...fixed, ...pairedCopper],
        widths,
        candidates,
        unitNames,
        matchingGroups,
        terminalLayers
      );
      let step = generator.next();
      try {
        while (!step.done) {
          yield [...paired, ...routed.values()];
          step = generator.next();
        }
      } finally {
        if (!step.done) generator.return(null);
      }
      if (step.value) {
        routed.clear();
        for (const trace of step.value) {
          routed.set(trace.connection_name, trace);
          for (const point of connections.find(
            (c2) => c2.name === trace.connection_name
          ).pointsToConnect)
            point.layer = trace.route[0].layer;
        }
        missing = 0;
      }
    }
    reportProgress?.(iteration + 1, missing);
    yield [...paired, ...routed.values()];
    if (missing) continue;
    const result = [...paired, ...routed.values()];
    for (const trace of routed.values()) {
      if (trace.coupledSection) continue;
      const connection = connections.find(
        (c2) => c2.name === trace.connection_name
      ), width = widths.get(connection.name);
      const scene = new VectorScene(input, connection, width, [
        ...fixed,
        ...result.flatMap(routeCopper)
      ]);
      trace.route = reduceOrdinaryTurns(trace.route, scene).map((p2) => ({
        ...p2,
        route_type: "wire",
        layer: connection.pointsToConnect[0].layer,
        width
      }));
    }
    return result;
  }
  return null;
}

// lib/route-independent-buses.ts
function independentBusGroups(input) {
  if ((input.buses?.length ?? 0) < 2) return null;
  const constrained = /* @__PURE__ */ new Set([
    ...(input.buses ?? []).flatMap((b2) => b2.connectionNames),
    ...(input.differentialPairs ?? []).flatMap((p2) => p2.connectionNames)
  ]);
  if (input.connections.some(
    (c2) => !constrained.has(c2.name) || c2.pointsToConnect.some((p2) => p2.layer !== c2.pointsToConnect[0].layer)
  ))
    return null;
  const layers = [
    ...new Set(input.connections.map((c2) => c2.pointsToConnect[0].layer))
  ];
  if (layers.length < 2) return null;
  const groups = layers.map((layer) => {
    const connections = input.connections.filter(
      (c2) => c2.pointsToConnect[0].layer === layer
    );
    const names = new Set(connections.map((c2) => c2.name));
    const buses = (input.buses ?? []).filter(
      (b2) => b2.connectionNames.some((n2) => names.has(n2))
    );
    const differentialPairs = (input.differentialPairs ?? []).filter(
      (p2) => p2.connectionNames.some((n2) => names.has(n2))
    );
    if (buses.some((b2) => b2.connectionNames.some((n2) => !names.has(n2))) || differentialPairs.some(
      (p2) => p2.connectionNames.some((n2) => !names.has(n2))
    ) || differentialPairs.length > 1)
      return null;
    return { ...input, connections, buses, differentialPairs };
  });
  return groups.every((g2) => g2 !== null) ? groups : null;
}
function* routeIndependentBuses(groups, fixed, widths, finish) {
  const completed = [];
  for (const input of groups) {
    const pair = input.differentialPairs?.[0];
    const ordinary = input.connections.filter(
      (c2) => !pair?.connectionNames.includes(c2.name)
    );
    let solved = null;
    const variants = backwardFacingPackageTerminals(input) ? [0, 5, 1, 4, 2, 3] : [0, 1, 2, 3, 4, 5];
    for (const variant of variants) {
      if (solved) break;
      let paired = [];
      if (pair) {
        const search2 = routeCoupledPair(input, pair, fixed, {
          copper: [],
          penalty: 0,
          variant
        });
        let state2 = search2.next(), steps2 = 0;
        try {
          while (!state2.done && steps2++ < 12e3) {
            yield completed;
            state2 = search2.next();
          }
        } finally {
          if (!state2.done) search2.return(null);
        }
        if (!state2.done || !state2.value) continue;
        paired = state2.value;
      }
      if (!ordinary.length) {
        solved = finish(input, paired);
        continue;
      }
      const search = negotiateLanes(
        input,
        ordinary,
        fixed,
        paired,
        widths,
        void 0,
        /* @__PURE__ */ new Map(),
        () => false
      );
      let state = search.next(), steps = 0;
      try {
        while (!state.done && steps++ < 12e3) {
          yield [...completed, ...state.value];
          state = search.next();
        }
      } finally {
        if (!state.done) search.return(null);
      }
      if (state.done && state.value) {
        const repair = repairGridJogs(input, state.value, fixed);
        let repaired = repair.next(), repairSteps = 0;
        try {
          while (!repaired.done && repairSteps++ < 6e3) {
            yield [...completed, ...state.value];
            repaired = repair.next();
          }
        } finally {
          if (!repaired.done) repair.return(false);
        }
        if (!repaired.done || !repaired.value) continue;
        solved = finish(input, state.value);
      }
    }
    if (!solved) return null;
    completed.push(...solved);
    yield completed;
  }
  return completed;
}

// lib/paired-network.ts
function* preparePairedNetwork(input, layers, variantOffset = 0) {
  const constrained = /* @__PURE__ */ new Set([
    ...(input.buses ?? []).flatMap((b2) => b2.connectionNames),
    ...(input.differentialPairs ?? []).flatMap((p2) => p2.connectionNames)
  ]);
  const groups = independentBusGroups({
    ...input,
    connections: input.connections.filter((c2) => constrained.has(c2.name))
  });
  if (!groups || groups.some((g2) => g2.differentialPairs?.length !== 1))
    return null;
  const fixed = fixedCopper(input), transforms = [], guards = [];
  for (const group of groups) {
    const pair = group.differentialPairs[0];
    let accepted = false;
    for (let variant = 0; variant < 6 && !accepted; variant++) {
      const generator = routeCoupledPair(group, pair, fixed, {
        copper: [],
        penalty: 0,
        variant: (variant + (typeof variantOffset === "number" ? variantOffset : variantOffset[transforms.length] ?? 0)) % 6
      });
      let state = generator.next(), steps = 0;
      try {
        while (!state.done && steps++ < 8e3) {
          yield;
          state = generator.next();
        }
      } finally {
        if (!state.done) generator.return(null);
      }
      if (!state.done || !state.value) continue;
      const rails = alignCoupledSectionBoundaries(group, state.value);
      const sections = rails.map(
        (t48) => t48.route.slice(
          t48.coupledSection[0],
          t48.coupledSection[1] + 1
        )
      );
      if (sections[0].length !== sections[1].length) continue;
      const center = sections[0].map((p2, i2) => ({
        x: (p2.x + sections[1][i2].x) / 2,
        y: (p2.y + sections[1][i2].y) / 2
      }));
      const width = sections[0][0].width, gap = pair.traceGap ?? input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
      const separation = width + gap, envelope = width + separation, layer = sections[0][0].layer;
      const inset = (a2, b2) => {
        const span = distance(a2, b2), d2 = Math.min(span * 0.95, width * 5);
        return {
          x: a2.x + (b2.x - a2.x) * d2 / span,
          y: a2.y + (b2.y - a2.y) * d2 / span
        };
      };
      const first = inset(center[0], center[1]), last = inset(center.at(-1), center.at(-2));
      const name = `pair_${pair.connectionNames[0]}`;
      const offsets = [-separation / 2, separation / 2].sort(
        (a2, b2) => distance(offsetPath(center, a2)[0], sections[0][0]) - distance(offsetPath(center, b2)[0], sections[0][0])
      );
      const connection = {
        name,
        nominalTraceWidth: envelope,
        pointsToConnect: [first, last].map((p2) => ({ ...p2, layer }))
      };
      const approaches = [], candidateGuards = [], fixedApproaches = [];
      for (let side = 0; side < 2; side++)
        for (let end = 0; end < 2; end++) {
          const rail = rails[side], section = sections[side], point = end ? section.at(-1) : section[0];
          const terminal = input.connections.find(
            (c2) => c2.name === rail.connection_name
          ).pointsToConnect[end];
          const approachName = `approach_${rail.connection_name}_${end}`;
          approaches.push({
            name: approachName,
            source_trace_id: rail.connection_name,
            nominalTraceWidth: width,
            pointsToConnect: [terminal, point]
          });
          const path = offsetPath(
            end ? [last, center.at(-1)] : [center[0], first],
            offsets[side]
          ).map((p2) => ({ ...p2, route_type: "wire", layer, width }));
          const guard = {
            type: "pcb_trace",
            pcb_trace_id: approachName,
            connection_name: name,
            source_trace_id: rail.connection_name,
            route: path
          };
          candidateGuards.push(guard);
          const [s2, e2] = rail.coupledSection;
          fixedApproaches.push({
            ...guard,
            route: end ? [...path, ...rail.route.slice(e2 + 1)] : [...rail.route.slice(0, s2), ...path]
          });
        }
      const search = new GridVisibilitySearch(
        new VectorScene(input, connection, envelope, [
          ...fixed,
          ...fixedApproaches.flatMap(routeCopper)
        ]),
        connection.pointsToConnect[0],
        connection.pointsToConnect[1]
      );
      try {
        let steps2 = 0;
        while (!search.solved && !search.failed && steps2++ < 4e3) {
          search.step();
          yield;
        }
        if (!search.solved) continue;
      } finally {
        search.cancel();
      }
      const standalonePair = !input.buses?.some(
        (b2) => pair.connectionNames.some((n2) => b2.connectionNames.includes(n2))
      );
      transforms.push({
        rails,
        sections,
        center,
        width,
        envelope,
        offsets,
        connection,
        approaches: standalonePair ? [] : approaches,
        pair
      });
      guards.push(...standalonePair ? fixedApproaches : candidateGuards);
      accepted = true;
    }
    if (!accepted) return null;
  }
  const names = new Map(
    transforms.flatMap(
      (t48) => t48.pair.connectionNames.map((n2) => [n2, t48.connection.name])
    )
  );
  const local = {
    ...input,
    // A wide corridor must retain enough room to reach both handoffs. The two
    // narrow rail guards alone leave gaps around their end caps that another
    // lane can enter while making the wide terminal unreachable.
    obstacles: [
      ...input.obstacles,
      ...transforms.flatMap(
        (t48) => t48.connection.pointsToConnect.map((p2) => ({
          shape: "circle",
          center: { x: p2.x, y: p2.y },
          width: t48.envelope,
          height: t48.envelope,
          layers: [p2.layer],
          connectedTo: [t48.connection.name, ...t48.pair.connectionNames]
        }))
      )
    ],
    connections: [
      ...input.connections.filter((c2) => !names.has(c2.name)),
      ...transforms.map((t48) => t48.connection),
      ...transforms.flatMap((t48) => t48.approaches)
    ],
    differentialPairs: [],
    traces: [...input.traces ?? [], ...guards],
    buses: input.buses?.map((b2) => {
      const members = [
        ...new Set(b2.connectionNames.map((n2) => names.get(n2) ?? n2))
      ];
      return {
        ...b2,
        connectionNames: [
          ...members,
          ...transforms.filter((t48) => members.includes(t48.connection.name)).flatMap((t48) => t48.approaches.map((c2) => c2.name))
        ]
      };
    })
  };
  return {
    input,
    local,
    transforms,
    layers,
    copper: fixedCopper(local),
    widths: new Map(
      local.connections.map((c2) => [
        c2.name,
        input.buses?.find((b2) => b2.connectionNames.includes(c2.name))?.traceWidth ?? c2.nominalTraceWidth ?? c2.width ?? input.minTraceWidth
      ])
    )
  };
}

// lib/rebuild-paired-network.ts
function* rebuildPairedNetwork(network, raw, options = {}) {
  const { input, local, transforms } = network, fixed = fixedCopper(input);
  const traces = [...raw];
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const result = traces.filter(
    (t48) => input.connections.some((c2) => c2.name === t48.connection_name)
  );
  for (const transform2 of transforms) {
    const { connection, center, width, envelope, offsets } = transform2;
    const index2 = traces.findIndex((t48) => t48.connection_name === connection.name);
    if (index2 < 0) return null;
    const layer = traces[index2].route[0].layer;
    const others = traces.filter((_2, i2) => i2 !== index2);
    let accepted = null;
    for (const lead of [0, width * 6, width * 10]) {
      const directions = [
        {
          x: connection.pointsToConnect[0].x - center[0].x,
          y: connection.pointsToConnect[0].y - center[0].y
        },
        {
          x: center.at(-1).x - connection.pointsToConnect[1].x,
          y: center.at(-1).y - connection.pointsToConnect[1].y
        }
      ];
      const scene = new VectorScene({ ...local }, connection, envelope, [
        ...network.copper,
        ...others.flatMap(routeCopper)
      ]);
      const visible = scene.visible.bind(scene);
      const aligned = (a2, b2, d2) => (b2.x - a2.x) * d2.x + (b2.y - a2.y) * d2.y > 0 && Math.abs((b2.x - a2.x) * d2.y - (b2.y - a2.y) * d2.x) < 1e-8;
      scene.visible = (a2, b2) => {
        for (const [end, p2] of connection.pointsToConnect.entries()) {
          const d2 = directions[end], reverse4 = { x: -d2.x, y: -d2.y };
          if (distance(a2, p2) < 1e-8 && !aligned(a2, b2, end ? reverse4 : d2))
            return false;
          if (distance(b2, p2) < 1e-8 && !aligned(a2, b2, end ? d2 : reverse4))
            return false;
        }
        return visible(a2, b2);
      };
      const ends = connection.pointsToConnect.map((p2, i2) => {
        const d2 = directions[i2], factor = (i2 ? -1 : 1) * lead / Math.hypot(d2.x, d2.y);
        return { ...p2, x: p2.x + factor * d2.x, y: p2.y + factor * d2.y };
      });
      if (lead && (!scene.pathVisible([connection.pointsToConnect[0], ends[0]]) || !scene.pathVisible([ends[1], connection.pointsToConnect[1]])))
        continue;
      const search = new GridVisibilitySearch(
        scene,
        ends[0],
        ends[1],
        [],
        4,
        void 0,
        { allTerminalAttachments: true }
      );
      let path = null;
      try {
        let steps = 0;
        while (!search.solved && !search.failed && steps++ < 1e3) {
          search.step();
          yield;
        }
        if (search.solved) path = reduceOrdinaryTurns(search.result, scene);
      } finally {
        search.cancel();
      }
      if (!path) continue;
      if (lead)
        path = [
          connection.pointsToConnect[0],
          ...path,
          connection.pointsToConnect[1]
        ];
      if (!tuningPathIsSelfClear(path, envelope + clearance)) continue;
      const demand = {
        ...traces[index2],
        route: path.map((p2) => ({
          ...p2,
          route_type: "wire",
          layer,
          width: envelope
        }))
      };
      const carrier = {
        ...demand,
        route: simplify([center[0], ...path, center.at(-1)]).map((p2) => ({
          ...p2,
          route_type: "wire",
          layer,
          width: envelope
        }))
      };
      const shapingInput = {
        ...local,
        connections: local.connections.map(
          (c2) => c2.name === connection.name ? {
            ...c2,
            pointsToConnect: [center[0], center.at(-1)].map((p2) => ({
              ...p2,
              layer
            }))
          } : c2
        )
      };
      const shaped = chamferOrdinaryCorners(
        shapingInput,
        [carrier],
        [
          ...fixed,
          ...others.filter(
            (t48) => !transform2.approaches.some((c2) => c2.name === t48.connection_name)
          ).flatMap(routeCopper)
        ],
        2
      )[0];
      const candidate = restoreRails(transform2, shaped, traces);
      if (!candidate) continue;
      const nativeCopper = [...fixed, ...candidate.flatMap(routeCopper)];
      if (transform2.approaches.length && candidate.some(
        (t48) => !new VectorScene(
          input,
          input.connections.find((c2) => c2.name === t48.connection_name),
          width,
          nativeCopper
        ).pathVisible(t48.route)
      ))
        continue;
      if (candidate.some(
        (t48) => !tuningPathIsSelfClear(
          t48.route.slice(t48.coupledSection[0], t48.coupledSection[1] + 1),
          width + clearance
        )
      ))
        continue;
      traces[index2] = demand;
      accepted = candidate;
      break;
    }
    if (!accepted) return null;
    result.push(...accepted);
  }
  for (const c2 of input.connections) {
    const trace = result.find((t48) => t48.connection_name === c2.name);
    if (!trace) {
      if (options.allowPartial) continue;
      return null;
    }
    for (const p2 of c2.pointsToConnect) p2.layer = trace.route[0].layer;
  }
  return result;
}
function restoreRails(transform2, carrier, traces) {
  const { width, offsets } = transform2, layer = carrier.route[0].layer;
  const rails = [];
  for (const [side, original] of transform2.rails.entries()) {
    const [s2, e2] = original.coupledSection;
    const prefix = traces.find(
      (t48) => t48.connection_name === `approach_${original.connection_name}_0`
    )?.route ?? (transform2.approaches.length ? void 0 : original.route.slice(0, s2 + 1));
    const suffix = traces.find(
      (t48) => t48.connection_name === `approach_${original.connection_name}_1`
    )?.route.toReversed() ?? (transform2.approaches.length ? void 0 : original.route.slice(e2));
    if (!prefix || !suffix) return null;
    const mid = offsetPath(carrier.route, offsets[side]).map((p2) => ({
      ...p2,
      route_type: "wire",
      layer,
      width
    }));
    if (distance(prefix.at(-1), mid[0]) > 1e-8 || distance(suffix[0], mid.at(-1)) > 1e-8)
      return null;
    rails.push({
      ...original,
      curvedSegments: transform2.approaches.length ? [] : original.curvedSegments?.flatMap(
        (k2) => k2 <= s2 ? [k2] : k2 > e2 ? [k2 + mid.length - (e2 - s2 + 1)] : []
      ),
      route: [...prefix.slice(0, -1), ...mid, ...suffix.slice(1)],
      coupledSection: [prefix.length - 1, prefix.length + mid.length - 2]
    });
  }
  return rails;
}

// lib/bevel-coupled-corners.ts
function bevelCoupledCorners(input, traces) {
  const result = [...traces], fixed = fixedCopper(input);
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  for (const pair of input.differentialPairs ?? []) {
    const indices = pair.connectionNames.map(
      (n2) => result.findIndex((t48) => t48.connection_name === n2)
    );
    const rails = indices.map((i2) => result[i2]);
    if (rails.some(
      (t48) => !t48?.coupledSection || t48.curvedSegments?.some(
        (k2) => k2 > t48.coupledSection[0] && k2 <= t48.coupledSection[1]
      )
    ))
      continue;
    const sections = rails.map(
      (t48) => t48.route.slice(t48.coupledSection[0], t48.coupledSection[1] + 1)
    );
    if (sections[0].length !== sections[1].length) continue;
    const width = sections[0][0].width, halfSpacing = (width + (pair.traceGap ?? clearance)) / 2;
    let center = sections[0].map((p2, i2) => ({
      x: (p2.x + sections[1][i2].x) / 2,
      y: (p2.y + sections[1][i2].y) / 2
    }));
    const offsets = [-halfSpacing, halfSpacing].sort(
      (a2, b2) => distance(offsetPath(center, a2)[0], sections[0][0]) - distance(offsetPath(center, b2)[0], sections[0][0])
    );
    const rebuild = (points) => rails.map((t48, side) => {
      const [s2, e2] = t48.coupledSection, mid = offsetPath(points, offsets[side]).map((p2) => ({
        ...p2,
        route_type: "wire",
        layer: sections[side][0].layer,
        width
      }));
      const delta = mid.length - (e2 - s2 + 1);
      return {
        ...t48,
        route: [...t48.route.slice(0, s2), ...mid, ...t48.route.slice(e2 + 1)],
        coupledSection: [s2, e2 + delta],
        curvedSegments: t48.curvedSegments?.map((k2) => k2 > e2 ? k2 + delta : k2)
      };
    });
    const others = result.filter((_2, i2) => !indices.includes(i2)).flatMap(routeCopper);
    let latest = rails;
    for (let i2 = 1; i2 + 1 < center.length; i2++) {
      const [a2, b2, c2] = center.slice(i2 - 1, i2 + 2), before = distance(a2, b2), after = distance(b2, c2);
      if (Math.min(before, after) < 1e-8) continue;
      const u2 = { x: (b2.x - a2.x) / before, y: (b2.y - a2.y) / before }, v2 = { x: (c2.x - b2.x) / after, y: (c2.y - b2.y) / after }, dot2 = u2.x * v2.x + u2.y * v2.y;
      if (dot2 > Math.SQRT1_2 - 1e-8) continue;
      for (let attempt = 0; attempt < 10; attempt++) {
        const trim = Math.min(width * 10, before / 2, after / 2) / 2 ** attempt;
        const start = { x: b2.x - u2.x * trim, y: b2.y - u2.y * trim }, end = { x: b2.x + v2.x * trim, y: b2.y + v2.y * trim };
        const turn = Math.sign(u2.x * v2.y - u2.y * v2.x), bevel2 = (Math.SQRT2 - 1) * trim;
        const middle = {
          x: start.x + (u2.x - turn * u2.y) * Math.SQRT1_2 * bevel2,
          y: start.y + (u2.y + turn * u2.x) * Math.SQRT1_2 * bevel2
        };
        const inserted = dot2 < -0.1 ? [start, middle, end] : [start, end];
        const points = [
          ...center.slice(0, i2),
          ...inserted,
          ...center.slice(i2 + 1)
        ], candidate = rebuild(points);
        if (candidate.some(
          (t48, side) => tuningPathIsSelfClear(latest[side].route, width + clearance) && !tuningPathIsSelfClear(t48.route, width + clearance)
        ))
          continue;
        const copper = [...fixed, ...others, ...candidate.flatMap(routeCopper)];
        if (candidate.some(
          (t48) => !new VectorScene(
            input,
            input.connections.find((c3) => c3.name === t48.connection_name),
            width,
            copper
          ).pathVisible(t48.route)
        ))
          continue;
        if (sharedPairSpacingReports(
          { ...input, differentialPairs: [pair] },
          candidate
        ).some((p2) => !p2.matched))
          continue;
        center = points;
        latest = candidate;
        i2 += inserted.length - 1;
        break;
      }
    }
    indices.forEach((index2, side) => {
      result[index2] = latest[side];
    });
  }
  return result;
}

// lib/round-coupled-return-bends.ts
function roundCoupledReturnBends(input, traces, fixed = fixedCopper(input)) {
  const result = [...traces];
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const chords = 32;
  for (const pair of input.differentialPairs ?? []) {
    const indices = pair.connectionNames.map(
      (name) => result.findIndex((t48) => t48.connection_name === name)
    );
    const rails = indices.map((index2) => result[index2]);
    if (rails.some((t48) => !t48?.coupledSection)) continue;
    const sections = rails.map(
      (t48) => t48.route.slice(t48.coupledSection[0], t48.coupledSection[1] + 1)
    );
    const width = sections[0][0].width;
    if (sections[0].length !== sections[1].length || sections.flat().some(
      (p2) => p2.route_type !== "wire" || p2.width !== width || p2.layer !== sections[0][0].layer
    ))
      continue;
    const center = sections[0].map((p2, i2) => ({
      x: (p2.x + sections[1][i2].x) / 2,
      y: (p2.y + sections[1][i2].y) / 2
    }));
    const halfSpacing = (width + (pair.traceGap ?? clearance)) / 2;
    const offsets = [-halfSpacing, halfSpacing].sort(
      (a2, b2) => distance(offsetPath(center, a2)[0], sections[0][0]) - distance(offsetPath(center, b2)[0], sections[0][0])
    );
    const other = result.filter((_2, i2) => !indices.includes(i2)).flatMap(routeCopper);
    for (let i2 = 1; i2 + 2 < center.length; i2++) {
      if (rails.some(
        (t48) => t48.curvedSegments?.some(
          (k2) => k2 >= t48.coupledSection[0] + i2 && k2 <= t48.coupledSection[0] + i2 + 2
        )
      ))
        continue;
      const [a2, b2, c2, d2] = center.slice(i2 - 1, i2 + 3);
      const before = distance(a2, b2), after = distance(c2, d2);
      if (Math.min(before, after) < 1e-8) continue;
      const u2 = { x: (b2.x - a2.x) / before, y: (b2.y - a2.y) / before };
      const v2 = { x: (d2.x - c2.x) / after, y: (d2.y - c2.y) / after };
      if (u2.x * v2.x + u2.y * v2.y > -1 + 1e-8) continue;
      const n2 = { x: -u2.y, y: u2.x };
      const separation = (c2.x - b2.x) * n2.x + (c2.y - b2.y) * n2.y;
      const turn = Math.sign(separation), radius = Math.abs(separation) / 2;
      if (radius < halfSpacing / Math.cos(Math.PI / (2 * chords)) + (width + clearance) / 2 + 1e-8)
        continue;
      const advance = (b2.x - c2.x) * u2.x + (b2.y - c2.y) * u2.y;
      const trimBefore = Math.max(0, advance), trimAfter = Math.max(0, -advance);
      if (trimBefore >= before - 1e-8 || trimAfter >= after - 1e-8) continue;
      const start = { x: b2.x - u2.x * trimBefore, y: b2.y - u2.y * trimBefore };
      const end = { x: c2.x + v2.x * trimAfter, y: c2.y + v2.y * trimAfter };
      const origin = {
        x: start.x + n2.x * radius * turn,
        y: start.y + n2.y * radius * turn
      };
      const angle = Math.atan2(start.y - origin.y, start.x - origin.x);
      const arc = Array.from({ length: chords + 1 }, (_2, k2) => ({
        x: origin.x + radius * Math.cos(angle + turn * Math.PI * k2 / chords),
        y: origin.y + radius * Math.sin(angle + turn * Math.PI * k2 / chords)
      }));
      arc[0] = start;
      arc[chords] = end;
      const points = [...center.slice(0, i2), ...arc, ...center.slice(i2 + 2)];
      const delta = chords - 1;
      const candidate = rails.map((t48, side) => {
        const [s2, e2] = t48.coupledSection;
        const mid = offsetPath(points, offsets[side]).map((p2) => ({
          ...p2,
          route_type: "wire",
          layer: sections[side][0].layer,
          width
        }));
        mid[0] = { ...t48.route[s2] };
        mid[mid.length - 1] = { ...t48.route[e2] };
        return {
          ...t48,
          route: [...t48.route.slice(0, s2), ...mid, ...t48.route.slice(e2 + 1)],
          coupledSection: [s2, e2 + delta],
          curvedSegments: [
            ...(t48.curvedSegments ?? []).map(
              (k2) => k2 > s2 + i2 + 1 ? k2 + delta : k2
            ),
            ...Array.from({ length: chords }, (_2, k2) => s2 + i2 + k2 + 1)
          ].sort((a3, b3) => a3 - b3)
        };
      });
      const copper = [...fixed, ...other, ...candidate.flatMap(routeCopper)];
      if (candidate.some(
        (t48) => !tuningPathIsSelfClear(t48.route, width + clearance) || !new VectorScene(
          input,
          input.connections.find((c3) => c3.name === t48.connection_name),
          width,
          copper
        ).pathVisible(t48.route)
      ))
        continue;
      if (sharedPairSpacingReports(
        { ...input, differentialPairs: [pair] },
        candidate
      ).some((p2) => !p2.matched))
        continue;
      indices.forEach((index2, side) => {
        result[index2] = candidate[side];
      });
      break;
    }
  }
  return result;
}

// lib/eject-blocking-lanes.ts
function* ejectBlockingLanes(input, initial, fixed, widths, layers = /* @__PURE__ */ new Map(), options = {}) {
  let searches = 0;
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  function* route(connection, retained, layer) {
    if (++searches > (options.maxSearches ?? 200)) return null;
    const local = {
      ...connection,
      pointsToConnect: connection.pointsToConnect.map((p2) => ({ ...p2, layer }))
    };
    const width = widths.get(connection.name) ?? input.minTraceWidth;
    const scene = new VectorScene(input, local, width, [
      ...fixed,
      ...retained.flatMap(routeCopper)
    ]);
    const search = new GridVisibilitySearch(
      scene,
      local.pointsToConnect[0],
      local.pointsToConnect[1]
    );
    try {
      let steps = 0;
      while (!search.solved && !search.failed && steps++ < 1e3) {
        search.step();
        yield;
      }
      if (!search.solved) return null;
      const path = options.requireSelfClear ? reduceOrdinaryTurns(search.result, scene) : search.result;
      if (options.requireSelfClear && !tuningPathIsSelfClear(path, width + clearance))
        return null;
      return {
        type: "pcb_trace",
        pcb_trace_id: connection.name,
        connection_name: connection.name,
        source_trace_id: connection.source_trace_id,
        route: path.map((p2) => ({ ...p2, route_type: "wire", layer, width }))
      };
    } finally {
      search.cancel();
    }
  }
  function* fill(pending, traces, depth = 0, visited = /* @__PURE__ */ new Set()) {
    if (!pending.length) return traces;
    if (searches >= (options.maxSearches ?? 200)) return null;
    const connection = pending[0];
    const available = layers.get(connection.name) ?? [
      connection.pointsToConnect[0].layer
    ];
    for (const layer of available) {
      const path = yield* route(connection, traces, layer);
      if (!path) continue;
      const result = yield* fill(
        pending.slice(1),
        [...traces, path],
        depth,
        /* @__PURE__ */ new Set([...visited, connection.name])
      );
      if (result) return result;
    }
    if (depth >= (options.maxDepth ?? 5)) return null;
    for (const trace of traces) {
      if (trace.coupledSection || !trace.connection_name || visited.has(trace.connection_name) || !available.includes(trace.route[0].layer))
        continue;
      const displaced = input.connections.find(
        (c2) => c2.name === trace.connection_name
      );
      if (!displaced) continue;
      for (const layer of available) {
        const retained = traces.filter((t48) => t48 !== trace);
        const path = yield* route(connection, retained, layer);
        if (!path) continue;
        const result = yield* fill(
          [...pending.slice(1), displaced],
          [...retained, path],
          depth + 1,
          /* @__PURE__ */ new Set([...visited, connection.name])
        );
        if (result) return result;
      }
    }
    return null;
  }
  return yield* fill(
    input.connections.filter(
      (c2) => !initial.some((t48) => t48.connection_name === c2.name)
    ),
    initial
  );
}

// lib/finish-paired-network.ts
function* finishPairedNetwork(network, raw) {
  const { input, layers, transforms } = network, fixed = fixedCopper(input);
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const traces = structuredClone(raw), rejected = /* @__PURE__ */ new Set();
  const widths = new Map(
    input.connections.map((c2) => [
      c2.name,
      input.buses?.find((b2) => b2.connectionNames.includes(c2.name))?.traceWidth ?? c2.nominalTraceWidth ?? c2.width ?? input.minTraceWidth
    ])
  );
  for (const trace of traces) {
    if (trace.coupledSection) continue;
    const repaired2 = yield* repairGridJogs(
      input,
      [trace],
      [...fixed, ...traces.filter((t48) => t48 !== trace).flatMap(routeCopper)]
    );
    if (!repaired2) rejected.add(trace);
  }
  for (const trace of traces) {
    if (!trace.coupledSection) continue;
    for (const end of [0, 1]) {
      const [s3, e3] = trace.coupledSection;
      const path = end ? trace.route.slice(e3) : trace.route.slice(0, s3 + 1);
      const rest = end ? trace.route.slice(0, e3) : trace.route.slice(s3 + 1);
      const part = {
        ...trace,
        coupledSection: void 0,
        curvedSegments: void 0,
        route: path
      };
      const connection = {
        ...input.connections.find((c2) => c2.name === trace.connection_name),
        pointsToConnect: [path[0], path.at(-1)]
      };
      const partInput = { ...input, connections: [connection] };
      const copper = [
        ...fixed,
        ...traces.filter((t48) => t48 !== trace).flatMap(routeCopper),
        ...routeCopper({
          ...trace,
          connection_name: "reserved_other_approach",
          source_trace_id: void 0,
          route: rest
        })
      ];
      const repaired2 = yield* repairGridJogs(partInput, [part], copper);
      if (repaired2) {
        if (part.route !== path) {
          const delta = part.route.length - path.length;
          trace.curvedSegments = trace.curvedSegments?.flatMap(
            (k2) => end ? k2 <= e3 ? [k2] : [] : k2 > s3 ? [k2 + delta] : []
          );
        }
        trace.route = end ? [...trace.route.slice(0, e3), ...part.route] : [...part.route, ...trace.route.slice(s3 + 1)];
        if (!end)
          trace.coupledSection = [
            part.route.length - 1,
            e3 + part.route.length - path.length
          ];
      }
    }
    const [s2, e2] = trace.coupledSection, width = trace.route[0].width;
    const scene = new VectorScene(
      input,
      input.connections.find((c2) => c2.name === trace.connection_name),
      width,
      [...fixed, ...traces.flatMap(routeCopper)]
    );
    const prefix = trace.curvedSegments?.some((k2) => k2 <= s2) ? trace.route.slice(0, s2 + 1) : reduceOrdinaryTurns(trace.route.slice(0, s2 + 1), scene);
    const suffix = trace.curvedSegments?.some((k2) => k2 > e2) ? trace.route.slice(e2) : reduceOrdinaryTurns(trace.route.slice(e2), scene);
    trace.curvedSegments = trace.curvedSegments?.map(
      (k2) => k2 > s2 ? k2 + prefix.length - (s2 + 1) : k2
    );
    trace.route = [
      ...prefix.slice(0, -1),
      ...trace.route.slice(s2, e2 + 1),
      ...suffix.slice(1)
    ].map((p2) => ({
      ...p2,
      route_type: "wire",
      width,
      layer: trace.route[0].layer
    }));
    trace.coupledSection = [prefix.length - 1, prefix.length + e2 - s2 - 1];
  }
  const firstRepair = yield* ejectBlockingLanes(
    input,
    traces.filter((t48) => !rejected.has(t48)),
    fixed,
    widths,
    layers,
    { requireSelfClear: true, maxSearches: 1e3 }
  );
  if (!firstRepair) return null;
  let repaired = roundCoupledReturnBends(
    input,
    bevelCoupledCorners(input, firstRepair),
    fixed
  );
  const total = (t48) => length(t48.route) + fixedRouteLength(input, t48.connection_name);
  for (const transform2 of transforms) {
    const rails2 = transform2.pair.connectionNames.map(
      (n2) => repaired.find((t48) => t48.connection_name === n2)
    );
    const restored = rails2.map((t48) => {
      const old = transform2.rails.find(
        (r2) => r2.connection_name === t48.connection_name
      ), [s2, e2] = old.coupledSection, [a2, b2] = t48.coupledSection;
      const mid = t48.route.slice(a2, b2 + 1), delta = mid.length - (e2 - s2 + 1);
      return {
        ...t48,
        route: [...old.route.slice(0, s2), ...mid, ...old.route.slice(e2 + 1)],
        coupledSection: [s2, s2 + mid.length - 1],
        curvedSegments: [
          ...(old.curvedSegments ?? []).flatMap(
            (k2) => k2 <= s2 ? [k2] : k2 > e2 ? [k2 + delta] : []
          ),
          ...(t48.curvedSegments ?? []).filter((k2) => k2 > a2 && k2 <= b2).map((k2) => k2 + s2 - a2)
        ]
      };
    });
    if (Math.abs(total(restored[0]) - total(restored[1])) >= Math.abs(total(rails2[0]) - total(rails2[1])) - 1e-8)
      continue;
    const immutable = [
      ...fixed,
      ...repaired.filter((t48) => t48.coupledSection && !rails2.includes(t48)).flatMap(routeCopper),
      ...restored.flatMap(routeCopper)
    ];
    if (restored.some(
      (t48) => !tuningPathIsSelfClear(
        t48.route,
        t48.route[0].width + clearance
      ) || !new VectorScene(
        input,
        input.connections.find((c2) => c2.name === t48.connection_name),
        t48.route[0].width,
        immutable
      ).pathVisible(t48.route)
    ))
      continue;
    const candidate = repaired.map(
      (t48) => restored.find((r2) => r2.connection_name === t48.connection_name) ?? t48
    );
    const retained2 = candidate.filter(
      (t48) => t48.coupledSection || restored.every(
        (r2) => new VectorScene(
          input,
          input.connections.find((c2) => c2.name === r2.connection_name),
          r2.route[0].width,
          routeCopper(t48)
        ).pathVisible(r2.route)
      )
    );
    const repairedCandidate = yield* ejectBlockingLanes(
      input,
      retained2,
      fixed,
      widths,
      layers,
      { requireSelfClear: true, maxSearches: 200 }
    );
    if (repairedCandidate) repaired = repairedCandidate;
  }
  const rails = repaired.filter((t48) => t48.coupledSection);
  const retained = repaired.filter(
    (t48) => t48.coupledSection || rails.every(
      (r2) => new VectorScene(
        input,
        input.connections.find((c2) => c2.name === r2.connection_name),
        r2.route[0].width,
        routeCopper(t48)
      ).pathVisible(r2.route)
    )
  );
  const firstComplete = yield* ejectBlockingLanes(
    input,
    retained,
    fixed,
    widths,
    layers,
    { requireSelfClear: true, maxSearches: 1e3 }
  );
  if (!firstComplete) return null;
  let complete = firstComplete;
  for (const transform2 of transforms.filter((t48) => !t48.approaches.length)) {
    const restored = complete.map(
      (t48) => transform2.rails.find((r2) => r2.connection_name === t48.connection_name) ?? t48
    );
    const retained2 = restored.filter(
      (t48) => t48.coupledSection || transform2.rails.every(
        (r2) => new VectorScene(
          input,
          input.connections.find((c2) => c2.name === r2.connection_name),
          r2.route[0].width,
          routeCopper(t48)
        ).pathVisible(r2.route)
      )
    );
    const nextComplete = yield* ejectBlockingLanes(
      input,
      retained2,
      fixed,
      widths,
      layers,
      { requireSelfClear: true, maxSearches: 1e3 }
    );
    if (!nextComplete) return null;
    complete = nextComplete;
  }
  for (const c2 of input.connections)
    for (const p2 of c2.pointsToConnect)
      p2.layer = complete.find((t48) => t48.connection_name === c2.name).route[0].layer;
  return complete;
}

// lib/route-paired-network.ts
function* routePairedNetwork(input, layers) {
  const network = yield* preparePairedNetwork(input, layers);
  if (!network) return null;
  const { local, copper, widths } = network;
  const negotiate = negotiateLanes(
    local,
    local.connections,
    copper,
    [],
    widths,
    void 0,
    layers,
    () => false,
    true
  );
  let raw = null, best = 0;
  try {
    let state = negotiate.next(), steps = 0;
    while (!state.done && steps++ < 2e5) {
      if (state.value.length > best) {
        best = state.value.length;
        if (best >= local.connections.length - 1) {
          raw = yield* ejectBlockingLanes(
            local,
            state.value,
            copper,
            widths,
            layers,
            { maxSearches: 120 }
          );
          if (raw) break;
        }
      }
      yield;
      state = negotiate.next();
    }
    if (state.done) raw = state.value;
  } finally {
    negotiate.return(null);
  }
  if (!raw) return null;
  const rebuilt = yield* rebuildPairedNetwork(network, raw);
  if (!rebuilt) return null;
  return yield* finishPairedNetwork(network, rebuilt);
}

// lib/tighten-pair-approaches.ts
function tightenPairApproaches(input, members, traces, fixed, width, gap, clearance) {
  const result = traces.map((t48) => ({
    ...t48,
    route: t48.route.map((p2) => ({ ...p2 }))
  }));
  const pitch = width + gap;
  const cross4 = (a2, b2) => a2.x * b2.y - a2.y * b2.x;
  const sub = (a2, b2) => ({ x: a2.x - b2.x, y: a2.y - b2.y });
  for (let rail = 0; rail < 2; rail++) {
    const trace = result[rail];
    for (let k2 = 1; k2 + 2 < trace.route.length; k2++) {
      if (trace.coupledSection && k2 + 1 >= trace.coupledSection[0] && k2 <= trace.coupledSection[1])
        continue;
      const [before, a2, b2, after] = trace.route.slice(k2 - 1, k2 + 3);
      const span = distance(a2, b2);
      if (span < 4 * pitch) continue;
      const u2 = { x: (b2.x - a2.x) / span, y: (b2.y - a2.y) / span };
      const other = result[1 - rail].route;
      for (let j2 = 0; j2 + 1 < other.length; j2++) {
        const c2 = other[j2], d2 = other[j2 + 1], delta = sub(d2, c2);
        if (Math.abs(cross4(u2, delta)) > 1e-7) continue;
        const offset = cross4(u2, sub(c2, a2));
        if (Math.abs(offset) <= pitch + 1e-7 || Math.abs(offset) > 2 * pitch)
          continue;
        const projections = [c2, d2].map(
          (p2) => (p2.x - a2.x) * u2.x + (p2.y - a2.y) * u2.y
        );
        if (Math.min(span, Math.max(...projections)) - Math.max(0, Math.min(...projections)) < 4 * pitch)
          continue;
        const move = offset - Math.sign(offset) * pitch;
        const shifted = { x: a2.x - u2.y * move, y: a2.y + u2.x * move };
        const intersect = (origin, heading) => {
          const denominator = cross4(heading, u2);
          if (Math.abs(denominator) < 1e-8) return null;
          const t48 = cross4(sub(shifted, origin), u2) / denominator;
          return { x: origin.x + t48 * heading.x, y: origin.y + t48 * heading.y };
        };
        const start = intersect(before, sub(a2, before)), end = intersect(after, sub(b2, after));
        if (!start || !end || distance(start, a2) > 2 * pitch || distance(end, b2) > 2 * pitch)
          continue;
        const shiftedEnd = {
          ...b2,
          x: b2.x - u2.x * (2 * pitch + Math.abs(move)) - u2.y * move,
          y: b2.y - u2.y * (2 * pitch + Math.abs(move)) + u2.x * move
        };
        const returnEnd = {
          ...b2,
          x: b2.x - u2.x * 2 * pitch,
          y: b2.y - u2.y * 2 * pitch
        };
        for (const replacement of [
          [
            { ...a2, ...start },
            { ...b2, ...end }
          ],
          [{ ...a2, ...start }, shiftedEnd, returnEnd, b2]
        ]) {
          const forward = (from, to, heading) => (to.x - from.x) * heading.x + (to.y - from.y) * heading.y > 1e-10;
          if (!forward(before, replacement[0], sub(a2, before)) || !forward(replacement.at(-1), after, sub(after, b2)) || !forward(replacement[0], replacement.at(-1), u2))
            continue;
          const route = [
            ...trace.route.slice(0, k2),
            ...replacement,
            ...trace.route.slice(k2 + 2)
          ];
          if (!tuningPathIsSelfClear(route, width + clearance)) continue;
          if (!new VectorScene(input, members[rail], width, [
            ...fixed,
            ...routeCopper(result[1 - rail])
          ]).pathVisible(route))
            continue;
          trace.route = route;
          if (trace.coupledSection)
            trace.coupledSection = trace.coupledSection.map(
              (index2) => index2 > k2 ? index2 + replacement.length - 2 : index2
            );
          k2 += replacement.length - 2;
          break;
        }
        if (trace.route[k2] !== a2) break;
      }
    }
  }
  return result;
}

// lib/chamfer-pair-approaches.ts
function chamferPairApproaches(input, members, traces, fixed, width, clearance, maxTrimInTraceWidths = 6) {
  if (!Number.isFinite(maxTrimInTraceWidths) || maxTrimInTraceWidths <= 0)
    throw Error(
      "Pair corner trim must be a positive finite number of trace widths"
    );
  const result = traces.map((t48) => ({ ...t48, route: [...t48.route] }));
  for (let rail = 0; rail < 2; rail++) {
    const trace = result[rail];
    for (let i2 = 1; i2 < trace.route.length - 1; i2++) {
      if (trace.curvedSegments?.includes(i2) || trace.curvedSegments?.includes(i2 + 1))
        continue;
      if (trace.coupledSection && i2 > trace.coupledSection[0] && i2 < trace.coupledSection[1])
        continue;
      const [a2, b2, c2] = trace.route.slice(i2 - 1, i2 + 2), before = distance(a2, b2), after = distance(b2, c2);
      if (before < 1e-8 || after < 1e-8) continue;
      const u2 = { x: (b2.x - a2.x) / before, y: (b2.y - a2.y) / before }, v2 = { x: (c2.x - b2.x) / after, y: (c2.y - b2.y) / after };
      if (Math.abs(u2.x * v2.x + u2.y * v2.y + Math.SQRT1_2) > 1e-6) continue;
      const turn = Math.sign(u2.x * v2.y - u2.y * v2.x);
      const trim = Math.min(
        width * maxTrimInTraceWidths,
        before / 2,
        after * 0.8
      );
      const start = { ...b2, x: b2.x - u2.x * trim, y: b2.y - u2.y * trim };
      const bevel2 = (Math.SQRT2 - 1) * trim;
      const middle = {
        ...b2,
        x: start.x + (u2.x - turn * u2.y) * Math.SQRT1_2 * bevel2,
        y: start.y + (u2.y + turn * u2.x) * Math.SQRT1_2 * bevel2
      };
      const end = { ...b2, x: b2.x + v2.x * trim, y: b2.y + v2.y * trim };
      const route = [
        ...trace.route.slice(0, i2),
        start,
        middle,
        end,
        ...trace.route.slice(i2 + 1)
      ];
      if (!tuningPathIsSelfClear(route, width + clearance) || !new VectorScene(input, members[rail], width, [
        ...fixed,
        ...routeCopper(result[1 - rail])
      ]).pathVisible(route))
        continue;
      trace.route = route;
      if (trace.curvedSegments)
        trace.curvedSegments = trace.curvedSegments.map(
          (index2) => index2 > i2 ? index2 + 2 : index2
        );
      if (trace.coupledSection)
        trace.coupledSection = trace.coupledSection.map(
          (index2, boundary) => index2 > i2 ? index2 + 2 : index2 === i2 && boundary === 0 ? index2 + 2 : index2
        );
      i2 += 2;
    }
  }
  return result;
}

// lib/extend-pair-approaches.ts
function extendPairApproaches(input, members, traces, fixed, width, gap, clearance, offsetPath2) {
  const result = traces.map((t48) => ({ ...t48, route: [...t48.route] }));
  const pitch = width + gap;
  for (let leader = 0; leader < 2; leader++) {
    const first = result[leader], mate = result[1 - leader];
    if (!first.coupledSection || !mate.coupledSection) continue;
    const start = first.coupledSection[1] - 1, mateStart = mate.coupledSection[1] - 1;
    for (let i2 = first.coupledSection[1] + 1; i2 < first.route.length - 1; i2++) {
      const a2 = first.route[i2], b2 = first.route[i2 + 1], span = distance(a2, b2);
      if (span < 4 * pitch) continue;
      const u2 = { x: (b2.x - a2.x) / span, y: (b2.y - a2.y) / span };
      for (let j2 = mate.coupledSection[1] + 1; j2 < mate.route.length - 1; j2++) {
        const c2 = mate.route[j2], d2 = mate.route[j2 + 1], otherSpan = distance(c2, d2);
        if (otherSpan < 4 * pitch || Math.abs((d2.x - c2.x) / otherSpan - u2.x) > 1e-7 || Math.abs((d2.y - c2.y) / otherSpan - u2.y) > 1e-7)
          continue;
        const offset = -(c2.x - a2.x) * u2.y + (c2.y - a2.y) * u2.x;
        if (Math.abs(Math.abs(offset) - pitch) > 1e-7) continue;
        const projection = (p2) => (p2.x - a2.x) * u2.x + (p2.y - a2.y) * u2.y;
        if (projection(d2) < span - 1e-7 || projection(c2) > span - 4 * pitch)
          continue;
        let shared;
        try {
          shared = offsetPath2(first.route.slice(start, i2 + 2), offset);
        } catch {
          continue;
        }
        const originalStart = mate.route[mateStart], originalEnd = mate.route[mateStart + 1];
        const dx2 = originalEnd.x - originalStart.x, dy2 = originalEnd.y - originalStart.y;
        if (Math.abs(
          (shared[0].x - originalStart.x) * dy2 - (shared[0].y - originalStart.y) * dx2
        ) > 1e-7)
          continue;
        const firstDirection = {
          x: shared[1].x - shared[0].x,
          y: shared[1].y - shared[0].y
        };
        if ((shared[1].x - originalStart.x) * firstDirection.x + (shared[1].y - originalStart.y) * firstDirection.y <= 1e-10)
          continue;
        shared = shared.slice(1);
        const route = [
          ...mate.route.slice(0, mateStart + 1),
          ...shared.map((p2) => ({ ...mate.route[0], ...p2 })),
          ...mate.route.slice(
            distance(shared.at(-1), mate.route[j2 + 1]) < 1e-8 ? j2 + 2 : j2 + 1
          )
        ];
        if (!tuningPathIsSelfClear(route, width + clearance) || !new VectorScene(input, members[1 - leader], width, [
          ...fixed,
          ...routeCopper(first)
        ]).pathVisible(route))
          continue;
        mate.route = route;
        mate.coupledSection = [
          mate.coupledSection[0],
          mateStart + shared.length
        ];
        first.coupledSection = [first.coupledSection[0], i2 + 1];
        return result;
      }
    }
  }
  return traces;
}

// lib/align-pair-transitions.ts
var along = (p2, u2) => p2.x * u2.x + p2.y * u2.y;
var firstApproachJog = (trace) => {
  if (!trace.coupledSection) return;
  const end = trace.coupledSection[1];
  if (end < 1 || end + 2 >= trace.route.length) return;
  const a2 = trace.route[end - 1], b2 = trace.route[end], span = distance(a2, b2);
  if (span < 1e-8) return;
  const u2 = { x: (b2.x - a2.x) / span, y: (b2.y - a2.y) / span };
  for (let i2 = end; i2 + 2 < trace.route.length; i2++) {
    const [p2, q2, r2] = trace.route.slice(i2, i2 + 3);
    const size = distance(p2, q2);
    if (size < 1e-8) return;
    const v2 = { x: (q2.x - p2.x) / size, y: (q2.y - p2.y) / size };
    if (distance(v2, u2) < 1e-7) continue;
    const tail = distance(q2, r2);
    if (tail < 1e-8) return;
    const w2 = { x: (r2.x - q2.x) / tail, y: (r2.y - q2.y) / tail };
    if (Math.abs(u2.x * v2.x + u2.y * v2.y - Math.SQRT1_2) > 1e-7 || distance(w2, u2) > 1e-7 || trace.curvedSegments?.some(
      (index2) => index2 === i2 || index2 === i2 + 1 || index2 === i2 + 2
    ))
      return;
    return {
      index: i2,
      direction: u2,
      handedness: Math.sign(u2.x * v2.y - u2.y * v2.x)
    };
  }
};
function alignPairTransitions(input, members, traces, fixed, width, gap, clearance, offsetPath2) {
  const jogs = traces.map(firstApproachJog);
  if (!jogs[0] || !jogs[1] || jogs[0].handedness !== jogs[1].handedness || distance(jogs[0].direction, jogs[1].direction) > 1e-7)
    return traces;
  const u2 = jogs[0].direction, pitch = width + gap;
  const proposals = traces.map((trace, side) => {
    const jog = jogs[side], mateJog = jogs[1 - side], k2 = jog.index;
    if (k2 <= trace.coupledSection[1]) return;
    const mate = traces[1 - side], matePoint = mate.route[mateJog.index];
    const offset = -(trace.route[k2].x - matePoint.x) * u2.y + (trace.route[k2].y - matePoint.y) * u2.x;
    let reference;
    try {
      reference = offsetPath2(
        mate.route.slice(mateJog.index - 1, mateJog.index + 3),
        Math.sign(offset) * pitch
      );
    } catch {
      return;
    }
    const move = (along(reference[1], u2) - along(trace.route[k2], u2) + (along(reference[2], u2) - along(trace.route[k2 + 1], u2))) / 2;
    if (Math.abs(move) < 1e-8 || distance(trace.route[k2 - 1], trace.route[k2]) + move <= 1e-8 || distance(trace.route[k2 + 1], trace.route[k2 + 2]) - move <= 1e-8)
      return;
    const route = trace.route.map(
      (p2, i2) => i2 === k2 || i2 === k2 + 1 ? { ...p2, x: p2.x + u2.x * move, y: p2.y + u2.y * move } : p2
    );
    if (!tuningPathIsSelfClear(route, width + clearance) || !new VectorScene(input, members[side], width, [
      ...fixed,
      ...routeCopper(mate)
    ]).pathVisible(route))
      return;
    return { ...trace, route };
  });
  if (proposals.every((trace) => !trace)) return traces;
  const bounds = [
    traces,
    ...proposals.flatMap(
      (trace, side) => trace ? [traces.map((old, i2) => i2 === side ? trace : old)] : []
    )
  ].flatMap(
    (pair) => pair.flatMap((trace, side) => [
      trace.route[jogs[side].index],
      trace.route[jogs[side].index + 1]
    ]).map((p2) => along(p2, u2))
  );
  const lo = Math.min(...bounds) - pitch, hi = Math.max(...bounds) + pitch;
  const score = (pair) => {
    let maximum = 0;
    for (let side = 0; side < 2; side++) {
      const route = pair[side].route, mate = pair[1 - side].route, k2 = jogs[side].index;
      for (let i2 = k2 - 1; i2 <= k2 + 1; i2++) {
        const a2 = route[i2], b2 = route[i2 + 1], start = along(a2, u2), span = along(b2, u2) - start;
        if (span <= 0 || start > hi || start + span < lo) continue;
        const from = Math.max(0, (lo - start) / span), to = Math.min(1, (hi - start) / span);
        const count = Math.max(
          1,
          Math.ceil(distance(a2, b2) * (to - from) * 16 / pitch)
        );
        for (let n2 = 0; n2 <= count; n2++) {
          const t48 = from + (to - from) * n2 / count;
          const p2 = { x: a2.x + (b2.x - a2.x) * t48, y: a2.y + (b2.y - a2.y) * t48 };
          let closest = Infinity;
          for (let j2 = 1; j2 < mate.length; j2++)
            closest = Math.min(
              closest,
              pointSegmentDistance(p2, [mate[j2 - 1], mate[j2]])
            );
          maximum = Math.max(maximum, closest - width);
        }
      }
    }
    return maximum;
  };
  let result = traces, best = score(traces);
  for (let side = 0; side < 2; side++) {
    if (!proposals[side]) continue;
    const pair = traces.map(
      (trace, i2) => i2 === side ? proposals[side] : trace
    ), next = score(pair);
    if (next < best - 1e-7) {
      result = pair;
      best = next;
    }
  }
  return result;
}

// lib/refine-pair-approaches.ts
function refinePairApproaches(input, traces, fixed) {
  const result = [...traces];
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  for (const pair of input.differentialPairs ?? []) {
    const indices = pair.connectionNames.map(
      (name) => result.findIndex((t48) => t48.connection_name === name)
    );
    const rails = indices.map((i2) => result[i2]);
    if (rails.some((t48) => !t48?.coupledSection)) continue;
    const members = pair.connectionNames.map(
      (name) => input.connections.find((c2) => c2.name === name)
    );
    const copper = [
      ...fixed,
      ...result.filter((_2, i2) => !indices.includes(i2)).flatMap(routeCopper)
    ];
    const width = rails[0].route[0].width, gap = pair.traceGap ?? clearance;
    const tightened = tightenPairApproaches(
      input,
      members,
      rails,
      copper,
      width,
      gap,
      clearance
    );
    const chamfered = chamferPairApproaches(
      input,
      members,
      tightened,
      copper,
      width,
      clearance
    );
    const aligned = alignPairTransitions(
      input,
      members,
      chamfered,
      copper,
      width,
      gap,
      clearance,
      offsetPath
    );
    const extended = extendPairApproaches(
      input,
      members,
      aligned,
      copper,
      width,
      gap,
      clearance,
      offsetPath
    );
    indices.forEach((i2, k2) => {
      result[i2] = extended[k2];
    });
  }
  return result;
}

// lib/bevel-pair-approaches.ts
function bevelPairApproaches(input, traces, fixed, maxTrimInTraceWidths) {
  const result = [...traces];
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  for (const pair of input.differentialPairs ?? []) {
    const indices = pair.connectionNames.map(
      (name) => result.findIndex((trace) => trace.connection_name === name)
    );
    const rails = indices.map((index2) => result[index2]);
    if (rails.some((trace) => !trace?.coupledSection)) continue;
    const members = pair.connectionNames.map(
      (name) => input.connections.find((connection) => connection.name === name)
    );
    const copper = [
      ...fixed,
      ...result.filter((_2, index2) => !indices.includes(index2)).flatMap(routeCopper)
    ];
    const beveled = chamferPairApproaches(
      input,
      members,
      rails,
      copper,
      rails[0].route[0].width,
      clearance,
      maxTrimInTraceWidths
    );
    indices.forEach((index2, side) => {
      result[index2] = beveled[side];
    });
  }
  return result;
}

// lib/staggered-bank-entries.ts
function staggeredBankEntries(lanes, clearance) {
  const edges = lanes.map(() => /* @__PURE__ */ new Set());
  const incoming = lanes.map(() => 0);
  const connect = (a2, b2) => {
    if (!edges[a2].has(b2)) {
      edges[a2].add(b2);
      incoming[b2]++;
    }
  };
  for (let i2 = 0; i2 < lanes.length; i2++) {
    const a2 = lanes[i2];
    if (Math.abs(a2.to - a2.from) < 1e-8) continue;
    for (let j2 = 0; j2 < lanes.length; j2++) {
      if (i2 === j2) continue;
      const b2 = lanes[j2], margin = (a2.width + b2.width) / 2 + clearance;
      const between = (y2) => y2 > Math.min(a2.from, a2.to) - margin + 1e-8 && y2 < Math.max(a2.from, a2.to) + margin - 1e-8;
      if (between(b2.from)) connect(j2, i2);
      if (between(b2.to)) connect(i2, j2);
    }
  }
  const depths = lanes.map(() => 0), ready = incoming.flatMap((n2, i2) => n2 === 0 ? [i2] : []);
  let count = 0;
  for (let k2 = 0; k2 < ready.length; k2++) {
    const i2 = ready[k2];
    count++;
    for (const j2 of edges[i2]) {
      depths[j2] = Math.max(
        depths[j2],
        depths[i2] + (lanes[i2].width + lanes[j2].width) / 2 + clearance
      );
      if (--incoming[j2] === 0) ready.push(j2);
    }
  }
  return count === lanes.length ? depths : null;
}

// lib/remap-curved-segments.ts
function remapCurvedSegments(trace, route) {
  const chords = (trace.curvedSegments ?? []).flatMap(
    (i2) => i2 > 0 && i2 < trace.route.length ? [[trace.route[i2 - 1], trace.route[i2]]] : []
  );
  if (!chords.length) return [];
  const curved = new Set(trace.curvedSegments);
  return route.slice(1).flatMap((b2, i2) => {
    const a2 = route[i2];
    if (chords.some(
      ([a0, b0]) => distance(a2, a0) < 1e-7 && distance(b2, b0) < 1e-7
    ))
      return [i2 + 1];
    const start = trace.route.findIndex((p2) => distance(p2, a2) < 1e-7);
    const end = trace.route.findIndex((p2) => distance(p2, b2) < 1e-7);
    if (start < 0 || end <= start) return [];
    for (let k2 = start + 1; k2 <= end; k2++)
      if (!curved.has(k2) || pointSegmentDistanceToPoints(trace.route[k2 - 1], a2, b2) > 1e-10 || pointSegmentDistanceToPoints(trace.route[k2], a2, b2) > 1e-10)
        return [];
    return [i2 + 1];
  });
}

// lib/coalesce-shared-runs.ts
function coalesceSharedRuns(rails) {
  return rails.map((trace) => {
    const [start, end] = trace.coupledSection;
    const keep = trace.route.map((_2, i2) => i2).filter((i2) => {
      if (i2 <= start || i2 >= end || trace.curvedSegments?.includes(i2) || trace.curvedSegments?.includes(i2 + 1))
        return true;
      const a2 = trace.route[i2 - 1], b2 = trace.route[i2], c2 = trace.route[i2 + 1], ab2 = distance(a2, b2), bc = distance(b2, c2);
      return ab2 < 1e-8 || bc < 1e-8 || Math.abs((b2.x - a2.x) / ab2 - (c2.x - b2.x) / bc) > 1e-7 || Math.abs((b2.y - a2.y) / ab2 - (c2.y - b2.y) / bc) > 1e-7;
    });
    return {
      ...trace,
      route: keep.map((i2) => trace.route[i2]),
      coupledSection: [keep.indexOf(start), keep.indexOf(end)],
      curvedSegments: trace.curvedSegments?.map((i2) => keep.indexOf(i2)).filter((i2) => i2 > 0)
    };
  });
}

// lib/shared-straight-section.ts
function sharedStraightSection(rails, spacing) {
  rails = coalesceSharedRuns(rails);
  let best;
  for (let i2 = rails[0].coupledSection[0]; i2 < rails[0].coupledSection[1]; i2++) {
    const a2 = rails[0].route[i2], b2 = rails[0].route[i2 + 1], span = distance(a2, b2);
    if (span < 1e-8 || rails[0].curvedSegments?.includes(i2 + 1)) continue;
    const u3 = { x: (b2.x - a2.x) / span, y: (b2.y - a2.y) / span };
    const projection = (p2) => p2.x * u3.x + p2.y * u3.y;
    for (let j2 = rails[1].coupledSection[0]; j2 < rails[1].coupledSection[1]; j2++) {
      const c2 = rails[1].route[j2], d2 = rails[1].route[j2 + 1], otherSpan = distance(c2, d2);
      if (otherSpan < 1e-8 || rails[1].curvedSegments?.includes(j2 + 1)) continue;
      if (Math.abs((d2.x - c2.x) / otherSpan - u3.x) > 1e-7 || Math.abs((d2.y - c2.y) / otherSpan - u3.y) > 1e-7)
        continue;
      if (Math.abs(Math.abs((c2.x - a2.x) * u3.y - (c2.y - a2.y) * u3.x) - spacing) > 1e-7)
        continue;
      const low2 = Math.max(projection(a2), projection(c2)), high2 = Math.min(projection(b2), projection(d2));
      if (high2 - low2 > 1e-8 && (!best || high2 - low2 > best.high - best.low))
        best = { indices: [i2, j2], low: low2, high: high2, direction: u3 };
    }
  }
  if (!best) return null;
  const { indices, low, high, direction: u2 } = best;
  return rails.map((trace, side) => {
    const index2 = indices[side], a2 = trace.route[index2], b2 = trace.route[index2 + 1];
    const point = (projection) => {
      const advance = projection - a2.x * u2.x - a2.y * u2.y;
      return { ...a2, x: a2.x + advance * u2.x, y: a2.y + advance * u2.y };
    };
    const start = point(low), end = point(high);
    const before = trace.route.slice(0, index2), after = trace.route.slice(index2 + 2);
    if (distance(a2, start) > 1e-8) before.push(a2);
    if (distance(b2, end) > 1e-8) after.unshift(b2);
    const route = [...before, start, end, ...after], change = route.length - trace.route.length;
    return {
      ...trace,
      route,
      coupledSection: [before.length, before.length + 1],
      curvedSegments: trace.curvedSegments?.map(
        (k2) => k2 > index2 + 1 ? k2 + change : k2
      )
    };
  });
}

// lib/inter-package-tuning-window.ts
function interPackageTuningWindow(input, traces, along2, margin) {
  const physicalPorts = /* @__PURE__ */ new Map();
  for (const pad of input.obstacles) {
    const port = pad.circuitJsonMetadata?.pcb_port_id;
    if (port && pad.componentId) physicalPorts.set(port, pad.componentId);
  }
  const componentAt = (trace, last) => {
    const endpoint = last ? trace.route.at(-1) : trace.route[0];
    const connection = input.connections.find(
      (c2) => c2.name === trace.connection_name
    );
    const terminal = connection?.pointsToConnect.slice().sort((a2, b2) => distance(endpoint, a2) - distance(endpoint, b2))[0];
    const port = terminal?.pcb_port_id ?? endpoint.pcb_port_id;
    const owner = port ? physicalPorts.get(port) : void 0;
    if (owner) return owner;
    const aliases = new Set(
      [
        trace.connection_name,
        trace.source_trace_id,
        connection?.source_trace_id,
        terminal?.pointId,
        terminal?.pcb_port_id
      ].filter((alias) => !!alias)
    );
    return input.obstacles.filter(
      (pad) => pad.componentId && pad.connectedTo.some((alias) => aliases.has(alias))
    ).sort(
      (a2, b2) => distance(endpoint, a2.center) - distance(endpoint, b2.center)
    )[0]?.componentId;
  };
  const localCopper = fixedCopper(input).filter(
    (copper) => copper.a.x === copper.b.x && copper.a.y === copper.b.y
  );
  const extent = (ids) => {
    let min = Infinity, max = -Infinity;
    for (const id of ids) {
      const pads = input.obstacles.filter((pad) => pad.componentId === id);
      if (!pads.length) continue;
      const envelopes = pads.map((pad) => {
        const angle = (pad.ccwRotationDegrees ?? 0) * Math.PI / 180;
        const width = Math.abs(Math.cos(angle)) * pad.width + Math.abs(Math.sin(angle)) * pad.height;
        const height = Math.abs(Math.sin(angle)) * pad.width + Math.abs(Math.cos(angle)) * pad.height;
        return {
          left: pad.center.x - width / 2,
          right: pad.center.x + width / 2,
          bottom: pad.center.y - height / 2,
          top: pad.center.y + height / 2
        };
      });
      const left = Math.min(...envelopes.map((pad) => pad.left)), right = Math.max(...envelopes.map((pad) => pad.right)), bottom = Math.min(...envelopes.map((pad) => pad.bottom)), top = Math.max(...envelopes.map((pad) => pad.top));
      const halo = Math.max(
        input.minViaPadDiameter ?? 0.3,
        ...pads.flatMap((pad) => [pad.width, pad.height])
      ) * 2;
      for (const x2 of [left, right])
        for (const y2 of [bottom, top]) {
          min = Math.min(min, along2({ x: x2, y: y2 }));
          max = Math.max(max, along2({ x: x2, y: y2 }));
        }
      for (const copper of localCopper) {
        const point = copper.a;
        if (point.x < left - halo || point.x > right + halo || point.y < bottom - halo || point.y > top + halo)
          continue;
        min = Math.min(min, along2(point) - copper.radius);
        max = Math.max(max, along2(point) + copper.radius);
      }
    }
    return { min, max };
  };
  const componentIds = (last) => new Set(
    traces.map((trace) => componentAt(trace, last)).filter((id) => !!id)
  );
  return {
    start: extent(componentIds(false)).max + margin,
    end: extent(componentIds(true)).min - margin
  };
}

// lib/spread-coupled-tuning-lanes.ts
function cut(path, u2) {
  const crossings = [];
  for (let i2 = 1; i2 < path.length; i2++) {
    const a2 = path[i2 - 1], b2 = path[i2];
    if (!(a2.x <= u2 && b2.x > u2)) continue;
    const point = { x: u2, y: a2.y + (b2.y - a2.y) * (u2 - a2.x) / (b2.x - a2.x) };
    crossings.push({
      before: [...path.slice(0, i2), point],
      after: [point, ...path.slice(i2)],
      point
    });
  }
  return crossings.length === 1 ? crossings[0] : void 0;
}
function bevel(path, size, lo, hi) {
  const points = simplify(
    path.filter((p2, i2) => i2 === 0 || distance(p2, path[i2 - 1]) > 1e-8)
  ), result = [points[0]];
  for (let i2 = 1; i2 < points.length - 1; i2++) {
    if (points[i2].x < lo - 1e-8 || points[i2].x > hi + 1e-8) {
      result.push(points[i2]);
      continue;
    }
    const a2 = points[i2 - 1], b2 = points[i2], c2 = points[i2 + 1];
    const da = distance(a2, b2), db2 = distance(b2, c2);
    const u2 = { x: (b2.x - a2.x) / da, y: (b2.y - a2.y) / da }, v2 = { x: (c2.x - b2.x) / db2, y: (c2.y - b2.y) / db2 };
    const dot2 = u2.x * v2.x + u2.y * v2.y;
    if (dot2 < -1e-6) return null;
    if (dot2 < 0.7) {
      const d2 = Math.min(size, da * 0.4, db2 * 0.4);
      result.push(
        { x: b2.x - u2.x * d2, y: b2.y - u2.y * d2 },
        { x: b2.x + v2.x * d2, y: b2.y + v2.y * d2 }
      );
    } else result.push(b2);
  }
  return [...result, points.at(-1)];
}
function spreadCoupledTuningLanes(input, traces, pitch, style = "dogleg", packUnconstrained = false) {
  let result = alignCoupledSectionBoundaries(input, structuredClone(traces));
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const busNames = new Set(input.buses?.flatMap((bus) => bus.connectionNames));
  const highDemandPairs = packUnconstrained ? highDemandPairedLanes(input, traces) : /* @__PURE__ */ new Set();
  const layers = new Set(
    result.filter((trace) => busNames.has(trace.connection_name)).map((trace) => trace.route[0].layer)
  );
  for (const layer of layers) {
    const members = result.filter((t48) => t48.route[0].layer === layer);
    if (members.length < 3) continue;
    const first = members[0].route[0], last = members[0].route.at(-1);
    const vertical = Math.abs(last.y - first.y) >= Math.abs(last.x - first.x);
    const sign = Math.sign(vertical ? last.y - first.y : last.x - first.x) || 1;
    const uv2 = (p2) => vertical ? { x: p2.y * sign, y: -p2.x * sign } : { x: p2.x * sign, y: p2.y * sign };
    const xy2 = (p2) => vertical ? { x: -p2.y * sign, y: p2.x * sign } : { x: p2.x * sign, y: p2.y * sign };
    const channels = [];
    const used = /* @__PURE__ */ new Set();
    for (const trace of members) {
      if (used.has(trace.connection_name)) continue;
      const pair = input.differentialPairs?.find(
        (p2) => p2.connectionNames.includes(trace.connection_name) && p2.connectionNames.every(
          (n2) => members.some((t48) => t48.connection_name === n2)
        )
      );
      let rails = pair?.connectionNames.map(
        (n2) => members.find((t48) => t48.connection_name === n2)
      );
      if (rails?.every((t48) => t48.coupledSection)) {
        rails = coalesceSharedRuns(rails);
        const existing = rails.map(
          (t48) => t48.route.slice(t48.coupledSection[0], t48.coupledSection[1] + 1)
        );
        const wholeCorridor = existing[0].length === existing[1].length && [0, existing[0].length - 1].every((i2) => {
          const a2 = existing[0][i2], b2 = existing[1][i2], q2 = existing[0][i2 === 0 ? 1 : i2 - 1], span = distance(a2, q2);
          return span > 1e-8 && Math.abs(
            ((b2.x - a2.x) * (q2.x - a2.x) + (b2.y - a2.y) * (q2.y - a2.y)) / span
          ) < 1e-7;
        }) && existing[0].slice(1).every((point, i2) => {
          const a2 = existing[0][i2], c2 = existing[1][i2], d2 = existing[1][i2 + 1];
          const first2 = distance(a2, point), second = distance(c2, d2);
          return first2 > 1e-8 && second > 1e-8 && Math.abs((point.x - a2.x) / first2 - (d2.x - c2.x) / second) < 1e-7 && Math.abs((point.y - a2.y) / first2 - (d2.y - c2.y) / second) < 1e-7;
        });
        if (!wholeCorridor) {
          const selected = sharedStraightSection(
            rails,
            trace.route[0].width + (pair.traceGap ?? clearance)
          );
          if (!selected) return null;
          rails = selected;
        }
        const sections = rails.map(
          (t48) => t48.route.slice(t48.coupledSection[0], t48.coupledSection[1] + 1)
        );
        if (sections[0].length !== sections[1].length) return null;
        const path = sections[0].map(
          (p2, i2) => uv2({
            x: (p2.x + sections[1][i2].x) / 2,
            y: (p2.y + sections[1][i2].y) / 2
          })
        );
        channels.push({
          traces: rails,
          path,
          width: 2 * trace.route[0].width + (pair.traceGap ?? clearance)
        });
        rails.forEach((t48) => used.add(t48.connection_name));
      } else {
        channels.push({
          traces: [trace],
          path: trace.route.map(uv2),
          width: trace.route[0].width
        });
        used.add(trace.connection_name);
      }
    }
    const width = Math.max(...members.map((t48) => t48.route[0].width));
    let start = Math.max(...channels.map((c2) => c2.path[0].x)) + width * 2;
    let end = Math.min(...channels.map((c2) => c2.path.at(-1).x)) - width * 2;
    const window2 = interPackageTuningWindow(
      input,
      members,
      (point) => uv2(point).x,
      Math.max(...channels.map((channel) => channel.width)) / 2 + clearance
    );
    start = Math.max(start, window2.start);
    end = Math.min(end, window2.end);
    if (end - start < pitch * 2) return null;
    let accepted;
    attempts: for (const trim of [0, 0.05, 0.1, 0.2]) {
      const lo = start + (end - start) * trim, hi = end - (end - start) * trim;
      const cuts = channels.map((c2) => ({
        channel: c2,
        a: cut(c2.path, lo),
        b: cut(c2.path, hi)
      }));
      if (cuts.some((c2) => !c2.a || !c2.b)) continue;
      cuts.sort((a2, b2) => a2.a.point.y - b2.a.point.y);
      if (cuts.some((c2, i2) => i2 > 0 && c2.b.point.y < cuts[i2 - 1].b.point.y))
        continue;
      const minV = Math.min(
        ...cuts.flatMap((c2) => [c2.a.point.y, c2.b.point.y])
      ), maxV = Math.max(...cuts.flatMap((c2) => [c2.a.point.y, c2.b.point.y]));
      const center = (minV + maxV) / 2, split = Math.floor(cuts.length / 2);
      const bankPositions = cuts.map(
        (_2, ordinal) => center + (ordinal - (cuts.length - 1) / 2) * pitch
      );
      const entries = style === "interior" ? staggeredBankEntries(
        cuts.map((c2, i2) => ({
          from: c2.a.point.y,
          to: bankPositions[i2],
          width: c2.channel.width
        })),
        clearance
      ) : null;
      const exits = style === "interior" ? staggeredBankEntries(
        cuts.map((c2, i2) => ({
          from: c2.b.point.y,
          to: bankPositions[i2],
          width: c2.channel.width
        })),
        clearance
      ) : null;
      if (style === "interior" && (!entries || !exits)) continue;
      for (const extra of style === "interior" ? [1] : [1, 2, 3]) {
        const extent = Math.max(
          (maxV - minV) / 2 + pitch,
          Math.ceil(cuts.length / 2) * pitch
        ) + extra * width;
        const replacements = [];
        for (const [side, group] of [
          [-1, cuts.slice(0, split).toReversed()],
          [1, cuts.slice(split)]
        ]) {
          const distances = group.map((_2, i2) => (group.length - 1 - i2) * pitch);
          for (let i2 = group.length - 2; i2 >= 0; i2--) {
            const inner = group[i2].channel, outer = group[i2 + 1].channel;
            const tuning = outer.traces.some(
              (t48) => busNames.has(t48.connection_name)
            );
            const paired = [inner, outer].some(
              (c2) => c2.traces.some((t48) => highDemandPairs.has(t48.connection_name))
            );
            const gap = packUnconstrained ? Math.max(
              (inner.width + outer.width) / 2 + clearance + width * 0.2,
              paired ? pitch * 2 : tuning ? pitch : 0
            ) : pitch;
            if (packUnconstrained) distances[i2] = distances[i2 + 1] + gap;
          }
          const sideExtent = Math.max(
            packUnconstrained ? distances[0] + pitch : extent,
            ...group.map(
              (c2, i2) => Math.max(
                side * (c2.a.point.y - center),
                side * (c2.b.point.y - center)
              ) + distances[i2] + width * 2
            )
          );
          const depths = group.map(() => 0);
          for (let i2 = group.length - 2; i2 >= 0; i2--)
            depths[i2] = depths[i2 + 1] + (group[i2].channel.width + group[i2 + 1].channel.width) / 2 + clearance + width * 1.2;
          for (const [i2, c2] of group.entries()) {
            const top = lo + depths[i2], bottom = hi - depths[i2];
            if (bottom - top < pitch) continue;
            const ordinal = cuts.indexOf(c2);
            const v2 = style !== "dogleg" ? center + (ordinal - (cuts.length - 1) / 2) * pitch : center + side * (sideExtent - distances[i2]);
            const lead = Math.abs(v2 - c2.a.point.y), tail = Math.abs(v2 - c2.b.point.y);
            const entry = lo + (entries ? entries[ordinal] : (v2 > c2.a.point.y ? cuts.length - 1 - ordinal : ordinal) * (width + clearance));
            const exit = hi - (exits ? exits[ordinal] : (v2 > c2.b.point.y ? cuts.length - 1 - ordinal : ordinal) * (width + clearance));
            if (style === "diagonal" && lead + tail >= exit - entry - 4 * width)
              continue;
            const diagonal = [
              ...c2.a.before,
              { x: entry, y: c2.a.point.y },
              { x: entry + lead, y: v2 },
              { x: exit - tail, y: v2 },
              { x: exit, y: c2.b.point.y },
              ...c2.b.after
            ];
            const path = bevel(
              style === "diagonal" ? diagonal : [
                ...c2.a.before,
                { x: style === "interior" ? entry : top, y: c2.a.point.y },
                { x: style === "interior" ? entry : top, y: v2 },
                { x: style === "interior" ? exit : bottom, y: v2 },
                {
                  x: style === "interior" ? exit : bottom,
                  y: c2.b.point.y
                },
                ...c2.b.after
              ],
              width * 1.5,
              lo,
              hi
            );
            if (!path) continue;
            const channel = c2.channel;
            if (channel.traces.length === 1) {
              const trace = channel.traces[0];
              replacements.push({
                ...trace,
                curvedSegments: remapCurvedSegments(trace, path.map(xy2)),
                route: path.map((p2) => ({
                  ...xy2(p2),
                  route_type: "wire",
                  layer: trace.route[0].layer,
                  width: trace.route[0].width
                }))
              });
            } else {
              const centerPath = path.map(xy2), rails = channel.traces;
              const separation = channel.width - rails[0].route[0].width;
              const offsets = [-separation / 2, separation / 2].sort(
                (a2, b2) => distance(
                  offsetPath(centerPath, a2)[0],
                  rails[0].route[rails[0].coupledSection[0]]
                ) - distance(
                  offsetPath(centerPath, b2)[0],
                  rails[0].route[rails[0].coupledSection[0]]
                )
              );
              for (const [k2, trace] of rails.entries()) {
                const [s2, e2] = trace.coupledSection, points = offsetPath(centerPath, offsets[k2]);
                if (distance(points[0], trace.route[s2]) > 1e-7 || distance(points.at(-1), trace.route[e2]) > 1e-7)
                  continue;
                replacements.push({
                  ...trace,
                  coupledSection: [s2, s2 + points.length - 1],
                  curvedSegments: remapCurvedSegments(trace, [
                    ...trace.route.slice(0, s2),
                    ...points,
                    ...trace.route.slice(e2 + 1)
                  ]),
                  route: [
                    ...trace.route.slice(0, s2),
                    ...points.map((p2) => ({
                      ...p2,
                      route_type: "wire",
                      layer: trace.route[0].layer,
                      width: trace.route[0].width
                    })),
                    ...trace.route.slice(e2 + 1)
                  ]
                });
              }
            }
          }
        }
        if (replacements.length !== members.length) continue;
        const combined = result.map(
          (t48) => replacements.find((r2) => r2.connection_name === t48.connection_name) ?? t48
        );
        const copper = [...fixedCopper(input), ...combined.flatMap(routeCopper)];
        const bad = replacements.filter(
          (t48) => !new VectorScene(
            input,
            input.connections.find((c2) => c2.name === t48.connection_name),
            t48.route[0].width,
            copper
          ).pathVisible(t48.route) || !tuningPathIsSelfClear(
            t48.route,
            t48.route[0].width + clearance
          )
        );
        if (bad.length) continue;
        accepted = combined;
        break attempts;
      }
    }
    if (!accepted) return null;
    result = accepted;
  }
  return result;
}

// lib/simplify-matched-traces.ts
function* ordinaryRunCandidates(a2, b2, original = []) {
  const dx2 = b2.x - a2.x, dy2 = b2.y - a2.y;
  const x2 = Math.abs(dx2), y2 = Math.abs(dy2), sx2 = Math.sign(dx2), sy2 = Math.sign(dy2);
  const offsets = new Set(
    Array.from({ length: 9 }, (_2, i2) => Math.abs(x2 - y2) * i2 / 8)
  );
  for (const p2 of original) {
    const offset = x2 >= y2 ? (p2.x - a2.x) * sx2 - (p2.y - a2.y) * sy2 : (p2.y - a2.y) * sy2 - (p2.x - a2.x) * sx2;
    if (offset >= 0 && offset <= Math.abs(x2 - y2)) offsets.add(offset);
  }
  for (const k2 of offsets) {
    yield simplify(
      x2 >= y2 ? [a2, { x: a2.x + sx2 * k2, y: a2.y }, { x: a2.x + sx2 * (k2 + y2), y: b2.y }, b2] : [
        a2,
        { x: a2.x, y: a2.y + sy2 * k2 },
        { x: b2.x, y: a2.y + sy2 * (k2 + x2) },
        b2
      ]
    );
  }
}
var gentleTurns = (points) => points.slice(1, -1).every((p2, i2) => {
  const a2 = points[i2], b2 = points[i2 + 2], scale2 = distance(a2, p2) * distance(p2, b2);
  return scale2 < 1e-12 || ((p2.x - a2.x) * (b2.x - p2.x) + (p2.y - a2.y) * (b2.y - p2.y)) / scale2 >= Math.SQRT1_2 - 1e-8;
});
function simplifyMatchedTraces(input, traces) {
  const result = structuredClone(traces);
  const fixed = fixedCopper(input);
  for (const trace of result) {
    if (trace.coupledSection) continue;
    const connection = input.connections.find(
      (c2) => c2.name === trace.connection_name
    );
    const width = trace.route[0].width;
    const scene = new VectorScene(input, connection, width, [
      ...fixed,
      ...result.flatMap(routeCopper)
    ]);
    const indexCurves = () => {
      const prefix = new Uint32Array(trace.route.length);
      for (const index2 of new Set(trace.curvedSegments)) prefix[index2] = 1;
      for (let i2 = 1; i2 < prefix.length; i2++) prefix[i2] += prefix[i2 - 1];
      return prefix;
    };
    let curvedPrefix = indexCurves();
    for (let pass = 0; pass < 3; pass++) {
      let changed = false;
      for (let i2 = 0; i2 < trace.route.length - 3; i2++) {
        for (let j2 = Math.min(trace.route.length - 1, i2 + 70); j2 >= i2 + 3; j2--) {
          if (curvedPrefix[j2] !== curvedPrefix[i2]) continue;
          const originalLength = length(trace.route.slice(i2, j2 + 1));
          let accepted = false;
          for (const replacement of ordinaryRunCandidates(
            trace.route[i2],
            trace.route[j2],
            trace.route.slice(i2, j2 + 1)
          )) {
            if (replacement.length >= j2 - i2 + 1 || Math.abs(length(replacement) - originalLength) > 1e-8 || !scene.pathVisible(replacement))
              continue;
            if (!gentleTurns([
              ...trace.route.slice(Math.max(0, i2 - 1), i2),
              ...replacement,
              ...trace.route.slice(j2 + 1, j2 + 2)
            ]))
              continue;
            const wire = trace.route[i2];
            const candidate = [
              ...trace.route.slice(0, i2),
              ...replacement.map((p2) => ({
                ...p2,
                route_type: "wire",
                layer: wire.layer,
                width
              })),
              ...trace.route.slice(j2 + 1)
            ];
            if (!tuningPathIsSelfClear(candidate, width / 2 + scene.margin))
              continue;
            const delta = replacement.length - (j2 - i2 + 1);
            trace.route = candidate;
            trace.curvedSegments = trace.curvedSegments?.map(
              (index2) => index2 > j2 ? index2 + delta : index2
            );
            curvedPrefix = indexCurves();
            changed = accepted = true;
            break;
          }
          if (accepted) break;
        }
      }
      if (!changed) break;
    }
  }
  return result;
}

// lib/bipolar-tuning.ts
function bipolarPairedLobes(a2, b2, spacing, deficit, lobes, side, minRadius) {
  const span = distance(a2, b2), radius = minRadius + spacing / 2, posts = 2 * lobes + 1;
  if (!Number.isFinite(span + spacing + deficit + minRadius) || spacing < 0 || deficit <= 0 || minRadius <= 0 || !Number.isInteger(lobes) || lobes < 1 || lobes > 64 || side !== 1 && side !== -1 || span < (4 * lobes + 2) * radius - 1e-9)
    return null;
  const ux2 = (b2.x - a2.x) / span, uy2 = (b2.y - a2.y) / span;
  const generate = (height2) => {
    const vertices = [{ x: 0, y: 0 }];
    let y2 = 0;
    for (let j2 = 0; j2 < posts; j2++) {
      const x2 = radius + (span - 2 * radius) * j2 / (posts - 1);
      vertices.push({ x: x2, y: y2 });
      y2 = j2 === posts - 1 ? 0 : j2 % 2 ? -height2 : height2;
      vertices.push({ x: x2, y: y2 });
    }
    vertices.push({ x: span, y: 0 });
    const rails2 = [[], []];
    const emit = (x2, y3, tx2, ty2) => {
      for (let k2 = 0; k2 < 2; k2++) {
        const offset = (k2 === 0 ? 1 : -1) * spacing / 2, px2 = x2 - side * ty2 * offset, py2 = side * y3 + tx2 * offset, p2 = { x: a2.x + ux2 * px2 - uy2 * py2, y: a2.y + uy2 * px2 + ux2 * py2 };
        if (!rails2[k2].length || distance(rails2[k2].at(-1), p2) > 1e-10)
          rails2[k2].push(p2);
      }
    };
    emit(0, 0, 1, 0);
    for (let i2 = 1; i2 < vertices.length - 1; i2++) {
      const p2 = vertices[i2 - 1], q2 = vertices[i2], s2 = vertices[i2 + 1], d1 = distance(p2, q2), d2 = distance(q2, s2), u2 = { x: (q2.x - p2.x) / d1, y: (q2.y - p2.y) / d1 }, v2 = { x: (s2.x - q2.x) / d2, y: (s2.y - q2.y) / d2 }, start = { x: q2.x - u2.x * radius, y: q2.y - u2.y * radius }, center = { x: start.x + v2.x * radius, y: start.y + v2.y * radius }, turn = u2.x * v2.y - u2.y * v2.x, angle = Math.atan2(start.y - center.y, start.x - center.x);
      for (let j2 = 0; j2 <= 18; j2++) {
        const theta = angle + turn * Math.PI / 2 * j2 / 18;
        emit(
          center.x + radius * Math.cos(theta),
          center.y + radius * Math.sin(theta),
          -turn * Math.sin(theta),
          turn * Math.cos(theta)
        );
      }
    }
    emit(span, 0, 1, 0);
    return rails2;
  };
  const correction = (4 * lobes + 2) * radius * (36 * Math.sin(Math.PI / 72) - 2), minHeight = 2 * radius, minAddition = 4 * lobes * minHeight + correction;
  if (minAddition > deficit + 1e-8) return null;
  let height = Math.max(minHeight, (deficit - correction) / (4 * lobes));
  let rails = generate(height);
  height = Math.max(
    minHeight,
    height + (deficit - Math.min(...rails.map((r2) => length(r2) - span))) / (4 * lobes)
  );
  return generate(height);
}

// lib/tune-coupled-lengths.ts
function tuneCoupledLengths(input, traces, options = {}) {
  const pairedInput = { ...input, buses: [] };
  let result = tuneSmoothLengths(
    input,
    traces,
    minimumLengthTargets(pairedInput, traces),
    options
  );
  let attempted = 0;
  const fixed = fixedCopper(input);
  const total = (trace) => length(trace.route) + fixedRouteLength(input, trace.connection_name);
  for (const pair of input.differentialPairs ?? []) {
    const indices = pair.connectionNames.map(
      (n2) => result.findIndex((t48) => t48.connection_name === n2)
    );
    const rails = indices.map((i2) => result[i2]);
    if (rails.some((t48) => !t48.coupledSection)) continue;
    const targets = minimumLengthTargets(input, result);
    const deficit = Math.max(
      ...rails.map((t48) => targets.get(t48.connection_name) - total(t48))
    );
    if (deficit < 1e-8) continue;
    const width = rails[0].route[0].width;
    const gap = pair.traceGap ?? input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
    const spacing = width + gap, clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
    let accepted;
    for (const folded of options.packMeanders ? [false, true] : [false]) {
      if (accepted) break;
      for (let i2 = rails[0].coupledSection[0]; i2 < rails[0].coupledSection[1] && !accepted; i2++) {
        const a2 = rails[0].route[i2], b2 = rails[0].route[i2 + 1], span = distance(a2, b2);
        if (span < width * 8) continue;
        const ux2 = (b2.x - a2.x) / span, uy2 = (b2.y - a2.y) / span;
        for (let j2 = rails[1].coupledSection[0]; j2 < rails[1].coupledSection[1] && !accepted; j2++) {
          const c2 = rails[1].route[j2], d2 = rails[1].route[j2 + 1], otherSpan = distance(c2, d2);
          if (otherSpan < width * 8 || Math.abs((d2.x - c2.x) / otherSpan - ux2) > 1e-6 || Math.abs((d2.y - c2.y) / otherSpan - uy2) > 1e-6)
            continue;
          const offset = -(c2.x - a2.x) * uy2 + (c2.y - a2.y) * ux2;
          if (Math.abs(Math.abs(offset) - spacing) > 1e-6) continue;
          const project = (p2) => (p2.x - a2.x) * ux2 + (p2.y - a2.y) * uy2;
          const lo = Math.max(0, project(c2)) + width * 2, hi = Math.min(span, project(d2)) - width * 2;
          if (hi - lo < width * 8) continue;
          const center = (x2) => ({
            x: a2.x + ux2 * x2 - uy2 * offset / 2,
            y: a2.y + uy2 * x2 + ux2 * offset / 2
          });
          function* patterns() {
            if (!folded)
              for (const fraction of [0.9, 0.65, 0.4])
                for (const lobes of options.packMeanders ? Array.from(
                  {
                    length: Math.max(
                      1,
                      Math.floor(
                        (hi - lo) * fraction / (4 * (Math.max(width * 1.2, clearance) + spacing / 2))
                      )
                    )
                  },
                  (_2, i3) => i3 + 1
                ).reverse() : Array.from({ length: 16 }, (_2, i3) => i3 + 1))
                  for (const side of [1, -1])
                    for (const createLobes of [
                      bipolarPairedLobes,
                      roundedPairedLobes,
                      smoothPairedLobes
                    ])
                      yield { fraction, lobes, createLobes, side };
            if (folded)
              for (const lobes of [1, 2, 3])
                for (const fraction of [0.9, 0.65, 0.4])
                  for (const side of [1, -1])
                    yield {
                      fraction,
                      lobes,
                      createLobes: foldedPairedLobes,
                      side
                    };
          }
          tuningCandidate: for (const {
            fraction,
            lobes,
            createLobes,
            side
          } of patterns()) {
            if (++attempted > (options.maxCandidates ?? Infinity))
              throw Error("Coupled tuning candidate budget exhausted");
            const margin = (hi - lo) * (1 - fraction) / 2;
            const waves = createLobes(
              center(lo + margin),
              center(hi - margin),
              spacing,
              deficit,
              lobes,
              side,
              Math.max(width * 1.2, clearance)
            );
            if (!waves) continue;
            const ordered = offset > 0 ? waves.toReversed() : waves;
            const candidate = rails.map((t48, k2) => {
              const segment = k2 === 0 ? i2 : j2, points = [
                ...t48.route.slice(0, segment + 1),
                ...ordered[k2],
                ...t48.route.slice(segment + 1)
              ];
              const added = points.length - t48.route.length;
              return {
                ...t48,
                coupledSection: [
                  t48.coupledSection[0],
                  t48.coupledSection[1] + added
                ],
                curvedSegments: points.slice(1).flatMap((p2, n2) => {
                  const dx2 = Math.abs(p2.x - points[n2].x), dy2 = Math.abs(p2.y - points[n2].y);
                  return Math.min(dx2, dy2) > 1e-8 && Math.abs(dx2 - dy2) > 1e-8 ? [n2 + 1] : [];
                }),
                route: points.map((p2) => ({
                  ...p2,
                  route_type: "wire",
                  layer: t48.route[0].layer,
                  width
                }))
              };
            });
            const copper = [
              ...fixed,
              ...result.filter((_2, n2) => !indices.includes(n2)).flatMap(routeCopper),
              ...candidate.flatMap(routeCopper)
            ];
            if (candidate.some(
              (t48, k2) => !new VectorScene(
                input,
                input.connections.find(
                  (c3) => c3.name === t48.connection_name
                ),
                width,
                copper
              ).pathVisible(t48.route) || !tuningPathIsSelfClear(t48.route, width + clearance) || total(t48) < targets.get(t48.connection_name) - 1e-6
            ))
              continue;
            if (Math.abs(total(candidate[0]) - total(candidate[1])) > pair.lengthTolerance + 1e-6)
              continue;
            accepted = candidate;
            break tuningCandidate;
          }
        }
      }
    }
    if (!accepted)
      throw Error(
        `No shared tuning corridor for ${pair.connectionNames.join(", ")}`
      );
    indices.forEach((index2, k2) => {
      result[index2] = accepted[k2];
    });
  }
  return tuneSmoothLengths(
    input,
    result,
    minimumLengthTargets(input, result),
    options
  );
}

// lib/pair-coupling.ts
function pairCouplingReports(input, traces) {
  const shared = sharedPairSpacingReports(input, traces);
  const all = [...input.traces ?? [], ...traces];
  const segments = (name) => all.filter((t48) => t48.connection_name === name || t48.source_trace_id === name).flatMap(
    (t48) => t48.route.slice(1).flatMap((b2, i2) => {
      const a2 = t48.route[i2];
      return a2.route_type === "wire" && b2.route_type === "wire" && a2.layer === b2.layer ? [{ a: a2, b: b2 }] : [];
    })
  );
  return (input.differentialPairs ?? []).filter(
    (p2) => p2.traceGap !== void 0 || p2.maxUncoupledLength !== void 0
  ).map((pair) => {
    const routes = pair.connectionNames.map(segments);
    const gap = pair.traceGap ?? input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
    const tolerance = Math.max(2e-3, gap * 0.1);
    const indexes = routes.map((route) => {
      const layers = new Set(route.map((s2) => s2.a.layer));
      return new Map(
        [...layers].map((layer) => [
          layer,
          new CopperIndex(
            route.filter((s2) => s2.a.layer === layer).map((s2) => ({
              ...s2,
              radius: s2.a.width / 2,
              layer,
              owners: []
            }))
          )
        ])
      );
    });
    const conductors = routes.map((route, index2) => {
      let uncoupled = 0, total = 0;
      for (const { a: a2, b: b2 } of route) {
        const span = distance(a2, b2), count = Math.max(1, Math.ceil(span / (tolerance / 2)));
        total += span;
        const mate = indexes[1 - index2].get(a2.layer);
        const spacing = (p2) => mate?.distanceToPoint(
          p2,
          (s2) => pointSegmentDistanceToPoints(p2, s2.a, s2.b) - (a2.width + s2.radius * 2) / 2,
          a2.width / 2
        ) ?? Infinity;
        for (let k2 = 0; k2 < count; k2++) {
          const t48 = (k2 + 0.5) / count, p2 = { x: a2.x + (b2.x - a2.x) * t48, y: a2.y + (b2.y - a2.y) * t48 };
          const error = Math.abs(spacing(p2) - gap);
          if (error + span / (2 * count) > tolerance)
            uncoupled += span / count;
        }
      }
      return {
        name: pair.connectionNames[index2],
        totalLengthMm: total,
        uncoupledLengthMm: uncoupled,
        coupledFraction: total ? 1 - uncoupled / total : 0
      };
    });
    return {
      connectionNames: pair.connectionNames,
      conductors,
      maxUncoupledLengthMm: pair.maxUncoupledLength ?? null,
      matched: shared.find(
        (report) => report.connectionNames === pair.connectionNames
      ).matched && (pair.maxUncoupledLength === void 0 || conductors.every(
        (c2) => c2.uncoupledLengthMm <= pair.maxUncoupledLength + 1e-8
      ))
    };
  });
}

// ../bus-lanes-solver/node_modules/@tscircuit/alphabet/dist/index.js
var svgAlphabet = {
  "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"
};
var lineAlphabet = {};
for (const letter in svgAlphabet) {
  lineAlphabet[letter] = [];
  const segs = svgAlphabet[letter].split("M").slice(1).map(
    (seg) => seg.split("L").map((pr) => pr.trim().split(" ").map(parseFloat))
  );
  for (const seg of segs) {
    for (let i2 = 0; i2 < seg.length - 1; i2++) {
      lineAlphabet[letter].push({
        x1: seg[i2][0],
        y1: 1 - seg[i2][1],
        x2: seg[i2 + 1][0],
        y2: 1 - seg[i2 + 1][1]
      });
    }
  }
}

// ../bus-lanes-solver/node_modules/iobuffer/lib/text.js
var encoder = new TextEncoder();

// ../bus-lanes-solver/node_modules/iobuffer/lib/iobuffer.js
var defaultByteLength = 1024 * 8;
var hostBigEndian = (() => {
  const array = new Uint8Array(4);
  const view = new Uint32Array(array.buffer);
  return !((view[0] = 1) & array[0]);
})();
var typedArrays = {
  int8: globalThis.Int8Array,
  uint8: globalThis.Uint8Array,
  int16: globalThis.Int16Array,
  uint16: globalThis.Uint16Array,
  int32: globalThis.Int32Array,
  uint32: globalThis.Uint32Array,
  uint64: globalThis.BigUint64Array,
  int64: globalThis.BigInt64Array,
  float32: globalThis.Float32Array,
  float64: globalThis.Float64Array
};

// ../bus-lanes-solver/node_modules/fast-png/lib/helpers/crc.js
var crcTable = [];
for (let n2 = 0; n2 < 256; n2++) {
  let c2 = n2;
  for (let k2 = 0; k2 < 8; k2++) {
    if (c2 & 1) {
      c2 = 3988292384 ^ c2 >>> 1;
    } else {
      c2 = c2 >>> 1;
    }
  }
  crcTable[n2] = c2;
}

// ../bus-lanes-solver/node_modules/fast-png/lib/helpers/decode_interlace_adam7.js
var uint16 = new Uint16Array([255]);
var uint8 = new Uint8Array(uint16.buffer);
var osIsLittleEndian = uint8[0] === 255;

// ../bus-lanes-solver/node_modules/fast-png/lib/helpers/decode_interlace_null.js
var uint162 = new Uint16Array([255]);
var uint82 = new Uint8Array(uint162.buffer);
var osIsLittleEndian2 = uint82[0] === 255;
var empty = new Uint8Array(0);

// ../bus-lanes-solver/node_modules/fast-png/lib/helpers/signature.js
var pngSignature = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10);

// ../bus-lanes-solver/node_modules/fast-png/lib/helpers/text.js
var latin1Decoder = new TextDecoder("latin1");

// ../bus-lanes-solver/node_modules/transformation-matrix/src/rotate.js
var { cos, sin, PI } = Math;

// ../bus-lanes-solver/node_modules/transformation-matrix/src/skew.js
var { tan } = Math;

// ../bus-lanes-solver/node_modules/graphics-debug/dist/chunk-WDTSQY35.js
var import_svgson = __toESM(require_svgson_umd(), 1);

// ../bus-lanes-solver/node_modules/@tscircuit/solver-utils/dist/index.js
var BaseSolver = class {
  MAX_ITERATIONS = 1e5;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  _setupDone = false;
  getSolverName() {
    return this.constructor.name;
  }
  setup() {
    if (this._setupDone) return;
    this._setup();
    this._setupDone = true;
  }
  /** Override this method to perform setup logic */
  _setup() {
  }
  /** DO NOT OVERRIDE! Override _step() instead */
  step() {
    if (!this._setupDone) {
      this.setup();
    }
    if (this.solved) return;
    if (this.failed) return;
    this.iterations++;
    try {
      this._step();
    } catch (e2) {
      this.error = `${this.getSolverName()} error: ${e2}`;
      this.failed = true;
      throw e2;
    }
    if (!this.solved && this.iterations >= this.MAX_ITERATIONS) {
      this.tryFinalAcceptance();
    }
    if (!this.solved && this.iterations >= this.MAX_ITERATIONS) {
      this.error = `${this.getSolverName()} ran out of iterations`;
      this.failed = true;
    }
    if ("computeProgress" in this) {
      this.progress = this.computeProgress();
    }
  }
  /** Override this method to implement solver logic */
  _step() {
  }
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  /**
   * Override this method to return the standardized output of the solver.
   * This method should only be called after the solver has completed successfully.
   * Returns null by default - solvers with outputs should override this method.
   */
  getOutput() {
    return null;
  }
  solve() {
    const startTime = Date.now();
    while (!this.solved && !this.failed) {
      this.step();
    }
    const endTime = Date.now();
    this.timeToSolve = endTime - startTime;
  }
  visualize() {
    return {
      lines: [],
      points: [],
      rects: [],
      circles: []
    };
  }
  /**
   * Called when the solver is about to fail, but we want to see if we have an
   * "acceptable" or "passable" solution. Mostly used for optimizers that
   * have an aggressive early stopping criterion.
   */
  tryFinalAcceptance() {
  }
  /**
   * A lightweight version of the visualize method that can be used to stream
   * progress
   */
  preview() {
    return {
      lines: [],
      points: [],
      rects: [],
      circles: []
    };
  }
};

// lib/winding-orders.ts
function windingOrders(connections) {
  if (!connections.length) return [[]];
  const orders = [];
  const seen = /* @__PURE__ */ new Set();
  const add = (order) => {
    const key = order.map((c2) => c2.name).join("\0");
    if (!seen.has(key)) {
      seen.add(key);
      orders.push(order);
    }
  };
  const direction = connections.reduce(
    (v2, c2) => ({
      x: v2.x + c2.pointsToConnect[1].x - c2.pointsToConnect[0].x,
      y: v2.y + c2.pointsToConnect[1].y - c2.pointsToConnect[0].y
    }),
    { x: 0, y: 0 }
  );
  const transverse = (c2) => -direction.y * c2.pointsToConnect[0].x + direction.x * c2.pointsToConnect[0].y;
  const sweep = [...connections].sort(
    (a2, b2) => a2.pointsToConnect[0].layer.localeCompare(b2.pointsToConnect[0].layer) || transverse(a2) - transverse(b2) || a2.name.localeCompare(b2.name)
  );
  const span = (endpoint, axis) => Math.max(...connections.map((c2) => c2.pointsToConnect[endpoint][axis])) - Math.min(...connections.map((c2) => c2.pointsToConnect[endpoint][axis]));
  const transverseAxis = span(0, "x") < 1e-7 && span(1, "x") < 1e-7 ? "y" : span(0, "y") < 1e-7 && span(1, "y") < 1e-7 ? "x" : void 0;
  if (transverseAxis) {
    const drift = connections.reduce(
      (s2, c2) => s2 + c2.pointsToConnect[1][transverseAxis] - c2.pointsToConnect[0][transverseAxis],
      0
    );
    if (Math.abs(drift) > 1e-7)
      add(
        [...connections].sort(
          (a2, b2) => a2.pointsToConnect[0].layer.localeCompare(
            b2.pointsToConnect[0].layer
          ) || -Math.sign(drift) * (a2.pointsToConnect[0][transverseAxis] - b2.pointsToConnect[0][transverseAxis]) || a2.name.localeCompare(b2.name)
        )
      );
  }
  add(sweep);
  add([...sweep].reverse());
  add(connections);
  for (const endpoint of [1, 0]) {
    const center = connections.reduce(
      (p2, c2) => ({
        x: p2.x + c2.pointsToConnect[endpoint].x / connections.length,
        y: p2.y + c2.pointsToConnect[endpoint].y / connections.length
      }),
      { x: 0, y: 0 }
    );
    const angle = (c2) => Math.atan2(
      c2.pointsToConnect[endpoint].y - center.y,
      c2.pointsToConnect[endpoint].x - center.x
    );
    const angular = [...connections].sort(
      (a2, b2) => angle(a2) - angle(b2) || a2.name.localeCompare(b2.name)
    );
    add(angular);
    add([...angular].reverse());
    for (const axis of ["x", "y"]) {
      const other = axis === "x" ? "y" : "x";
      const sorted = [...connections].sort(
        (a2, b2) => a2.pointsToConnect[endpoint][axis] - b2.pointsToConnect[endpoint][axis] || a2.pointsToConnect[endpoint][other] - b2.pointsToConnect[endpoint][other]
      );
      add(sorted);
      add([...sorted].reverse());
    }
    for (let i2 = 1; i2 < angular.length; i2++) {
      const rotated = [...angular.slice(i2), ...angular.slice(0, i2)];
      add(rotated);
      add([...rotated].reverse());
    }
  }
  return orders;
}

// lib/spread-tuning-lanes.ts
function spreadTuningLanes(input, traces, pitch) {
  if (input.buses?.length && hasTerminalInsidePadField(input, traces))
    return spreadCoupledTuningLanes(input, traces, pitch);
  const dx2 = traces.reduce((s2, t48) => s2 + t48.route.at(-1).x - t48.route[0].x, 0);
  const dy2 = traces.reduce((s2, t48) => s2 + t48.route.at(-1).y - t48.route[0].y, 0);
  const angle = Math.round(Math.atan2(dy2, dx2) / (Math.PI / 4)) * Math.PI / 4, ux2 = Math.cos(angle), uy2 = Math.sin(angle);
  const uv2 = (p2) => ({ u: p2.x * ux2 + p2.y * uy2, v: -p2.x * uy2 + p2.y * ux2 });
  const xy2 = (u2, v2) => ({
    x: u2 * ux2 - v2 * uy2,
    y: u2 * uy2 + v2 * ux2
  });
  const result = [];
  for (const layer of new Set(traces.map((t48) => t48.route[0].layer))) {
    const group = traces.filter((t48) => t48.route[0].layer === layer).sort((a2, b2) => uv2(a2.route[0]).v - uv2(b2.route[0]).v);
    const center = group.reduce(
      (s2, t48) => s2 + (uv2(t48.route[0]).v + uv2(t48.route.at(-1)).v) / 2,
      0
    ) / group.length;
    for (const [index2, t48] of group.entries()) {
      const a2 = uv2(t48.route[0]), b2 = uv2(t48.route.at(-1)), v2 = center + (index2 - (group.length - 1) / 2) * pitch;
      const da = Math.abs(v2 - a2.v), db2 = Math.abs(v2 - b2.v), space = b2.u - a2.u - da - db2;
      if (space < 1) return null;
      const lead = space * 0.15;
      const points = simplify([
        xy2(a2.u, a2.v),
        xy2(a2.u + lead, a2.v),
        xy2(a2.u + lead + da, v2),
        xy2(b2.u - lead - db2, v2),
        xy2(b2.u - lead, b2.v),
        xy2(b2.u, b2.v)
      ]);
      result.push({
        ...t48,
        route: points.map((p2) => ({
          ...p2,
          route_type: "wire",
          layer,
          width: t48.route[0].width
        }))
      });
    }
  }
  const copper = [...fixedCopper(input), ...result.flatMap(routeCopper)];
  for (const t48 of result) {
    const c2 = input.connections.find((c3) => c3.name === t48.connection_name);
    if (!new VectorScene(
      input,
      c2,
      t48.route[0].width,
      copper
    ).pathVisible(t48.route))
      return null;
  }
  return traces.map(
    (t48) => result.find((r2) => r2.connection_name === t48.connection_name)
  );
}
function hasTerminalInsidePadField(input, traces) {
  const fields = /* @__PURE__ */ new Map();
  for (const pad of input.obstacles) {
    if (!pad.componentId) continue;
    const angle = (pad.ccwRotationDegrees ?? 0) * Math.PI / 180;
    const width = Math.abs(Math.cos(angle)) * pad.width + Math.abs(Math.sin(angle)) * pad.height;
    const height = Math.abs(Math.sin(angle)) * pad.width + Math.abs(Math.cos(angle)) * pad.height;
    const field = fields.get(pad.componentId) ?? {
      left: Infinity,
      right: -Infinity,
      bottom: Infinity,
      top: -Infinity,
      padSize: 0
    };
    field.left = Math.min(field.left, pad.center.x - width / 2);
    field.right = Math.max(field.right, pad.center.x + width / 2);
    field.bottom = Math.min(field.bottom, pad.center.y - height / 2);
    field.top = Math.max(field.top, pad.center.y + height / 2);
    field.padSize = Math.max(field.padSize, pad.width, pad.height);
    fields.set(pad.componentId, field);
  }
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  return traces.some(
    (trace) => [trace.route[0], trace.route.at(-1)].some(
      (terminal) => [...fields.values()].some((field) => {
        const halo = Math.max(input.minViaPadDiameter ?? 0.3, field.padSize) / 2 + clearance;
        return terminal.x >= field.left - halo && terminal.x <= field.right + halo && terminal.y >= field.bottom - halo && terminal.y <= field.top + halo;
      })
    )
  );
}

// lib/layer-colors.ts
var layerColors = {
  top: "#dc2626",
  inner1: "#ca8a04",
  inner2: "#16a34a",
  inner3: "#0891b2",
  inner4: "#9333ea",
  inner5: "#ea580c",
  inner6: "#db2777",
  bottom: "#2563eb"
};
var layerColor = (layer) => layerColors[layer] ?? "#64748b";

// lib/bus-lanes-solver.ts
var BusLanesSolver = class _BusLanesSolver extends BaseSolver {
  constructor(input, options = {}, terminalLayers = /* @__PURE__ */ new Map()) {
    super();
    this.terminalLayers = terminalLayers;
    this.input = structuredClone(input);
    this.options = options;
    this.MAX_ITERATIONS = options.maxSearchIterations ?? 2e5;
  }
  terminalLayers;
  input;
  options;
  phase = "validate";
  failureCode = null;
  traces = [];
  widths = /* @__PURE__ */ new Map();
  fixed = [];
  orders = [];
  attempt = 0;
  lane = 0;
  search;
  bestPartial = [];
  pairedTraces = [];
  pairIndex = 0;
  congestionPass = 0;
  conflictingLanes = 0;
  independent;
  independentAttempted = false;
  pairedNetwork;
  pairedNetworkAttempted = false;
  negotiated;
  reservePackageExits;
  pairSearch;
  reportedRoutes;
  lengthStats;
  /** Rematch freshly computed carrier geometry after a pipeline refinement.
   * The ordinary output validator still checks every endpoint and copper edge. */
  static forRefinement(input, traces, options = {}) {
    const solver = new _BusLanesSolver(input, options);
    solver.initialize();
    if (solver.failed) return solver;
    if (solver.search instanceof GridVisibilitySearch) solver.search.cancel();
    solver.search = void 0;
    solver.traces = structuredClone(traces);
    solver.phase = "match";
    return solver;
  }
  /** Accept already matched candidates through the ordinary output validator. */
  static forValidation(input, traces, options = {}) {
    const solver = _BusLanesSolver.forRefinement(input, traces, options);
    if (!solver.failed) solver.phase = "validate_output";
    return solver;
  }
  getConstructorParams() {
    return [this.input, this.options];
  }
  getOutput() {
    if (!this.solved) throw Error(this.error ?? "Bus lanes are not solved");
    return {
      ...this.input,
      traces: [...this.input.traces ?? [], ...this.traces]
    };
  }
  fail(code, message) {
    this.failureCode = code;
    this.error = message;
    this.failed = true;
    this.phase = "failed";
    if (this.search instanceof GridVisibilitySearch) this.search.cancel();
    this.pairedNetwork?.return(null);
    this.pairedNetwork = void 0;
    this.pairSearch?.return(null);
    this.negotiated?.return(null);
    this.pairSearch = void 0;
    this.negotiated = void 0;
  }
  tryFinalAcceptance() {
    this.pairedNetwork?.return(null);
    this.pairedNetwork = void 0;
    this.independent?.return(null);
    this.independent = void 0;
    if (!this.solved)
      this.fail(
        "search_budget_exhausted",
        "Vector visibility search budget exhausted"
      );
  }
  initialize() {
    const input = this.input;
    if (input.outline?.length) {
      this.fail("unsupported_outline", "Custom board outlines are unsupported");
      return;
    }
    const names = /* @__PURE__ */ new Set();
    for (const c2 of input.connections) {
      if (names.has(c2.name)) throw Error(`Duplicate connection ${c2.name}`);
      names.add(c2.name);
      if (c2.pointsToConnect.length !== 2) {
        this.fail(
          "invalid_terminals",
          `${c2.name}: exactly two terminals required`
        );
        return;
      }
      const [a2, b2] = c2.pointsToConnect;
      if (a2.layers || b2.layers || a2.layer !== b2.layer) {
        this.fail(
          "layer_change_required",
          `${c2.name}: ${a2.layer} \u2192 ${b2.layer}; a common fixed layer is required; fanout handoff layers must agree`
        );
        return;
      }
      if (input.allowedLayers && !input.allowedLayers.includes(a2.layer)) {
        this.fail(
          "forbidden_layer",
          `${c2.name}: forbidden signal layer ${a2.layer}`
        );
        return;
      }
      if (![a2.x, a2.y, b2.x, b2.y].every(Number.isFinite))
        throw Error("Nonfinite terminal");
      this.widths.set(
        c2.name,
        c2.nominalTraceWidth ?? c2.width ?? input.minTraceWidth
      );
    }
    for (const bus of input.buses ?? [])
      if (bus.maxLength !== void 0 && (!Number.isFinite(bus.maxLength) || bus.maxLength < 0))
        throw Error("Invalid maximum bus length");
    for (const bus of input.buses ?? [])
      if (bus.minLength !== void 0 && (!Number.isFinite(bus.minLength) || bus.minLength < 0 || bus.minLength > (bus.maxLength ?? Infinity)))
        throw Error("Invalid minimum bus length");
    for (const b2 of input.buses ?? [])
      if (b2.maxLengthSkew !== void 0 && (!Number.isFinite(b2.maxLengthSkew) || b2.maxLengthSkew < 0))
        throw Error("Invalid maximum length skew");
    for (const { names: members, tolerance } of lengthConstraints(input)) {
      if (!Number.isFinite(tolerance) || tolerance < 0)
        throw Error("Invalid maximum length skew");
      if (members.length < 1 || new Set(members).size !== members.length || members.some((n2) => !names.has(n2)))
        throw Error("Invalid length matching members");
    }
    const claimed = /* @__PURE__ */ new Set();
    for (const b2 of input.buses ?? [])
      for (const name of b2.connectionNames) {
        const c2 = input.connections.find((c3) => c3.name === name);
        if (!c2 || claimed.has(name))
          throw Error(`Missing or duplicated bus member ${name}`);
        claimed.add(name);
        const layer = c2.pointsToConnect[0].layer;
        if (b2.allowedLayers && !b2.allowedLayers.includes(layer))
          throw Error(`${b2.busId}: forbidden layer ${layer}`);
        const width = b2.traceWidth;
        if (width !== void 0) this.widths.set(name, width);
      }
    for (const width of this.widths.values())
      if (!Number.isFinite(width) || width <= 0 || width < input.minTraceWidth)
        throw Error("Invalid trace width");
    this.fixed = fixedCopper(input);
    for (const c2 of input.connections)
      for (const p2 of c2.pointsToConnect)
        this.fixed.push({
          a: p2,
          b: p2,
          layer: p2.layer,
          radius: this.widths.get(c2.name) / 2,
          owners: [c2.name]
        });
    const negotiatePairs = this.useNegotiation;
    const paired = new Set(
      negotiatePairs ? [] : this.coupledPairs().flatMap((p2) => p2.connectionNames)
    );
    this.orders = windingOrders(
      input.connections.filter((c2) => !paired.has(c2.name))
    );
    if (!input.connections.length) {
      this.solved = true;
      this.phase = "solved";
      return;
    }
    if (!negotiatePairs && this.coupledPairs().length) {
      this.phase = "coupled_pairs";
      return;
    }
    this.phase = "route";
    this.startLane();
  }
  // Small remainders still need layer negotiation when their dogbone terminals
  // can reach more than one signal layer. The fixed-layer visibility search
  // cannot explore that choice, regardless of how few connections remain.
  get useNegotiation() {
    return this.options.denseSearch && (this.input.connections.length > 12 || this.input.connections.some(
      (c2) => (this.terminalLayers.get(c2.name)?.length ?? 0) > 1
    ));
  }
  coupledPairs() {
    return (this.input.differentialPairs ?? []).filter(
      (p2) => p2.traceGap !== void 0 || p2.maxUncoupledLength !== void 0
    );
  }
  routePair() {
    const pair = this.coupledPairs()[this.pairIndex];
    if (!pair) {
      this.pairedTraces = structuredClone(this.traces);
      this.phase = "route";
      this.startLane();
      return;
    }
    this.pairSearch ??= routeCoupledPair(this.input, pair, [
      ...this.fixed,
      ...this.traces.flatMap(routeCopper)
    ]);
    const step = this.pairSearch.next();
    if (!step.done) return;
    if (!step.value) {
      this.fail(
        "coupled_routing_failed",
        "No legal coupled corridor and package approaches"
      );
      return;
    }
    this.traces.push(...step.value);
    this.pairSearch = void 0;
    this.pairIndex++;
  }
  scene(c2) {
    return new VectorScene(this.input, c2, this.widths.get(c2.name), [
      ...this.fixed,
      ...this.traces.flatMap(routeCopper)
    ]);
  }
  startLane() {
    if (this.lane === this.orders[this.attempt].length) {
      this.phase = "match";
      return;
    }
    const c2 = this.orders[this.attempt][this.lane], [a2, b2] = c2.pointsToConnect;
    this.search = this.useNegotiation ? new GridVisibilitySearch(this.scene(c2), a2, b2) : new VectorVisibilitySearch(this.scene(c2), a2, b2);
  }
  retry() {
    if (this.traces.length > this.bestPartial.length)
      this.bestPartial = structuredClone(this.traces);
    if (this.options.denseSearch && this.attempt < 300) {
      const current = this.orders[this.attempt];
      const failed = current[this.lane];
      if (failed) {
        const next = [...current];
        next.splice(this.lane, 1);
        next.splice(
          Math.max(0, this.lane - 1 - Math.floor(this.attempt / 8)),
          0,
          failed
        );
        const key = next.map((c2) => c2.name).join("\0");
        if (!this.orders.slice(0, this.attempt + 1).some((order) => order.map((c2) => c2.name).join("\0") === key))
          this.orders.splice(this.attempt + 1, 0, next);
      }
    }
    this.attempt++;
    if (this.attempt >= this.orders.length) {
      this.traces = this.bestPartial;
      this.fail(
        "no_planar_route",
        "No collision-free routing found in the vector visibility graph"
      );
      return;
    }
    this.traces = structuredClone(this.pairedTraces);
    this.lane = 0;
    this.startLane();
  }
  route() {
    if (this.useNegotiation) {
      if (this.search instanceof GridVisibilitySearch) this.search.cancel();
      this.search = void 0;
      if (!this.pairedNetworkAttempted) {
        this.pairedNetworkAttempted = true;
        const constrained = /* @__PURE__ */ new Set([
          ...(this.input.buses ?? []).flatMap((b2) => b2.connectionNames),
          ...(this.input.differentialPairs ?? []).flatMap(
            (p2) => p2.connectionNames
          )
        ]);
        if (this.input.connections.some((c2) => !constrained.has(c2.name)) && backwardFacingPackageTerminals(this.input))
          this.pairedNetwork = routePairedNetwork(
            this.input,
            this.terminalLayers
          );
      }
      if (this.pairedNetwork) {
        const state = this.pairedNetwork.next();
        if (!state.done) return;
        this.pairedNetwork = void 0;
        if (state.value) {
          this.traces = state.value;
          this.phase = "match";
          return;
        }
      }
      if (!this.independentAttempted) {
        this.independentAttempted = true;
        const groups = independentBusGroups(this.input);
        if (groups)
          this.independent = routeIndependentBuses(
            groups,
            this.fixed,
            this.widths,
            (input, traces) => {
              const child = new _BusLanesSolver(input, this.options);
              child.step();
              child.traces = traces;
              child.phase = "match";
              child.step();
              if (!child.failed) child.step();
              return child.solved ? child.traces : null;
            }
          );
      }
      if (this.independent) {
        const state = this.independent.next();
        if (!state.done) {
          this.traces = state.value;
          this.lane = this.traces.length;
          return;
        }
        this.independent = void 0;
        if (state.value) {
          this.traces = state.value;
          this.phase = "validate_output";
          return;
        }
      }
      this.reservePackageExits ??= backwardFacingPackageTerminals(this.input);
      this.negotiated ??= negotiateLanes(
        this.input,
        this.orders[0],
        this.fixed,
        this.pairedTraces,
        this.widths,
        (pass, conflicts) => {
          this.congestionPass = pass;
          this.conflictingLanes = conflicts;
        },
        this.terminalLayers,
        () => this.reservePackageExits
      );
      const step = this.negotiated.next();
      if (!step.done) {
        this.traces = step.value;
        this.lane = this.traces.length - this.pairedTraces.length;
        return;
      }
      if (!step.value) {
        this.fail(
          "no_planar_route",
          "Negotiated lane search exhausted without a complete route"
        );
        return;
      }
      this.traces = step.value;
      this.phase = "match";
      return;
    }
    const s2 = this.search;
    s2.step();
    if (s2.solved) {
      const c2 = this.orders[this.attempt][this.lane];
      this.traces.push({
        type: "pcb_trace",
        pcb_trace_id: `bus_lane_${c2.name}`,
        connection_name: c2.name,
        source_trace_id: c2.source_trace_id ?? c2.name,
        route: reduceOrdinaryTurns(s2.result, this.scene(c2)).map((p2) => ({
          route_type: "wire",
          x: p2.x,
          y: p2.y,
          layer: c2.pointsToConnect[0].layer,
          width: this.widths.get(c2.name)
        }))
      });
      this.lane++;
      this.startLane();
    } else if (s2.failed || s2.expanded >= (this.options.maxLaneIterations ?? (s2 instanceof GridVisibilitySearch ? 1e6 : 4e3))) {
      if (s2 instanceof GridVisibilitySearch) s2.cancel();
      this.retry();
    }
  }
  match() {
    const input = this.input;
    const original = this.traces;
    const fixed = this.fixed;
    const compactCorridors = /* @__PURE__ */ new WeakSet();
    const demandPackedCorridors = /* @__PURE__ */ new WeakSet();
    const narrowCorridors = /* @__PURE__ */ new WeakSet();
    const packBanks = this.options.smoothTuning && original.some((t48) => t48.coupledSection);
    function* candidates() {
      yield original;
      if (packBanks) {
        const busNames = new Set(input.buses?.flatMap((b2) => b2.connectionNames));
        if ((input.allowedLayers?.length ?? input.layerCount) === 2 && original.some((t48) => !busNames.has(t48.connection_name))) {
          const highDemand = highDemandPairedLanes(input, original).size > 0;
          for (const multiplier of highDemand ? [12, 14, 16, 10, 8] : [10, 8, 12, 14, 16]) {
            const spread = spreadCoupledTuningLanes(
              input,
              original,
              input.minTraceWidth * multiplier,
              "dogleg",
              true
            );
            if (spread) {
              compactCorridors.add(spread);
              demandPackedCorridors.add(spread);
              yield spread;
            }
          }
        }
        for (const multiplier of (input.buses?.length ?? 0) > 1 ? [5, 6, 8, 12, 16, 20] : [5, 6, 8, 12]) {
          const spread = spreadCoupledTuningLanes(
            input,
            original,
            input.minTraceWidth * multiplier,
            "interior"
          );
          if (spread) {
            if (multiplier < 8) narrowCorridors.add(spread);
            compactCorridors.add(spread);
            yield spread;
          }
        }
        for (const multiplier of [8, 12]) {
          const spread = spreadCoupledTuningLanes(
            input,
            original,
            input.minTraceWidth * multiplier
          );
          if (spread) {
            compactCorridors.add(spread);
            yield spread;
          }
        }
      }
      if (packBanks) yield original;
      const rounded = roundCoupledReturnBends(input, original, fixed);
      if (rounded.some((t48, i2) => t48 !== original[i2])) yield rounded;
      if (original.some((t48) => t48.coupledSection)) {
        for (const multiplier of packBanks ? [20, 16, 6, 4] : [20, 16, 12, 8, 6, 4]) {
          const spread = spreadCoupledTuningLanes(
            input,
            original,
            input.minTraceWidth * multiplier
          );
          if (spread) yield spread;
        }
        for (const multiplier of [8, 12, 6, 16, 4, 20]) {
          const spread = spreadCoupledTuningLanes(
            input,
            original,
            input.minTraceWidth * multiplier,
            "diagonal"
          );
          if (spread) yield spread;
        }
        return;
      }
      const width = Math.max(...original.map((t48) => t48.route[0].width));
      for (const multiplier of [16, 24, 28, 32]) {
        const spread = spreadTuningLanes(input, original, width * multiplier);
        if (spread) yield spread;
      }
    }
    let error;
    const attemptedShapes = /* @__PURE__ */ new Set();
    let triedOriginal = false;
    for (const corridor of candidates()) {
      const quickOriginal = packBanks && corridor === original && !triedOriginal;
      const quickCorridor = quickOriginal || narrowCorridors.has(corridor);
      if (corridor === original) triedOriginal = true;
      const refinements = function* (fixed2, smooth) {
        yield corridor;
        if (quickCorridor) return;
        if (smooth) yield refinePairApproaches(input, corridor, fixed2);
        if (smooth && corridor.some((t48) => t48.coupledSection))
          for (const trim of [
            2.75,
            2.5,
            2.25,
            2,
            3,
            1.5,
            1,
            0.5,
            0.25,
            0.125,
            0.0625,
            0.03125
          ])
            yield bevelPairApproaches(input, corridor, fixed2, trim);
      };
      for (const refined of refinements(
        this.fixed,
        this.options.smoothTuning
      )) {
        for (const trim of this.options.smoothTuning ? quickCorridor ? [1.5] : [1.5, 0.75, 0.375, 0.1875, 0.09375, 0.046875, 0.0234375] : [0]) {
          const candidate = alignCoupledSectionBoundaries(
            input,
            trim ? chamferOrdinaryCorners(input, refined, this.fixed, trim) : refined
          );
          const shapeKey = JSON.stringify(
            candidate.map((t48) => [t48.route, t48.coupledSection, t48.curvedSegments])
          );
          if (attemptedShapes.has(shapeKey)) continue;
          attemptedShapes.add(shapeKey);
          if (this.options.smoothTuning && !routeAnglesAreConventional(candidate)) {
            error = Error("No clear conventional approach corners");
            continue;
          }
          if (sharedPairSpacingReports(input, candidate).some((p2) => !p2.matched)) {
            error = Error("Pair approach refinement separated the shared rails");
            continue;
          }
          try {
            const targets = minimumLengthTargets(input, candidate);
            assertLengthTargets(input, targets);
            this.traces = this.options.smoothTuning && candidate.some((t48) => t48.coupledSection) ? tuneCoupledLengths(input, candidate, {
              // Narrow banks need more curve period/offset combinations.
              // Keep that extra bounded work local to packed candidates.
              maxCandidates: corridor === original ? input.buses?.some(
                (bus) => bus.maxLength !== void 0
              ) ? 65536 : 512 : demandPackedCorridors.has(corridor) ? 65536 : 16384,
              packMeanders: quickOriginal || compactCorridors.has(corridor)
            }) : (this.options.smoothTuning ? tuneSmoothLengths : tuneLengths)(
              input,
              candidate,
              targets
            );
            if (this.options.smoothTuning)
              this.traces = simplifyMatchedTraces(input, this.traces);
            if (this.options.smoothTuning && !routeAnglesAreConventional(this.traces))
              throw Error("Length tuning introduced a sharp corner");
            if (sharedPairSpacingReports(input, this.traces).some(
              (p2) => !p2.matched
            ))
              throw Error("Length tuning separated the shared pair rails");
            this.phase = "validate_output";
            return;
          } catch (e2) {
            error = e2;
          }
        }
      }
    }
    this.fail("length_matching_failed", String(error));
    return;
  }
  validateOutput() {
    if (this.options.smoothTuning && !routeAnglesAreConventional(this.traces))
      throw Error("Final route has a nonconventional corner");
    for (const c2 of this.input.connections) {
      const t48 = this.traces.find((t49) => t49.connection_name === c2.name);
      if (!t48) throw Error("Missing lane");
      if (t48.route.length < 2 || t48.route.some(
        (p2) => !Number.isFinite(p2.x) || !Number.isFinite(p2.y) || p2.route_type !== "wire" || !Number.isFinite(p2.width) || p2.width <= 0
      ))
        throw Error("Invalid lane geometry");
      if (t48.route.some(
        (p2) => p2.route_type !== "wire" || p2.layer !== c2.pointsToConnect[0].layer
      ))
        throw Error("Carrier layer does not match its terminals");
      const scene = this.scene(c2);
      if (!tuningPathIsSelfClear(
        t48.route,
        this.widths.get(c2.name) / 2 + scene.margin
      ))
        throw Error("Final self-clearance violation");
      if (distance(t48.route[0], c2.pointsToConnect[0]) > 1e-8 || distance(t48.route.at(-1), c2.pointsToConnect[1]) > 1e-8)
        throw Error("Broken lane endpoints");
      for (let i2 = 1; i2 < t48.route.length; i2++) {
        const a2 = t48.route[i2 - 1], b2 = t48.route[i2], dx2 = Math.abs(a2.x - b2.x), dy2 = Math.abs(a2.y - b2.y);
        if (a2.route_type !== "wire" || b2.route_type !== "wire" || a2.layer !== b2.layer)
          throw Error("Forbidden layer transition");
        if (Math.min(dx2, dy2) > 1e-8 && Math.abs(dx2 - dy2) > 1e-8 && !t48.curvedSegments?.includes(i2))
          throw Error("Non-octilinear segment");
        if (!scene.visible(a2, b2))
          throw Error("Final copper clearance violation");
      }
    }
    if ([
      ...busLengthReports(this.input, this.traces),
      ...pairLengthReports(this.input, this.traces)
    ].some((b2) => b2.toleranceMm !== null && !b2.matched))
      throw Error("Final bus length skew violation");
    if (busLengthReports(this.input, this.traces).some(
      (b2) => !b2.withinLengthLimit || !b2.aboveMinimumLength
    ))
      throw Error("Final absolute bus length violation");
    if (pairCouplingReports(this.input, this.traces).some((p2) => !p2.matched))
      throw Error("Final pair spacing or uncoupled length violation");
    this.phase = "solved";
    this.solved = true;
  }
  _step() {
    try {
      if (this.phase === "validate") this.initialize();
      else if (this.phase === "coupled_pairs") this.routePair();
      else if (this.phase === "route") this.route();
      else if (this.phase === "match") this.match();
      else if (this.phase === "validate_output") this.validateOutput();
    } catch (e2) {
      this.fail("constraint_error", String(e2));
    }
    this.progress = this.lane / Math.max(1, this.input.connections.length);
    if (!this.reportedRoutes || this.reportedRoutes.length !== this.traces.length || this.reportedRoutes.some(
      (old, i2) => old.trace !== this.traces[i2] || old.route !== this.traces[i2].route
    )) {
      this.reportedRoutes = this.traces.map((trace) => ({
        trace,
        route: trace.route
      }));
      this.lengthStats = {
        busLengths: busLengthReports(this.input, this.traces),
        pairLengths: pairLengthReports(this.input, this.traces),
        traceLengthsMm: this.traces.map((t48) => ({
          name: t48.connection_name,
          length: length(t48.route)
        }))
      };
    }
    this.stats = {
      ...this.lengthStats,
      phase: this.phase,
      algorithm: "octilinear_visibility",
      attempt: this.attempt,
      lane: this.lane,
      totalLanes: this.input.connections.length,
      congestionPass: this.congestionPass,
      conflictingLanes: this.conflictingLanes,
      vertices: (this.search instanceof VectorVisibilitySearch ? this.search.vertices.length : 0) ?? 0,
      expandedVertices: this.search?.expanded ?? 0,
      frontier: (this.search instanceof VectorVisibilitySearch ? this.search.open.length : 0) ?? 0,
      failureCode: this.failureCode
    };
  }
  visualize() {
    const lines = [], points = [], rects = [], circles = [];
    for (const c2 of fixedCopper(this.input)) {
      if (c2.rect) {
        rects.push({
          center: {
            x: (c2.rect.minX + c2.rect.maxX) / 2,
            y: (c2.rect.minY + c2.rect.maxY) / 2
          },
          width: c2.rect.maxX - c2.rect.minX,
          height: c2.rect.maxY - c2.rect.minY,
          layer: c2.layer,
          fill: `${layerColor(c2.layer)}30`,
          stroke: layerColor(c2.layer)
        });
        continue;
      }
      if (distance(c2.a, c2.b) < 1e-9)
        circles.push({
          center: c2.a,
          radius: c2.radius,
          layer: c2.layer,
          fill: "transparent",
          stroke: layerColor(c2.layer)
        });
      else
        lines.push({
          points: [
            { x: c2.a.x, y: c2.a.y },
            { x: c2.b.x, y: c2.b.y }
          ],
          strokeWidth: c2.radius * 2,
          strokeColor: layerColor(c2.layer),
          layer: c2.layer,
          label: `Fixed fanout [${c2.layer}]`
        });
    }
    for (const t48 of this.traces)
      lines.push({
        points: t48.route.map(({ x: x2, y: y2 }) => ({ x: x2, y: y2 })),
        strokeWidth: t48.route[0].width,
        strokeColor: layerColor(t48.route[0].layer),
        layer: t48.route[0].layer,
        label: t48.connection_name
      });
    for (const c2 of this.input.connections)
      for (const [i2, p2] of c2.pointsToConnect.entries())
        points.push({
          ...p2,
          color: i2 ? "#d97706" : "#2563eb",
          label: `${c2.name} ${i2 ? "target" : "source"} [${p2.layer}]`
        });
    if (this.search instanceof VectorVisibilitySearch && this.phase === "route") {
      const layer = this.orders[this.attempt][this.lane]?.pointsToConnect[0].layer;
      for (const edge of this.search.visibleEdges)
        lines.push({
          points: edge,
          strokeWidth: 0.02,
          strokeColor: "#67e8f980",
          layer
        });
      for (const n2 of this.search.open.values().slice(0, 80))
        points.push({ ...this.search.vertices[n2.id], color: "#06b6d4", layer });
      lines.push({
        points: this.search.currentPath(),
        strokeColor: "#f43f5e",
        strokeWidth: 0.09,
        layer
      });
    }
    return {
      title: `Vector bus lanes \xB7 ${this.phase}`,
      lines,
      points,
      rects,
      circles
    };
  }
};

// lib/exterior-pair-spacing.ts
function exteriorIntervals(a2, b2, boxes) {
  const inside = [];
  for (const box of boxes) {
    let lo = 0, hi = 1;
    for (const [axis, min, max] of [
      ["x", box.minX, box.maxX],
      ["y", box.minY, box.maxY]
    ]) {
      const delta = b2[axis] - a2[axis];
      if (Math.abs(delta) < 1e-15) {
        if (a2[axis] < min || a2[axis] > max) {
          lo = 1;
          hi = 0;
          break;
        }
      } else {
        const p2 = (min - a2[axis]) / delta, q2 = (max - a2[axis]) / delta;
        lo = Math.max(lo, Math.min(p2, q2));
        hi = Math.min(hi, Math.max(p2, q2));
      }
    }
    if (lo < hi) inside.push([lo, hi]);
  }
  inside.sort((a3, b3) => a3[0] - b3[0]);
  const outside = [];
  let end = 0;
  for (const [lo, hi] of inside) {
    if (lo > end) outside.push([end, lo]);
    end = Math.max(end, hi);
  }
  if (end < 1) outside.push([end, 1]);
  return outside;
}
function exteriorPairSpacingReports(input, traces) {
  const localDogbones = traces.flatMap((t48) => {
    const vias = t48.route.flatMap((p2, i2) => p2.route_type === "via" ? [i2] : []);
    return vias.length === 2 ? [
      { ...t48, route: t48.route.slice(0, vias[0] + 2) },
      { ...t48, route: t48.route.slice(vias[1] - 1).toReversed() }
    ] : [];
  });
  return (input.differentialPairs ?? []).map((pair) => {
    const rails = pair.connectionNames.map(
      (name) => traces.find(
        (t48) => t48.connection_name === name || t48.source_trace_id === name
      )
    );
    const width = Math.max(
      ...rails.flatMap(
        (t48) => t48?.route.flatMap((p2) => p2.route_type === "wire" ? [p2.width] : []) ?? []
      )
    );
    const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
    const gap = pair.traceGap ?? clearance;
    const regions = packageApproachRegions(
      { ...input, traces: [...input.traces ?? [], ...localDogbones] },
      width + gap / 2 + clearance
    );
    const fields = [0, 1].flatMap((end) => {
      const r2 = regions.find(
        (r3) => rails.every(
          (t48) => t48?.route.length && pointInBox(end ? t48.route.at(-1) : t48.route[0], r3.copper)
        )
      );
      return r2 ? [r2.copper] : [];
    });
    const applicable = (pair.traceGap !== void 0 || pair.maxUncoupledLength !== void 0) && fields.length === 2 && rails.every((t48) => t48?.route.length);
    const base = { connectionNames: pair.connectionNames, applicable };
    if (!applicable)
      return {
        ...base,
        matched: true,
        maxExteriorEdgeGapMm: null,
        maxSamplingErrorMm: null,
        separatedExteriorLengthMm: null
      };
    const segments = (trace) => trace.route.slice(1).flatMap((b2, i2) => {
      const a2 = trace.route[i2];
      return a2.route_type === "wire" && b2.route_type === "wire" && a2.layer === b2.layer ? [{ a: a2, b: b2, radius: a2.width / 2, layer: a2.layer, owners: [] }] : [];
    });
    let max = -Infinity, error = 0, separated = 0;
    const maxAllowed = (width + gap) / Math.cos(Math.PI / 8) - width + 2e-3;
    for (let side = 0; side < 2; side++) {
      const mate = segments(rails[1 - side]);
      const indexes = new Map(
        [...new Set(mate.map((s2) => s2.layer))].map((layer) => [
          layer,
          new CopperIndex(mate.filter((s2) => s2.layer === layer))
        ])
      );
      for (const { a: a2, b: b2 } of segments(rails[side])) {
        const span = distance(a2, b2);
        for (const [lo, hi] of exteriorIntervals(a2, b2, fields)) {
          const count = Math.max(1, Math.ceil((hi - lo) * span / 2e-3));
          const step = (hi - lo) * span / count;
          error = Math.max(error, step / 2);
          for (let k2 = 0; k2 < count; k2++) {
            const t48 = lo + (hi - lo) * (k2 + 0.5) / count;
            const p2 = { x: a2.x + (b2.x - a2.x) * t48, y: a2.y + (b2.y - a2.y) * t48 };
            const spacing = (indexes.get(a2.layer)?.distanceToPoint(
              p2,
              (s2) => pointSegmentDistanceToPoints(p2, s2.a, s2.b) - s2.radius
            ) ?? Infinity) - a2.width / 2;
            max = Math.max(max, spacing);
            if (spacing + step / 2 > maxAllowed) separated += step;
          }
        }
      }
    }
    return {
      ...base,
      matched: separated === 0,
      maxExteriorEdgeGapMm: max === -Infinity ? null : max,
      maxSamplingErrorMm: error,
      separatedExteriorLengthMm: separated
    };
  });
}

// lib/rebalance-pair-escapes.ts
var reverse2 = (trace) => ({
  ...trace,
  route: trace.route.toReversed(),
  coupledSection: trace.coupledSection ? [
    trace.route.length - 1 - trace.coupledSection[1],
    trace.route.length - 1 - trace.coupledSection[0]
  ] : void 0,
  curvedSegments: trace.curvedSegments?.map((i2) => trace.route.length - i2)
});
function* rebalancePairEscapes(input, traces, generatedEscapes, options) {
  const targets = minimumLengthTargets(input, traces);
  const paired = new Set(
    input.differentialPairs?.flatMap((p2) => p2.connectionNames)
  );
  const generatedIds = new Set(generatedEscapes.map((t48) => t48.pcb_trace_id));
  const short = traces.filter(
    (t48) => paired.has(t48.connection_name) && t48.coupledSection && (targets.get(t48.connection_name) ?? 0) > length(t48.route) + fixedRouteLength(input, t48.connection_name) + 1e-7
  );
  let attempts = 0;
  for (const original of short)
    for (const end of [0, 1]) {
      const trace = end ? reverse2(original) : original, name = trace.connection_name, layer = trace.route[0].layer;
      const escape = input.traces?.find(
        (t48) => generatedIds.has(t48.pcb_trace_id) && t48.connection_name === name && t48.route.filter((p2) => p2.route_type === "via").length === 1 && distance(t48.route.at(-1), trace.route[0]) < 1e-7
      );
      if (!escape) continue;
      const pad = escape.route[0], oldVia = escape.route.find((p2) => p2.route_type === "via");
      if (pad.layer !== "top" || oldVia.from_layer !== "top") continue;
      const owner = input.obstacles.find(
        (o2) => o2.componentId && distance(o2.center, pad) < 1e-4
      );
      if (!owner) continue;
      const pads = input.obstacles.filter(
        (o2) => o2.componentId === owner.componentId
      );
      const pitch = Math.min(
        ...pads.map((o2) => distance(o2.center, pad)).filter((d2) => d2 > 1e-4)
      );
      if (!Number.isFinite(pitch)) continue;
      const surfaceLimit = Math.min(2, 2.5 * pitch);
      const minX = Math.min(...pads.map((p2) => p2.center.x - p2.width / 2)), maxX = Math.max(...pads.map((p2) => p2.center.x + p2.width / 2));
      const minY = Math.min(...pads.map((p2) => p2.center.y - p2.height / 2)), maxY = Math.max(...pads.map((p2) => p2.center.y + p2.height / 2));
      const directions = [
        { x: -1, y: 0, d: pad.x - minX },
        { x: 1, y: 0, d: maxX - pad.x },
        { x: 0, y: -1, d: pad.y - minY },
        { x: 0, y: 1, d: maxY - pad.y }
      ].sort((a2, b2) => a2.d - b2.d).slice(0, 2);
      const held = traces.filter((t48) => t48 !== original), connection = input.connections.find((c2) => c2.name === name);
      const base = {
        ...input,
        traces: input.traces.filter((t48) => t48 !== escape)
      }, fixed = [...fixedCopper(base), ...held.flatMap(routeCopper)];
      const width = trace.route[0].width;
      function* find(a2, b2, carrier, maximum) {
        const localConnection = {
          ...connection,
          pointsToConnect: [
            { ...a2, layer: carrier },
            { ...b2, layer: carrier }
          ]
        };
        const scene = new VectorScene(base, localConnection, width, fixed);
        const search = new GridVisibilitySearch(
          scene,
          localConnection.pointsToConnect[0],
          localConnection.pointsToConnect[1],
          [],
          0,
          void 0,
          { maxLength: maximum, paretoLength: true, checkReachability: true }
        );
        try {
          let steps = 0;
          while (!search.solved && !search.failed && steps++ < 4e3) {
            search.step();
            yield;
          }
          return search.solved ? reduceOrdinaryTurns(search.result, scene).map((p2) => ({
            ...p2,
            route_type: "wire",
            layer: carrier,
            width
          })) : null;
        } finally {
          search.cancel();
        }
      }
      for (const normal of directions)
        for (const outward of [1, 0.875, 1.125, 1.25, 1.5])
          for (const across of [1.125, 1, 0.875, 0.75, 1.25, 1.375, 1.5, 0.625])
            for (const sign of [-1, 1]) {
              if (++attempts > 192) return null;
              const site = {
                x: pad.x + pitch * (normal.x * outward - normal.y * across * sign),
                y: pad.y + pitch * (normal.y * outward + normal.x * across * sign)
              };
              const via = { ...oldVia, ...site, to_layer: layer };
              const physical = Array.from(
                { length: input.layerCount },
                (_2, i2) => i2 === 0 ? "top" : i2 === input.layerCount - 1 ? "bottom" : `inner${i2}`
              );
              if (physical.some(
                (carrier) => !new VectorScene(
                  base,
                  {
                    ...connection,
                    pointsToConnect: [
                      { ...site, layer: carrier },
                      { ...site, layer: carrier }
                    ]
                  },
                  via.via_diameter ?? 0.3,
                  fixed
                ).visible(site, site)
              ))
                continue;
              let top = yield* find(pad, site, "top", surfaceLimit);
              const s2 = trace.coupledSection[0], prefix = yield* find(site, trace.route[s2], layer, 4 * pitch);
              if (!top || !prefix) continue;
              top = chamferOrdinaryCorners(
                {
                  ...base,
                  connections: [
                    {
                      ...connection,
                      pointsToConnect: [pad, { ...site, layer: "top" }]
                    }
                  ]
                },
                [{ ...escape, route: top }],
                fixed
              )[0].route;
              const replacement = {
                ...escape,
                route: [
                  ...top,
                  via,
                  { ...site, route_type: "wire", layer, width }
                ]
              };
              const offset = prefix.length - 1 - s2;
              let changed = {
                ...trace,
                route: [...prefix.slice(0, -1), ...trace.route.slice(s2)],
                coupledSection: trace.coupledSection.map(
                  (i2) => i2 + offset
                ),
                curvedSegments: trace.curvedSegments?.filter((i2) => i2 > s2).map((i2) => i2 + offset)
              };
              if (end) changed = reverse2(changed);
              const local = {
                ...input,
                traces: input.traces.map(
                  (t48) => t48 === escape ? replacement : t48
                ),
                connections: input.connections.map(
                  (c2) => c2 === connection ? {
                    ...c2,
                    pointsToConnect: [
                      changed.route[0],
                      changed.route.at(-1)
                    ]
                  } : c2
                )
              };
              const total = length(changed.route) + fixedRouteLength(local, name);
              if (Math.abs(total - targets.get(name)) > 1) continue;
              for (const trim of [0.75, 0.375, 1.5])
                try {
                  const candidate = alignCoupledSectionBoundaries(
                    local,
                    chamferOrdinaryCorners(
                      local,
                      traces.map((t48) => t48 === original ? changed : t48),
                      void 0,
                      trim
                    )
                  );
                  const tuned = tuneCoupledLengths(local, candidate, {
                    maxCandidates: 65536,
                    packMeanders: true,
                    packageOnlyPairTuning: true
                  });
                  if (tuned.some(
                    (t48) => !createTerminalViaClearanceChecker(local, t48, {
                      preserveExistingApproach: false
                    })(t48.route)
                  ))
                    continue;
                  const validator = BusLanesSolver.forValidation(
                    local,
                    tuned,
                    options
                  );
                  try {
                    while (!validator.solved && !validator.failed) {
                      validator.step();
                      yield;
                    }
                    const coupling = exteriorPairSpacingReports(local, tuned);
                    if (validator.solved && coupling.length === (input.differentialPairs?.length ?? 0) && coupling.every((p2) => p2.applicable && p2.matched))
                      return {
                        input: local,
                        traces: tuned,
                        escapes: generatedEscapes.map(
                          (t48) => t48.pcb_trace_id === escape.pcb_trace_id ? replacement : t48
                        )
                      };
                  } finally {
                    if (!validator.solved && !validator.failed)
                      validator.tryFinalAcceptance();
                  }
                } catch {
                  yield;
                }
            }
    }
  return null;
}

// .cache/yalps-0.6.4/package/dist/index.js
var import_heap = __toESM(require_package(), 1);
var index = (tableau, row, col) => tableau.matrix[Math.imul(row, tableau.width) + col];
var update = (tableau, row, col, value) => {
  tableau.matrix[Math.imul(row, tableau.width) + col] = value;
};
var convertToIterable = (seq) => Symbol.iterator in seq && typeof seq[Symbol.iterator] === "function" ? seq : (
  // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
  Object.entries(seq)
);
var convertToSet = (set) => set === true ? true : set === false ? /* @__PURE__ */ new Set() : set instanceof Set ? set : new Set(set);
var tableauModel = (model) => {
  const { direction, objective, integers, binaries } = model;
  const sign = direction === "minimize" ? -1 : 1;
  const constraintsIter = convertToIterable(model.constraints);
  const variablesIter = convertToIterable(model.variables);
  const variables = Array.isArray(variablesIter) ? variablesIter : Array.from(variablesIter);
  const binaryConstraintCol = [];
  const ints = [];
  if (integers != null || binaries != null) {
    const binaryVariables = convertToSet(binaries);
    const integerVariables = binaryVariables === true ? true : convertToSet(integers);
    for (let i2 = 1; i2 <= variables.length; i2++) {
      const [key] = variables[i2 - 1];
      if (binaryVariables === true || binaryVariables.has(key)) {
        binaryConstraintCol.push(i2);
        ints.push(i2);
      } else if (integerVariables === true || integerVariables.has(key)) {
        ints.push(i2);
      }
    }
  }
  const constraints = /* @__PURE__ */ new Map();
  for (const [key, constraint] of constraintsIter) {
    const bounds = constraints.get(key) ?? { row: NaN, lower: -Infinity, upper: Infinity };
    bounds.lower = Math.max(bounds.lower, constraint.equal ?? constraint.min ?? -Infinity);
    bounds.upper = Math.min(bounds.upper, constraint.equal ?? constraint.max ?? Infinity);
    if (!constraints.has(key)) constraints.set(key, bounds);
  }
  let numConstraints = 1;
  for (const constraint of constraints.values()) {
    constraint.row = numConstraints;
    numConstraints += (Number.isFinite(constraint.lower) ? 1 : 0) + (Number.isFinite(constraint.upper) ? 1 : 0);
  }
  const width = variables.length + 1;
  const height = numConstraints + binaryConstraintCol.length;
  const numVars = width + height;
  const matrix = new Float64Array(width * height);
  const positionOfVariable = new Int32Array(numVars);
  const variableAtPosition = new Int32Array(numVars);
  const tableau = { matrix, width, height, positionOfVariable, variableAtPosition };
  for (let i2 = 0; i2 < numVars; i2++) {
    positionOfVariable[i2] = i2;
    variableAtPosition[i2] = i2;
  }
  for (let c2 = 1; c2 < width; c2++) {
    for (const [constraint, coef] of convertToIterable(variables[c2 - 1][1])) {
      if (constraint === objective) {
        update(tableau, 0, c2, sign * coef);
      }
      const bounds = constraints.get(constraint);
      if (bounds != null) {
        if (Number.isFinite(bounds.upper)) {
          update(tableau, bounds.row, c2, coef);
          if (Number.isFinite(bounds.lower)) {
            update(tableau, bounds.row + 1, c2, -coef);
          }
        } else if (Number.isFinite(bounds.lower)) {
          update(tableau, bounds.row, c2, -coef);
        }
      }
    }
  }
  for (const bounds of constraints.values()) {
    if (Number.isFinite(bounds.upper)) {
      update(tableau, bounds.row, 0, bounds.upper);
      if (Number.isFinite(bounds.lower)) {
        update(tableau, bounds.row + 1, 0, -bounds.lower);
      }
    } else if (Number.isFinite(bounds.lower)) {
      update(tableau, bounds.row, 0, -bounds.lower);
    }
  }
  for (let b2 = 0; b2 < binaryConstraintCol.length; b2++) {
    const row = numConstraints + b2;
    update(tableau, row, 0, 1);
    update(tableau, row, binaryConstraintCol[b2], 1);
  }
  return { tableau, sign, variables, integers: ints };
};
var roundToPrecision = (num, precision) => {
  const rounding = Math.round(1 / precision);
  return Math.round((num + Number.EPSILON) * rounding) / rounding;
};
var pivot = (tableau, row, col) => {
  const quotient = index(tableau, row, col);
  const leaving = tableau.variableAtPosition[tableau.width + row];
  const entering = tableau.variableAtPosition[col];
  tableau.variableAtPosition[tableau.width + row] = entering;
  tableau.variableAtPosition[col] = leaving;
  tableau.positionOfVariable[leaving] = col;
  tableau.positionOfVariable[entering] = tableau.width + row;
  const nonZeroColumns = [];
  for (let c2 = 0; c2 < tableau.width; c2++) {
    const value = index(tableau, row, c2);
    if (Math.abs(value) > 1e-16) {
      update(tableau, row, c2, value / quotient);
      nonZeroColumns.push(c2);
    } else {
      update(tableau, row, c2, 0);
    }
  }
  update(tableau, row, col, 1 / quotient);
  for (let r2 = 0; r2 < tableau.height; r2++) {
    if (r2 === row) continue;
    const coef = index(tableau, r2, col);
    if (Math.abs(coef) > 1e-16) {
      for (let i2 = 0; i2 < nonZeroColumns.length; i2++) {
        const c2 = nonZeroColumns[i2];
        update(tableau, r2, c2, index(tableau, r2, c2) - coef * index(tableau, row, c2));
      }
      update(tableau, r2, col, -coef / quotient);
    }
  }
};
var hasCycle = (history, tableau, row, col) => {
  history.push([tableau.variableAtPosition[tableau.width + row], tableau.variableAtPosition[col]]);
  for (let length2 = 6; length2 <= Math.trunc(history.length / 2); length2++) {
    let cycle = true;
    for (let i2 = 0; i2 < length2; i2++) {
      const item = history.length - 1 - i2;
      const [row1, col1] = history[item];
      const [row2, col2] = history[item - length2];
      if (row1 !== row2 || col1 !== col2) {
        cycle = false;
        break;
      }
    }
    if (cycle) return true;
  }
  return false;
};
var phase2 = (tableau, options) => {
  const pivotHistory = [];
  const { precision, maxPivots, checkCycles } = options;
  for (let iter = 0; iter < maxPivots; iter++) {
    let col = 0;
    let value = precision;
    for (let c2 = 1; c2 < tableau.width; c2++) {
      const reducedCost = index(tableau, 0, c2);
      if (reducedCost > value) {
        value = reducedCost;
        col = c2;
      }
    }
    if (col === 0) return ["optimal", roundToPrecision(index(tableau, 0, 0), precision)];
    let row = 0;
    let minRatio = Infinity;
    for (let r2 = 1; r2 < tableau.height; r2++) {
      const value2 = index(tableau, r2, col);
      if (value2 <= precision) continue;
      const rhs = index(tableau, r2, 0);
      const ratio = rhs / value2;
      if (ratio < minRatio) {
        row = r2;
        minRatio = ratio;
        if (ratio <= precision) break;
      }
    }
    if (row === 0) return ["unbounded", col];
    if (checkCycles && hasCycle(pivotHistory, tableau, row, col)) return ["cycled", NaN];
    pivot(tableau, row, col);
  }
  return ["cycled", NaN];
};
var phase1 = (tableau, options) => {
  const pivotHistory = [];
  const { precision, maxPivots, checkCycles } = options;
  for (let iter = 0; iter < maxPivots; iter++) {
    let row = 0;
    let rhs = -precision;
    for (let r2 = 1; r2 < tableau.height; r2++) {
      const value = index(tableau, r2, 0);
      if (value < rhs) {
        rhs = value;
        row = r2;
      }
    }
    if (row === 0) return phase2(tableau, options);
    let col = 0;
    let maxRatio = -Infinity;
    for (let c2 = 1; c2 < tableau.width; c2++) {
      const coefficient = index(tableau, row, c2);
      if (coefficient < -precision) {
        const ratio = -index(tableau, 0, c2) / coefficient;
        if (ratio > maxRatio) {
          maxRatio = ratio;
          col = c2;
        }
      }
    }
    if (col === 0) return ["infeasible", NaN];
    if (checkCycles && hasCycle(pivotHistory, tableau, row, col)) return ["cycled", NaN];
    pivot(tableau, row, col);
  }
  return ["cycled", NaN];
};
var buffer = (matrixLength, posVarLength) => ({
  matrix: new Float64Array(matrixLength),
  positionOfVariable: new Int32Array(posVarLength),
  variableAtPosition: new Int32Array(posVarLength)
});
var applyCuts = (tableau, { matrix, positionOfVariable, variableAtPosition }, cuts) => {
  const { width, height } = tableau;
  matrix.set(tableau.matrix);
  for (let i2 = 0; i2 < cuts.length; i2++) {
    const [sign, variable, value] = cuts[i2];
    const r2 = (height + i2) * width;
    const pos = tableau.positionOfVariable[variable];
    if (pos < width) {
      matrix[r2] = sign * value;
      matrix.fill(0, r2 + 1, r2 + width);
      matrix[r2 + pos] = sign;
    } else {
      const row = (pos - width) * width;
      matrix[r2] = sign * (value - matrix[row]);
      for (let c2 = 1; c2 < width; c2++) {
        matrix[r2 + c2] = -sign * matrix[row + c2];
      }
    }
  }
  positionOfVariable.set(tableau.positionOfVariable);
  variableAtPosition.set(tableau.variableAtPosition);
  const length2 = width + height + cuts.length;
  for (let i2 = width + height; i2 < length2; i2++) {
    positionOfVariable[i2] = i2;
    variableAtPosition[i2] = i2;
  }
  return {
    matrix: matrix.subarray(0, tableau.matrix.length + width * cuts.length),
    width,
    height: height + cuts.length,
    positionOfVariable: positionOfVariable.subarray(0, length2),
    variableAtPosition: variableAtPosition.subarray(0, length2)
  };
};
var mostFractionalVar = (tableau, intVars) => {
  let highestFrac = 0;
  let variable = 0;
  let value = 0;
  for (let i2 = 0; i2 < intVars.length; i2++) {
    const intVar = intVars[i2];
    const row = tableau.positionOfVariable[intVar] - tableau.width;
    if (row < 0) continue;
    const val = index(tableau, row, 0);
    const frac = Math.abs(val - Math.round(val));
    if (frac > highestFrac) {
      highestFrac = frac;
      variable = intVar;
      value = val;
    }
  }
  return [variable, value, highestFrac];
};
var branchAndCut = (tabmod, initResult, options) => {
  const { tableau, sign, integers } = tabmod;
  const { precision, maxIterations, tolerance, timeout } = options;
  const [initVariable, initValue, initFrac] = mostFractionalVar(tableau, integers);
  if (initFrac <= precision) return [tabmod, "optimal", initResult];
  const branches = new import_heap.default((x2, y2) => x2[0] - y2[0]);
  branches.push([initResult, [[-1, initVariable, Math.ceil(initValue)]]]);
  branches.push([initResult, [[1, initVariable, Math.floor(initValue)]]]);
  const maxExtraRows = integers.length * 2;
  const matrixLength = tableau.matrix.length + maxExtraRows * tableau.width;
  const posVarLength = tableau.positionOfVariable.length + maxExtraRows;
  let candidateBuffer = buffer(matrixLength, posVarLength);
  let solutionBuffer = buffer(matrixLength, posVarLength);
  const optimalThreshold = initResult * (1 - sign * tolerance);
  const stopTime = timeout + Date.now();
  let timedout = Date.now() >= stopTime;
  let solutionFound = false;
  let bestEval = Infinity;
  let bestTableau = tableau;
  let iter = 0;
  while (iter < maxIterations && !branches.empty() && bestEval >= optimalThreshold && !timedout) {
    const [relaxedEval, cuts] = branches.pop();
    if (relaxedEval > bestEval) break;
    const currentTableau = applyCuts(tableau, candidateBuffer, cuts);
    const [status2, result] = phase1(currentTableau, options);
    if (status2 === "optimal" && result < bestEval) {
      const [variable, value, frac] = mostFractionalVar(currentTableau, integers);
      if (frac <= precision) {
        solutionFound = true;
        bestEval = result;
        bestTableau = currentTableau;
        const temp = solutionBuffer;
        solutionBuffer = candidateBuffer;
        candidateBuffer = temp;
      } else {
        const cutsUpper = [];
        const cutsLower = [];
        for (let i2 = 0; i2 < cuts.length; i2++) {
          const cut2 = cuts[i2];
          const [dir, v2] = cut2;
          if (v2 === variable) {
            if (dir < 0) {
              cutsLower.push(cut2);
            } else {
              cutsUpper.push(cut2);
            }
          } else {
            cutsUpper.push(cut2);
            cutsLower.push(cut2);
          }
        }
        cutsLower.push([1, variable, Math.floor(value)]);
        cutsUpper.push([-1, variable, Math.ceil(value)]);
        branches.push([result, cutsUpper]);
        branches.push([result, cutsLower]);
      }
    }
    timedout = Date.now() >= stopTime;
    iter++;
  }
  const unfinished = (timedout || iter >= maxIterations) && !branches.empty() && bestEval >= optimalThreshold;
  const status = unfinished ? "timedout" : !solutionFound ? "infeasible" : "optimal";
  return [{ ...tabmod, tableau: bestTableau }, status, solutionFound ? bestEval : NaN];
};
var solution = ({ tableau, sign, variables: vars }, status, result, { precision, includeZeroVariables }) => {
  if (status === "optimal" || status === "timedout" && !Number.isNaN(result)) {
    const variables = [];
    for (let i2 = 0; i2 < vars.length; i2++) {
      const [variable] = vars[i2];
      const row = tableau.positionOfVariable[i2 + 1] - tableau.width;
      const value = row >= 0 ? index(tableau, row, 0) : 0;
      if (value > precision) {
        variables.push([variable, roundToPrecision(value, precision)]);
      } else if (includeZeroVariables) {
        variables.push([variable, 0]);
      }
    }
    return {
      status,
      result: -sign * result,
      variables
    };
  } else if (status === "unbounded") {
    const variable = tableau.variableAtPosition[result] - 1;
    return {
      status: "unbounded",
      result: sign * Infinity,
      // prettier-ignore
      variables: 0 <= variable && variable < vars.length ? [[vars[variable][0], Infinity]] : []
    };
  } else {
    return {
      status,
      result: NaN,
      variables: []
    };
  }
};
var defaultOptionValues = {
  precision: 1e-8,
  checkCycles: false,
  maxPivots: 8192,
  tolerance: 0,
  timeout: Infinity,
  maxIterations: 32768,
  includeZeroVariables: false
};
var defaultOptions = { ...defaultOptionValues };
var solve = (model, options) => {
  const tabmod = tableauModel(model);
  const opt = { ...defaultOptionValues, ...options };
  const [status, result] = phase1(tabmod.tableau, opt);
  if (tabmod.integers.length === 0 || status !== "optimal") {
    return solution(tabmod, status, result, opt);
  } else {
    const [intTabmod, intStatus, intResult] = branchAndCut(tabmod, result, opt);
    return solution(intTabmod, intStatus, intResult, opt);
  }
};

// lib/compact-envelope.ts
var MAX_CUT_PASSES = 24;
var MAX_TABLEAU_CELLS = 64e6;
function* compactEnvelopeCandidate(input, traces) {
  const variables = {}, constraints = {};
  if (!traces.length) return traces;
  let serial = 0, groups = 0;
  const add = (coeff, bound) => {
    const key = `c${serial++}`;
    if (![...coeff.values()].some((n2) => Math.abs(n2) > 1e-10)) return;
    constraints[key] = bound;
    for (const [v2, n2] of coeff)
      if (Math.abs(n2) > 1e-10) (variables[v2] ??= {})[key] = n2;
  };
  const term = (coeff, p2, n2, sign = 1) => {
    if (p2.group === void 0) return;
    for (const d2 of ["x", "y"])
      for (const s2 of [-1, 1]) {
        const k2 = `${p2.group}_${d2}_${s2}`, v2 = sign * n2[d2] * s2;
        coeff.set(k2, (coeff.get(k2) ?? 0) + v2);
      }
  };
  const motion = 2;
  const paired = new Set(
    input.differentialPairs?.flatMap((p2) => p2.connectionNames)
  );
  const paths = traces.map((t48) => {
    const first = Math.min(...t48.curvedSegments ?? []) - 1, last = Math.max(...t48.curvedSegments ?? []);
    const block = groups++;
    return t48.route.map((p2, i2) => ({
      ...p2,
      group: i2 === 0 || i2 === t48.route.length - 1 || paired.has(t48.connection_name) || i2 >= first && i2 <= last && (first === 0 || last === t48.route.length - 1) ? void 0 : i2 >= first && i2 <= last ? block : groups++
    }));
  });
  for (const path of paths)
    for (const p2 of path)
      if (p2.group !== void 0)
        for (const d2 of ["x", "y"])
          for (const s2 of [-1, 1]) {
            const v2 = `${p2.group}_${d2}_${s2}`;
            if (variables[v2]) continue;
            variables[v2] = { objective: 1e-4 };
            add(/* @__PURE__ */ new Map([[v2, 1]]), { max: motion });
          }
  for (const [ti, path] of paths.entries()) {
    const lengthTerms = /* @__PURE__ */ new Map();
    for (let i2 = 1; i2 < path.length; i2++) {
      const a2 = path[i2 - 1], b2 = path[i2], span = distance(a2, b2);
      if (a2.group === b2.group) continue;
      if (span < 1e-8) {
        for (const n3 of [
          { x: 1, y: 0 },
          { x: 0, y: 1 }
        ]) {
          const c3 = /* @__PURE__ */ new Map();
          term(c3, b2, n3);
          term(c3, a2, n3, -1);
          add(c3, { equal: 0 });
        }
        continue;
      }
      const u2 = { x: (b2.x - a2.x) / span, y: (b2.y - a2.y) / span }, n2 = { x: -u2.y, y: u2.x };
      const c2 = /* @__PURE__ */ new Map();
      term(c2, b2, n2);
      term(c2, a2, n2, -1);
      add(c2, { equal: 0 });
      const forward = /* @__PURE__ */ new Map();
      term(forward, b2, u2);
      term(forward, a2, u2, -1);
      add(forward, { min: Math.min(span, 0.01) - span });
      term(lengthTerms, b2, u2);
      term(lengthTerms, a2, u2, -1);
    }
    add(
      lengthTerms,
      input.buses?.some(
        (b2) => b2.maxLengthSkew !== void 0 && b2.connectionNames.includes(traces[ti].connection_name)
      ) ? { equal: 0 } : { max: 0 }
    );
  }
  for (const d2 of ["x", "y"]) {
    const lo = Math.min(...paths.flat().map((p2) => p2[d2])), hi = Math.max(...paths.flat().map((p2) => p2[d2]));
    for (const sign of [-1, 1]) {
      const v2 = `bound_${d2}_${sign}`;
      variables[v2] = { objective: -1 };
      add(/* @__PURE__ */ new Map([[v2, 1]]), { max: hi - lo });
      const seen = /* @__PURE__ */ new Map();
      for (const p2 of paths.flat()) {
        const k2 = String(p2.group);
        const limit = sign === 1 ? hi - p2[d2] : p2[d2] - lo;
        seen.set(k2, Math.min(seen.get(k2) ?? Infinity, limit));
      }
      for (const [g2, limit] of seen) {
        const c2 = /* @__PURE__ */ new Map([[v2, 1]]);
        term(
          c2,
          { x: 0, y: 0, group: g2 === "undefined" ? void 0 : Number(g2) },
          d2 === "x" ? { x: sign, y: 0 } : { x: 0, y: sign }
        );
        add(c2, { max: limit });
      }
    }
  }
  const fixed = fixedCopper(input), clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const originals = paths.flatMap(
    (path, t48) => path.slice(1).map((p2, i2) => ({
      a: path[i2],
      b: p2,
      radius: traces[t48].route[i2].width / 2,
      layer: traces[t48].route[i2].layer,
      owners: [traces[t48].connection_name, traces[t48].source_trace_id ?? ""]
    }))
  );
  const projection = (p2, a2, b2) => {
    const dx2 = b2.x - a2.x, dy2 = b2.y - a2.y, v2 = Math.max(
      0,
      Math.min(
        1,
        ((p2.x - a2.x) * dx2 + (p2.y - a2.y) * dy2) / (dx2 * dx2 + dy2 * dy2 || 1)
      )
    );
    return { x: a2.x + v2 * dx2, y: a2.y + v2 * dy2 };
  };
  const used = /* @__PURE__ */ new Set();
  const variableCount = Object.keys(variables).length;
  for (let pass = 0; pass < MAX_CUT_PASSES; pass++) {
    const rows = Object.values(constraints).reduce(
      (n2, c2) => n2 + (c2.equal !== void 0 || c2.min !== void 0 && c2.max !== void 0 ? 2 : 1),
      0
    );
    if ((rows + 1) * (variableCount + 1) > MAX_TABLEAU_CELLS) return traces;
    yield;
    const solution2 = solve(
      { direction: "minimize", objective: "objective", variables, constraints },
      { precision: 1e-10, maxPivots: 4096 }
    );
    if (solution2.status !== "optimal") return traces;
    const values = new Map(solution2.variables);
    const at2 = (p2) => ({
      ...p2,
      x: p2.x + (p2.group === void 0 ? 0 : (values.get(`${p2.group}_x_1`) ?? 0) - (values.get(`${p2.group}_x_-1`) ?? 0)),
      y: p2.y + (p2.group === void 0 ? 0 : (values.get(`${p2.group}_y_1`) ?? 0) - (values.get(`${p2.group}_y_-1`) ?? 0))
    });
    const copper = originals.map((c2) => ({ ...c2, a: at2(c2.a), b: at2(c2.b) }));
    const index2 = new CopperIndex([...fixed, ...copper]), lookup = new Map(
      copper.map((c2, i2) => [c2, originals[i2]])
    );
    const identities = new Map(
      [...fixed, ...copper].map((c2, i2) => [c2, i2])
    );
    let added = 0;
    const groupPairs = /* @__PURE__ */ new Map();
    for (let ci = 0; ci < copper.length; ci++) {
      const c2 = copper[ci], old = originals[ci];
      const near2 = [];
      const r2 = c2.radius + clearance;
      index2.some(
        {
          minX: Math.min(c2.a.x, c2.b.x) - r2,
          maxX: Math.max(c2.a.x, c2.b.x) + r2,
          minY: Math.min(c2.a.y, c2.b.y) - r2,
          maxY: Math.max(c2.a.y, c2.b.y) + r2
        },
        (other) => {
          near2.push(other);
          return false;
        }
      );
      for (const other of near2) {
        if (c2.layer !== other.layer) continue;
        const moving = lookup.get(other);
        const sameNet = other.owners.some((o2) => o2 && c2.owners.includes(o2));
        if (sameNet && !moving) continue;
        const base = moving ?? other;
        if (sameNet && (old.a === base.a || old.a === base.b || old.b === base.a || old.b === base.b || old.a.group === old.b.group && old.a.group === base.a.group && old.a.group === base.b.group))
          continue;
        const requiredGap = sameNet ? Math.min(
          c2.radius + clearance + base.radius,
          segmentDistance([old.a, old.b], [base.a, base.b])
        ) : c2.radius + clearance + (base.rect ? 0 : base.radius);
        if (clearanceToCopper(c2.a, c2.b, other) >= requiredGap - (base.rect ? 0 : base.radius) - 1e-9)
          continue;
        const key = `${ci}:${identities.get(other)}`;
        const groupKey = `${old.a.group}:${old.b.group}:${base.a.group}:${base.b.group}:${lookup.has(other) ? "moving" : "f" + identities.get(other)}`;
        if (used.has(key) || (groupPairs.get(groupKey) ?? 0) >= 4) continue;
        groupPairs.set(groupKey, (groupPairs.get(groupKey) ?? 0) + 1);
        used.add(key);
        const corners = base.rect ? [
          { x: base.rect.minX, y: base.rect.minY },
          { x: base.rect.maxX, y: base.rect.minY },
          { x: base.rect.maxX, y: base.rect.maxY },
          { x: base.rect.minX, y: base.rect.maxY }
        ] : [base.a, base.b];
        const directions = [
          { x: 1, y: 0 },
          { x: 0, y: 1 }
        ];
        for (const a2 of [old.a, old.b])
          for (let j2 = 0; j2 < corners.length; j2++) {
            const b2 = projection(
              a2,
              corners[j2],
              corners[(j2 + 1) % corners.length]
            );
            directions.push({ x: a2.x - b2.x, y: a2.y - b2.y });
          }
        for (const b2 of corners) {
          const a2 = projection(b2, old.a, old.b);
          directions.push({ x: a2.x - b2.x, y: a2.y - b2.y });
        }
        let best, gap = -Infinity;
        for (const u2 of directions) {
          const size = Math.hypot(u2.x, u2.y);
          if (size < 1e-10) continue;
          for (const sign of [-1, 1]) {
            const n2 = { x: u2.x / size * sign, y: u2.y / size * sign }, g2 = Math.min(...[old.a, old.b].map((p2) => p2.x * n2.x + p2.y * n2.y)) - Math.max(...corners.map((p2) => p2.x * n2.x + p2.y * n2.y));
            if (g2 > gap) {
              gap = g2;
              best = n2;
            }
          }
        }
        if (!best || gap < 0) return traces;
        const required = Math.min(gap, requiredGap + 1e-6);
        for (const a2 of [old.a, old.b])
          for (const b2 of corners) {
            const coeff = /* @__PURE__ */ new Map();
            term(coeff, a2, best);
            term(coeff, b2, best, -1);
            add(coeff, {
              min: required - ((a2.x - b2.x) * best.x + (a2.y - b2.y) * best.y)
            });
          }
        added++;
      }
    }
    if (!added || pass === MAX_CUT_PASSES - 1)
      return traces.map((t48, i2) => ({
        ...t48,
        route: t48.route.map((p2, j2) => ({
          ...p2,
          x: at2(paths[i2][j2]).x,
          y: at2(paths[i2][j2]).y
        }))
      }));
  }
  return traces;
}

// lib/carrier-compaction-view.ts
function carrierCompactionView(input, traces) {
  const runs = traces.map((trace) => {
    let best = { start: 0, end: 0, length: 0 };
    let start = 0, span = 0;
    for (let i2 = 1; i2 < trace.route.length; i2++) {
      const a2 = trace.route[i2 - 1], b2 = trace.route[i2];
      if (a2.route_type !== "wire" || b2.route_type !== "wire" || a2.layer !== b2.layer) {
        start = i2;
        span = 0;
        continue;
      }
      span += distance(a2, b2);
      if (span > best.length) best = { start, end: i2, length: span };
    }
    return best;
  });
  if (runs.some((run) => run.end <= run.start)) return null;
  const carriers = traces.map((trace, i2) => {
    const { start, end } = runs[i2];
    return {
      ...trace,
      route: trace.route.slice(start, end + 1),
      curvedSegments: trace.curvedSegments?.filter((k2) => k2 > start && k2 <= end).map((k2) => k2 - start),
      coupledSection: trace.coupledSection?.map((k2) => k2 - start)
    };
  });
  const byName = new Map(
    carriers.map((trace) => [trace.connection_name, trace])
  );
  if (input.connections.some((c2) => !byName.has(c2.name))) return null;
  const local = {
    ...input,
    connections: input.connections.map((c2) => {
      const carrier = byName.get(c2.name);
      return {
        ...c2,
        pointsToConnect: [
          carrier.route[0],
          carrier.route.at(-1)
        ]
      };
    }),
    traces: [
      ...input.traces ?? [],
      ...traces.flatMap((trace, i2) => {
        const { start, end } = runs[i2];
        return [
          ...start ? [{ ...trace, route: trace.route.slice(0, start + 1) }] : [],
          ...end < trace.route.length - 1 ? [{ ...trace, route: trace.route.slice(end) }] : []
        ];
      })
    ]
  };
  return {
    input: local,
    carriers,
    join: (result) => traces.map((trace, i2) => ({
      ...trace,
      route: [
        ...trace.route.slice(0, runs[i2].start),
        ...result[i2].route,
        ...trace.route.slice(runs[i2].end + 1)
      ]
    }))
  };
}
function signalEnvelope(traces) {
  let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
  for (const trace of traces)
    for (const p2 of trace.route) {
      const radius = p2.route_type === "wire" ? p2.width / 2 : (p2.via_diameter ?? 0.3) / 2;
      minX = Math.min(minX, p2.x - radius);
      maxX = Math.max(maxX, p2.x + radius);
      minY = Math.min(minY, p2.y - radius);
      maxY = Math.max(maxY, p2.y + radius);
    }
  return {
    minX,
    maxX,
    minY,
    maxY,
    areaMm2: traces.length ? (maxX - minX) * (maxY - minY) : 0
  };
}

// lib/compact-unconstrained-lanes.ts
var cross2 = (a2, b2) => a2.x * b2.y - a2.y * b2.x;
var vector = (a2, b2) => ({ x: b2.x - a2.x, y: b2.y - a2.y });
var dot = (a2, b2) => a2.x * b2.x + a2.y * b2.y;
function intersection(a2, u2, b2, v2) {
  const denominator = cross2(u2, v2);
  if (Math.abs(denominator) < 1e-8) return null;
  const t48 = cross2(vector(a2, b2), v2) / denominator;
  return { x: a2.x + t48 * u2.x, y: a2.y + t48 * u2.y };
}
function compactUnconstrainedLanes(input, traces) {
  if (!traces.length) return traces;
  const locked = /* @__PURE__ */ new Set([
    ...input.buses?.flatMap((b2) => b2.connectionNames) ?? [],
    ...input.differentialPairs?.flatMap((p2) => p2.connectionNames) ?? []
  ]);
  const result = structuredClone(traces);
  const free = result.filter(
    (t48) => !locked.has(t48.connection_name) && !t48.coupledSection && !t48.curvedSegments?.length && t48.route.every(
      (p2) => p2.route_type === "wire" && p2.layer === t48.route[0].layer
    )
  );
  if (!free.length) return traces;
  const terminals = result.flatMap((t48) => [t48.route[0], t48.route.at(-1)]);
  const span = result.reduce(
    (s2, t48) => ({
      x: s2.x + Math.abs(t48.route[0].x - t48.route.at(-1).x),
      y: s2.y + Math.abs(t48.route[0].y - t48.route.at(-1).y)
    }),
    { x: 0, y: 0 }
  );
  const axis = span.x > span.y ? "y" : "x";
  const center = terminals.reduce((s2, p2) => s2 + p2[axis], 0) / terminals.length;
  const cost = (path) => path.slice(1).reduce(
    (s2, b2, i2) => s2 + distance(path[i2], b2) * (Math.abs(path[i2][axis] - center) + Math.abs(b2[axis] - center)) / 2,
    0
  );
  const fixed = fixedCopper(input);
  for (let pass = 0; pass < 8; pass++) {
    let changed = false;
    free.sort((a2, b2) => cost(a2.route) - cost(b2.route));
    for (const trace of free) {
      const connection = input.connections.find(
        (c2) => c2.name === trace.connection_name
      );
      if (!connection) continue;
      const width = trace.route[0].width;
      const scene = new VectorScene(input, connection, width, [
        ...fixed,
        ...result.flatMap(routeCopper)
      ]);
      let path = trace.route, score = cost(path), span2 = length(path);
      for (let i2 = 1; i2 < path.length - 2; i2++) {
        const a2 = path[i2 - 1], b2 = path[i2], c2 = path[i2 + 1], e2 = path[i2 + 2];
        const v2 = vector(b2, c2), size = distance(b2, c2);
        if (size < width * 2) continue;
        const normal = { x: -v2.y / size, y: v2.x / size };
        let best = path;
        for (const factor of [
          20,
          10,
          5,
          2.5,
          1,
          0.5,
          -20,
          -10,
          -5,
          -2.5,
          -1,
          -0.5
        ]) {
          const q2 = {
            x: b2.x + factor * width * normal.x,
            y: b2.y + factor * width * normal.y
          };
          const p2 = intersection(a2, vector(a2, b2), q2, v2), r2 = intersection(e2, vector(e2, c2), q2, v2);
          if (!p2 || !r2 || dot(vector(a2, p2), vector(a2, b2)) <= 1e-8 || dot(vector(e2, r2), vector(e2, c2)) <= 1e-8 || dot(vector(p2, r2), v2) <= 1e-8)
            continue;
          if (["x", "y"].some((dimension) => {
            const lo = Math.min(...path.map((p3) => p3[dimension]));
            const hi = Math.max(...path.map((p3) => p3[dimension]));
            return [p2, r2].some(
              (point) => point[dimension] < lo - 1e-8 || point[dimension] > hi + 1e-8
            );
          }))
            continue;
          const candidate = [
            ...path.slice(0, i2),
            { ...b2, ...p2 },
            { ...c2, ...r2 },
            ...path.slice(i2 + 2)
          ];
          const nextScore = cost(candidate), nextSpan = length(candidate);
          if (nextScore >= score - 1e-6 || nextSpan > span2 + 1e-8 || !scene.pathVisible([a2, p2, r2, e2]) || !tuningPathIsSelfClear(candidate, width / 2 + scene.margin))
            continue;
          best = candidate;
          score = nextScore;
          span2 = nextSpan;
        }
        if (best !== path) {
          path = best;
          changed = true;
        }
      }
      trace.route = path;
    }
    if (!changed) break;
  }
  return result;
}

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/geometry.ts
var EPSILON = 1e-9;
function obstacleIsCircular(obstacle) {
  return obstacle.shape === "circle";
}
function toObstacleLocalPoint(point, obstacle) {
  const rotationRadians = -(obstacle.ccwRotationDegrees ?? 0) * Math.PI / 180;
  const dx2 = point.x - obstacle.center.x;
  const dy2 = point.y - obstacle.center.y;
  return {
    x: dx2 * Math.cos(rotationRadians) - dy2 * Math.sin(rotationRadians),
    y: dx2 * Math.sin(rotationRadians) + dy2 * Math.cos(rotationRadians)
  };
}
function distance3(a2, b2) {
  return Math.hypot(a2.x - b2.x, a2.y - b2.y);
}
function distancePointToSegment(point, start, end) {
  const dx2 = end.x - start.x;
  const dy2 = end.y - start.y;
  const lengthSquared = dx2 * dx2 + dy2 * dy2;
  const rawT = lengthSquared < EPSILON ? 0 : ((point.x - start.x) * dx2 + (point.y - start.y) * dy2) / lengthSquared;
  const t48 = Math.max(0, Math.min(1, rawT));
  return Math.hypot(point.x - (start.x + t48 * dx2), point.y - (start.y + t48 * dy2));
}
function cross3(origin, a2, b2) {
  return (a2.x - origin.x) * (b2.y - origin.y) - (a2.y - origin.y) * (b2.x - origin.x);
}
function segmentsProperlyCross(a2, b2, c2, d2) {
  const d1 = cross3(c2, d2, a2);
  const d22 = cross3(c2, d2, b2);
  const d3 = cross3(a2, b2, c2);
  const d4 = cross3(a2, b2, d2);
  return (d1 > 0 && d22 < 0 || d1 < 0 && d22 > 0) && (d3 > 0 && d4 < 0 || d3 < 0 && d4 > 0);
}
function distanceSegmentToSegment(firstStart, firstEnd, secondStart, secondEnd) {
  if (segmentsProperlyCross(firstStart, firstEnd, secondStart, secondEnd)) {
    return 0;
  }
  return Math.min(
    distancePointToSegment(firstStart, secondStart, secondEnd),
    distancePointToSegment(firstEnd, secondStart, secondEnd),
    distancePointToSegment(secondStart, firstStart, firstEnd),
    distancePointToSegment(secondEnd, firstStart, firstEnd)
  );
}
function pointIsInsideObstacle(point, obstacle, tolerance = EPSILON) {
  if (obstacleIsCircular(obstacle)) {
    return distance3(point, obstacle.center) <= obstacle.width / 2 + tolerance;
  }
  const localPoint = toObstacleLocalPoint(point, obstacle);
  return Math.abs(localPoint.x) <= obstacle.width / 2 + tolerance && Math.abs(localPoint.y) <= obstacle.height / 2 + tolerance;
}
function distancePointToObstacle(point, obstacle) {
  if (obstacleIsCircular(obstacle)) {
    return Math.max(0, distance3(point, obstacle.center) - obstacle.width / 2);
  }
  const localPoint = toObstacleLocalPoint(point, obstacle);
  const dx2 = Math.max(Math.abs(localPoint.x) - obstacle.width / 2, 0);
  const dy2 = Math.max(Math.abs(localPoint.y) - obstacle.height / 2, 0);
  return Math.hypot(dx2, dy2);
}
function distanceSegmentToObstacle(segment, obstacle) {
  if (obstacleIsCircular(obstacle)) {
    return Math.max(
      0,
      distancePointToSegment(obstacle.center, segment.start, segment.end) - obstacle.width / 2
    );
  }
  const localStart = toObstacleLocalPoint(segment.start, obstacle);
  const localEnd = toObstacleLocalPoint(segment.end, obstacle);
  if (Math.abs(localStart.x) <= obstacle.width / 2 + EPSILON && Math.abs(localStart.y) <= obstacle.height / 2 + EPSILON) {
    return 0;
  }
  if (Math.abs(localEnd.x) <= obstacle.width / 2 + EPSILON && Math.abs(localEnd.y) <= obstacle.height / 2 + EPSILON) {
    return 0;
  }
  const minX = -obstacle.width / 2;
  const maxX = obstacle.width / 2;
  const minY = -obstacle.height / 2;
  const maxY = obstacle.height / 2;
  const corners = [
    { x: minX, y: minY },
    { x: maxX, y: minY },
    { x: maxX, y: maxY },
    { x: minX, y: maxY }
  ];
  let minimumDistance = Number.POSITIVE_INFINITY;
  for (let index2 = 0; index2 < corners.length; index2++) {
    minimumDistance = Math.min(
      minimumDistance,
      distanceSegmentToSegment(
        localStart,
        localEnd,
        corners[index2],
        corners[(index2 + 1) % corners.length]
      )
    );
  }
  return minimumDistance;
}
function segmentsAreClear(first, second, clearance) {
  if (first.layer !== second.layer) return true;
  const requiredDistance = (first.width + second.width) / 2 + clearance;
  const broadPhaseDistance = requiredDistance + EPSILON;
  if (Math.min(first.start.x, first.end.x) - Math.max(second.start.x, second.end.x) > broadPhaseDistance || Math.min(second.start.x, second.end.x) - Math.max(first.start.x, first.end.x) > broadPhaseDistance || Math.min(first.start.y, first.end.y) - Math.max(second.start.y, second.end.y) > broadPhaseDistance || Math.min(second.start.y, second.end.y) - Math.max(first.start.y, first.end.y) > broadPhaseDistance) {
    return true;
  }
  return distanceSegmentToSegment(
    first.start,
    first.end,
    second.start,
    second.end
  ) >= requiredDistance - EPSILON;
}

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/layer-names.ts
function getCopperLayerNames(layerCount) {
  if (!Number.isInteger(layerCount) || layerCount < 1) {
    throw new Error(
      `FanoutSolver: layerCount must be a positive integer, received ${layerCount}`
    );
  }
  if (layerCount === 1) return ["top"];
  if (layerCount === 2) return ["top", "bottom"];
  return [
    "top",
    ...Array.from(
      { length: layerCount - 2 },
      (_2, index2) => `inner${index2 + 1}`
    ),
    "bottom"
  ];
}
function getLayerSpan(fromLayer, toLayer, layerNames) {
  const fromIndex = layerNames.indexOf(fromLayer);
  const toIndex = layerNames.indexOf(toLayer);
  if (fromIndex < 0 || toIndex < 0) {
    throw new Error(
      `FanoutSolver: cannot build via span from "${fromLayer}" to "${toLayer}"`
    );
  }
  const firstIndex = Math.min(fromIndex, toIndex);
  const lastIndex = Math.max(fromIndex, toIndex);
  return layerNames.slice(firstIndex, lastIndex + 1);
}
function getViaSpanLayers(params) {
  const { fromLayer, toLayer, layerNames, allowBlindAndBuriedVias } = params;
  const logicalSpan = getLayerSpan(fromLayer, toLayer, layerNames);
  return allowBlindAndBuriedVias ? logicalSpan : [...layerNames];
}

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/fanout-exit-position.ts
var FANOUT_EXIT_POSITION_CONFIGS = {
  topside_left: {
    direction: "left",
    preferredExit: "top-left",
    exitEdge: "top"
  },
  topside_center: {
    direction: "up",
    preferredExit: "top",
    exitEdge: "top"
  },
  topside_right: {
    direction: "right",
    preferredExit: "top-right",
    exitEdge: "top"
  },
  rightside_top: {
    direction: "up",
    preferredExit: "top-right",
    exitEdge: "right"
  },
  rightside_center: {
    direction: "right",
    preferredExit: "right",
    exitEdge: "right"
  },
  rightside_bottom: {
    direction: "down",
    preferredExit: "bottom-right",
    exitEdge: "right"
  },
  bottomside_right: {
    direction: "right",
    preferredExit: "bottom-right",
    exitEdge: "bottom"
  },
  bottomside_center: {
    direction: "down",
    preferredExit: "bottom",
    exitEdge: "bottom"
  },
  bottomside_left: {
    direction: "left",
    preferredExit: "bottom-left",
    exitEdge: "bottom"
  },
  leftside_bottom: {
    direction: "down",
    preferredExit: "bottom-left",
    exitEdge: "left"
  },
  leftside_center: {
    direction: "left",
    preferredExit: "left",
    exitEdge: "left"
  },
  leftside_top: {
    direction: "up",
    preferredExit: "top-left",
    exitEdge: "left"
  },
  center: {}
};
function getFanoutExitPositionConfig(exitPosition) {
  const config = FANOUT_EXIT_POSITION_CONFIGS[exitPosition];
  if (!config) {
    throw new Error(`Invalid fanout exit position "${exitPosition}"`);
  }
  return config;
}

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/boundary-exit.ts
function borderTargetIncludesEdge(preferredExit, exitEdge) {
  return preferredExit === exitEdge || preferredExit.includes(exitEdge);
}
function getCornerBandSide(exitEdge, preferredExit) {
  if (!exitEdge || !preferredExit?.includes("-")) return void 0;
  if (!borderTargetIncludesEdge(preferredExit, exitEdge)) return void 0;
  if (exitEdge === "left" || exitEdge === "right") {
    return preferredExit.startsWith("top-") ? "maximum" : "minimum";
  }
  return preferredExit.endsWith("-right") ? "maximum" : "minimum";
}

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/match-component-dogbone-via-sites.ts
var EPSILON2 = 1e-9;
var DEFAULT_MAXIMUM_SEARCH_STATES = 1e5;
function assertGeometryRules(rules) {
  for (const [name, value] of [
    ["viaDiameter", rules.viaDiameter],
    ["traceWidth", rules.traceWidth]
  ]) {
    if (!Number.isFinite(value) || value <= 0) {
      throw new Error(
        `FanoutSolver: dogbone ${name} must be a positive finite number, received ${value}`
      );
    }
  }
  if (!Number.isFinite(rules.clearance) || rules.clearance < 0) {
    throw new Error(
      `FanoutSolver: dogbone clearance must be a non-negative finite number, received ${rules.clearance}`
    );
  }
  if (rules.viaHoleDiameter !== void 0 && (!Number.isFinite(rules.viaHoleDiameter) || rules.viaHoleDiameter <= 0)) {
    throw new Error(
      `FanoutSolver: dogbone viaHoleDiameter must be a positive finite number, received ${rules.viaHoleDiameter}`
    );
  }
  if (rules.holeToHoleClearance !== void 0 && (!Number.isFinite(rules.holeToHoleClearance) || rules.holeToHoleClearance < 0)) {
    throw new Error(
      `FanoutSolver: dogbone holeToHoleClearance must be a non-negative finite number, received ${rules.holeToHoleClearance}`
    );
  }
  if (rules.holeToHoleClearance !== void 0 && rules.viaHoleDiameter === void 0) {
    throw new Error(
      "FanoutSolver: dogbone holeToHoleClearance requires viaHoleDiameter"
    );
  }
  const maximumSearchStates = rules.maximumSearchStates ?? DEFAULT_MAXIMUM_SEARCH_STATES;
  if (!Number.isInteger(maximumSearchStates) || maximumSearchStates < 1) {
    throw new Error(
      `FanoutSolver: dogbone maximumSearchStates must be a positive integer, received ${maximumSearchStates}`
    );
  }
  return maximumSearchStates;
}
function uniqueSortedCoordinates(values) {
  const result = [];
  for (const value of values.toSorted((first, second) => first - second)) {
    if (!Number.isFinite(value)) continue;
    if (result.length === 0 || Math.abs(result.at(-1) - value) > EPSILON2) {
      result.push(value);
    }
  }
  return result;
}
function getComponentMatchingInputs(preparedBuses) {
  const byComponent = /* @__PURE__ */ new Map();
  const componentByConnectionIndex = /* @__PURE__ */ new Map();
  const obstacleSetByComponentId = /* @__PURE__ */ new Map();
  for (const bus of preparedBuses) {
    let component = byComponent.get(bus.componentId);
    if (!component) {
      component = {
        componentId: bus.componentId,
        connections: [],
        obstacles: [],
        xCoordinates: [],
        yCoordinates: [],
        pitchX: Number.POSITIVE_INFINITY,
        pitchY: Number.POSITIVE_INFINITY
      };
      byComponent.set(bus.componentId, component);
      obstacleSetByComponentId.set(bus.componentId, /* @__PURE__ */ new Set());
    }
    component.xCoordinates.push(...bus.xCoordinates);
    component.yCoordinates.push(...bus.yCoordinates);
    if (Number.isFinite(bus.pitchX) && bus.pitchX > EPSILON2) {
      component.pitchX = Math.min(component.pitchX, bus.pitchX);
    }
    if (Number.isFinite(bus.pitchY) && bus.pitchY > EPSILON2) {
      component.pitchY = Math.min(component.pitchY, bus.pitchY);
    }
    const obstacleSet = obstacleSetByComponentId.get(bus.componentId);
    for (const obstacle of bus.componentObstacles) {
      if (!obstacleSet.has(obstacle)) {
        obstacleSet.add(obstacle);
        component.obstacles.push(obstacle);
      }
    }
    for (const preparedConnection of bus.connections) {
      const existingComponent = componentByConnectionIndex.get(
        preparedConnection.connectionIndex
      );
      if (existingComponent !== void 0) {
        if (existingComponent !== bus.componentId) {
          throw new Error(
            `FanoutSolver: connection index ${preparedConnection.connectionIndex} belongs to multiple components`
          );
        }
        continue;
      }
      componentByConnectionIndex.set(
        preparedConnection.connectionIndex,
        bus.componentId
      );
      component.connections.push({
        preparedConnection,
        busId: bus.busId,
        direction: bus.direction,
        terminationType: bus.termination.type
      });
    }
  }
  return [...byComponent.values()].map((component) => ({
    ...component,
    connections: component.connections.toSorted(
      (first, second) => first.preparedConnection.connectionIndex - second.preparedConnection.connectionIndex
    ),
    xCoordinates: uniqueSortedCoordinates(component.xCoordinates),
    yCoordinates: uniqueSortedCoordinates(component.yCoordinates)
  })).toSorted(
    (first, second) => first.componentId.localeCompare(second.componentId)
  );
}
function getInterstitialCoordinates(params) {
  const { coordinates, pitch } = params;
  if (coordinates.length === 0 || !Number.isFinite(pitch) || pitch <= EPSILON2) {
    return [];
  }
  const interstitialCoordinates = [coordinates[0] - pitch / 2];
  for (let index2 = 1; index2 < coordinates.length; index2++) {
    interstitialCoordinates.push(
      (coordinates[index2 - 1] + coordinates[index2]) / 2
    );
  }
  interstitialCoordinates.push(coordinates.at(-1) + pitch / 2);
  return uniqueSortedCoordinates(interstitialCoordinates);
}
function getAdjacentInterstitialCoordinates(params) {
  const { sourceCoordinate, coordinates, pitch } = params;
  const interstitialCoordinates = getInterstitialCoordinates({
    coordinates,
    pitch
  });
  const before = interstitialCoordinates.filter((coordinate) => coordinate < sourceCoordinate - EPSILON2).at(-1);
  const after = interstitialCoordinates.find(
    (coordinate) => coordinate > sourceCoordinate + EPSILON2
  );
  return [before, after].filter(
    (coordinate) => coordinate !== void 0
  );
}
function directSegmentIsStraightOr45(start, end) {
  const absoluteX = Math.abs(end.x - start.x);
  const absoluteY = Math.abs(end.y - start.y);
  return absoluteX <= EPSILON2 || absoluteY <= EPSILON2 || Math.abs(absoluteX - absoluteY) <= EPSILON2;
}
function getOutwardRank(params) {
  const { source, site, direction } = params;
  const outwardDisplacement = direction === "right" ? site.x - source.x : direction === "left" ? source.x - site.x : direction === "up" ? site.y - source.y : source.y - site.y;
  return outwardDisplacement > EPSILON2 ? 0 : Math.abs(outwardDisplacement) <= EPSILON2 ? 1 : 2;
}
function viaSiteClearsObstacles(params) {
  const { point, obstacles, viaDiameter, clearance } = params;
  const requiredClearance = viaDiameter / 2 + clearance;
  return obstacles.every(
    (obstacle) => distancePointToObstacle(point, obstacle) >= requiredClearance - EPSILON2
  );
}
function sourceSegmentClearsOtherObstacles(params) {
  const { segment, sourceObstacle, obstacles, clearance } = params;
  const requiredClearance = segment.width / 2 + clearance;
  return obstacles.every(
    (obstacle) => obstacle === sourceObstacle || distanceSegmentToObstacle(segment, obstacle) >= requiredClearance - EPSILON2
  );
}
function getConnectionCandidates(params) {
  const { connection, component, rules } = params;
  const { preparedConnection, direction } = connection;
  const obstacles = rules.additionalObstacles ? [.../* @__PURE__ */ new Set([...component.obstacles, ...rules.additionalObstacles])] : component.obstacles;
  const source = {
    x: preparedConnection.sourcePoint.x,
    y: preparedConnection.sourcePoint.y
  };
  const adjacentX = getAdjacentInterstitialCoordinates({
    sourceCoordinate: source.x,
    coordinates: component.xCoordinates,
    pitch: component.pitchX
  });
  const adjacentY = getAdjacentInterstitialCoordinates({
    sourceCoordinate: source.y,
    coordinates: component.yCoordinates,
    pitch: component.pitchY
  });
  const rawPoints = [
    ...adjacentX.map((x2) => ({ x: x2, y: source.y })),
    ...adjacentY.map((y2) => ({ x: source.x, y: y2 })),
    ...adjacentX.flatMap((x2) => adjacentY.map((y2) => ({ x: x2, y: y2 })))
  ];
  const uniquePoints = [];
  for (const point of rawPoints) {
    if (!uniquePoints.some((candidate) => distance3(candidate, point) <= EPSILON2)) {
      uniquePoints.push(point);
    }
  }
  const fixedViaPoint = rules.fixedViaPointsByConnectionIndex?.get(
    preparedConnection.connectionIndex
  );
  const candidatePoints = fixedViaPoint ? [fixedViaPoint] : uniquePoints;
  const candidates = [];
  for (const point of candidatePoints) {
    if (connection.terminationType === "plane" && !directSegmentIsStraightOr45(source, point)) {
      continue;
    }
    if (!viaSiteClearsObstacles({
      point,
      obstacles,
      viaDiameter: rules.viaDiameter,
      clearance: rules.clearance
    })) {
      continue;
    }
    const sourceSegment = {
      start: source,
      end: point,
      width: rules.traceWidth,
      layer: preparedConnection.sourceLayer
    };
    if (!sourceSegmentClearsOtherObstacles({
      segment: sourceSegment,
      sourceObstacle: preparedConnection.sourceObstacle,
      obstacles,
      clearance: rules.clearance
    })) {
      continue;
    }
    const candidateClearsRoutedCopper = (rules.blockingSegments ?? []).every(
      (blocker) => {
        if (blocker.connectionIndex === preparedConnection.connectionIndex) {
          return true;
        }
        if (rules.canShareCopper?.(
          preparedConnection.connectionIndex,
          blocker.connectionIndex
        )) {
          return true;
        }
        const viaToTraceClearance = rules.viaDiameter / 2 + blocker.segment.width / 2 + rules.clearance;
        if (distancePointToSegment(
          point,
          blocker.segment.start,
          blocker.segment.end
        ) < viaToTraceClearance - EPSILON2) {
          return false;
        }
        return blocker.segment.layer !== sourceSegment.layer || segmentsAreClear(sourceSegment, blocker.segment, rules.clearance);
      }
    );
    if (!candidateClearsRoutedCopper) continue;
    const candidateClearsRoutedVias = (rules.blockingVias ?? []).every(
      (blocker) => {
        if (blocker.connectionIndex === preparedConnection.connectionIndex) {
          return true;
        }
        if (distance3(point, blocker.center) < (rules.viaDiameter + blocker.diameter) / 2 + rules.clearance - EPSILON2) {
          return false;
        }
        if (blocker.spanLayers.includes(sourceSegment.layer) && distancePointToSegment(
          blocker.center,
          sourceSegment.start,
          sourceSegment.end
        ) < blocker.diameter / 2 + sourceSegment.width / 2 + rules.clearance - EPSILON2) {
          return false;
        }
        return true;
      }
    );
    if (!candidateClearsRoutedVias) continue;
    candidates.push({
      connectionIndex: preparedConnection.connectionIndex,
      point,
      sourceSegment,
      outwardRank: getOutwardRank({ source, site: point, direction })
    });
  }
  const perpendicularCoordinates = direction === "left" || direction === "right" ? component.yCoordinates : component.xCoordinates;
  const sourcePerpendicularCoordinate = direction === "left" || direction === "right" ? source.y : source.x;
  const perpendicularGridIndex = perpendicularCoordinates.findIndex(
    (coordinate) => Math.abs(coordinate - sourcePerpendicularCoordinate) <= EPSILON2
  );
  const planeCheckerboardSide = perpendicularGridIndex >= 0 ? perpendicularGridIndex % 2 === 0 ? 1 : -1 : void 0;
  const preferredPerpendicularSide = connection.terminationType === "boundary" ? rules.preferredBoundaryPerpendicularSideByBusId?.get(connection.busId) : rules.preferPlaneCheckerboardSites && connection.terminationType === "plane" && (direction === "left" || direction === "right") ? planeCheckerboardSide : void 0;
  const preferOutward = connection.terminationType === "boundary" ? rules.preferBoundaryOutwardByBusId?.get(connection.busId) ?? true : true;
  const preferredViaPoint = rules.preferredViaPointsByConnectionIndex?.get(
    preparedConnection.connectionIndex
  );
  const getPerpendicularPreferenceRank = (candidate) => {
    if (preferredPerpendicularSide === void 0) return 0;
    const displacement = direction === "left" || direction === "right" ? candidate.point.y - source.y : candidate.point.x - source.x;
    return displacement * preferredPerpendicularSide > EPSILON2 ? 0 : Math.abs(displacement) <= EPSILON2 ? 1 : 2;
  };
  return candidates.toSorted(
    (first, second) => (preferredViaPoint ? Number(distance3(first.point, preferredViaPoint) > EPSILON2) - Number(distance3(second.point, preferredViaPoint) > EPSILON2) : 0) || (preferOutward ? first.outwardRank - second.outwardRank : second.outwardRank - first.outwardRank) || getPerpendicularPreferenceRank(first) - getPerpendicularPreferenceRank(second) || distance3(source, first.point) - distance3(source, second.point) || first.point.x - second.point.x || first.point.y - second.point.y
  );
}
function candidatesAreMutuallyClear(params) {
  const { first, second, rules } = params;
  const canShareCopper = rules.canShareCopper?.(first.connectionIndex, second.connectionIndex) ?? false;
  const requiredHoleSeparation = rules.viaHoleDiameter ? rules.viaHoleDiameter + (rules.holeToHoleClearance ?? rules.clearance) : 0;
  const requiredViaSeparation = canShareCopper ? requiredHoleSeparation : Math.max(rules.viaDiameter + rules.clearance, requiredHoleSeparation);
  if (distance3(first.point, second.point) < requiredViaSeparation - EPSILON2) {
    return false;
  }
  const requiredViaToTraceClearance = rules.viaDiameter / 2 + rules.traceWidth / 2 + rules.clearance;
  if (!canShareCopper) {
    if (distancePointToSegment(
      first.point,
      second.sourceSegment.start,
      second.sourceSegment.end
    ) < requiredViaToTraceClearance - EPSILON2 || distancePointToSegment(
      second.point,
      first.sourceSegment.start,
      first.sourceSegment.end
    ) < requiredViaToTraceClearance - EPSILON2) {
      return false;
    }
  }
  if (canShareCopper) return true;
  return segmentsAreClear(
    first.sourceSegment,
    second.sourceSegment,
    rules.clearance
  );
}
function matchComponent(params) {
  const { component, rules, consumeSearchState } = params;
  const entries = component.connections.map(
    (connection) => ({
      connection,
      candidates: getConnectionCandidates({ connection, component, rules })
    })
  );
  if (entries.some((entry) => entry.candidates.length === 0)) return null;
  const compatibilityCache = /* @__PURE__ */ new Map();
  const candidatesAreCompatible = (first, second) => {
    const cached = compatibilityCache.get(first)?.get(second);
    if (cached !== void 0) return cached;
    const compatible = candidatesAreMutuallyClear({ first, second, rules });
    const firstCache = compatibilityCache.get(first) ?? /* @__PURE__ */ new Map();
    firstCache.set(second, compatible);
    compatibilityCache.set(first, firstCache);
    const secondCache = compatibilityCache.get(second) ?? /* @__PURE__ */ new Map();
    secondCache.set(first, compatible);
    compatibilityCache.set(second, secondCache);
    return compatible;
  };
  const forcedCandidates = entries.flatMap(
    (entry) => entry.candidates.length === 1 ? [entry.candidates[0]] : []
  );
  for (let candidateIndex = 0; candidateIndex < forcedCandidates.length; candidateIndex++) {
    const candidate = forcedCandidates[candidateIndex];
    for (let previousIndex = 0; previousIndex < candidateIndex; previousIndex++) {
      if (!candidatesAreCompatible(candidate, forcedCandidates[previousIndex])) {
        return null;
      }
    }
  }
  const assignedCandidates = new Map(
    forcedCandidates.map((candidate) => [candidate.connectionIndex, candidate])
  );
  const remaining = new Set(
    entries.flatMap(
      (entry) => entry.candidates.length > 1 ? [entry.connection.preparedConnection.connectionIndex] : []
    )
  );
  const entryByConnectionIndex = new Map(
    entries.map((entry) => [
      entry.connection.preparedConnection.connectionIndex,
      entry
    ])
  );
  if (remaining.size === 0) {
    return new Map(
      [...assignedCandidates.entries()].map(([connectionIndex, candidate]) => [
        connectionIndex,
        { ...candidate.point }
      ])
    );
  }
  const getViableCandidates = (entry) => entry.candidates.filter(
    (candidate) => [...assignedCandidates.values()].every(
      (assignedCandidate) => candidatesAreCompatible(candidate, assignedCandidate)
    )
  );
  const augmentMatching = () => {
    if (!consumeSearchState()) return false;
    if (remaining.size === 0) return true;
    let selectedEntry;
    let selectedCandidates = [];
    for (const connectionIndex2 of [...remaining].toSorted(
      (first, second) => first - second
    )) {
      const entry = entryByConnectionIndex.get(connectionIndex2);
      const viableCandidates = getViableCandidates(entry);
      if (viableCandidates.length === 0) return false;
      if (!selectedEntry || viableCandidates.length < selectedCandidates.length || viableCandidates.length === selectedCandidates.length && connectionIndex2 < selectedEntry.connection.preparedConnection.connectionIndex) {
        selectedEntry = entry;
        selectedCandidates = viableCandidates;
      }
    }
    const connectionIndex = selectedEntry.connection.preparedConnection.connectionIndex;
    remaining.delete(connectionIndex);
    for (const candidate of selectedCandidates) {
      assignedCandidates.set(connectionIndex, candidate);
      if (augmentMatching()) return true;
      assignedCandidates.delete(connectionIndex);
    }
    remaining.add(connectionIndex);
    return false;
  };
  if (!augmentMatching()) return null;
  return new Map(
    [...assignedCandidates.entries()].toSorted(([first], [second]) => first - second).map(([connectionIndex, candidate]) => [
      connectionIndex,
      { ...candidate.point }
    ])
  );
}
function matchComponentDogboneViaSites(preparedBuses, rules) {
  const maximumSearchStates = assertGeometryRules(rules);
  if (preparedBuses.length === 0) return /* @__PURE__ */ new Map();
  let consumedSearchStates = 0;
  const consumeSearchState = () => {
    consumedSearchStates++;
    return consumedSearchStates <= maximumSearchStates;
  };
  const result = /* @__PURE__ */ new Map();
  for (const component of getComponentMatchingInputs(preparedBuses)) {
    const componentResult = matchComponent({
      component,
      rules,
      consumeSearchState
    });
    if (!componentResult) return null;
    for (const [connectionIndex, point] of componentResult) {
      result.set(connectionIndex, point);
    }
  }
  return result;
}
function getComponentDogboneViaSiteCandidates(preparedBuses, rules) {
  assertGeometryRules(rules);
  return getComponentMatchingInputs(preparedBuses).flatMap(
    (component) => component.connections.flatMap(
      (connection) => getConnectionCandidates({ connection, component, rules }).map(
        (candidate) => ({
          connectionIndex: candidate.connectionIndex,
          point: { ...candidate.point }
        })
      )
    )
  );
}

// ../bus-lanes-solver/node_modules/@tscircuit/capacity-autorouter/dist/index.js
var import_object_hash = __toESM(require_object_hash(), 1);
var import_object_hash2 = __toESM(require_object_hash(), 1);
var import_object_hash3 = __toESM(require_object_hash(), 1);
var t = Object.create;
var e = Object.defineProperty;
var n = Object.getOwnPropertyDescriptor;
var o = Object.getOwnPropertyNames;
var i = Object.getPrototypeOf;
var r = Object.prototype.hasOwnProperty;
var s = (t48, e2) => function() {
  return e2 || (0, t48[o(t48)[0]])((e2 = { exports: {} }).exports, e2), e2.exports;
};
var a = (t48, n2) => {
  for (var o2 in n2) e(t48, o2, { get: n2[o2], enumerable: true });
};
var c = (s2, a2, c2) => (c2 = null != s2 ? t(i(s2)) : {}, ((t48, i2, s3, a3) => {
  if (i2 && "object" == typeof i2 || "function" == typeof i2) for (let c3 of o(i2)) r.call(t48, c3) || c3 === s3 || e(t48, c3, { get: () => i2[c3], enumerable: !(a3 = n(i2, c3)) || a3.enumerable });
  return t48;
})(!a2 && s2 && s2.__esModule ? c2 : e(c2, "default", { value: s2, enumerable: true }), s2));
var l = s({ "node_modules/is-buffer/index.js"(t48, e2) {
  function n2(t49) {
    return !!t49.constructor && "function" == typeof t49.constructor.isBuffer && t49.constructor.isBuffer(t49);
  }
  e2.exports = function(t49) {
    return null != t49 && (n2(t49) || (function(t50) {
      return "function" == typeof t50.readFloatLE && "function" == typeof t50.slice && n2(t50.slice(0, 0));
    })(t49) || !!t49._isBuffer);
  };
} });
var h = s({ "node_modules/kind-of/index.js"(t48, e2) {
  var n2 = l(), o2 = Object.prototype.toString;
  e2.exports = function(t49) {
    if (void 0 === t49) return "undefined";
    if (null === t49) return "null";
    if (true === t49 || false === t49 || t49 instanceof Boolean) return "boolean";
    if ("string" == typeof t49 || t49 instanceof String) return "string";
    if ("number" == typeof t49 || t49 instanceof Number) return "number";
    if ("function" == typeof t49 || t49 instanceof Function) return "function";
    if (void 0 !== Array.isArray && Array.isArray(t49)) return "array";
    if (t49 instanceof RegExp) return "regexp";
    if (t49 instanceof Date) return "date";
    var e3 = o2.call(t49);
    return "[object RegExp]" === e3 ? "regexp" : "[object Date]" === e3 ? "date" : "[object Arguments]" === e3 ? "arguments" : "[object Error]" === e3 ? "error" : n2(t49) ? "buffer" : "[object Set]" === e3 ? "set" : "[object WeakSet]" === e3 ? "weakset" : "[object Map]" === e3 ? "map" : "[object WeakMap]" === e3 ? "weakmap" : "[object Symbol]" === e3 ? "symbol" : "[object Int8Array]" === e3 ? "int8array" : "[object Uint8Array]" === e3 ? "uint8array" : "[object Uint8ClampedArray]" === e3 ? "uint8clampedarray" : "[object Int16Array]" === e3 ? "int16array" : "[object Uint16Array]" === e3 ? "uint16array" : "[object Int32Array]" === e3 ? "int32array" : "[object Uint32Array]" === e3 ? "uint32array" : "[object Float32Array]" === e3 ? "float32array" : "[object Float64Array]" === e3 ? "float64array" : "object";
  };
} });
var d = s({ "node_modules/rename-keys/index.js"(t48, e2) {
  !(function() {
    function t49(t50, e3) {
      if ("function" != typeof e3) return t50;
      var n2 = {};
      for (var o2 in t50) Object.prototype.hasOwnProperty.call(t50, o2) && (n2[e3(o2, t50[o2]) || o2] = t50[o2]);
      return n2;
    }
    void 0 !== e2 && e2.exports ? e2.exports = t49 : "function" == typeof define && define.amd ? define([], function() {
      return t49;
    }) : window.rename = t49;
  })();
} });
var u = s({ "node_modules/deep-rename-keys/index.js"(t48, e2) {
  var n2 = h(), o2 = d();
  e2.exports = function t49(e3, i2) {
    var r2 = n2(e3);
    if ("object" !== r2 && "array" !== r2) throw new Error("expected an object");
    var s2 = [];
    for (var a2 in "object" === r2 && (e3 = o2(e3, i2), s2 = {}), e3) if (e3.hasOwnProperty(a2)) {
      var c2 = e3[a2];
      "object" === n2(c2) || "array" === n2(c2) ? s2[a2] = t49(c2, i2) : s2[a2] = c2;
    }
    return s2;
  };
} });
var p = s({ "node_modules/xml-reader/node_modules/eventemitter3/index.js"(t48, e2) {
  var n2 = Object.prototype.hasOwnProperty, o2 = "~";
  function i2() {
  }
  function r2(t49, e3, n3) {
    this.fn = t49, this.context = e3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i2(), this._eventsCount = 0;
  }
  Object.create && (i2.prototype = /* @__PURE__ */ Object.create(null), new i2().__proto__ || (o2 = false)), s2.prototype.eventNames = function() {
    var t49, e3, i3 = [];
    if (0 === this._eventsCount) return i3;
    for (e3 in t49 = this._events) n2.call(t49, e3) && i3.push(o2 ? e3.slice(1) : e3);
    return Object.getOwnPropertySymbols ? i3.concat(Object.getOwnPropertySymbols(t49)) : i3;
  }, s2.prototype.listeners = function(t49, e3) {
    var n3 = o2 ? o2 + t49 : t49, i3 = this._events[n3];
    if (e3) return !!i3;
    if (!i3) return [];
    if (i3.fn) return [i3.fn];
    for (var r3 = 0, s3 = i3.length, a2 = new Array(s3); r3 < s3; r3++) a2[r3] = i3[r3].fn;
    return a2;
  }, s2.prototype.emit = function(t49, e3, n3, i3, r3, s3) {
    var a2 = o2 ? o2 + t49 : t49;
    if (!this._events[a2]) return false;
    var c2, l2, h2 = this._events[a2], d2 = arguments.length;
    if (h2.fn) {
      switch (h2.once && this.removeListener(t49, h2.fn, void 0, true), d2) {
        case 1:
          return h2.fn.call(h2.context), true;
        case 2:
          return h2.fn.call(h2.context, e3), true;
        case 3:
          return h2.fn.call(h2.context, e3, n3), true;
        case 4:
          return h2.fn.call(h2.context, e3, n3, i3), true;
        case 5:
          return h2.fn.call(h2.context, e3, n3, i3, r3), true;
        case 6:
          return h2.fn.call(h2.context, e3, n3, i3, r3, s3), true;
      }
      for (l2 = 1, c2 = new Array(d2 - 1); l2 < d2; l2++) c2[l2 - 1] = arguments[l2];
      h2.fn.apply(h2.context, c2);
    } else {
      var u2, p2 = h2.length;
      for (l2 = 0; l2 < p2; l2++) switch (h2[l2].once && this.removeListener(t49, h2[l2].fn, void 0, true), d2) {
        case 1:
          h2[l2].fn.call(h2[l2].context);
          break;
        case 2:
          h2[l2].fn.call(h2[l2].context, e3);
          break;
        case 3:
          h2[l2].fn.call(h2[l2].context, e3, n3);
          break;
        case 4:
          h2[l2].fn.call(h2[l2].context, e3, n3, i3);
          break;
        default:
          if (!c2) for (u2 = 1, c2 = new Array(d2 - 1); u2 < d2; u2++) c2[u2 - 1] = arguments[u2];
          h2[l2].fn.apply(h2[l2].context, c2);
      }
    }
    return true;
  }, s2.prototype.on = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.once = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this, true), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(t49, e3, n3, r3) {
    var s3 = o2 ? o2 + t49 : t49;
    if (!this._events[s3]) return this;
    if (!e3) return 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3], this;
    var a2 = this._events[s3];
    if (a2.fn) a2.fn !== e3 || r3 && !a2.once || n3 && a2.context !== n3 || (0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3]);
    else {
      for (var c2 = 0, l2 = [], h2 = a2.length; c2 < h2; c2++) (a2[c2].fn !== e3 || r3 && !a2[c2].once || n3 && a2[c2].context !== n3) && l2.push(a2[c2]);
      l2.length ? this._events[s3] = 1 === l2.length ? l2[0] : l2 : 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(t49) {
    var e3;
    return t49 ? (e3 = o2 ? o2 + t49 : t49, this._events[e3] && (0 === --this._eventsCount ? this._events = new i2() : delete this._events[e3])) : (this._events = new i2(), this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o2, s2.EventEmitter = s2, void 0 !== e2 && (e2.exports = s2);
} });
var m = s({ "node_modules/xml-lexer/node_modules/eventemitter3/index.js"(t48, e2) {
  var n2 = Object.prototype.hasOwnProperty, o2 = "~";
  function i2() {
  }
  function r2(t49, e3, n3) {
    this.fn = t49, this.context = e3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i2(), this._eventsCount = 0;
  }
  Object.create && (i2.prototype = /* @__PURE__ */ Object.create(null), new i2().__proto__ || (o2 = false)), s2.prototype.eventNames = function() {
    var t49, e3, i3 = [];
    if (0 === this._eventsCount) return i3;
    for (e3 in t49 = this._events) n2.call(t49, e3) && i3.push(o2 ? e3.slice(1) : e3);
    return Object.getOwnPropertySymbols ? i3.concat(Object.getOwnPropertySymbols(t49)) : i3;
  }, s2.prototype.listeners = function(t49, e3) {
    var n3 = o2 ? o2 + t49 : t49, i3 = this._events[n3];
    if (e3) return !!i3;
    if (!i3) return [];
    if (i3.fn) return [i3.fn];
    for (var r3 = 0, s3 = i3.length, a2 = new Array(s3); r3 < s3; r3++) a2[r3] = i3[r3].fn;
    return a2;
  }, s2.prototype.emit = function(t49, e3, n3, i3, r3, s3) {
    var a2 = o2 ? o2 + t49 : t49;
    if (!this._events[a2]) return false;
    var c2, l2, h2 = this._events[a2], d2 = arguments.length;
    if (h2.fn) {
      switch (h2.once && this.removeListener(t49, h2.fn, void 0, true), d2) {
        case 1:
          return h2.fn.call(h2.context), true;
        case 2:
          return h2.fn.call(h2.context, e3), true;
        case 3:
          return h2.fn.call(h2.context, e3, n3), true;
        case 4:
          return h2.fn.call(h2.context, e3, n3, i3), true;
        case 5:
          return h2.fn.call(h2.context, e3, n3, i3, r3), true;
        case 6:
          return h2.fn.call(h2.context, e3, n3, i3, r3, s3), true;
      }
      for (l2 = 1, c2 = new Array(d2 - 1); l2 < d2; l2++) c2[l2 - 1] = arguments[l2];
      h2.fn.apply(h2.context, c2);
    } else {
      var u2, p2 = h2.length;
      for (l2 = 0; l2 < p2; l2++) switch (h2[l2].once && this.removeListener(t49, h2[l2].fn, void 0, true), d2) {
        case 1:
          h2[l2].fn.call(h2[l2].context);
          break;
        case 2:
          h2[l2].fn.call(h2[l2].context, e3);
          break;
        case 3:
          h2[l2].fn.call(h2[l2].context, e3, n3);
          break;
        case 4:
          h2[l2].fn.call(h2[l2].context, e3, n3, i3);
          break;
        default:
          if (!c2) for (u2 = 1, c2 = new Array(d2 - 1); u2 < d2; u2++) c2[u2 - 1] = arguments[u2];
          h2[l2].fn.apply(h2[l2].context, c2);
      }
    }
    return true;
  }, s2.prototype.on = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.once = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this, true), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(t49, e3, n3, r3) {
    var s3 = o2 ? o2 + t49 : t49;
    if (!this._events[s3]) return this;
    if (!e3) return 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3], this;
    var a2 = this._events[s3];
    if (a2.fn) a2.fn !== e3 || r3 && !a2.once || n3 && a2.context !== n3 || (0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3]);
    else {
      for (var c2 = 0, l2 = [], h2 = a2.length; c2 < h2; c2++) (a2[c2].fn !== e3 || r3 && !a2[c2].once || n3 && a2[c2].context !== n3) && l2.push(a2[c2]);
      l2.length ? this._events[s3] = 1 === l2.length ? l2[0] : l2 : 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(t49) {
    var e3;
    return t49 ? (e3 = o2 ? o2 + t49 : t49, this._events[e3] && (0 === --this._eventsCount ? this._events = new i2() : delete this._events[e3])) : (this._events = new i2(), this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o2, s2.EventEmitter = s2, void 0 !== e2 && (e2.exports = s2);
} });
var g = s({ "node_modules/xml-lexer/dist/lexer.js"(t48, e2) {
  function n2(t49, e3, n3) {
    return e3 in t49 ? Object.defineProperty(t49, e3, { value: n3, enumerable: true, configurable: true, writable: true }) : t49[e3] = n3, t49;
  }
  var o2 = m(), i2 = function() {
  }, r2 = { 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" }, s2 = { lt: "action-lt", gt: "action-gt", space: "action-space", equal: "action-equal", quote: "action-quote", slash: "action-slash", char: "action-char", error: "action-error" }, a2 = { text: "text", openTag: "open-tag", closeTag: "close-tag", attributeName: "attribute-name", attributeValue: "attribute-value" }, c2 = { " ": s2.space, "	": s2.space, "\n": s2.space, "\r": s2.space, "<": s2.lt, ">": s2.gt, '"': s2.quote, "'": s2.quote, "=": s2.equal, "/": s2.slash };
  e2.exports = { State: r2, Action: s2, Type: a2, create: function(t49) {
    var e3, l2, h2, d2, u2, p2, m2, g2, f2, _2;
    t49 = Object.assign({ debug: false }, t49);
    var y2 = new o2(), b2 = r2.data, x2 = "", v2 = "", S2 = "", I2 = "", P2 = "", M2 = "", C2 = function(e4, n3) {
      if ("?" !== v2[0] && "!" !== v2[0]) {
        var o3 = { type: e4, value: n3 };
        t49.debug && console.log("emit:", o3), y2.emit("data", o3);
      }
    };
    y2.stateMachine = (n2(_2 = {}, r2.data, (n2(e3 = {}, s2.lt, function() {
      x2.trim() && C2(a2.text, x2), v2 = "", P2 = false, b2 = r2.tagBegin;
    }), n2(e3, s2.char, function(t50) {
      x2 += t50;
    }), e3)), n2(_2, r2.cdata, n2({}, s2.char, function(t50) {
      "]]>" === (x2 += t50).substr(-3) && (C2(a2.text, x2.slice(0, -3)), x2 = "", b2 = r2.data);
    })), n2(_2, r2.tagBegin, (n2(l2 = {}, s2.space, i2), n2(l2, s2.char, function(t50) {
      v2 = t50, b2 = r2.tagName;
    }), n2(l2, s2.slash, function() {
      v2 = "", P2 = true;
    }), l2)), n2(_2, r2.tagName, (n2(h2 = {}, s2.space, function() {
      P2 ? b2 = r2.tagEnd : (b2 = r2.attributeNameStart, C2(a2.openTag, v2));
    }), n2(h2, s2.gt, function() {
      C2(P2 ? a2.closeTag : a2.openTag, v2), x2 = "", b2 = r2.data;
    }), n2(h2, s2.slash, function() {
      b2 = r2.tagEnd, C2(a2.openTag, v2);
    }), n2(h2, s2.char, function(t50) {
      "![CDATA[" === (v2 += t50) && (b2 = r2.cdata, x2 = "", v2 = "");
    }), h2)), n2(_2, r2.tagEnd, (n2(d2 = {}, s2.gt, function() {
      C2(a2.closeTag, v2), x2 = "", b2 = r2.data;
    }), n2(d2, s2.char, i2), d2)), n2(_2, r2.attributeNameStart, (n2(u2 = {}, s2.char, function(t50) {
      S2 = t50, b2 = r2.attributeName;
    }), n2(u2, s2.gt, function() {
      x2 = "", b2 = r2.data;
    }), n2(u2, s2.space, i2), n2(u2, s2.slash, function() {
      P2 = true, b2 = r2.tagEnd;
    }), u2)), n2(_2, r2.attributeName, (n2(p2 = {}, s2.space, function() {
      b2 = r2.attributeNameEnd;
    }), n2(p2, s2.equal, function() {
      C2(a2.attributeName, S2), b2 = r2.attributeValueBegin;
    }), n2(p2, s2.gt, function() {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), x2 = "", b2 = r2.data;
    }), n2(p2, s2.slash, function() {
      P2 = true, I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), b2 = r2.tagEnd;
    }), n2(p2, s2.char, function(t50) {
      S2 += t50;
    }), p2)), n2(_2, r2.attributeNameEnd, (n2(m2 = {}, s2.space, i2), n2(m2, s2.equal, function() {
      C2(a2.attributeName, S2), b2 = r2.attributeValueBegin;
    }), n2(m2, s2.gt, function() {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), x2 = "", b2 = r2.data;
    }), n2(m2, s2.char, function(t50) {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), S2 = t50, b2 = r2.attributeName;
    }), m2)), n2(_2, r2.attributeValueBegin, (n2(g2 = {}, s2.space, i2), n2(g2, s2.quote, function(t50) {
      M2 = t50, I2 = "", b2 = r2.attributeValue;
    }), n2(g2, s2.gt, function() {
      C2(a2.attributeValue, I2 = ""), x2 = "", b2 = r2.data;
    }), n2(g2, s2.char, function(t50) {
      M2 = "", I2 = t50, b2 = r2.attributeValue;
    }), g2)), n2(_2, r2.attributeValue, (n2(f2 = {}, s2.space, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), b2 = r2.attributeNameStart);
    }), n2(f2, s2.quote, function(t50) {
      M2 === t50 ? (C2(a2.attributeValue, I2), b2 = r2.attributeNameStart) : I2 += t50;
    }), n2(f2, s2.gt, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), x2 = "", b2 = r2.data);
    }), n2(f2, s2.slash, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), P2 = true, b2 = r2.tagEnd);
    }), n2(f2, s2.char, function(t50) {
      I2 += t50;
    }), f2)), _2);
    var N2 = function(e4) {
      t49.debug && console.log(b2, e4);
      var n3 = y2.stateMachine[b2], o3 = n3[(function(t50) {
        return c2[t50] || s2.char;
      })(e4)] || n3[s2.error] || n3[s2.char];
      o3(e4);
    };
    return y2.write = function(t50) {
      for (var e4 = t50.length, n3 = 0; n3 < e4; n3++) N2(t50[n3]);
    }, y2;
  } };
} });
var f = s({ "node_modules/xml-reader/dist/reader.js"(t48, e2) {
  var n2 = p(), o2 = g(), i2 = o2.Type, r2 = { element: "element", text: "text" }, s2 = function(t49) {
    return Object.assign({ name: "", type: r2.element, value: "", parent: null, attributes: {}, children: [] }, t49);
  }, a2 = function(t49) {
    t49 = Object.assign({ stream: false, parentNodes: true, doneEvent: "done", tagPrefix: "tag:", emitTopLevelOnly: false, debug: false }, t49);
    var e3 = void 0, a3 = void 0, c2 = void 0, l2 = void 0, h2 = new n2(), d2 = function(n3) {
      switch (n3.type) {
        case i2.openTag:
          if (null === c2) (c2 = a3).name = n3.value;
          else {
            var o3 = s2({ name: n3.value, parent: c2 });
            c2.children.push(o3), c2 = o3;
          }
          break;
        case i2.closeTag:
          var d3 = c2.parent;
          if (t49.parentNodes || (c2.parent = null), c2.name !== n3.value) break;
          t49.stream && d3 === a3 && (a3.children = [], c2.parent = null), t49.emitTopLevelOnly && d3 !== a3 || (h2.emit(t49.tagPrefix + c2.name, c2), h2.emit("tag", c2.name, c2)), c2 === a3 && (e3.removeAllListeners("data"), h2.emit(t49.doneEvent, c2), a3 = null), c2 = d3;
          break;
        case i2.text:
          c2 && c2.children.push(s2({ type: r2.text, value: n3.value, parent: t49.parentNodes ? c2 : null }));
          break;
        case i2.attributeName:
          l2 = n3.value, c2.attributes[l2] = "";
          break;
        case i2.attributeValue:
          c2.attributes[l2] = n3.value;
      }
    };
    return h2.reset = function() {
      (e3 = o2.create({ debug: t49.debug })).on("data", d2), a3 = s2(), c2 = null, l2 = "", h2.parse = e3.write;
    }, h2.reset(), h2;
  };
  e2.exports = { parseSync: function(t49, e3) {
    e3 = Object.assign({}, e3, { stream: false, tagPrefix: ":" });
    var n3 = a2(e3), o3 = void 0;
    return n3.on("done", function(t50) {
      o3 = t50;
    }), n3.parse(t49), o3;
  }, create: a2, NodeType: r2 };
} });
var _ = s({ "node_modules/binary-search-bounds/search-bounds.js"(t48, e2) {
  function n2(t49, e3, n3, o3, i3) {
    for (var r3 = i3 + 1; o3 <= i3; ) {
      var s3 = o3 + i3 >>> 1, a3 = t49[s3];
      (void 0 !== n3 ? n3(a3, e3) : a3 - e3) >= 0 ? (r3 = s3, i3 = s3 - 1) : o3 = s3 + 1;
    }
    return r3;
  }
  function o2(t49, e3, n3, o3, i3) {
    for (var r3 = i3 + 1; o3 <= i3; ) {
      var s3 = o3 + i3 >>> 1, a3 = t49[s3];
      (void 0 !== n3 ? n3(a3, e3) : a3 - e3) > 0 ? (r3 = s3, i3 = s3 - 1) : o3 = s3 + 1;
    }
    return r3;
  }
  function i2(t49, e3, n3, o3, i3) {
    for (var r3 = o3 - 1; o3 <= i3; ) {
      var s3 = o3 + i3 >>> 1, a3 = t49[s3];
      (void 0 !== n3 ? n3(a3, e3) : a3 - e3) < 0 ? (r3 = s3, o3 = s3 + 1) : i3 = s3 - 1;
    }
    return r3;
  }
  function r2(t49, e3, n3, o3, i3) {
    for (var r3 = o3 - 1; o3 <= i3; ) {
      var s3 = o3 + i3 >>> 1, a3 = t49[s3];
      (void 0 !== n3 ? n3(a3, e3) : a3 - e3) <= 0 ? (r3 = s3, o3 = s3 + 1) : i3 = s3 - 1;
    }
    return r3;
  }
  function s2(t49, e3, n3, o3, i3) {
    for (; o3 <= i3; ) {
      var r3 = o3 + i3 >>> 1, s3 = t49[r3], a3 = void 0 !== n3 ? n3(s3, e3) : s3 - e3;
      if (0 === a3) return r3;
      a3 <= 0 ? o3 = r3 + 1 : i3 = r3 - 1;
    }
    return -1;
  }
  function a2(t49, e3, n3, o3, i3, r3) {
    return "function" == typeof n3 ? r3(t49, e3, n3, void 0 === o3 ? 0 : 0 | o3, void 0 === i3 ? t49.length - 1 : 0 | i3) : r3(t49, e3, void 0, void 0 === n3 ? 0 : 0 | n3, void 0 === o3 ? t49.length - 1 : 0 | o3);
  }
  e2.exports = { ge: function(t49, e3, o3, i3, r3) {
    return a2(t49, e3, o3, i3, r3, n2);
  }, gt: function(t49, e3, n3, i3, r3) {
    return a2(t49, e3, n3, i3, r3, o2);
  }, lt: function(t49, e3, n3, o3, r3) {
    return a2(t49, e3, n3, o3, r3, i2);
  }, le: function(t49, e3, n3, o3, i3) {
    return a2(t49, e3, n3, o3, i3, r2);
  }, eq: function(t49, e3, n3, o3, i3) {
    return a2(t49, e3, n3, o3, i3, s2);
  } };
} });
var y = s({ "node_modules/two-product/two-product.js"(t48, e2) {
  e2.exports = function(t49, e3, o2) {
    var i2 = t49 * e3, r2 = n2 * t49, s2 = r2 - (r2 - t49), a2 = t49 - s2, c2 = n2 * e3, l2 = c2 - (c2 - e3), h2 = e3 - l2, d2 = a2 * h2 - (i2 - s2 * l2 - a2 * l2 - s2 * h2);
    if (o2) return o2[0] = d2, o2[1] = i2, o2;
    return [d2, i2];
  };
  var n2 = +(Math.pow(2, 27) + 1);
} });
var b = s({ "node_modules/robust-sum/robust-sum.js"(t48, e2) {
  e2.exports = function(t49, e3) {
    var n2 = 0 | t49.length, o2 = 0 | e3.length;
    if (1 === n2 && 1 === o2) return (function(t50, e4) {
      var n3 = t50 + e4, o3 = n3 - t50, i3 = n3 - o3, r3 = e4 - o3, s3 = t50 - i3, a3 = s3 + r3;
      if (a3) return [a3, n3];
      return [n3];
    })(t49[0], e3[0]);
    var i2, r2, s2 = new Array(n2 + o2), a2 = 0, c2 = 0, l2 = 0, h2 = Math.abs, d2 = t49[c2], u2 = h2(d2), p2 = e3[l2], m2 = h2(p2);
    u2 < m2 ? (r2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (r2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = e3[l2])));
    c2 < n2 && u2 < m2 || l2 >= o2 ? (i2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (i2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = e3[l2])));
    var g2, f2, _2 = i2 + r2, y2 = _2 - i2, b2 = r2 - y2, x2 = b2, v2 = _2;
    for (; c2 < n2 && l2 < o2; ) u2 < m2 ? (i2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (i2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = e3[l2]))), (b2 = (r2 = x2) - (y2 = (_2 = i2 + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2;
    for (; c2 < n2; ) (b2 = (r2 = x2) - (y2 = (_2 = (i2 = d2) + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (c2 += 1) < n2 && (d2 = t49[c2]);
    for (; l2 < o2; ) (b2 = (r2 = x2) - (y2 = (_2 = (i2 = p2) + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (l2 += 1) < o2 && (p2 = e3[l2]);
    x2 && (s2[a2++] = x2);
    v2 && (s2[a2++] = v2);
    a2 || (s2[a2++] = 0);
    return s2.length = a2, s2;
  };
} });
var x = s({ "node_modules/two-sum/two-sum.js"(t48, e2) {
  e2.exports = function(t49, e3, n2) {
    var o2 = t49 + e3, i2 = o2 - t49, r2 = e3 - i2, s2 = t49 - (o2 - i2);
    if (n2) return n2[0] = s2 + r2, n2[1] = o2, n2;
    return [s2 + r2, o2];
  };
} });
var v = s({ "node_modules/robust-scale/robust-scale.js"(t48, e2) {
  var n2 = y(), o2 = x();
  e2.exports = function(t49, e3) {
    var i2 = t49.length;
    if (1 === i2) {
      var r2 = n2(t49[0], e3);
      return r2[0] ? r2 : [r2[1]];
    }
    var s2 = new Array(2 * i2), a2 = [0.1, 0.1], c2 = [0.1, 0.1], l2 = 0;
    n2(t49[0], e3, a2), a2[0] && (s2[l2++] = a2[0]);
    for (var h2 = 1; h2 < i2; ++h2) {
      n2(t49[h2], e3, c2);
      var d2 = a2[1];
      o2(d2, c2[0], a2), a2[0] && (s2[l2++] = a2[0]);
      var u2 = c2[1], p2 = a2[1], m2 = u2 + p2, g2 = p2 - (m2 - u2);
      a2[1] = m2, g2 && (s2[l2++] = g2);
    }
    a2[1] && (s2[l2++] = a2[1]);
    0 === l2 && (s2[l2++] = 0);
    return s2.length = l2, s2;
  };
} });
var S = s({ "node_modules/robust-subtract/robust-diff.js"(t48, e2) {
  e2.exports = function(t49, e3) {
    var n2 = 0 | t49.length, o2 = 0 | e3.length;
    if (1 === n2 && 1 === o2) return (function(t50, e4) {
      var n3 = t50 + e4, o3 = n3 - t50, i3 = n3 - o3, r3 = e4 - o3, s3 = t50 - i3, a3 = s3 + r3;
      if (a3) return [a3, n3];
      return [n3];
    })(t49[0], -e3[0]);
    var i2, r2, s2 = new Array(n2 + o2), a2 = 0, c2 = 0, l2 = 0, h2 = Math.abs, d2 = t49[c2], u2 = h2(d2), p2 = -e3[l2], m2 = h2(p2);
    u2 < m2 ? (r2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (r2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = -e3[l2])));
    c2 < n2 && u2 < m2 || l2 >= o2 ? (i2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (i2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = -e3[l2])));
    var g2, f2, _2 = i2 + r2, y2 = _2 - i2, b2 = r2 - y2, x2 = b2, v2 = _2;
    for (; c2 < n2 && l2 < o2; ) u2 < m2 ? (i2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (i2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = -e3[l2]))), (b2 = (r2 = x2) - (y2 = (_2 = i2 + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2;
    for (; c2 < n2; ) (b2 = (r2 = x2) - (y2 = (_2 = (i2 = d2) + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (c2 += 1) < n2 && (d2 = t49[c2]);
    for (; l2 < o2; ) (b2 = (r2 = x2) - (y2 = (_2 = (i2 = p2) + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (l2 += 1) < o2 && (p2 = -e3[l2]);
    x2 && (s2[a2++] = x2);
    v2 && (s2[a2++] = v2);
    a2 || (s2[a2++] = 0);
    return s2.length = a2, s2;
  };
} });
var I = s({ "node_modules/robust-orientation/orientation.js"(t48, e2) {
  var n2 = y(), o2 = b(), i2 = v(), r2 = S();
  function s2(t49, e3, n3, o3) {
    return function(n4, i3, r3) {
      var s3 = t49(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), t49(e3(n4[1], i3[0]), e3(-i3[1], n4[0]))), a3 = t49(e3(n4[1], r3[0]), e3(-r3[1], n4[0])), c3 = o3(s3, a3);
      return c3[c3.length - 1];
    };
  }
  function a2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3) {
      var c3 = t49(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), a3[2]))), t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), a3[2])))), l3 = t49(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), a3[2]))), t49(n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), s3[2])))), h3 = o3(c3, l3);
      return h3[h3.length - 1];
    };
  }
  function c2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3, c3) {
      var l3 = t49(t49(t49(n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), s3[2]), t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), -a3[2]), n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), c3[2]))), r3[3]), t49(n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), r3[2]), t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), -a3[2]), n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), c3[2]))), -s3[3]), n3(t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), c3[2]))), a3[3]))), t49(n3(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), a3[2]))), -c3[3]), t49(n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), r3[2]), t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), -a3[2]), n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), c3[2]))), i3[3]), n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -a3[2]), n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), c3[2]))), -r3[3])))), t49(t49(n3(t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), c3[2]))), a3[3]), t49(n3(t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), a3[2]))), -c3[3]), n3(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), a3[2]))), i3[3]))), t49(n3(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), a3[2]))), -r3[3]), t49(n3(t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), a3[2]))), s3[3]), n3(t49(n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), s3[2]))), -a3[3]))))), h3 = t49(t49(t49(n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), s3[2]), t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), -a3[2]), n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), c3[2]))), i3[3]), n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -a3[2]), n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), c3[2]))), -s3[3])), t49(n3(t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), c3[2]))), a3[3]), n3(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), a3[2]))), -c3[3]))), t49(t49(n3(t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), c3[2]))), i3[3]), n3(t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), c3[2]))), -r3[3])), t49(n3(t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), c3[2]))), s3[3]), n3(t49(n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), s3[2]))), -c3[3])))), d3 = o3(l3, h3);
      return d3[d3.length - 1];
    };
  }
  function l2(t49) {
    return (3 === t49 ? s2 : 4 === t49 ? a2 : c2)(o2, n2, i2, r2);
  }
  var h2 = l2(3), d2 = l2(4), u2 = [function() {
    return 0;
  }, function() {
    return 0;
  }, function(t49, e3) {
    return e3[0] - t49[0];
  }, function(t49, e3, n3) {
    var o3, i3 = (t49[1] - n3[1]) * (e3[0] - n3[0]), r3 = (t49[0] - n3[0]) * (e3[1] - n3[1]), s3 = i3 - r3;
    if (i3 > 0) {
      if (r3 <= 0) return s3;
      o3 = i3 + r3;
    } else {
      if (!(i3 < 0)) return s3;
      if (r3 >= 0) return s3;
      o3 = -(i3 + r3);
    }
    var a3 = 33306690738754716e-32 * o3;
    return s3 >= a3 || s3 <= -a3 ? s3 : h2(t49, e3, n3);
  }, function(t49, e3, n3, o3) {
    var i3 = t49[0] - o3[0], r3 = e3[0] - o3[0], s3 = n3[0] - o3[0], a3 = t49[1] - o3[1], c3 = e3[1] - o3[1], l3 = n3[1] - o3[1], h3 = t49[2] - o3[2], u3 = e3[2] - o3[2], p3 = n3[2] - o3[2], m3 = r3 * l3, g2 = s3 * c3, f2 = s3 * a3, _2 = i3 * l3, y2 = i3 * c3, b2 = r3 * a3, x2 = h3 * (m3 - g2) + u3 * (f2 - _2) + p3 * (y2 - b2), v2 = 7771561172376103e-31 * ((Math.abs(m3) + Math.abs(g2)) * Math.abs(h3) + (Math.abs(f2) + Math.abs(_2)) * Math.abs(u3) + (Math.abs(y2) + Math.abs(b2)) * Math.abs(p3));
    return x2 > v2 || -x2 > v2 ? x2 : d2(t49, e3, n3, o3);
  }];
  function p2(t49) {
    var e3 = u2[t49.length];
    return e3 || (e3 = u2[t49.length] = l2(t49.length)), e3.apply(void 0, t49);
  }
  function m2(t49, e3, n3, o3, i3, r3, s3) {
    return function(e4, n4, a3, c3, l3) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o3(e4, n4);
        case 3:
          return i3(e4, n4, a3);
        case 4:
          return r3(e4, n4, a3, c3);
        case 5:
          return s3(e4, n4, a3, c3, l3);
      }
      for (var h3 = new Array(arguments.length), d3 = 0; d3 < arguments.length; ++d3) h3[d3] = arguments[d3];
      return t49(h3);
    };
  }
  !(function() {
    for (; u2.length <= 5; ) u2.push(l2(u2.length));
    e2.exports = m2.apply(void 0, [p2].concat(u2));
    for (var t49 = 0; t49 <= 5; ++t49) e2.exports[t49] = u2[t49];
  })();
} });
var P = s({ "node_modules/cdt2d/lib/monotone.js"(t48, e2) {
  var n2 = _(), o2 = I()[3];
  function i2(t49, e3, n3, o3, i3) {
    this.a = t49, this.b = e3, this.idx = n3, this.lowerIds = o3, this.upperIds = i3;
  }
  function r2(t49, e3, n3, o3) {
    this.a = t49, this.b = e3, this.type = n3, this.idx = o3;
  }
  function s2(t49, e3) {
    var n3 = t49.a[0] - e3.a[0] || t49.a[1] - e3.a[1] || t49.type - e3.type;
    return n3 || (0 !== t49.type && (n3 = o2(t49.a, t49.b, e3.b)) ? n3 : t49.idx - e3.idx);
  }
  function a2(t49, e3) {
    return o2(t49.a, t49.b, e3);
  }
  function c2(t49, e3, i3, r3, s3) {
    for (var c3 = n2.lt(e3, r3, a2), l3 = n2.gt(e3, r3, a2), h3 = c3; h3 < l3; ++h3) {
      for (var d3 = e3[h3], u2 = d3.lowerIds, p2 = u2.length; p2 > 1 && o2(i3[u2[p2 - 2]], i3[u2[p2 - 1]], r3) > 0; ) t49.push([u2[p2 - 1], u2[p2 - 2], s3]), p2 -= 1;
      u2.length = p2, u2.push(s3);
      var m2 = d3.upperIds;
      for (p2 = m2.length; p2 > 1 && o2(i3[m2[p2 - 2]], i3[m2[p2 - 1]], r3) < 0; ) t49.push([m2[p2 - 2], m2[p2 - 1], s3]), p2 -= 1;
      m2.length = p2, m2.push(s3);
    }
  }
  function l2(t49, e3) {
    var n3;
    return (n3 = t49.a[0] < e3.a[0] ? o2(t49.a, t49.b, e3.a) : o2(e3.b, e3.a, t49.a)) ? n3 : (n3 = e3.b[0] < t49.b[0] ? o2(t49.a, t49.b, e3.b) : o2(e3.b, e3.a, t49.b)) || t49.idx - e3.idx;
  }
  function h2(t49, e3, o3) {
    var r3 = n2.le(t49, o3, l2), s3 = t49[r3], a3 = s3.upperIds, c3 = a3[a3.length - 1];
    s3.upperIds = [c3], t49.splice(r3 + 1, 0, new i2(o3.a, o3.b, o3.idx, [c3], a3));
  }
  function d2(t49, e3, o3) {
    var i3 = o3.a;
    o3.a = o3.b, o3.b = i3;
    var r3 = n2.eq(t49, o3, l2), s3 = t49[r3];
    t49[r3 - 1].upperIds = s3.upperIds, t49.splice(r3, 1);
  }
  e2.exports = function(t49, e3) {
    for (var n3 = t49.length, o3 = e3.length, a3 = [], l3 = 0; l3 < n3; ++l3) a3.push(new r2(t49[l3], null, 0, l3));
    for (l3 = 0; l3 < o3; ++l3) {
      var u2 = e3[l3], p2 = t49[u2[0]], m2 = t49[u2[1]];
      p2[0] < m2[0] ? a3.push(new r2(p2, m2, 2, l3), new r2(m2, p2, 1, l3)) : p2[0] > m2[0] && a3.push(new r2(m2, p2, 2, l3), new r2(p2, m2, 1, l3));
    }
    a3.sort(s2);
    for (var g2 = a3[0].a[0] - (1 + Math.abs(a3[0].a[0])) * Math.pow(2, -52), f2 = [new i2([g2, 1], [g2, 0], -1, [], [], [], [])], _2 = [], y2 = (l3 = 0, a3.length); l3 < y2; ++l3) {
      var b2 = a3[l3], x2 = b2.type;
      0 === x2 ? c2(_2, f2, t49, b2.a, b2.idx) : 2 === x2 ? h2(f2, t49, b2) : d2(f2, t49, b2);
    }
    return _2;
  };
} });
var M = s({ "node_modules/cdt2d/lib/triangulation.js"(t48, e2) {
  var n2 = _();
  function o2(t49, e3) {
    this.stars = t49, this.edges = e3;
  }
  e2.exports = function(t49, e3) {
    for (var n3 = new Array(t49), i3 = 0; i3 < t49; ++i3) n3[i3] = [];
    return new o2(n3, e3);
  };
  var i2 = o2.prototype;
  function r2(t49, e3, n3) {
    for (var o3 = 1, i3 = t49.length; o3 < i3; o3 += 2) if (t49[o3 - 1] === e3 && t49[o3] === n3) return t49[o3 - 1] = t49[i3 - 2], t49[o3] = t49[i3 - 1], void (t49.length = i3 - 2);
  }
  i2.isConstraint = /* @__PURE__ */ (function() {
    var t49 = [0, 0];
    function e3(t50, e4) {
      return t50[0] - e4[0] || t50[1] - e4[1];
    }
    return function(o3, i3) {
      return t49[0] = Math.min(o3, i3), t49[1] = Math.max(o3, i3), n2.eq(this.edges, t49, e3) >= 0;
    };
  })(), i2.removeTriangle = function(t49, e3, n3) {
    var o3 = this.stars;
    r2(o3[t49], e3, n3), r2(o3[e3], n3, t49), r2(o3[n3], t49, e3);
  }, i2.addTriangle = function(t49, e3, n3) {
    var o3 = this.stars;
    o3[t49].push(e3, n3), o3[e3].push(n3, t49), o3[n3].push(t49, e3);
  }, i2.opposite = function(t49, e3) {
    for (var n3 = this.stars[e3], o3 = 1, i3 = n3.length; o3 < i3; o3 += 2) if (n3[o3] === t49) return n3[o3 - 1];
    return -1;
  }, i2.flip = function(t49, e3) {
    var n3 = this.opposite(t49, e3), o3 = this.opposite(e3, t49);
    this.removeTriangle(t49, e3, n3), this.removeTriangle(e3, t49, o3), this.addTriangle(t49, o3, n3), this.addTriangle(e3, n3, o3);
  }, i2.edges = function() {
    for (var t49 = this.stars, e3 = [], n3 = 0, o3 = t49.length; n3 < o3; ++n3) for (var i3 = t49[n3], r3 = 0, s2 = i3.length; r3 < s2; r3 += 2) e3.push([i3[r3], i3[r3 + 1]]);
    return e3;
  }, i2.cells = function() {
    for (var t49 = this.stars, e3 = [], n3 = 0, o3 = t49.length; n3 < o3; ++n3) for (var i3 = t49[n3], r3 = 0, s2 = i3.length; r3 < s2; r3 += 2) {
      var a2 = i3[r3], c2 = i3[r3 + 1];
      n3 < Math.min(a2, c2) && e3.push([n3, a2, c2]);
    }
    return e3;
  };
} });
var C = s({ "node_modules/robust-in-sphere/in-sphere.js"(t48, e2) {
  var n2 = y(), o2 = b(), i2 = S(), r2 = v();
  function s2(t49) {
    return (3 === t49 ? a2 : 4 === t49 ? c2 : 5 === t49 ? l2 : h2)(o2, i2, n2, r2);
  }
  function a2(t49, e3, n3, o3) {
    return function(i3, r3, s3) {
      var a3 = n3(i3[0], i3[0]), c3 = o3(a3, r3[0]), l3 = o3(a3, s3[0]), h3 = n3(r3[0], r3[0]), d3 = o3(h3, i3[0]), u3 = o3(h3, s3[0]), p3 = n3(s3[0], s3[0]), m2 = o3(p3, i3[0]), g2 = o3(p3, r3[0]), f2 = t49(e3(g2, u3), e3(d3, c3)), _2 = e3(m2, l3), y2 = e3(f2, _2);
      return y2[y2.length - 1];
    };
  }
  function c2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3) {
      var c3 = t49(n3(i3[0], i3[0]), n3(i3[1], i3[1])), l3 = o3(c3, r3[0]), h3 = o3(c3, s3[0]), d3 = o3(c3, a3[0]), u3 = t49(n3(r3[0], r3[0]), n3(r3[1], r3[1])), p3 = o3(u3, i3[0]), m2 = o3(u3, s3[0]), g2 = o3(u3, a3[0]), f2 = t49(n3(s3[0], s3[0]), n3(s3[1], s3[1])), _2 = o3(f2, i3[0]), y2 = o3(f2, r3[0]), b2 = o3(f2, a3[0]), x2 = t49(n3(a3[0], a3[0]), n3(a3[1], a3[1])), v2 = o3(x2, i3[0]), S2 = o3(x2, r3[0]), I2 = o3(x2, s3[0]), P2 = t49(t49(o3(e3(I2, b2), r3[1]), t49(o3(e3(S2, g2), -s3[1]), o3(e3(y2, m2), a3[1]))), t49(o3(e3(S2, g2), i3[1]), t49(o3(e3(v2, d3), -r3[1]), o3(e3(p3, l3), a3[1])))), M2 = t49(t49(o3(e3(I2, b2), i3[1]), t49(o3(e3(v2, d3), -s3[1]), o3(e3(_2, h3), a3[1]))), t49(o3(e3(y2, m2), i3[1]), t49(o3(e3(_2, h3), -r3[1]), o3(e3(p3, l3), s3[1])))), C2 = e3(P2, M2);
      return C2[C2.length - 1];
    };
  }
  function l2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3, c3) {
      var l3 = t49(n3(i3[0], i3[0]), t49(n3(i3[1], i3[1]), n3(i3[2], i3[2]))), h3 = o3(l3, r3[0]), d3 = o3(l3, s3[0]), u3 = o3(l3, a3[0]), p3 = o3(l3, c3[0]), m2 = t49(n3(r3[0], r3[0]), t49(n3(r3[1], r3[1]), n3(r3[2], r3[2]))), g2 = o3(m2, i3[0]), f2 = o3(m2, s3[0]), _2 = o3(m2, a3[0]), y2 = o3(m2, c3[0]), b2 = t49(n3(s3[0], s3[0]), t49(n3(s3[1], s3[1]), n3(s3[2], s3[2]))), x2 = o3(b2, i3[0]), v2 = o3(b2, r3[0]), S2 = o3(b2, a3[0]), I2 = o3(b2, c3[0]), P2 = t49(n3(a3[0], a3[0]), t49(n3(a3[1], a3[1]), n3(a3[2], a3[2]))), M2 = o3(P2, i3[0]), C2 = o3(P2, r3[0]), N2 = o3(P2, s3[0]), w2 = o3(P2, c3[0]), T2 = t49(n3(c3[0], c3[0]), t49(n3(c3[1], c3[1]), n3(c3[2], c3[2]))), R2 = o3(T2, i3[0]), E2 = o3(T2, r3[0]), A2 = o3(T2, s3[0]), O2 = o3(T2, a3[0]), L2 = t49(t49(t49(o3(t49(o3(e3(O2, w2), s3[1]), t49(o3(e3(A2, I2), -a3[1]), o3(e3(N2, S2), c3[1]))), r3[2]), t49(o3(t49(o3(e3(O2, w2), r3[1]), t49(o3(e3(E2, y2), -a3[1]), o3(e3(C2, _2), c3[1]))), -s3[2]), o3(t49(o3(e3(A2, I2), r3[1]), t49(o3(e3(E2, y2), -s3[1]), o3(e3(v2, f2), c3[1]))), a3[2]))), t49(o3(t49(o3(e3(N2, S2), r3[1]), t49(o3(e3(C2, _2), -s3[1]), o3(e3(v2, f2), a3[1]))), -c3[2]), t49(o3(t49(o3(e3(O2, w2), r3[1]), t49(o3(e3(E2, y2), -a3[1]), o3(e3(C2, _2), c3[1]))), i3[2]), o3(t49(o3(e3(O2, w2), i3[1]), t49(o3(e3(R2, p3), -a3[1]), o3(e3(M2, u3), c3[1]))), -r3[2])))), t49(t49(o3(t49(o3(e3(E2, y2), i3[1]), t49(o3(e3(R2, p3), -r3[1]), o3(e3(g2, h3), c3[1]))), a3[2]), t49(o3(t49(o3(e3(C2, _2), i3[1]), t49(o3(e3(M2, u3), -r3[1]), o3(e3(g2, h3), a3[1]))), -c3[2]), o3(t49(o3(e3(N2, S2), r3[1]), t49(o3(e3(C2, _2), -s3[1]), o3(e3(v2, f2), a3[1]))), i3[2]))), t49(o3(t49(o3(e3(N2, S2), i3[1]), t49(o3(e3(M2, u3), -s3[1]), o3(e3(x2, d3), a3[1]))), -r3[2]), t49(o3(t49(o3(e3(C2, _2), i3[1]), t49(o3(e3(M2, u3), -r3[1]), o3(e3(g2, h3), a3[1]))), s3[2]), o3(t49(o3(e3(v2, f2), i3[1]), t49(o3(e3(x2, d3), -r3[1]), o3(e3(g2, h3), s3[1]))), -a3[2]))))), D2 = t49(t49(t49(o3(t49(o3(e3(O2, w2), s3[1]), t49(o3(e3(A2, I2), -a3[1]), o3(e3(N2, S2), c3[1]))), i3[2]), o3(t49(o3(e3(O2, w2), i3[1]), t49(o3(e3(R2, p3), -a3[1]), o3(e3(M2, u3), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(A2, I2), i3[1]), t49(o3(e3(R2, p3), -s3[1]), o3(e3(x2, d3), c3[1]))), a3[2]), o3(t49(o3(e3(N2, S2), i3[1]), t49(o3(e3(M2, u3), -s3[1]), o3(e3(x2, d3), a3[1]))), -c3[2]))), t49(t49(o3(t49(o3(e3(A2, I2), r3[1]), t49(o3(e3(E2, y2), -s3[1]), o3(e3(v2, f2), c3[1]))), i3[2]), o3(t49(o3(e3(A2, I2), i3[1]), t49(o3(e3(R2, p3), -s3[1]), o3(e3(x2, d3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(E2, y2), i3[1]), t49(o3(e3(R2, p3), -r3[1]), o3(e3(g2, h3), c3[1]))), s3[2]), o3(t49(o3(e3(v2, f2), i3[1]), t49(o3(e3(x2, d3), -r3[1]), o3(e3(g2, h3), s3[1]))), -c3[2])))), z2 = e3(L2, D2);
      return z2[z2.length - 1];
    };
  }
  function h2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3, c3, l3) {
      var h3 = t49(t49(n3(i3[0], i3[0]), n3(i3[1], i3[1])), t49(n3(i3[2], i3[2]), n3(i3[3], i3[3]))), d3 = o3(h3, r3[0]), u3 = o3(h3, s3[0]), p3 = o3(h3, a3[0]), m2 = o3(h3, c3[0]), g2 = o3(h3, l3[0]), f2 = t49(t49(n3(r3[0], r3[0]), n3(r3[1], r3[1])), t49(n3(r3[2], r3[2]), n3(r3[3], r3[3]))), _2 = o3(f2, i3[0]), y2 = o3(f2, s3[0]), b2 = o3(f2, a3[0]), x2 = o3(f2, c3[0]), v2 = o3(f2, l3[0]), S2 = t49(t49(n3(s3[0], s3[0]), n3(s3[1], s3[1])), t49(n3(s3[2], s3[2]), n3(s3[3], s3[3]))), I2 = o3(S2, i3[0]), P2 = o3(S2, r3[0]), M2 = o3(S2, a3[0]), C2 = o3(S2, c3[0]), N2 = o3(S2, l3[0]), w2 = t49(t49(n3(a3[0], a3[0]), n3(a3[1], a3[1])), t49(n3(a3[2], a3[2]), n3(a3[3], a3[3]))), T2 = o3(w2, i3[0]), R2 = o3(w2, r3[0]), E2 = o3(w2, s3[0]), A2 = o3(w2, c3[0]), O2 = o3(w2, l3[0]), L2 = t49(t49(n3(c3[0], c3[0]), n3(c3[1], c3[1])), t49(n3(c3[2], c3[2]), n3(c3[3], c3[3]))), D2 = o3(L2, i3[0]), z2 = o3(L2, r3[0]), k2 = o3(L2, s3[0]), F2 = o3(L2, a3[0]), j2 = o3(L2, l3[0]), Y2 = t49(t49(n3(l3[0], l3[0]), n3(l3[1], l3[1])), t49(n3(l3[2], l3[2]), n3(l3[3], l3[3]))), $2 = o3(Y2, i3[0]), X2 = o3(Y2, r3[0]), B2 = o3(Y2, s3[0]), H2 = o3(Y2, a3[0]), W2 = o3(Y2, c3[0]), V2 = t49(t49(t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), s3[2]), o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), -l3[2]))), r3[3]), t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), r3[2]), o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), -l3[2]))), -s3[3]), o3(t49(t49(o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), r3[2]), o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), c3[2]), o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), -l3[2]))), a3[3]))), t49(t49(o3(t49(t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), r3[2]), o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), -l3[2]))), -c3[3]), o3(t49(t49(o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), r3[2]), o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), -c3[2]))), l3[3])), t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), r3[2]), o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), -l3[2]))), i3[3]), o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -l3[2]))), -r3[3])))), t49(t49(t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), c3[2]), o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), -l3[2]))), a3[3]), o3(t49(t49(o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), i3[2]), o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), a3[2]), o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), -l3[2]))), -c3[3])), t49(o3(t49(t49(o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), i3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), a3[2]), o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), -c3[2]))), l3[3]), o3(t49(t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), r3[2]), o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), -l3[2]))), i3[3]))), t49(t49(o3(t49(t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), i3[2]), o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -l3[2]))), -r3[3]), o3(t49(t49(o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), i3[2]), o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), a3[2]), o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), -l3[2]))), s3[3])), t49(o3(t49(t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), i3[2]), o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -l3[2]))), -a3[3]), o3(t49(t49(o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), i3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -r3[2])), t49(o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -a3[2]))), l3[3]))))), U2 = t49(t49(t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), s3[2]), o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), -l3[2]))), i3[3]), t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -l3[2]))), -s3[3]), o3(t49(t49(o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), c3[2]), o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), -l3[2]))), a3[3]))), t49(t49(o3(t49(t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), i3[2]), o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -l3[2]))), -c3[3]), o3(t49(t49(o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), i3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -c3[2]))), l3[3])), t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), r3[2]), o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), c3[2]), o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), -l3[2]))), i3[3]), o3(t49(t49(o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), c3[2]), o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), -l3[2]))), -r3[3])))), t49(t49(t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), c3[2]), o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), -l3[2]))), s3[3]), o3(t49(t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), i3[2]), o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -l3[2]))), -c3[3])), t49(o3(t49(t49(o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), i3[2]), o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -c3[2]))), l3[3]), o3(t49(t49(o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), r3[2]), o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), -c3[2]))), i3[3]))), t49(t49(o3(t49(t49(o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), i3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -c3[2]))), -r3[3]), o3(t49(t49(o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), i3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), a3[2]), o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), -c3[2]))), s3[3])), t49(o3(t49(t49(o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), i3[2]), o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -c3[2]))), -a3[3]), o3(t49(t49(o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), i3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -r3[2])), t49(o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -a3[2]))), c3[3]))))), G2 = e3(V2, U2);
      return G2[G2.length - 1];
    };
  }
  var d2 = [function() {
    return 0;
  }, function() {
    return 0;
  }, function() {
    return 0;
  }];
  function u2(t49) {
    var e3 = d2[t49.length];
    return e3 || (e3 = d2[t49.length] = s2(t49.length)), e3.apply(void 0, t49);
  }
  function p2(t49, e3, n3, o3, i3, r3, s3, a3) {
    return function(e4, n4, c3, l3, h3, d3) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o3(e4, n4);
        case 3:
          return i3(e4, n4, c3);
        case 4:
          return r3(e4, n4, c3, l3);
        case 5:
          return s3(e4, n4, c3, l3, h3);
        case 6:
          return a3(e4, n4, c3, l3, h3, d3);
      }
      for (var u3 = new Array(arguments.length), p3 = 0; p3 < arguments.length; ++p3) u3[p3] = arguments[p3];
      return t49(u3);
    };
  }
  !(function() {
    for (; d2.length <= 6; ) d2.push(s2(d2.length));
    e2.exports = p2.apply(void 0, [u2].concat(d2));
    for (var t49 = 0; t49 <= 6; ++t49) e2.exports[t49] = d2[t49];
  })();
} });
var N = s({ "node_modules/cdt2d/lib/delaunay.js"(t48, e2) {
  var n2 = C()[4];
  _();
  function o2(t49, e3, o3, i2, r2, s2) {
    var a2 = e3.opposite(i2, r2);
    if (!(a2 < 0)) {
      if (r2 < i2) {
        var c2 = i2;
        i2 = r2, r2 = c2, c2 = s2, s2 = a2, a2 = c2;
      }
      e3.isConstraint(i2, r2) || n2(t49[i2], t49[r2], t49[s2], t49[a2]) < 0 && o3.push(i2, r2);
    }
  }
  e2.exports = function(t49, e3) {
    for (var i2 = [], r2 = t49.length, s2 = e3.stars, a2 = 0; a2 < r2; ++a2) for (var c2 = s2[a2], l2 = 1; l2 < c2.length; l2 += 2) {
      if (!((p2 = c2[l2]) < a2) && !e3.isConstraint(a2, p2)) {
        for (var h2 = c2[l2 - 1], d2 = -1, u2 = 1; u2 < c2.length; u2 += 2) if (c2[u2 - 1] === p2) {
          d2 = c2[u2];
          break;
        }
        d2 < 0 || n2(t49[a2], t49[p2], t49[h2], t49[d2]) < 0 && i2.push(a2, p2);
      }
    }
    for (; i2.length > 0; ) {
      for (var p2 = i2.pop(), m2 = (h2 = -1, d2 = -1, c2 = s2[a2 = i2.pop()], 1); m2 < c2.length; m2 += 2) {
        var g2 = c2[m2 - 1], f2 = c2[m2];
        g2 === p2 ? d2 = f2 : f2 === p2 && (h2 = g2);
      }
      h2 < 0 || d2 < 0 || (n2(t49[a2], t49[p2], t49[h2], t49[d2]) >= 0 || (e3.flip(a2, p2), o2(t49, e3, i2, h2, a2, d2), o2(t49, e3, i2, a2, d2, h2), o2(t49, e3, i2, d2, p2, h2), o2(t49, e3, i2, p2, h2, d2)));
    }
  };
} });
var w = s({ "node_modules/cdt2d/lib/filter.js"(t48, e2) {
  var n2 = _();
  function o2(t49, e3, n3, o3, i3, r2, s2) {
    this.cells = t49, this.neighbor = e3, this.flags = o3, this.constraint = n3, this.active = i3, this.next = r2, this.boundary = s2;
  }
  function i2(t49, e3) {
    return t49[0] - e3[0] || t49[1] - e3[1] || t49[2] - e3[2];
  }
  e2.exports = function(t49, e3, n3) {
    var r2 = (function(t50, e4) {
      for (var n4 = t50.cells(), r3 = n4.length, s3 = 0; s3 < r3; ++s3) {
        var a3 = (_3 = n4[s3])[0], c3 = _3[1], l3 = _3[2];
        c3 < l3 ? c3 < a3 && (_3[0] = c3, _3[1] = l3, _3[2] = a3) : l3 < a3 && (_3[0] = l3, _3[1] = a3, _3[2] = c3);
      }
      n4.sort(i2);
      var h3 = new Array(r3);
      for (s3 = 0; s3 < h3.length; ++s3) h3[s3] = 0;
      var d3 = [], u3 = [], p3 = new Array(3 * r3), m3 = new Array(3 * r3), g3 = null;
      e4 && (g3 = []);
      var f3 = new o2(n4, p3, m3, h3, d3, u3, g3);
      for (s3 = 0; s3 < r3; ++s3) for (var _3 = n4[s3], y2 = 0; y2 < 3; ++y2) {
        a3 = _3[y2], c3 = _3[(y2 + 1) % 3];
        var b2 = p3[3 * s3 + y2] = f3.locate(c3, a3, t50.opposite(c3, a3)), x2 = m3[3 * s3 + y2] = t50.isConstraint(a3, c3);
        b2 < 0 && (x2 ? u3.push(s3) : (d3.push(s3), h3[s3] = 1), e4 && g3.push([c3, a3, -1]));
      }
      return f3;
    })(t49, n3);
    if (0 === e3) return n3 ? r2.cells.concat(r2.boundary) : r2.cells;
    var s2 = 1, a2 = r2.active, c2 = r2.next, l2 = r2.flags, h2 = r2.cells, d2 = r2.constraint, u2 = r2.neighbor;
    for (; a2.length > 0 || c2.length > 0; ) {
      for (; a2.length > 0; ) {
        var p2 = a2.pop();
        if (l2[p2] !== -s2) {
          l2[p2] = s2;
          h2[p2];
          for (var m2 = 0; m2 < 3; ++m2) {
            var g2 = u2[3 * p2 + m2];
            g2 >= 0 && 0 === l2[g2] && (d2[3 * p2 + m2] ? c2.push(g2) : (a2.push(g2), l2[g2] = s2));
          }
        }
      }
      var f2 = c2;
      c2 = a2, a2 = f2, c2.length = 0, s2 = -s2;
    }
    var _2 = (function(t50, e4, n4) {
      for (var o3 = 0, i3 = 0; i3 < t50.length; ++i3) e4[i3] === n4 && (t50[o3++] = t50[i3]);
      return t50.length = o3, t50;
    })(h2, l2, e3);
    if (n3) return _2.concat(r2.boundary);
    return _2;
  }, o2.prototype.locate = /* @__PURE__ */ (function() {
    var t49 = [0, 0, 0];
    return function(e3, o3, r2) {
      var s2 = e3, a2 = o3, c2 = r2;
      return o3 < r2 ? o3 < e3 && (s2 = o3, a2 = r2, c2 = e3) : r2 < e3 && (s2 = r2, a2 = e3, c2 = o3), s2 < 0 ? -1 : (t49[0] = s2, t49[1] = a2, t49[2] = c2, n2.eq(this.cells, t49, i2));
    };
  })();
} });
var T = s({ "node_modules/cdt2d/cdt2d.js"(t48, e2) {
  var n2 = P(), o2 = M(), i2 = N(), r2 = w();
  function s2(t49) {
    return [Math.min(t49[0], t49[1]), Math.max(t49[0], t49[1])];
  }
  function a2(t49, e3) {
    return t49[0] - e3[0] || t49[1] - e3[1];
  }
  function c2(t49, e3, n3) {
    return e3 in t49 ? t49[e3] : n3;
  }
  e2.exports = function(t49, e3, l2) {
    Array.isArray(e3) ? (l2 = l2 || {}, e3 = e3 || []) : (l2 = e3 || {}, e3 = []);
    var h2 = !!c2(l2, "delaunay", true), d2 = !!c2(l2, "interior", true), u2 = !!c2(l2, "exterior", true), p2 = !!c2(l2, "infinity", false);
    if (!d2 && !u2 || 0 === t49.length) return [];
    var m2 = n2(t49, e3);
    if (h2 || d2 !== u2 || p2) {
      for (var g2 = o2(t49.length, (function(t50) {
        return t50.map(s2).sort(a2);
      })(e3)), f2 = 0; f2 < m2.length; ++f2) {
        var _2 = m2[f2];
        g2.addTriangle(_2[0], _2[1], _2[2]);
      }
      return h2 && i2(t49, g2), u2 ? d2 ? p2 ? r2(g2, 0, p2) : g2.cells() : r2(g2, 1, p2) : r2(g2, -1);
    }
    return m2;
  };
} });
var R = { 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" };
var E = {};
for (const t48 in R) {
  E[t48] = [];
  const e2 = R[t48].split("M").slice(1).map((t49) => t49.split("L").map((t50) => t50.trim().split(" ").map(parseFloat)));
  for (const n2 of e2) for (let e3 = 0; e3 < n2.length - 1; e3++) E[t48].push({ x1: n2[e3][0], y1: 1 - n2[e3][1], x2: n2[e3 + 1][0], y2: 1 - n2[e3 + 1][1] });
}
new TextEncoder(), (() => {
  const t48 = new Uint8Array(4);
  new Uint32Array(t48.buffer)[0] = 1, t48[0];
})(), globalThis.Int8Array, globalThis.Uint8Array, globalThis.Int16Array, globalThis.Uint16Array, globalThis.Int32Array, globalThis.Uint32Array, globalThis.BigUint64Array, globalThis.BigInt64Array, globalThis.Float32Array, globalThis.Float64Array;
var A = [];
for (let t48 = 0; t48 < 256; t48++) {
  let e2 = t48;
  for (let t49 = 0; t49 < 8; t49++) 1 & e2 ? e2 = 3988292384 ^ e2 >>> 1 : e2 >>>= 1;
  A[t48] = e2;
}
var O = new Uint16Array([255]);
var L = (new Uint8Array(O.buffer)[0], new Uint16Array([255]));
new Uint8Array(L.buffer)[0], new Uint8Array(0), Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10), new TextDecoder("latin1");
function D() {
  return D = Object.assign ? Object.assign.bind() : function(t48) {
    for (var e2 = 1; e2 < arguments.length; e2++) {
      var n2 = arguments[e2];
      for (var o2 in n2) ({}).hasOwnProperty.call(n2, o2) && (t48[o2] = n2[o2]);
    }
    return t48;
  }, D.apply(null, arguments);
}
function z(t48, e2) {
  return (z = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function(t49, e3) {
    return t49.__proto__ = e3, t49;
  })(t48, e2);
}
function k(t48) {
  return (k = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function(t49) {
    return t49.__proto__ || Object.getPrototypeOf(t49);
  })(t48);
}
function F() {
  try {
    var t48 = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
    }));
  } catch (t49) {
  }
  return (F = function() {
    return !!t48;
  })();
}
function j(t48) {
  var e2 = "function" == typeof Map ? /* @__PURE__ */ new Map() : void 0;
  return j = function(t49) {
    if (null === t49 || !(function(t50) {
      try {
        return -1 !== Function.toString.call(t50).indexOf("[native code]");
      } catch (e3) {
        return "function" == typeof t50;
      }
    })(t49)) return t49;
    if ("function" != typeof t49) throw new TypeError("Super expression must either be null or a function");
    if (void 0 !== e2) {
      if (e2.has(t49)) return e2.get(t49);
      e2.set(t49, n2);
    }
    function n2() {
      return (function(t50, e3, n3) {
        if (F()) return Reflect.construct.apply(null, arguments);
        var o2 = [null];
        o2.push.apply(o2, e3);
        var i2 = new (t50.bind.apply(t50, o2))();
        return n3 && z(i2, n3.prototype), i2;
      })(t49, arguments, k(this).constructor);
    }
    return n2.prototype = Object.create(t49.prototype, { constructor: { value: n2, enumerable: false, writable: true, configurable: true } }), z(n2, t49);
  }, j(t48);
}
var Y = { 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 }).\n\n", 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 }).\n\n", 3: "Passed an incorrect argument to a color function, please pass a string representation of a color.\n\n", 4: "Couldn't generate valid rgb string from %s, it returned %s.\n\n", 5: "Couldn't parse the color string. Please provide the color as a string in hex, rgb, rgba, hsl or hsla notation.\n\n", 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 }).\n\n", 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 }).\n\n", 8: "Passed invalid argument to toColorString, please pass a RgbColor, RgbaColor, HslColor or HslaColor object.\n\n", 9: "Please provide a number of steps to the modularScale helper.\n\n", 10: "Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n", 11: 'Invalid value passed as base to modularScale, expected number or em string but got "%s"\n\n', 12: 'Expected a string ending in "px" or a number passed as the first argument to %s(), got "%s" instead.\n\n', 13: 'Expected a string ending in "px" or a number passed as the second argument to %s(), got "%s" instead.\n\n', 14: 'Passed invalid pixel value ("%s") to %s(), please pass a value like "12px" or 12.\n\n', 15: 'Passed invalid base value ("%s") to %s(), please pass a value like "12px" or 12.\n\n', 16: "You must provide a template to this method.\n\n", 17: "You passed an unsupported selector state to this method.\n\n", 18: "minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n", 19: "fromSize and toSize must be provided as stringified numbers with the same units.\n\n", 20: "expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n", 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.\n\n", 24: "fontFace expects either the path to the font file(s) or a name of a local copy.\n\n", 25: "fontFace expects localFonts to be an array.\n\n", 26: "fontFace expects fileFormats to be an array.\n\n", 27: "radialGradient requries at least 2 color-stops to properly render.\n\n", 28: "Please supply a filename to retinaImage() as the first argument.\n\n", 29: "Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n", 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\n\n", 32: "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')\n\n", 33: "The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation\n\n", 34: "borderRadius expects a radius value as a string or number as the second argument.\n\n", 35: 'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n', 36: "Property must be a string value.\n\n", 37: "Syntax Error at %s.\n\n", 38: "Formula contains a function that needs parentheses at %s.\n\n", 39: "Formula is missing closing parenthesis at %s.\n\n", 40: "Formula has too many closing parentheses at %s.\n\n", 41: "All values in a formula must have the same unit or be unitless.\n\n", 42: "Please provide a number of steps to the modularScale helper.\n\n", 43: "Please pass a number or one of the predefined scales to the modularScale helper as the ratio.\n\n", 44: "Invalid value passed as base to modularScale, expected number or em/rem string but got %s.\n\n", 45: "Passed invalid argument to hslToColorString, please pass a HslColor or HslaColor object.\n\n", 46: "Passed invalid argument to rgbToColorString, please pass a RgbColor or RgbaColor object.\n\n", 47: "minScreen and maxScreen must be provided as stringified numbers with the same units.\n\n", 48: "fromSize and toSize must be provided as stringified numbers with the same units.\n\n", 49: "Expects either an array of objects or a single object with the properties prop, fromSize, and toSize.\n\n", 50: "Expects the objects in the first argument array to have the properties prop, fromSize, and toSize.\n\n", 51: "Expects the first argument object to have the properties prop, fromSize, and toSize.\n\n", 52: "fontFace expects either the path to the font file(s) or a name of a local copy.\n\n", 53: "fontFace expects localFonts to be an array.\n\n", 54: "fontFace expects fileFormats to be an array.\n\n", 55: "fontFace expects a name of a font-family.\n\n", 56: "linearGradient requries at least 2 color-stops to properly render.\n\n", 57: "radialGradient requries at least 2 color-stops to properly render.\n\n", 58: "Please supply a filename to retinaImage() as the first argument.\n\n", 59: "Passed invalid argument to triangle, please pass correct pointingDirection e.g. 'right'.\n\n", 60: "Passed an invalid value to `height` or `width`. Please provide a pixel based unit.\n\n", 61: "Property must be a string value.\n\n", 62: "borderRadius expects a radius value as a string or number as the second argument.\n\n", 63: 'borderRadius expects one of "top", "bottom", "left" or "right" as the first argument.\n\n', 64: "The animation shorthand only takes 8 arguments. See the specification for more information: http://mdn.io/animation.\n\n", 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').\n\n", 66: "The animation shorthand arrays can only have 8 elements. See the specification for more information: http://mdn.io/animation.\n\n", 67: "You must provide a template to this method.\n\n", 68: "You passed an unsupported selector state to this method.\n\n", 69: 'Expected a string ending in "px" or a number passed as the first argument to %s(), got %s instead.\n\n', 70: 'Expected a string ending in "px" or a number passed as the second argument to %s(), got %s instead.\n\n', 71: 'Passed invalid pixel value %s to %s(), please pass a value like "12px" or 12.\n\n', 72: 'Passed invalid base value %s to %s(), please pass a value like "12px" or 12.\n\n', 73: "Please provide a valid CSS variable.\n\n", 74: "CSS variable not found and no default was provided.\n\n", 75: "important requires a valid style object, got a %s instead.\n\n", 76: "fromSize and toSize must be provided as stringified numbers with the same units as minScreen and maxScreen.\n\n", 77: 'remToPx expects a value in "rem" but you provided it in "%s".\n\n', 78: 'base must be set in "px" or "%" but you set it in "%s".\n' };
function $() {
  for (var t48 = arguments.length, e2 = new Array(t48), n2 = 0; n2 < t48; n2++) e2[n2] = arguments[n2];
  var o2, i2 = e2[0], r2 = [];
  for (o2 = 1; o2 < e2.length; o2 += 1) r2.push(e2[o2]);
  return r2.forEach(function(t49) {
    i2 = i2.replace(/%[a-z]/, t49);
  }), i2;
}
var X = (function(t48) {
  var e2, n2;
  function o2(e3) {
    var n3;
    if ("production" === process.env.NODE_ENV) n3 = t48.call(this, "An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#" + e3 + " for more information.") || this;
    else {
      for (var o3 = arguments.length, i2 = new Array(o3 > 1 ? o3 - 1 : 0), r2 = 1; r2 < o3; r2++) i2[r2 - 1] = arguments[r2];
      n3 = t48.call(this, $.apply(void 0, [Y[e3]].concat(i2))) || this;
    }
    return (function(t49) {
      if (void 0 === t49) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
      return t49;
    })(n3);
  }
  return n2 = t48, (e2 = o2).prototype = Object.create(n2.prototype), e2.prototype.constructor = e2, z(e2, n2), o2;
})(j(Error));
function B(t48, e2) {
  return t48.substr(-e2.length) === e2;
}
var H = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;
function W(t48) {
  return "string" != typeof t48 ? t48 : t48.match(H) ? parseFloat(t48) : t48;
}
var V = function(t48) {
  return function(e2, n2) {
    void 0 === n2 && (n2 = "16px");
    var o2 = e2, i2 = n2;
    if ("string" == typeof e2) {
      if (!B(e2, "px")) throw new X(69, t48, e2);
      o2 = W(e2);
    }
    if ("string" == typeof n2) {
      if (!B(n2, "px")) throw new X(70, t48, n2);
      i2 = W(n2);
    }
    if ("string" == typeof o2) throw new X(71, e2, t48);
    if ("string" == typeof i2) throw new X(72, n2, t48);
    return "" + o2 / i2 + t48;
  };
};
V("em"), V("rem");
function U(t48) {
  return Math.round(255 * t48);
}
function G(t48, e2, n2) {
  return U(t48) + "," + U(e2) + "," + U(n2);
}
function Z(t48, e2, n2, o2) {
  if (void 0 === o2 && (o2 = G), 0 === e2) return o2(n2, n2, n2);
  var i2 = (t48 % 360 + 360) % 360 / 60, r2 = (1 - Math.abs(2 * n2 - 1)) * e2, s2 = r2 * (1 - Math.abs(i2 % 2 - 1)), a2 = 0, c2 = 0, l2 = 0;
  i2 >= 0 && i2 < 1 ? (a2 = r2, c2 = s2) : i2 >= 1 && i2 < 2 ? (a2 = s2, c2 = r2) : i2 >= 2 && i2 < 3 ? (c2 = r2, l2 = s2) : i2 >= 3 && i2 < 4 ? (c2 = s2, l2 = r2) : i2 >= 4 && i2 < 5 ? (a2 = s2, l2 = r2) : i2 >= 5 && i2 < 6 && (a2 = r2, l2 = s2);
  var h2 = n2 - r2 / 2;
  return o2(a2 + h2, c2 + h2, l2 + h2);
}
var q = { 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" };
var J = /^#[a-fA-F0-9]{6}$/;
var K = /^#[a-fA-F0-9]{8}$/;
var Q = /^#[a-fA-F0-9]{3}$/;
var tt = /^#[a-fA-F0-9]{4}$/;
var et = /^rgb\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*\)$/i;
var nt = /^rgb(?:a)?\(\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,)?\s*(\d{1,3})\s*(?:,|\/)\s*([-+]?\d*[.]?\d+[%]?)\s*\)$/i;
var ot = /^hsl\(\s*(\d{0,3}[.]?[0-9]+(?:deg)?)\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*(?:,)?\s*(\d{1,3}[.]?[0-9]?)%\s*\)$/i;
var it = /^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 rt(t48) {
  if ("string" != typeof t48) throw new X(3);
  var e2 = (function(t49) {
    if ("string" != typeof t49) return t49;
    var e3 = t49.toLowerCase();
    return q[e3] ? "#" + q[e3] : t49;
  })(t48);
  if (e2.match(J)) return { red: parseInt("" + e2[1] + e2[2], 16), green: parseInt("" + e2[3] + e2[4], 16), blue: parseInt("" + e2[5] + e2[6], 16) };
  if (e2.match(K)) {
    var n2 = parseFloat((parseInt("" + e2[7] + e2[8], 16) / 255).toFixed(2));
    return { red: parseInt("" + e2[1] + e2[2], 16), green: parseInt("" + e2[3] + e2[4], 16), blue: parseInt("" + e2[5] + e2[6], 16), alpha: n2 };
  }
  if (e2.match(Q)) return { red: parseInt("" + e2[1] + e2[1], 16), green: parseInt("" + e2[2] + e2[2], 16), blue: parseInt("" + e2[3] + e2[3], 16) };
  if (e2.match(tt)) {
    var o2 = parseFloat((parseInt("" + e2[4] + e2[4], 16) / 255).toFixed(2));
    return { red: parseInt("" + e2[1] + e2[1], 16), green: parseInt("" + e2[2] + e2[2], 16), blue: parseInt("" + e2[3] + e2[3], 16), alpha: o2 };
  }
  var i2 = et.exec(e2);
  if (i2) return { red: parseInt("" + i2[1], 10), green: parseInt("" + i2[2], 10), blue: parseInt("" + i2[3], 10) };
  var r2 = nt.exec(e2.substring(0, 50));
  if (r2) return { red: parseInt("" + r2[1], 10), green: parseInt("" + r2[2], 10), blue: parseInt("" + r2[3], 10), alpha: parseFloat("" + r2[4]) > 1 ? parseFloat("" + r2[4]) / 100 : parseFloat("" + r2[4]) };
  var s2 = ot.exec(e2);
  if (s2) {
    var a2 = "rgb(" + Z(parseInt("" + s2[1], 10), parseInt("" + s2[2], 10) / 100, parseInt("" + s2[3], 10) / 100) + ")", c2 = et.exec(a2);
    if (!c2) throw new X(4, e2, a2);
    return { red: parseInt("" + c2[1], 10), green: parseInt("" + c2[2], 10), blue: parseInt("" + c2[3], 10) };
  }
  var l2 = it.exec(e2.substring(0, 50));
  if (l2) {
    var h2 = "rgb(" + Z(parseInt("" + l2[1], 10), parseInt("" + l2[2], 10) / 100, parseInt("" + l2[3], 10) / 100) + ")", d2 = et.exec(h2);
    if (!d2) throw new X(4, e2, h2);
    return { red: parseInt("" + d2[1], 10), green: parseInt("" + d2[2], 10), blue: parseInt("" + d2[3], 10), alpha: parseFloat("" + l2[4]) > 1 ? parseFloat("" + l2[4]) / 100 : parseFloat("" + l2[4]) };
  }
  throw new X(5);
}
function st(t48) {
  return (function(t49) {
    var e2, n2 = t49.red / 255, o2 = t49.green / 255, i2 = t49.blue / 255, r2 = Math.max(n2, o2, i2), s2 = Math.min(n2, o2, i2), a2 = (r2 + s2) / 2;
    if (r2 === s2) return void 0 !== t49.alpha ? { hue: 0, saturation: 0, lightness: a2, alpha: t49.alpha } : { hue: 0, saturation: 0, lightness: a2 };
    var c2 = r2 - s2, l2 = a2 > 0.5 ? c2 / (2 - r2 - s2) : c2 / (r2 + s2);
    switch (r2) {
      case n2:
        e2 = (o2 - i2) / c2 + (o2 < i2 ? 6 : 0);
        break;
      case o2:
        e2 = (i2 - n2) / c2 + 2;
        break;
      default:
        e2 = (n2 - o2) / c2 + 4;
    }
    return e2 *= 60, void 0 !== t49.alpha ? { hue: e2, saturation: l2, lightness: a2, alpha: t49.alpha } : { hue: e2, saturation: l2, lightness: a2 };
  })(rt(t48));
}
var at = function(t48) {
  return 7 === t48.length && t48[1] === t48[2] && t48[3] === t48[4] && t48[5] === t48[6] ? "#" + t48[1] + t48[3] + t48[5] : t48;
};
function ct(t48) {
  var e2 = t48.toString(16);
  return 1 === e2.length ? "0" + e2 : e2;
}
function lt(t48) {
  return ct(Math.round(255 * t48));
}
function ht(t48, e2, n2) {
  return at("#" + lt(t48) + lt(e2) + lt(n2));
}
function dt(t48, e2, n2) {
  return Z(t48, e2, n2, ht);
}
function ut(t48, e2, n2) {
  if ("number" == typeof t48 && "number" == typeof e2 && "number" == typeof n2) return at("#" + ct(t48) + ct(e2) + ct(n2));
  if ("object" == typeof t48 && void 0 === e2 && void 0 === n2) return at("#" + ct(t48.red) + ct(t48.green) + ct(t48.blue));
  throw new X(6);
}
function pt(t48, e2, n2, o2) {
  if ("string" == typeof t48 && "number" == typeof e2) {
    var i2 = rt(t48);
    return "rgba(" + i2.red + "," + i2.green + "," + i2.blue + "," + e2 + ")";
  }
  if ("number" == typeof t48 && "number" == typeof e2 && "number" == typeof n2 && "number" == typeof o2) return o2 >= 1 ? ut(t48, e2, n2) : "rgba(" + t48 + "," + e2 + "," + n2 + "," + o2 + ")";
  if ("object" == typeof t48 && void 0 === e2 && void 0 === n2 && void 0 === o2) return t48.alpha >= 1 ? ut(t48.red, t48.green, t48.blue) : "rgba(" + t48.red + "," + t48.green + "," + t48.blue + "," + t48.alpha + ")";
  throw new X(7);
}
function mt(t48) {
  if ("object" != typeof t48) throw new X(8);
  if ((function(t49) {
    return "number" == typeof t49.red && "number" == typeof t49.green && "number" == typeof t49.blue && "number" == typeof t49.alpha;
  })(t48)) return pt(t48);
  if ((function(t49) {
    return "number" == typeof t49.red && "number" == typeof t49.green && "number" == typeof t49.blue && ("number" != typeof t49.alpha || void 0 === t49.alpha);
  })(t48)) return ut(t48);
  if ((function(t49) {
    return "number" == typeof t49.hue && "number" == typeof t49.saturation && "number" == typeof t49.lightness && "number" == typeof t49.alpha;
  })(t48)) return (function(t49, e2, n2, o2) {
    if ("number" == typeof t49 && "number" == typeof e2 && "number" == typeof n2 && "number" == typeof o2) return o2 >= 1 ? dt(t49, e2, n2) : "rgba(" + Z(t49, e2, n2) + "," + o2 + ")";
    if ("object" == typeof t49 && void 0 === e2 && void 0 === n2 && void 0 === o2) return t49.alpha >= 1 ? dt(t49.hue, t49.saturation, t49.lightness) : "rgba(" + Z(t49.hue, t49.saturation, t49.lightness) + "," + t49.alpha + ")";
    throw new X(2);
  })(t48);
  if ((function(t49) {
    return "number" == typeof t49.hue && "number" == typeof t49.saturation && "number" == typeof t49.lightness && ("number" != typeof t49.alpha || void 0 === t49.alpha);
  })(t48)) return (function(t49, e2, n2) {
    if ("number" == typeof t49 && "number" == typeof e2 && "number" == typeof n2) return dt(t49, e2, n2);
    if ("object" == typeof t49 && void 0 === e2 && void 0 === n2) return dt(t49.hue, t49.saturation, t49.lightness);
    throw new X(1);
  })(t48);
  throw new X(8);
}
function gt(t48, e2, n2) {
  return function() {
    var o2 = n2.concat(Array.prototype.slice.call(arguments));
    return o2.length >= e2 ? t48.apply(this, o2) : gt(t48, e2, o2);
  };
}
function ft(t48) {
  return gt(t48, t48.length, []);
}
ft(function(t48, e2) {
  if ("transparent" === e2) return e2;
  var n2 = st(e2);
  return mt(D({}, n2, { hue: n2.hue + parseFloat(t48) }));
});
function _t(t48, e2, n2) {
  return Math.max(t48, Math.min(e2, n2));
}
ft(function(t48, e2) {
  if ("transparent" === e2) return e2;
  var n2 = st(e2);
  return mt(D({}, n2, { lightness: _t(0, 1, n2.lightness - parseFloat(t48)) }));
});
ft(function(t48, e2) {
  if ("transparent" === e2) return e2;
  var n2 = st(e2);
  return mt(D({}, n2, { saturation: _t(0, 1, n2.saturation - parseFloat(t48)) }));
});
ft(function(t48, e2) {
  if ("transparent" === e2) return e2;
  var n2 = st(e2);
  return mt(D({}, n2, { lightness: _t(0, 1, n2.lightness + parseFloat(t48)) }));
});
var yt = ft(function(t48, e2, n2) {
  if ("transparent" === e2) return n2;
  if ("transparent" === n2) return e2;
  if (0 === t48) return n2;
  var o2 = rt(e2), i2 = D({}, o2, { alpha: "number" == typeof o2.alpha ? o2.alpha : 1 }), r2 = rt(n2), s2 = D({}, r2, { alpha: "number" == typeof r2.alpha ? r2.alpha : 1 }), a2 = i2.alpha - s2.alpha, c2 = 2 * parseFloat(t48) - 1, l2 = ((c2 * a2 === -1 ? c2 : c2 + a2) / (1 + c2 * a2) + 1) / 2, h2 = 1 - l2;
  return pt({ red: Math.floor(i2.red * l2 + s2.red * h2), green: Math.floor(i2.green * l2 + s2.green * h2), blue: Math.floor(i2.blue * l2 + s2.blue * h2), alpha: i2.alpha * parseFloat(t48) + s2.alpha * (1 - parseFloat(t48)) });
});
ft(function(t48, e2) {
  if ("transparent" === e2) return e2;
  var n2 = rt(e2);
  return pt(D({}, n2, { alpha: _t(0, 1, (100 * ("number" == typeof n2.alpha ? n2.alpha : 1) + 100 * parseFloat(t48)) / 100) }));
});
ft(function(t48, e2) {
  if ("transparent" === e2) return e2;
  var n2 = st(e2);
  return mt(D({}, n2, { saturation: _t(0, 1, n2.saturation + parseFloat(t48)) }));
});
ft(function(t48, e2) {
  return "transparent" === e2 ? e2 : mt(D({}, st(e2), { hue: parseFloat(t48) }));
});
ft(function(t48, e2) {
  return "transparent" === e2 ? e2 : mt(D({}, st(e2), { lightness: parseFloat(t48) }));
});
ft(function(t48, e2) {
  return "transparent" === e2 ? e2 : mt(D({}, st(e2), { saturation: parseFloat(t48) }));
});
ft(function(t48, e2) {
  return "transparent" === e2 ? e2 : yt(parseFloat(t48), "rgb(0, 0, 0)", e2);
});
ft(function(t48, e2) {
  return "transparent" === e2 ? e2 : yt(parseFloat(t48), "rgb(255, 255, 255)", e2);
});
var bt = ft(function(t48, e2) {
  if ("transparent" === e2) return e2;
  var n2 = rt(e2);
  return pt(D({}, n2, { alpha: _t(0, 1, +(100 * ("number" == typeof n2.alpha ? n2.alpha : 1) - 100 * parseFloat(t48)).toFixed(2) / 100) }));
});
var { cos: St, sin: It, PI: Pt } = Math;
var { tan: Mt } = Math;
var Ct = (c(u()), c(f()), (t48, e2) => ({ ...t48, rects: [...t48.rects ?? [], ...e2.rects ?? []], points: [...t48.points ?? [], ...e2.points ?? []], lines: [...t48.lines ?? [], ...e2.lines ?? []], infiniteLines: [...t48.infiniteLines ?? [], ...e2.infiniteLines ?? []], polygons: [...t48.polygons ?? [], ...e2.polygons ?? []], circles: [...t48.circles ?? [], ...e2.circles ?? []], arrows: [...t48.arrows ?? [], ...e2.arrows ?? []], texts: [...t48.texts ?? [], ...e2.texts ?? []] }));
function Nt(t48, e2) {
  if (t48.points) for (const n2 of t48.points) n2.step = e2;
  if (t48.lines) for (const n2 of t48.lines) n2.step = e2;
  if (t48.infiniteLines) for (const n2 of t48.infiniteLines) n2.step = e2;
  if (t48.polygons) for (const n2 of t48.polygons) n2.step = e2;
  if (t48.rects) for (const n2 of t48.rects) n2.step = e2;
  if (t48.circles) for (const n2 of t48.circles) n2.step = e2;
  if (t48.texts) for (const n2 of t48.texts) n2.step = e2;
  if (t48.arrows) for (const n2 of t48.arrows) n2.step = e2;
  return t48;
}
var wt = class {
  MAX_ITERATIONS = 1e5;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  _setupDone = false;
  getSolverName() {
    return this.constructor.name;
  }
  setup() {
    this._setupDone || (this._setup(), this._setupDone = true);
  }
  _setup() {
  }
  step() {
    if (this._setupDone || this.setup(), !this.solved && !this.failed) {
      this.iterations++;
      try {
        this._step();
      } catch (t48) {
        throw this.error = `${this.getSolverName()} error: ${t48}`, this.failed = true, t48;
      }
      !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 = true), "computeProgress" in this && (this.progress = this.computeProgress());
    }
  }
  _step() {
  }
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  getOutput() {
    return null;
  }
  solve() {
    const t48 = Date.now();
    for (; !this.solved && !this.failed; ) this.step();
    const e2 = Date.now();
    this.timeToSolve = e2 - t48;
  }
  visualize() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
  tryFinalAcceptance() {
  }
  preview() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
};
function Tt(t48, e2, n2, o2 = {}) {
  return { solverName: t48, solverClass: e2, getConstructorParams: n2, onSolved: o2.onSolved };
}
var Rt = class extends wt {
  startTimeOfStage = {};
  endTimeOfStage = {};
  timeSpentOnStage = {};
  firstIterationOfStage = {};
  currentPipelineStageIndex = 0;
  inputProblem;
  pipelineOutputs = {};
  constructor(t48) {
    super(), this.inputProblem = t48, this.MAX_ITERATIONS = 1e6;
  }
  _step() {
    const t48 = this.pipelineDef[this.currentPipelineStageIndex];
    if (!t48) return void (this.solved = true);
    if (this.activeSubSolver) {
      if (this.activeSubSolver.step(), this.activeSubSolver.solved) {
        this.endTimeOfStage[t48.solverName] = performance.now(), this.timeSpentOnStage[t48.solverName] = this.endTimeOfStage[t48.solverName] - this.startTimeOfStage[t48.solverName];
        const e3 = this.activeSubSolver.getOutput();
        null !== e3 && (this.pipelineOutputs[t48.solverName] = e3), t48.onSolved?.(this), this.activeSubSolver = null, this.currentPipelineStageIndex++;
      } else this.activeSubSolver.failed && (this.error = this.activeSubSolver?.error, this.failed = true, this.activeSubSolver = null);
      return;
    }
    const e2 = t48.getConstructorParams(this);
    this.activeSubSolver = new t48.solverClass(...e2), this[t48.solverName] = this.activeSubSolver, this.timeSpentOnStage[t48.solverName] = 0, this.startTimeOfStage[t48.solverName] = performance.now(), this.firstIterationOfStage[t48.solverName] = this.iterations;
  }
  solveUntilStage(t48) {
    for (; this.getCurrentStageName().toLowerCase() !== t48.toLowerCase() && (this.step(), !this.failed && !this.solved); ) ;
  }
  getCurrentStageName() {
    return this.pipelineDef[this.currentPipelineStageIndex]?.solverName ?? "none";
  }
  getStageProgress() {
    const t48 = this.pipelineDef.length;
    if (0 === t48) return 1;
    const e2 = this.activeSubSolver?.progress ?? 0;
    return (this.currentPipelineStageIndex + e2) / t48;
  }
  getStageStats() {
    const t48 = {};
    for (const e2 of this.pipelineDef) {
      const n2 = this.timeSpentOnStage[e2.solverName] || 0, o2 = this.firstIterationOfStage[e2.solverName] || 0, i2 = this.iterations, r2 = e2.solverName === this.getCurrentStageName() ? i2 - o2 : 0, s2 = this.currentPipelineStageIndex > this.pipelineDef.findIndex((t49) => t49.solverName === e2.solverName);
      t48[e2.solverName] = { timeSpent: n2, iterations: r2, completed: s2 };
    }
    return t48;
  }
  initialVisualize() {
    return null;
  }
  finalVisualize() {
    return null;
  }
  visualize() {
    if (!this.solved && this.activeSubSolver) return this.activeSubSolver.visualize();
    let t48 = 0;
    const e2 = this.initialVisualize();
    e2 && (Nt(e2, 0), t48 = 1);
    let n2 = null;
    this.solved && (n2 = this.finalVisualize());
    const o2 = [e2].filter(Boolean).concat(this.pipelineDef.map((e3, n3) => {
      const o3 = this[e3.solverName], i2 = o3?.visualize();
      return i2 ? (Nt(i2, n3 + t48), i2) : null;
    }).filter(Boolean));
    return 0 === o2.length ? { points: [], rects: [], lines: [], circles: [], texts: [] } : (this.solved && n2 && (Nt(n2, o2.length + t48 + 1), o2.push(n2)), 1 === o2.length ? o2[0] : { points: o2.flatMap((t49) => t49.points || []), rects: o2.flatMap((t49) => t49.rects || []), lines: o2.flatMap((t49) => t49.lines || []), circles: o2.flatMap((t49) => t49.circles || []), texts: o2.flatMap((t49) => t49.texts || []) });
  }
  preview() {
    return this.activeSubSolver ? this.activeSubSolver.preview() : super.preview();
  }
  computeProgress() {
    return this.getStageProgress();
  }
  getStageOutput(t48) {
    return this.pipelineOutputs[t48];
  }
  getAllOutputs() {
    return { ...this.pipelineOutputs };
  }
  hasStageOutput(t48) {
    return t48 in this.pipelineOutputs;
  }
  getSolver(t48) {
    return this[t48];
  }
};
var Et = class {
  constructor(t48 = 1 / 0, e2 = Float64Array, n2 = Uint32Array) {
    const o2 = t48 !== 1 / 0;
    this.ids = o2 ? new n2(t48) : [], this.values = o2 ? new e2(t48) : [], this.capacity = t48, this.length = 0;
  }
  clear() {
    this.length = 0;
  }
  push(t48, e2) {
    if (this.length === this.capacity) throw new RangeError("Queue is at capacity.");
    let n2 = this.length++;
    for (; n2 > 0; ) {
      const t49 = n2 - 1 >> 1, o2 = this.values[t49];
      if (e2 >= o2) break;
      this.ids[n2] = this.ids[t49], this.values[n2] = o2, n2 = t49;
    }
    this.ids[n2] = t48, this.values[n2] = e2;
  }
  pop() {
    if (0 === this.length) return;
    const t48 = this.ids, e2 = this.values, n2 = t48[0], o2 = --this.length;
    if (o2 > 0) {
      const n3 = t48[o2], i2 = e2[o2];
      let r2 = 0;
      const s2 = o2 >> 1;
      for (; r2 < s2; ) {
        const n4 = 1 + (r2 << 1), s3 = n4 + 1, a2 = n4 + (+(s3 < o2) & +(e2[s3] < e2[n4]));
        if (e2[a2] >= i2) break;
        t48[r2] = t48[a2], e2[r2] = e2[a2], r2 = a2;
      }
      t48[r2] = n3, e2[r2] = i2;
    }
    return n2;
  }
  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);
  }
};
var At = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array];
var Ot = class t2 {
  static from(e2, n2 = 0) {
    if (n2 % 8 != 0) throw new Error("byteOffset must be 8-byte aligned.");
    if (!e2 || void 0 === e2.byteLength || "buffer" in e2) throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");
    const [o2, i2] = new Uint8Array(e2, n2 + 0, 2);
    if (251 !== o2) throw new Error("Data does not appear to be in a Flatbush format.");
    const r2 = i2 >> 4;
    if (3 !== r2) throw new Error(`Got v${r2} data when expected v3.`);
    const s2 = At[15 & i2];
    if (!s2) throw new Error("Unrecognized array type.");
    const [a2] = new Uint16Array(e2, n2 + 2, 1), [c2] = new Uint32Array(e2, n2 + 4, 1);
    return new t2(c2, a2, s2, void 0, e2, n2);
  }
  constructor(t48, e2 = 16, n2 = Float64Array, o2 = ArrayBuffer, i2, r2 = 0) {
    if (void 0 === t48) throw new Error("Missing required argument: numItems.");
    if (isNaN(t48) || t48 <= 0) throw new Error(`Unexpected numItems value: ${t48}.`);
    this.numItems = +t48, this.nodeSize = Math.min(Math.max(+e2, 2), 65535), this.byteOffset = r2;
    let s2 = t48, a2 = s2;
    this._levelBounds = [4 * s2];
    do {
      s2 = Math.ceil(s2 / this.nodeSize), a2 += s2, this._levelBounds.push(4 * a2);
    } while (1 !== s2);
    this.ArrayType = n2, this.IndexArrayType = a2 < 16384 ? Uint16Array : Uint32Array;
    const c2 = At.indexOf(n2), l2 = 4 * a2 * n2.BYTES_PER_ELEMENT;
    if (c2 < 0) throw new Error(`Unexpected typed array class: ${n2}.`);
    const h2 = n2, d2 = this.IndexArrayType;
    if (i2) this.data = i2, this._boxes = new h2(i2, r2 + 8, 4 * a2), this._indices = new d2(i2, r2 + 8 + l2, a2), this._pos = 4 * a2, 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 n3 = this.data = new o2(8 + l2 + a2 * this.IndexArrayType.BYTES_PER_ELEMENT);
      this._boxes = new h2(n3, 8, 4 * a2), this._indices = new d2(n3, 8 + l2, a2), this._pos = 0, this.minX = 1 / 0, this.minY = 1 / 0, this.maxX = -1 / 0, this.maxY = -1 / 0, new Uint8Array(n3, 0, 2).set([251, 48 + c2]), new Uint16Array(n3, 2, 1)[0] = e2, new Uint32Array(n3, 4, 1)[0] = t48;
    }
    this._queue = new Et();
  }
  add(t48, e2, n2 = t48, o2 = e2) {
    const i2 = this._pos, r2 = i2 >> 2, s2 = this._boxes;
    return this._indices[r2] = r2, s2[i2] = t48, s2[i2 + 1] = e2, s2[i2 + 2] = n2, s2[i2 + 3] = o2, this._pos = i2 + 4, t48 < this.minX && (this.minX = t48), e2 < this.minY && (this.minY = e2), n2 > this.maxX && (this.maxX = n2), o2 > this.maxY && (this.maxY = o2), r2;
  }
  finish() {
    if (this._pos >> 2 !== this.numItems) throw new Error(`Added ${this._pos >> 2} items when expected ${this.numItems}.`);
    const t48 = this._boxes;
    if (this.numItems <= this.nodeSize) return t48[this._pos++] = this.minX, t48[this._pos++] = this.minY, t48[this._pos++] = this.maxX, void (t48[this._pos++] = this.maxY);
    const { numItems: e2, minX: n2, minY: o2, nodeSize: i2, _indices: r2, _levelBounds: s2 } = this, a2 = this.maxX - n2 || 1, c2 = this.maxY - o2 || 1, l2 = new Int32Array(e2), h2 = 65535 / a2, d2 = 65535 / c2;
    for (let i3 = 0, r3 = 0; i3 < e2; i3++) {
      const e3 = t48[r3++], s3 = t48[r3++], a3 = h2 * ((e3 + t48[r3++]) / 2 - n2) | 0, c3 = d2 * ((s3 + t48[r3++]) / 2 - o2) | 0;
      l2[i3] = zt(a3, c3);
    }
    !(function(t49, e3, n3, o3, i3, r3) {
      const s3 = [o3, i3];
      for (; s3.length; ) {
        const o4 = s3.pop() || 0, i4 = s3.pop() || 0;
        if (o4 - i4 <= r3 && Math.floor(i4 / r3) >= Math.floor(o4 / r3)) continue;
        const a3 = t49[i4], c3 = t49[i4 + o4 >> 1], l3 = t49[o4], h3 = a3 > c3 != a3 > l3 ? a3 : c3 < a3 != c3 < l3 ? c3 : l3;
        let d3 = i4 - 1, u3 = o4 + 1;
        for (; ; ) {
          do {
            d3++;
          } while (t49[d3] < h3);
          do {
            u3--;
          } while (t49[u3] > h3);
          if (d3 >= u3) break;
          Dt(t49, e3, n3, d3, u3);
        }
        s3.push(i4, u3, u3 + 1, o4);
      }
    })(l2, t48, r2, 0, e2 - 1, i2);
    let u2 = 4 * e2;
    for (let e3 = 0, n3 = 0; e3 < s2.length - 1; e3++) {
      const o3 = s2[e3];
      for (; n3 < o3; ) {
        const e4 = n3;
        let s3 = t48[n3++], a3 = t48[n3++], c3 = t48[n3++], l3 = t48[n3++];
        for (let e5 = 1; e5 < i2 && n3 < o3; e5++) s3 = Math.min(s3, t48[n3++]), a3 = Math.min(a3, t48[n3++]), c3 = Math.max(c3, t48[n3++]), l3 = Math.max(l3, t48[n3++]);
        r2[u2 >> 2] = e4, t48[u2++] = s3, t48[u2++] = a3, t48[u2++] = c3, t48[u2++] = l3;
      }
    }
    this._pos = u2;
  }
  search(t48, e2, n2, o2, i2) {
    if (this._pos !== this._boxes.length) throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r2, _levelBounds: s2, _indices: a2, nodeSize: c2 } = this, l2 = 4 * this.numItems;
    let h2 = r2.length - 4, d2 = s2.length - 1;
    const u2 = [], p2 = [];
    let m2 = false;
    for (; void 0 !== h2; ) {
      const g2 = Math.min(h2 + 4 * c2, s2[d2]), f2 = h2 >= l2;
      if (m2) this._collectContained(h2, g2, d2, l2, p2, i2);
      else for (let s3 = h2; s3 < g2; s3 += 4) {
        const c3 = r2[s3];
        if (n2 < c3) continue;
        const l3 = r2[s3 + 1];
        if (o2 < l3) continue;
        const h3 = r2[s3 + 2];
        if (t48 > h3) continue;
        const m3 = r2[s3 + 3];
        if (e2 > m3) continue;
        const g3 = 0 | a2[s3 >> 2];
        if (f2) {
          const i3 = +(t48 <= c3 && e2 <= l3 && n2 >= h3 && o2 >= m3);
          u2.push(g3 | i3, d2 - 1);
        } else (void 0 === i2 || i2(g3, c3, l3, h3, m3)) && p2.push(g3);
      }
      d2 = u2.pop(), h2 = u2.pop(), void 0 !== h2 && (m2 = !(1 & ~h2), h2 &= -2);
    }
    return p2;
  }
  _collectContained(t48, e2, n2, o2, i2, r2) {
    const s2 = this._boxes, a2 = this._indices;
    let c2 = t48;
    for (let t49 = n2; t49 > 0; t49--) c2 = a2[c2 >> 2];
    const l2 = Math.min(c2 + (e2 - t48) * this.nodeSize ** n2, o2);
    if (void 0 === r2) for (; c2 < l2; c2 += 4) i2.push(0 | a2[c2 >> 2]);
    else for (; c2 < l2; c2 += 4) {
      const t49 = 0 | a2[c2 >> 2];
      r2(t49, s2[c2], s2[c2 + 1], s2[c2 + 2], s2[c2 + 3]) && i2.push(t49);
    }
  }
  neighbors(t48, e2, n2 = 1 / 0, o2 = 1 / 0, i2) {
    if (this._pos !== this._boxes.length) throw new Error("Data not yet indexed - call index.finish().");
    const { _boxes: r2, _levelBounds: s2, _indices: a2, _queue: c2, nodeSize: l2 } = this, h2 = 4 * this.numItems, d2 = 4 * l2, u2 = [], p2 = 1 === n2;
    let m2 = o2 * o2;
    for (c2.push(r2.length - 4 << 1, 0); c2.length; ) {
      const o3 = c2.ids[0];
      if (1 & o3) {
        if (c2.pop(), u2.push(o3 >> 1), u2.length === n2) break;
        continue;
      }
      c2.pop();
      const l3 = o3 >> 1, g2 = l3 < h2, f2 = Math.min(l3 + d2, Lt(l3, s2));
      for (let n3 = l3; n3 < f2; n3 += 4) {
        const o4 = r2[n3], s3 = r2[n3 + 1], l4 = r2[n3 + 2], h3 = r2[n3 + 3], d3 = Math.max(Math.max(o4 - t48, t48 - l4), 0), u3 = Math.max(Math.max(s3 - e2, e2 - h3), 0), f3 = d3 * d3 + u3 * u3;
        if (f3 > m2) continue;
        const _2 = 0 | a2[n3 >> 2];
        g2 ? (void 0 === i2 || i2(_2)) && (c2.push(_2 << 1 | 1, f3), p2 && f3 < m2 && (m2 = f3)) : c2.push(_2 << 1, f3);
      }
    }
    return c2.clear(), u2;
  }
};
function Lt(t48, e2) {
  let n2 = 0, o2 = e2.length - 1;
  for (; n2 < o2; ) {
    const i2 = n2 + o2 >> 1;
    e2[i2] > t48 ? o2 = i2 : n2 = i2 + 1;
  }
  return e2[n2];
}
function Dt(t48, e2, n2, o2, i2) {
  const r2 = t48[o2];
  t48[o2] = t48[i2], t48[i2] = r2;
  const s2 = 4 * o2, a2 = 4 * i2, c2 = e2[s2], l2 = e2[s2 + 1], h2 = e2[s2 + 2], d2 = e2[s2 + 3];
  e2[s2] = e2[a2], e2[s2 + 1] = e2[a2 + 1], e2[s2 + 2] = e2[a2 + 2], e2[s2 + 3] = e2[a2 + 3], e2[a2] = c2, e2[a2 + 1] = l2, e2[a2 + 2] = h2, e2[a2 + 3] = d2;
  const u2 = n2[o2];
  n2[o2] = n2[i2], n2[i2] = u2;
}
function zt(t48, e2) {
  let n2 = t48 ^ e2, o2 = 65535 ^ n2, i2 = 65535 ^ (t48 | e2), r2 = t48 & (65535 ^ e2), s2 = n2 | o2 >> 1, a2 = n2 >> 1 ^ n2, c2 = i2 ^ i2 >> 1 ^ o2 & r2 >> 1, l2 = r2 ^ n2 & i2 >> 1 ^ r2 >> 1;
  return n2 = s2 & s2 >> 2 ^ a2 & a2 >> 2, o2 = s2 & a2 >> 2 ^ a2 & (s2 ^ a2) >> 2, i2 = c2 ^ s2 & c2 >> 2 ^ a2 & l2 >> 2, r2 = l2 ^ a2 & c2 >> 2 ^ (s2 ^ a2) & l2 >> 2, s2 = n2 & n2 >> 4 ^ o2 & o2 >> 4, a2 = n2 & o2 >> 4 ^ o2 & (n2 ^ o2) >> 4, c2 = i2 ^ n2 & i2 >> 4 ^ o2 & r2 >> 4, l2 = r2 ^ o2 & i2 >> 4 ^ (n2 ^ o2) & r2 >> 4, i2 = c2 ^ s2 & c2 >> 8 ^ a2 & l2 >> 8, r2 = l2 ^ a2 & c2 >> 8 ^ (s2 ^ a2) & l2 >> 8, i2 ^= i2 >> 1, r2 ^= r2 >> 1, n2 = t48 ^ e2, o2 = r2 | 65535 ^ (n2 | i2), n2 = 16711935 & (n2 | n2 << 8), n2 = 252645135 & (n2 | n2 << 4), n2 = 858993459 & (n2 | n2 << 2), n2 = 1431655765 & (n2 | n2 << 1), o2 = 16711935 & (o2 | o2 << 8), o2 = 252645135 & (o2 | o2 << 4), o2 = 858993459 & (o2 | o2 << 2), o2 = 1431655765 & (o2 | o2 << 1), ((o2 << 1 | n2) >>> 0) - 2147483648;
}
var Ft = [{ facingDirection: "x-", dx: -1, dy: 0, startX: -0.5, startY: 0.5, endX: -0.5, endY: -0.5 }, { facingDirection: "x+", dx: 1, dy: 0, startX: 0.5, startY: 0.5, endX: 0.5, endY: -0.5 }, { facingDirection: "y-", dx: 0, dy: -1, startX: -0.5, startY: -0.5, endX: 0.5, endY: -0.5 }, { facingDirection: "y+", dx: 0, dy: 1, startX: 0.5, startY: 0.5, endX: -0.5, endY: 0.5 }];
var jt = { "x-": Ft.find((t48) => "x-" === t48.facingDirection), "x+": Ft.find((t48) => "x+" === t48.facingDirection), "y-": Ft.find((t48) => "y-" === t48.facingDirection), "y+": Ft.find((t48) => "y+" === t48.facingDirection) };
function me(t48, e2) {
  const n2 = t48.x - e2.x, o2 = t48.y - e2.y;
  return Math.sqrt(n2 * n2 + o2 * o2);
}
function Me(t48) {
  const e2 = t48.width / 2, n2 = t48.height / 2;
  return { minX: t48.center.x - e2, maxX: t48.center.x + e2, minY: t48.center.y - n2, maxY: t48.center.y + n2 };
}
function Ce(t48, e2, n2) {
  return Math.max(e2, Math.min(n2, t48));
}
function Oe(t48, e2) {
  const n2 = e2.width / 2, o2 = e2.height / 2, i2 = e2.center.x - n2, r2 = e2.center.x + n2, s2 = e2.center.y - o2, a2 = e2.center.y + o2;
  if (t48.x >= i2 && t48.x <= r2 && t48.y >= s2 && t48.y <= a2) return 0;
  return me(t48, { x: Ce(t48.x, i2, r2), y: Ce(t48.y, s2, a2) });
}
var ze = (t48, e2) => !(t48.maxX < e2.minX || e2.maxX < t48.minX || t48.maxY < e2.minY || e2.maxY < t48.minY);
var ke = (t48) => {
  const { center: e2, width: n2, height: o2 } = t48, i2 = n2 / 2, r2 = o2 / 2;
  return { minX: e2.x - i2, maxX: e2.x + i2, minY: e2.y - r2, maxY: e2.y + r2 };
};
var Vn = class {
  cacheHitsByPrefix = {};
  cacheMissesByPrefix = {};
  isSyncCache = true;
  cacheHits = 0;
  cacheMisses = 0;
  cache = /* @__PURE__ */ new Map();
  getCachedSolutionSync(t48) {
    const e2 = this.cache.get(t48);
    if (void 0 !== e2) {
      this.cacheHits++;
      const n2 = t48.split(":")[0];
      return this.cacheHitsByPrefix[n2] = (this.cacheHitsByPrefix[n2] || 0) + 1, structuredClone(e2);
    }
    {
      this.cacheMisses++;
      const e3 = t48.split(":")[0];
      return void (this.cacheMissesByPrefix[e3] = (this.cacheMissesByPrefix[e3] || 0) + 1);
    }
  }
  async getCachedSolution(t48) {
    return this.getCachedSolutionSync(t48);
  }
  setCachedSolutionSync(t48, e2) {
    this.cache.set(t48, structuredClone(e2));
  }
  async setCachedSolution(t48, e2) {
    this.setCachedSolutionSync(t48, e2);
  }
  clearCache() {
    this.cache.clear(), this.cacheHits = 0, this.cacheMisses = 0, this.cacheHitsByPrefix = {}, this.cacheMissesByPrefix = {};
  }
  getAllCacheKeys() {
    return Array.from(this.cache.keys());
  }
};
var Un = "tscircuit_autorouter_cache_";
var Gn = class {
  isSyncCache = true;
  cacheHits = 0;
  cacheMisses = 0;
  cacheHitsByPrefix = {};
  cacheMissesByPrefix = {};
  constructor() {
  }
  getKey(t48) {
    return `${Un}${t48}`;
  }
  getCachedSolutionSync(t48) {
    if ("undefined" == typeof localStorage) return;
    const e2 = this.getKey(t48);
    try {
      const n2 = localStorage.getItem(e2);
      if (null !== n2) {
        const e3 = JSON.parse(n2);
        this.cacheHits++;
        const o2 = t48.split(":")[0];
        return this.cacheHitsByPrefix[o2] = (this.cacheHitsByPrefix[o2] || 0) + 1, e3;
      }
      {
        this.cacheMisses++;
        const e3 = t48.split(":")[0];
        return void (this.cacheMissesByPrefix[e3] = (this.cacheMissesByPrefix[e3] || 0) + 1);
      }
    } catch (n2) {
      console.error(`Error getting cached solution sync for ${e2}:`, n2), this.cacheMisses++;
      const o2 = t48.split(":")[0];
      return void (this.cacheMissesByPrefix[o2] = (this.cacheMissesByPrefix[o2] || 0) + 1);
    }
  }
  async getCachedSolution(t48) {
    return this.getCachedSolutionSync(t48);
  }
  setCachedSolutionSync(t48, e2) {
    if ("undefined" == typeof localStorage) return;
    const n2 = this.getKey(t48);
    try {
      const t49 = JSON.stringify(e2);
      localStorage.setItem(n2, t49);
    } catch (t49) {
      console.error(`Error setting cached solution sync for ${n2}:`, t49), t49 instanceof DOMException && ("QuotaExceededError" === t49.name || "NS_ERROR_DOM_QUOTA_REACHED" === t49.name) && console.warn(`LocalStorage quota exceeded. Failed to cache solution for ${n2}. Consider clearing the cache.`);
    }
  }
  async setCachedSolution(t48, e2) {
    this.setCachedSolutionSync(t48, e2);
  }
  clearCache() {
    if ("undefined" != typeof localStorage) try {
      const t48 = [];
      for (let e2 = 0; e2 < localStorage.length; e2++) {
        const n2 = localStorage.key(e2);
        n2?.startsWith(Un) && t48.push(n2);
      }
      t48.forEach((t49) => localStorage.removeItem(t49)), console.log(`Cleared ${t48.length} items from LocalStorage cache.`);
    } catch (t48) {
      console.error("Error clearing LocalStorage cache:", t48);
    } finally {
      this.cacheHits = 0, this.cacheMisses = 0, this.cacheHitsByPrefix = {}, this.cacheMissesByPrefix = {};
    }
  }
  getAllCacheKeys() {
    const t48 = [];
    for (let e2 = 0; e2 < 1e4; e2++) {
      const n2 = localStorage.key(e2);
      if (!n2) break;
      n2.includes(Un) && t48.push(n2);
    }
    return t48;
  }
};
function Jn() {
  globalThis.TSCIRCUIT_AUTOROUTER_LOCAL_STORAGE_CACHE ??= new Gn(), globalThis.TSCIRCUIT_AUTOROUTER_IN_MEMORY_CACHE ??= new Vn();
}
function co(t48) {
  return "layers" in t48 && Array.isArray(t48.layers);
}
function uo(t48) {
  return co(t48) ? t48.layers : [t48.layer];
}
var No = (t48, e2) => "top" === t48 ? 0 : "bottom" === t48 ? e2 - 1 : parseInt(t48.slice(5));
function wo(t48, e2) {
  return [...new Set(t48)].filter((t49) => Number.isInteger(t49) && t49 >= 0 && t49 < e2).sort((t49, e3) => t49 - e3);
}
function To(t48, e2) {
  return wo(t48.map((t49) => No(t49, e2)), e2);
}
var Lo = (...t48) => t48.find((t49) => "number" == typeof t49 && Number.isFinite(t49));
var Do = (t48) => {
  const e2 = Lo(t48.min_via_hole_diameter, t48.minViaHoleDiameter), n2 = Lo(t48.min_via_pad_diameter, t48.minViaPadDiameter, t48.minViaDiameter), o2 = Math.max(n2 ?? t48.minViaDiameter ?? 0.3, e2 ?? 0);
  return { padDiameter: o2, holeDiameter: e2 ?? 0.5 * o2 };
};
Jn();
var us = Array.from({ length: 6 }, (t48, e2) => e2);
var zs = 1.6 * 3.2;
var ac = (t48, e2 = {}) => {
  const n2 = Math.min(...t48.availableZ);
  return { center: !e2.rectMargin || e2.zOffset ? { x: t48.center.x + n2 * t48.width * (e2.zOffset ?? 0.05), y: t48.center.y - n2 * t48.width * (e2.zOffset ?? 0.05) } : t48.center, width: e2.rectMargin ? t48.width - 2 * e2.rectMargin : Math.max(t48.width - 0.5, 0.8 * t48.width), height: e2.rectMargin ? t48.height - 2 * e2.rectMargin : Math.max(t48.height - 0.5, 0.8 * t48.height), fill: t48._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)" }[t48.availableZ.join(",")] ?? "rgba(0,200,200,0.1)", layer: `z${t48.availableZ.join(",")}`, label: [t48.capacityMeshNodeId, `availableZ: ${t48.availableZ.join(",")}`, t48._containsTarget ? "containsTarget" : "", t48._containsObstacle ? "containsObstacle" : ""].filter(Boolean).join("\n") };
};
Jn();
var yl = Object.create;
var bl = Object.defineProperty;
var xl = Object.getOwnPropertyDescriptor;
var vl = Object.getOwnPropertyNames;
var Sl = Object.getPrototypeOf;
var Il = Object.prototype.hasOwnProperty;
var Pl = (t48, e2) => function() {
  return e2 || (0, t48[vl(t48)[0]])((e2 = { exports: {} }).exports, e2), e2.exports;
};
var Ml = (t48, e2, n2) => (n2 = null != t48 ? yl(Sl(t48)) : {}, ((t49, e3, n3, o2) => {
  if (e3 && "object" == typeof e3 || "function" == typeof e3) for (let i2 of vl(e3)) Il.call(t49, i2) || i2 === n3 || bl(t49, i2, { get: () => e3[i2], enumerable: !(o2 = xl(e3, i2)) || o2.enumerable });
  return t49;
})(!e2 && t48 && t48.__esModule ? n2 : bl(n2, "default", { value: t48, enumerable: true }), t48));
var Cl = Pl({ "node_modules/is-buffer/index.js"(t48, e2) {
  function n2(t49) {
    return !!t49.constructor && "function" == typeof t49.constructor.isBuffer && t49.constructor.isBuffer(t49);
  }
  e2.exports = function(t49) {
    return null != t49 && (n2(t49) || (function(t50) {
      return "function" == typeof t50.readFloatLE && "function" == typeof t50.slice && n2(t50.slice(0, 0));
    })(t49) || !!t49._isBuffer);
  };
} });
var Nl = Pl({ "node_modules/kind-of/index.js"(t48, e2) {
  var n2 = Cl(), o2 = Object.prototype.toString;
  e2.exports = function(t49) {
    if (void 0 === t49) return "undefined";
    if (null === t49) return "null";
    if (true === t49 || false === t49 || t49 instanceof Boolean) return "boolean";
    if ("string" == typeof t49 || t49 instanceof String) return "string";
    if ("number" == typeof t49 || t49 instanceof Number) return "number";
    if ("function" == typeof t49 || t49 instanceof Function) return "function";
    if (void 0 !== Array.isArray && Array.isArray(t49)) return "array";
    if (t49 instanceof RegExp) return "regexp";
    if (t49 instanceof Date) return "date";
    var e3 = o2.call(t49);
    return "[object RegExp]" === e3 ? "regexp" : "[object Date]" === e3 ? "date" : "[object Arguments]" === e3 ? "arguments" : "[object Error]" === e3 ? "error" : n2(t49) ? "buffer" : "[object Set]" === e3 ? "set" : "[object WeakSet]" === e3 ? "weakset" : "[object Map]" === e3 ? "map" : "[object WeakMap]" === e3 ? "weakmap" : "[object Symbol]" === e3 ? "symbol" : "[object Int8Array]" === e3 ? "int8array" : "[object Uint8Array]" === e3 ? "uint8array" : "[object Uint8ClampedArray]" === e3 ? "uint8clampedarray" : "[object Int16Array]" === e3 ? "int16array" : "[object Uint16Array]" === e3 ? "uint16array" : "[object Int32Array]" === e3 ? "int32array" : "[object Uint32Array]" === e3 ? "uint32array" : "[object Float32Array]" === e3 ? "float32array" : "[object Float64Array]" === e3 ? "float64array" : "object";
  };
} });
var wl = Pl({ "node_modules/rename-keys/index.js"(t48, e2) {
  !(function() {
    function t49(t50, e3) {
      if ("function" != typeof e3) return t50;
      var n2 = {};
      for (var o2 in t50) Object.prototype.hasOwnProperty.call(t50, o2) && (n2[e3(o2, t50[o2]) || o2] = t50[o2]);
      return n2;
    }
    void 0 !== e2 && e2.exports ? e2.exports = t49 : "function" == typeof define && define.amd ? define([], function() {
      return t49;
    }) : window.rename = t49;
  })();
} });
var Tl = Pl({ "node_modules/deep-rename-keys/index.js"(t48, e2) {
  var n2 = Nl(), o2 = wl();
  e2.exports = function t49(e3, i2) {
    var r2 = n2(e3);
    if ("object" !== r2 && "array" !== r2) throw new Error("expected an object");
    var s2 = [];
    for (var a2 in "object" === r2 && (e3 = o2(e3, i2), s2 = {}), e3) if (e3.hasOwnProperty(a2)) {
      var c2 = e3[a2];
      "object" === n2(c2) || "array" === n2(c2) ? s2[a2] = t49(c2, i2) : s2[a2] = c2;
    }
    return s2;
  };
} });
var Rl = Pl({ "node_modules/eventemitter3/index.js"(t48, e2) {
  var n2 = Object.prototype.hasOwnProperty, o2 = "~";
  function i2() {
  }
  function r2(t49, e3, n3) {
    this.fn = t49, this.context = e3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i2(), this._eventsCount = 0;
  }
  Object.create && (i2.prototype = /* @__PURE__ */ Object.create(null), new i2().__proto__ || (o2 = false)), s2.prototype.eventNames = function() {
    var t49, e3, i3 = [];
    if (0 === this._eventsCount) return i3;
    for (e3 in t49 = this._events) n2.call(t49, e3) && i3.push(o2 ? e3.slice(1) : e3);
    return Object.getOwnPropertySymbols ? i3.concat(Object.getOwnPropertySymbols(t49)) : i3;
  }, s2.prototype.listeners = function(t49, e3) {
    var n3 = o2 ? o2 + t49 : t49, i3 = this._events[n3];
    if (e3) return !!i3;
    if (!i3) return [];
    if (i3.fn) return [i3.fn];
    for (var r3 = 0, s3 = i3.length, a2 = new Array(s3); r3 < s3; r3++) a2[r3] = i3[r3].fn;
    return a2;
  }, s2.prototype.emit = function(t49, e3, n3, i3, r3, s3) {
    var a2 = o2 ? o2 + t49 : t49;
    if (!this._events[a2]) return false;
    var c2, l2, h2 = this._events[a2], d2 = arguments.length;
    if (h2.fn) {
      switch (h2.once && this.removeListener(t49, h2.fn, void 0, true), d2) {
        case 1:
          return h2.fn.call(h2.context), true;
        case 2:
          return h2.fn.call(h2.context, e3), true;
        case 3:
          return h2.fn.call(h2.context, e3, n3), true;
        case 4:
          return h2.fn.call(h2.context, e3, n3, i3), true;
        case 5:
          return h2.fn.call(h2.context, e3, n3, i3, r3), true;
        case 6:
          return h2.fn.call(h2.context, e3, n3, i3, r3, s3), true;
      }
      for (l2 = 1, c2 = new Array(d2 - 1); l2 < d2; l2++) c2[l2 - 1] = arguments[l2];
      h2.fn.apply(h2.context, c2);
    } else {
      var u2, p2 = h2.length;
      for (l2 = 0; l2 < p2; l2++) switch (h2[l2].once && this.removeListener(t49, h2[l2].fn, void 0, true), d2) {
        case 1:
          h2[l2].fn.call(h2[l2].context);
          break;
        case 2:
          h2[l2].fn.call(h2[l2].context, e3);
          break;
        case 3:
          h2[l2].fn.call(h2[l2].context, e3, n3);
          break;
        case 4:
          h2[l2].fn.call(h2[l2].context, e3, n3, i3);
          break;
        default:
          if (!c2) for (u2 = 1, c2 = new Array(d2 - 1); u2 < d2; u2++) c2[u2 - 1] = arguments[u2];
          h2[l2].fn.apply(h2[l2].context, c2);
      }
    }
    return true;
  }, s2.prototype.on = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.once = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this, true), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(t49, e3, n3, r3) {
    var s3 = o2 ? o2 + t49 : t49;
    if (!this._events[s3]) return this;
    if (!e3) return 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3], this;
    var a2 = this._events[s3];
    if (a2.fn) a2.fn !== e3 || r3 && !a2.once || n3 && a2.context !== n3 || (0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3]);
    else {
      for (var c2 = 0, l2 = [], h2 = a2.length; c2 < h2; c2++) (a2[c2].fn !== e3 || r3 && !a2[c2].once || n3 && a2[c2].context !== n3) && l2.push(a2[c2]);
      l2.length ? this._events[s3] = 1 === l2.length ? l2[0] : l2 : 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(t49) {
    var e3;
    return t49 ? (e3 = o2 ? o2 + t49 : t49, this._events[e3] && (0 === --this._eventsCount ? this._events = new i2() : delete this._events[e3])) : (this._events = new i2(), this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o2, s2.EventEmitter = s2, void 0 !== e2 && (e2.exports = s2);
} });
var El = Pl({ "node_modules/xml-lexer/dist/lexer.js"(t48, e2) {
  function n2(t49, e3, n3) {
    return e3 in t49 ? Object.defineProperty(t49, e3, { value: n3, enumerable: true, configurable: true, writable: true }) : t49[e3] = n3, t49;
  }
  var o2 = Rl(), i2 = function() {
  }, r2 = { 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" }, s2 = { lt: "action-lt", gt: "action-gt", space: "action-space", equal: "action-equal", quote: "action-quote", slash: "action-slash", char: "action-char", error: "action-error" }, a2 = { text: "text", openTag: "open-tag", closeTag: "close-tag", attributeName: "attribute-name", attributeValue: "attribute-value" }, c2 = { " ": s2.space, "	": s2.space, "\n": s2.space, "\r": s2.space, "<": s2.lt, ">": s2.gt, '"': s2.quote, "'": s2.quote, "=": s2.equal, "/": s2.slash };
  e2.exports = { State: r2, Action: s2, Type: a2, create: function(t49) {
    var e3, l2, h2, d2, u2, p2, m2, g2, f2, _2;
    t49 = Object.assign({ debug: false }, t49);
    var y2 = new o2(), b2 = r2.data, x2 = "", v2 = "", S2 = "", I2 = "", P2 = "", M2 = "", C2 = function(e4, n3) {
      if ("?" !== v2[0] && "!" !== v2[0]) {
        var o3 = { type: e4, value: n3 };
        t49.debug && console.log("emit:", o3), y2.emit("data", o3);
      }
    };
    y2.stateMachine = (n2(_2 = {}, r2.data, (n2(e3 = {}, s2.lt, function() {
      x2.trim() && C2(a2.text, x2), v2 = "", P2 = false, b2 = r2.tagBegin;
    }), n2(e3, s2.char, function(t50) {
      x2 += t50;
    }), e3)), n2(_2, r2.cdata, n2({}, s2.char, function(t50) {
      "]]>" === (x2 += t50).substr(-3) && (C2(a2.text, x2.slice(0, -3)), x2 = "", b2 = r2.data);
    })), n2(_2, r2.tagBegin, (n2(l2 = {}, s2.space, i2), n2(l2, s2.char, function(t50) {
      v2 = t50, b2 = r2.tagName;
    }), n2(l2, s2.slash, function() {
      v2 = "", P2 = true;
    }), l2)), n2(_2, r2.tagName, (n2(h2 = {}, s2.space, function() {
      P2 ? b2 = r2.tagEnd : (b2 = r2.attributeNameStart, C2(a2.openTag, v2));
    }), n2(h2, s2.gt, function() {
      C2(P2 ? a2.closeTag : a2.openTag, v2), x2 = "", b2 = r2.data;
    }), n2(h2, s2.slash, function() {
      b2 = r2.tagEnd, C2(a2.openTag, v2);
    }), n2(h2, s2.char, function(t50) {
      "![CDATA[" === (v2 += t50) && (b2 = r2.cdata, x2 = "", v2 = "");
    }), h2)), n2(_2, r2.tagEnd, (n2(d2 = {}, s2.gt, function() {
      C2(a2.closeTag, v2), x2 = "", b2 = r2.data;
    }), n2(d2, s2.char, i2), d2)), n2(_2, r2.attributeNameStart, (n2(u2 = {}, s2.char, function(t50) {
      S2 = t50, b2 = r2.attributeName;
    }), n2(u2, s2.gt, function() {
      x2 = "", b2 = r2.data;
    }), n2(u2, s2.space, i2), n2(u2, s2.slash, function() {
      P2 = true, b2 = r2.tagEnd;
    }), u2)), n2(_2, r2.attributeName, (n2(p2 = {}, s2.space, function() {
      b2 = r2.attributeNameEnd;
    }), n2(p2, s2.equal, function() {
      C2(a2.attributeName, S2), b2 = r2.attributeValueBegin;
    }), n2(p2, s2.gt, function() {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), x2 = "", b2 = r2.data;
    }), n2(p2, s2.slash, function() {
      P2 = true, I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), b2 = r2.tagEnd;
    }), n2(p2, s2.char, function(t50) {
      S2 += t50;
    }), p2)), n2(_2, r2.attributeNameEnd, (n2(m2 = {}, s2.space, i2), n2(m2, s2.equal, function() {
      C2(a2.attributeName, S2), b2 = r2.attributeValueBegin;
    }), n2(m2, s2.gt, function() {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), x2 = "", b2 = r2.data;
    }), n2(m2, s2.char, function(t50) {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), S2 = t50, b2 = r2.attributeName;
    }), m2)), n2(_2, r2.attributeValueBegin, (n2(g2 = {}, s2.space, i2), n2(g2, s2.quote, function(t50) {
      M2 = t50, I2 = "", b2 = r2.attributeValue;
    }), n2(g2, s2.gt, function() {
      C2(a2.attributeValue, I2 = ""), x2 = "", b2 = r2.data;
    }), n2(g2, s2.char, function(t50) {
      M2 = "", I2 = t50, b2 = r2.attributeValue;
    }), g2)), n2(_2, r2.attributeValue, (n2(f2 = {}, s2.space, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), b2 = r2.attributeNameStart);
    }), n2(f2, s2.quote, function(t50) {
      M2 === t50 ? (C2(a2.attributeValue, I2), b2 = r2.attributeNameStart) : I2 += t50;
    }), n2(f2, s2.gt, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), x2 = "", b2 = r2.data);
    }), n2(f2, s2.slash, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), P2 = true, b2 = r2.tagEnd);
    }), n2(f2, s2.char, function(t50) {
      I2 += t50;
    }), f2)), _2);
    var N2 = function(e4) {
      t49.debug && console.log(b2, e4);
      var n3 = y2.stateMachine[b2], o3 = n3[(function(t50) {
        return c2[t50] || s2.char;
      })(e4)] || n3[s2.error] || n3[s2.char];
      o3(e4);
    };
    return y2.write = function(t50) {
      for (var e4 = t50.length, n3 = 0; n3 < e4; n3++) N2(t50[n3]);
    }, y2;
  } };
} });
var Al = Pl({ "node_modules/xml-reader/dist/reader.js"(t48, e2) {
  var n2 = Rl(), o2 = El(), i2 = o2.Type, r2 = { element: "element", text: "text" }, s2 = function(t49) {
    return Object.assign({ name: "", type: r2.element, value: "", parent: null, attributes: {}, children: [] }, t49);
  }, a2 = function(t49) {
    t49 = Object.assign({ stream: false, parentNodes: true, doneEvent: "done", tagPrefix: "tag:", emitTopLevelOnly: false, debug: false }, t49);
    var e3 = void 0, a3 = void 0, c2 = void 0, l2 = void 0, h2 = new n2(), d2 = function(n3) {
      switch (n3.type) {
        case i2.openTag:
          if (null === c2) (c2 = a3).name = n3.value;
          else {
            var o3 = s2({ name: n3.value, parent: c2 });
            c2.children.push(o3), c2 = o3;
          }
          break;
        case i2.closeTag:
          var d3 = c2.parent;
          if (t49.parentNodes || (c2.parent = null), c2.name !== n3.value) break;
          t49.stream && d3 === a3 && (a3.children = [], c2.parent = null), t49.emitTopLevelOnly && d3 !== a3 || (h2.emit(t49.tagPrefix + c2.name, c2), h2.emit("tag", c2.name, c2)), c2 === a3 && (e3.removeAllListeners("data"), h2.emit(t49.doneEvent, c2), a3 = null), c2 = d3;
          break;
        case i2.text:
          c2 && c2.children.push(s2({ type: r2.text, value: n3.value, parent: t49.parentNodes ? c2 : null }));
          break;
        case i2.attributeName:
          l2 = n3.value, c2.attributes[l2] = "";
          break;
        case i2.attributeValue:
          c2.attributes[l2] = n3.value;
      }
    };
    return h2.reset = function() {
      (e3 = o2.create({ debug: t49.debug })).on("data", d2), a3 = s2(), c2 = null, l2 = "", h2.parse = e3.write;
    }, h2.reset(), h2;
  };
  e2.exports = { parseSync: function(t49, e3) {
    e3 = Object.assign({}, e3, { stream: false, tagPrefix: ":" });
    var n3 = a2(e3), o3 = void 0;
    return n3.on("done", function(t50) {
      o3 = t50;
    }), n3.parse(t49), o3;
  }, create: a2, NodeType: r2 };
} });
var { cos: Ol, sin: Ll, PI: Dl } = Math;
var { tan: zl } = Math;
var kl = (Ml(Tl()), Ml(Al()), class {
  MAX_ITERATIONS = 1e5;
  solved = false;
  failed = false;
  iterations = 0;
  progress = 0;
  error = null;
  activeSubSolver;
  failedSubSolvers;
  timeToSolve;
  stats = {};
  _setupDone = false;
  setup() {
    this._setupDone || (this._setup(), this._setupDone = true);
  }
  _setup() {
  }
  step() {
    if (this._setupDone || this.setup(), !this.solved && !this.failed) {
      this.iterations++;
      try {
        this._step();
      } catch (t48) {
        throw this.error = `${this.constructor.name} error: ${t48}`, this.failed = true, t48;
      }
      !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 = true), "computeProgress" in this && (this.progress = this.computeProgress());
    }
  }
  _step() {
  }
  getConstructorParams() {
    throw new Error("getConstructorParams not implemented");
  }
  getOutput() {
    return null;
  }
  solve() {
    const t48 = Date.now();
    for (; !this.solved && !this.failed; ) this.step();
    const e2 = Date.now();
    this.timeToSolve = e2 - t48;
  }
  visualize() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
  tryFinalAcceptance() {
  }
  preview() {
    return { lines: [], points: [], rects: [], circles: [] };
  }
});
var Jl = Object.create;
var Kl = Object.defineProperty;
var Ql = Object.getOwnPropertyDescriptor;
var th = Object.getOwnPropertyNames;
var eh = Object.getPrototypeOf;
var nh = Object.prototype.hasOwnProperty;
var oh = (t48, e2) => function() {
  return e2 || (0, t48[th(t48)[0]])((e2 = { exports: {} }).exports, e2), e2.exports;
};
var ih = oh({ "node_modules/binary-search-bounds/search-bounds.js"(t48, e2) {
  function n2(t49, e3, n3, o3, i3) {
    for (var r3 = i3 + 1; o3 <= i3; ) {
      var s3 = o3 + i3 >>> 1, a3 = t49[s3];
      (void 0 !== n3 ? n3(a3, e3) : a3 - e3) >= 0 ? (r3 = s3, i3 = s3 - 1) : o3 = s3 + 1;
    }
    return r3;
  }
  function o2(t49, e3, n3, o3, i3) {
    for (var r3 = i3 + 1; o3 <= i3; ) {
      var s3 = o3 + i3 >>> 1, a3 = t49[s3];
      (void 0 !== n3 ? n3(a3, e3) : a3 - e3) > 0 ? (r3 = s3, i3 = s3 - 1) : o3 = s3 + 1;
    }
    return r3;
  }
  function i2(t49, e3, n3, o3, i3) {
    for (var r3 = o3 - 1; o3 <= i3; ) {
      var s3 = o3 + i3 >>> 1, a3 = t49[s3];
      (void 0 !== n3 ? n3(a3, e3) : a3 - e3) < 0 ? (r3 = s3, o3 = s3 + 1) : i3 = s3 - 1;
    }
    return r3;
  }
  function r2(t49, e3, n3, o3, i3) {
    for (var r3 = o3 - 1; o3 <= i3; ) {
      var s3 = o3 + i3 >>> 1, a3 = t49[s3];
      (void 0 !== n3 ? n3(a3, e3) : a3 - e3) <= 0 ? (r3 = s3, o3 = s3 + 1) : i3 = s3 - 1;
    }
    return r3;
  }
  function s2(t49, e3, n3, o3, i3) {
    for (; o3 <= i3; ) {
      var r3 = o3 + i3 >>> 1, s3 = t49[r3], a3 = void 0 !== n3 ? n3(s3, e3) : s3 - e3;
      if (0 === a3) return r3;
      a3 <= 0 ? o3 = r3 + 1 : i3 = r3 - 1;
    }
    return -1;
  }
  function a2(t49, e3, n3, o3, i3, r3) {
    return "function" == typeof n3 ? r3(t49, e3, n3, void 0 === o3 ? 0 : 0 | o3, void 0 === i3 ? t49.length - 1 : 0 | i3) : r3(t49, e3, void 0, void 0 === n3 ? 0 : 0 | n3, void 0 === o3 ? t49.length - 1 : 0 | o3);
  }
  e2.exports = { ge: function(t49, e3, o3, i3, r3) {
    return a2(t49, e3, o3, i3, r3, n2);
  }, gt: function(t49, e3, n3, i3, r3) {
    return a2(t49, e3, n3, i3, r3, o2);
  }, lt: function(t49, e3, n3, o3, r3) {
    return a2(t49, e3, n3, o3, r3, i2);
  }, le: function(t49, e3, n3, o3, i3) {
    return a2(t49, e3, n3, o3, i3, r2);
  }, eq: function(t49, e3, n3, o3, i3) {
    return a2(t49, e3, n3, o3, i3, s2);
  } };
} });
var rh = oh({ "node_modules/two-product/two-product.js"(t48, e2) {
  e2.exports = function(t49, e3, o2) {
    var i2 = t49 * e3, r2 = n2 * t49, s2 = r2 - (r2 - t49), a2 = t49 - s2, c2 = n2 * e3, l2 = c2 - (c2 - e3), h2 = e3 - l2, d2 = a2 * h2 - (i2 - s2 * l2 - a2 * l2 - s2 * h2);
    if (o2) return o2[0] = d2, o2[1] = i2, o2;
    return [d2, i2];
  };
  var n2 = +(Math.pow(2, 27) + 1);
} });
var sh = oh({ "node_modules/robust-sum/robust-sum.js"(t48, e2) {
  e2.exports = function(t49, e3) {
    var n2 = 0 | t49.length, o2 = 0 | e3.length;
    if (1 === n2 && 1 === o2) return (function(t50, e4) {
      var n3 = t50 + e4, o3 = n3 - t50, i3 = n3 - o3, r3 = e4 - o3, s3 = t50 - i3, a3 = s3 + r3;
      if (a3) return [a3, n3];
      return [n3];
    })(t49[0], e3[0]);
    var i2, r2, s2 = new Array(n2 + o2), a2 = 0, c2 = 0, l2 = 0, h2 = Math.abs, d2 = t49[c2], u2 = h2(d2), p2 = e3[l2], m2 = h2(p2);
    u2 < m2 ? (r2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (r2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = e3[l2])));
    c2 < n2 && u2 < m2 || l2 >= o2 ? (i2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (i2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = e3[l2])));
    var g2, f2, _2 = i2 + r2, y2 = _2 - i2, b2 = r2 - y2, x2 = b2, v2 = _2;
    for (; c2 < n2 && l2 < o2; ) u2 < m2 ? (i2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (i2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = e3[l2]))), (b2 = (r2 = x2) - (y2 = (_2 = i2 + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2;
    for (; c2 < n2; ) (b2 = (r2 = x2) - (y2 = (_2 = (i2 = d2) + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (c2 += 1) < n2 && (d2 = t49[c2]);
    for (; l2 < o2; ) (b2 = (r2 = x2) - (y2 = (_2 = (i2 = p2) + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (l2 += 1) < o2 && (p2 = e3[l2]);
    x2 && (s2[a2++] = x2);
    v2 && (s2[a2++] = v2);
    a2 || (s2[a2++] = 0);
    return s2.length = a2, s2;
  };
} });
var ah = oh({ "node_modules/two-sum/two-sum.js"(t48, e2) {
  e2.exports = function(t49, e3, n2) {
    var o2 = t49 + e3, i2 = o2 - t49, r2 = e3 - i2, s2 = t49 - (o2 - i2);
    if (n2) return n2[0] = s2 + r2, n2[1] = o2, n2;
    return [s2 + r2, o2];
  };
} });
var ch = oh({ "node_modules/robust-scale/robust-scale.js"(t48, e2) {
  var n2 = rh(), o2 = ah();
  e2.exports = function(t49, e3) {
    var i2 = t49.length;
    if (1 === i2) {
      var r2 = n2(t49[0], e3);
      return r2[0] ? r2 : [r2[1]];
    }
    var s2 = new Array(2 * i2), a2 = [0.1, 0.1], c2 = [0.1, 0.1], l2 = 0;
    n2(t49[0], e3, a2), a2[0] && (s2[l2++] = a2[0]);
    for (var h2 = 1; h2 < i2; ++h2) {
      n2(t49[h2], e3, c2);
      var d2 = a2[1];
      o2(d2, c2[0], a2), a2[0] && (s2[l2++] = a2[0]);
      var u2 = c2[1], p2 = a2[1], m2 = u2 + p2, g2 = p2 - (m2 - u2);
      a2[1] = m2, g2 && (s2[l2++] = g2);
    }
    a2[1] && (s2[l2++] = a2[1]);
    0 === l2 && (s2[l2++] = 0);
    return s2.length = l2, s2;
  };
} });
var lh = oh({ "node_modules/robust-subtract/robust-diff.js"(t48, e2) {
  e2.exports = function(t49, e3) {
    var n2 = 0 | t49.length, o2 = 0 | e3.length;
    if (1 === n2 && 1 === o2) return (function(t50, e4) {
      var n3 = t50 + e4, o3 = n3 - t50, i3 = n3 - o3, r3 = e4 - o3, s3 = t50 - i3, a3 = s3 + r3;
      if (a3) return [a3, n3];
      return [n3];
    })(t49[0], -e3[0]);
    var i2, r2, s2 = new Array(n2 + o2), a2 = 0, c2 = 0, l2 = 0, h2 = Math.abs, d2 = t49[c2], u2 = h2(d2), p2 = -e3[l2], m2 = h2(p2);
    u2 < m2 ? (r2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (r2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = -e3[l2])));
    c2 < n2 && u2 < m2 || l2 >= o2 ? (i2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (i2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = -e3[l2])));
    var g2, f2, _2 = i2 + r2, y2 = _2 - i2, b2 = r2 - y2, x2 = b2, v2 = _2;
    for (; c2 < n2 && l2 < o2; ) u2 < m2 ? (i2 = d2, (c2 += 1) < n2 && (u2 = h2(d2 = t49[c2]))) : (i2 = p2, (l2 += 1) < o2 && (m2 = h2(p2 = -e3[l2]))), (b2 = (r2 = x2) - (y2 = (_2 = i2 + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2;
    for (; c2 < n2; ) (b2 = (r2 = x2) - (y2 = (_2 = (i2 = d2) + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (c2 += 1) < n2 && (d2 = t49[c2]);
    for (; l2 < o2; ) (b2 = (r2 = x2) - (y2 = (_2 = (i2 = p2) + r2) - i2)) && (s2[a2++] = b2), x2 = v2 - ((g2 = v2 + _2) - (f2 = g2 - v2)) + (_2 - f2), v2 = g2, (l2 += 1) < o2 && (p2 = -e3[l2]);
    x2 && (s2[a2++] = x2);
    v2 && (s2[a2++] = v2);
    a2 || (s2[a2++] = 0);
    return s2.length = a2, s2;
  };
} });
var hh = oh({ "node_modules/robust-orientation/orientation.js"(t48, e2) {
  var n2 = rh(), o2 = sh(), i2 = ch(), r2 = lh();
  function s2(t49, e3, n3, o3) {
    return function(n4, i3, r3) {
      var s3 = t49(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), t49(e3(n4[1], i3[0]), e3(-i3[1], n4[0]))), a3 = t49(e3(n4[1], r3[0]), e3(-r3[1], n4[0])), c3 = o3(s3, a3);
      return c3[c3.length - 1];
    };
  }
  function a2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3) {
      var c3 = t49(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), a3[2]))), t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), a3[2])))), l3 = t49(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), a3[2]))), t49(n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), s3[2])))), h3 = o3(c3, l3);
      return h3[h3.length - 1];
    };
  }
  function c2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3, c3) {
      var l3 = t49(t49(t49(n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), s3[2]), t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), -a3[2]), n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), c3[2]))), r3[3]), t49(n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), r3[2]), t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), -a3[2]), n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), c3[2]))), -s3[3]), n3(t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), c3[2]))), a3[3]))), t49(n3(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), a3[2]))), -c3[3]), t49(n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), r3[2]), t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), -a3[2]), n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), c3[2]))), i3[3]), n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -a3[2]), n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), c3[2]))), -r3[3])))), t49(t49(n3(t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), c3[2]))), a3[3]), t49(n3(t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), a3[2]))), -c3[3]), n3(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), a3[2]))), i3[3]))), t49(n3(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), a3[2]))), -r3[3]), t49(n3(t49(n3(t49(e3(r3[1], a3[0]), e3(-a3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), a3[2]))), s3[3]), n3(t49(n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), s3[2]))), -a3[3]))))), h3 = t49(t49(t49(n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), s3[2]), t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), -a3[2]), n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), c3[2]))), i3[3]), n3(t49(n3(t49(e3(a3[1], c3[0]), e3(-c3[1], a3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -a3[2]), n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), c3[2]))), -s3[3])), t49(n3(t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), c3[2]))), a3[3]), n3(t49(n3(t49(e3(s3[1], a3[0]), e3(-a3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], a3[0]), e3(-a3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), a3[2]))), -c3[3]))), t49(t49(n3(t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), r3[2]), t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), -s3[2]), n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), c3[2]))), i3[3]), n3(t49(n3(t49(e3(s3[1], c3[0]), e3(-c3[1], s3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -s3[2]), n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), c3[2]))), -r3[3])), t49(n3(t49(n3(t49(e3(r3[1], c3[0]), e3(-c3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], c3[0]), e3(-c3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), c3[2]))), s3[3]), n3(t49(n3(t49(e3(r3[1], s3[0]), e3(-s3[1], r3[0])), i3[2]), t49(n3(t49(e3(i3[1], s3[0]), e3(-s3[1], i3[0])), -r3[2]), n3(t49(e3(i3[1], r3[0]), e3(-r3[1], i3[0])), s3[2]))), -c3[3])))), d3 = o3(l3, h3);
      return d3[d3.length - 1];
    };
  }
  function l2(t49) {
    return (3 === t49 ? s2 : 4 === t49 ? a2 : c2)(o2, n2, i2, r2);
  }
  var h2 = l2(3), d2 = l2(4), u2 = [function() {
    return 0;
  }, function() {
    return 0;
  }, function(t49, e3) {
    return e3[0] - t49[0];
  }, function(t49, e3, n3) {
    var o3, i3 = (t49[1] - n3[1]) * (e3[0] - n3[0]), r3 = (t49[0] - n3[0]) * (e3[1] - n3[1]), s3 = i3 - r3;
    if (i3 > 0) {
      if (r3 <= 0) return s3;
      o3 = i3 + r3;
    } else {
      if (!(i3 < 0)) return s3;
      if (r3 >= 0) return s3;
      o3 = -(i3 + r3);
    }
    var a3 = 33306690738754716e-32 * o3;
    return s3 >= a3 || s3 <= -a3 ? s3 : h2(t49, e3, n3);
  }, function(t49, e3, n3, o3) {
    var i3 = t49[0] - o3[0], r3 = e3[0] - o3[0], s3 = n3[0] - o3[0], a3 = t49[1] - o3[1], c3 = e3[1] - o3[1], l3 = n3[1] - o3[1], h3 = t49[2] - o3[2], u3 = e3[2] - o3[2], p3 = n3[2] - o3[2], m3 = r3 * l3, g2 = s3 * c3, f2 = s3 * a3, _2 = i3 * l3, y2 = i3 * c3, b2 = r3 * a3, x2 = h3 * (m3 - g2) + u3 * (f2 - _2) + p3 * (y2 - b2), v2 = 7771561172376103e-31 * ((Math.abs(m3) + Math.abs(g2)) * Math.abs(h3) + (Math.abs(f2) + Math.abs(_2)) * Math.abs(u3) + (Math.abs(y2) + Math.abs(b2)) * Math.abs(p3));
    return x2 > v2 || -x2 > v2 ? x2 : d2(t49, e3, n3, o3);
  }];
  function p2(t49) {
    var e3 = u2[t49.length];
    return e3 || (e3 = u2[t49.length] = l2(t49.length)), e3.apply(void 0, t49);
  }
  function m2(t49, e3, n3, o3, i3, r3, s3) {
    return function(e4, n4, a3, c3, l3) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o3(e4, n4);
        case 3:
          return i3(e4, n4, a3);
        case 4:
          return r3(e4, n4, a3, c3);
        case 5:
          return s3(e4, n4, a3, c3, l3);
      }
      for (var h3 = new Array(arguments.length), d3 = 0; d3 < arguments.length; ++d3) h3[d3] = arguments[d3];
      return t49(h3);
    };
  }
  !(function() {
    for (; u2.length <= 5; ) u2.push(l2(u2.length));
    e2.exports = m2.apply(void 0, [p2].concat(u2));
    for (var t49 = 0; t49 <= 5; ++t49) e2.exports[t49] = u2[t49];
  })();
} });
var dh = oh({ "node_modules/cdt2d/lib/monotone.js"(t48, e2) {
  var n2 = ih(), o2 = hh()[3];
  function i2(t49, e3, n3, o3, i3) {
    this.a = t49, this.b = e3, this.idx = n3, this.lowerIds = o3, this.upperIds = i3;
  }
  function r2(t49, e3, n3, o3) {
    this.a = t49, this.b = e3, this.type = n3, this.idx = o3;
  }
  function s2(t49, e3) {
    var n3 = t49.a[0] - e3.a[0] || t49.a[1] - e3.a[1] || t49.type - e3.type;
    return n3 || (0 !== t49.type && (n3 = o2(t49.a, t49.b, e3.b)) ? n3 : t49.idx - e3.idx);
  }
  function a2(t49, e3) {
    return o2(t49.a, t49.b, e3);
  }
  function c2(t49, e3, i3, r3, s3) {
    for (var c3 = n2.lt(e3, r3, a2), l3 = n2.gt(e3, r3, a2), h3 = c3; h3 < l3; ++h3) {
      for (var d3 = e3[h3], u2 = d3.lowerIds, p2 = u2.length; p2 > 1 && o2(i3[u2[p2 - 2]], i3[u2[p2 - 1]], r3) > 0; ) t49.push([u2[p2 - 1], u2[p2 - 2], s3]), p2 -= 1;
      u2.length = p2, u2.push(s3);
      var m2 = d3.upperIds;
      for (p2 = m2.length; p2 > 1 && o2(i3[m2[p2 - 2]], i3[m2[p2 - 1]], r3) < 0; ) t49.push([m2[p2 - 2], m2[p2 - 1], s3]), p2 -= 1;
      m2.length = p2, m2.push(s3);
    }
  }
  function l2(t49, e3) {
    var n3;
    return (n3 = t49.a[0] < e3.a[0] ? o2(t49.a, t49.b, e3.a) : o2(e3.b, e3.a, t49.a)) ? n3 : (n3 = e3.b[0] < t49.b[0] ? o2(t49.a, t49.b, e3.b) : o2(e3.b, e3.a, t49.b)) || t49.idx - e3.idx;
  }
  function h2(t49, e3, o3) {
    var r3 = n2.le(t49, o3, l2), s3 = t49[r3], a3 = s3.upperIds, c3 = a3[a3.length - 1];
    s3.upperIds = [c3], t49.splice(r3 + 1, 0, new i2(o3.a, o3.b, o3.idx, [c3], a3));
  }
  function d2(t49, e3, o3) {
    var i3 = o3.a;
    o3.a = o3.b, o3.b = i3;
    var r3 = n2.eq(t49, o3, l2), s3 = t49[r3];
    t49[r3 - 1].upperIds = s3.upperIds, t49.splice(r3, 1);
  }
  e2.exports = function(t49, e3) {
    for (var n3 = t49.length, o3 = e3.length, a3 = [], l3 = 0; l3 < n3; ++l3) a3.push(new r2(t49[l3], null, 0, l3));
    for (l3 = 0; l3 < o3; ++l3) {
      var u2 = e3[l3], p2 = t49[u2[0]], m2 = t49[u2[1]];
      p2[0] < m2[0] ? a3.push(new r2(p2, m2, 2, l3), new r2(m2, p2, 1, l3)) : p2[0] > m2[0] && a3.push(new r2(m2, p2, 2, l3), new r2(p2, m2, 1, l3));
    }
    a3.sort(s2);
    for (var g2 = a3[0].a[0] - (1 + Math.abs(a3[0].a[0])) * Math.pow(2, -52), f2 = [new i2([g2, 1], [g2, 0], -1, [], [], [], [])], _2 = [], y2 = (l3 = 0, a3.length); l3 < y2; ++l3) {
      var b2 = a3[l3], x2 = b2.type;
      0 === x2 ? c2(_2, f2, t49, b2.a, b2.idx) : 2 === x2 ? h2(f2, t49, b2) : d2(f2, t49, b2);
    }
    return _2;
  };
} });
var uh = oh({ "node_modules/cdt2d/lib/triangulation.js"(t48, e2) {
  var n2 = ih();
  function o2(t49, e3) {
    this.stars = t49, this.edges = e3;
  }
  e2.exports = function(t49, e3) {
    for (var n3 = new Array(t49), i3 = 0; i3 < t49; ++i3) n3[i3] = [];
    return new o2(n3, e3);
  };
  var i2 = o2.prototype;
  function r2(t49, e3, n3) {
    for (var o3 = 1, i3 = t49.length; o3 < i3; o3 += 2) if (t49[o3 - 1] === e3 && t49[o3] === n3) return t49[o3 - 1] = t49[i3 - 2], t49[o3] = t49[i3 - 1], void (t49.length = i3 - 2);
  }
  i2.isConstraint = /* @__PURE__ */ (function() {
    var t49 = [0, 0];
    function e3(t50, e4) {
      return t50[0] - e4[0] || t50[1] - e4[1];
    }
    return function(o3, i3) {
      return t49[0] = Math.min(o3, i3), t49[1] = Math.max(o3, i3), n2.eq(this.edges, t49, e3) >= 0;
    };
  })(), i2.removeTriangle = function(t49, e3, n3) {
    var o3 = this.stars;
    r2(o3[t49], e3, n3), r2(o3[e3], n3, t49), r2(o3[n3], t49, e3);
  }, i2.addTriangle = function(t49, e3, n3) {
    var o3 = this.stars;
    o3[t49].push(e3, n3), o3[e3].push(n3, t49), o3[n3].push(t49, e3);
  }, i2.opposite = function(t49, e3) {
    for (var n3 = this.stars[e3], o3 = 1, i3 = n3.length; o3 < i3; o3 += 2) if (n3[o3] === t49) return n3[o3 - 1];
    return -1;
  }, i2.flip = function(t49, e3) {
    var n3 = this.opposite(t49, e3), o3 = this.opposite(e3, t49);
    this.removeTriangle(t49, e3, n3), this.removeTriangle(e3, t49, o3), this.addTriangle(t49, o3, n3), this.addTriangle(e3, n3, o3);
  }, i2.edges = function() {
    for (var t49 = this.stars, e3 = [], n3 = 0, o3 = t49.length; n3 < o3; ++n3) for (var i3 = t49[n3], r3 = 0, s2 = i3.length; r3 < s2; r3 += 2) e3.push([i3[r3], i3[r3 + 1]]);
    return e3;
  }, i2.cells = function() {
    for (var t49 = this.stars, e3 = [], n3 = 0, o3 = t49.length; n3 < o3; ++n3) for (var i3 = t49[n3], r3 = 0, s2 = i3.length; r3 < s2; r3 += 2) {
      var a2 = i3[r3], c2 = i3[r3 + 1];
      n3 < Math.min(a2, c2) && e3.push([n3, a2, c2]);
    }
    return e3;
  };
} });
var ph = oh({ "node_modules/robust-in-sphere/in-sphere.js"(t48, e2) {
  var n2 = rh(), o2 = sh(), i2 = lh(), r2 = ch();
  function s2(t49) {
    return (3 === t49 ? a2 : 4 === t49 ? c2 : 5 === t49 ? l2 : h2)(o2, i2, n2, r2);
  }
  function a2(t49, e3, n3, o3) {
    return function(i3, r3, s3) {
      var a3 = n3(i3[0], i3[0]), c3 = o3(a3, r3[0]), l3 = o3(a3, s3[0]), h3 = n3(r3[0], r3[0]), d3 = o3(h3, i3[0]), u3 = o3(h3, s3[0]), p3 = n3(s3[0], s3[0]), m2 = o3(p3, i3[0]), g2 = o3(p3, r3[0]), f2 = t49(e3(g2, u3), e3(d3, c3)), _2 = e3(m2, l3), y2 = e3(f2, _2);
      return y2[y2.length - 1];
    };
  }
  function c2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3) {
      var c3 = t49(n3(i3[0], i3[0]), n3(i3[1], i3[1])), l3 = o3(c3, r3[0]), h3 = o3(c3, s3[0]), d3 = o3(c3, a3[0]), u3 = t49(n3(r3[0], r3[0]), n3(r3[1], r3[1])), p3 = o3(u3, i3[0]), m2 = o3(u3, s3[0]), g2 = o3(u3, a3[0]), f2 = t49(n3(s3[0], s3[0]), n3(s3[1], s3[1])), _2 = o3(f2, i3[0]), y2 = o3(f2, r3[0]), b2 = o3(f2, a3[0]), x2 = t49(n3(a3[0], a3[0]), n3(a3[1], a3[1])), v2 = o3(x2, i3[0]), S2 = o3(x2, r3[0]), I2 = o3(x2, s3[0]), P2 = t49(t49(o3(e3(I2, b2), r3[1]), t49(o3(e3(S2, g2), -s3[1]), o3(e3(y2, m2), a3[1]))), t49(o3(e3(S2, g2), i3[1]), t49(o3(e3(v2, d3), -r3[1]), o3(e3(p3, l3), a3[1])))), M2 = t49(t49(o3(e3(I2, b2), i3[1]), t49(o3(e3(v2, d3), -s3[1]), o3(e3(_2, h3), a3[1]))), t49(o3(e3(y2, m2), i3[1]), t49(o3(e3(_2, h3), -r3[1]), o3(e3(p3, l3), s3[1])))), C2 = e3(P2, M2);
      return C2[C2.length - 1];
    };
  }
  function l2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3, c3) {
      var l3 = t49(n3(i3[0], i3[0]), t49(n3(i3[1], i3[1]), n3(i3[2], i3[2]))), h3 = o3(l3, r3[0]), d3 = o3(l3, s3[0]), u3 = o3(l3, a3[0]), p3 = o3(l3, c3[0]), m2 = t49(n3(r3[0], r3[0]), t49(n3(r3[1], r3[1]), n3(r3[2], r3[2]))), g2 = o3(m2, i3[0]), f2 = o3(m2, s3[0]), _2 = o3(m2, a3[0]), y2 = o3(m2, c3[0]), b2 = t49(n3(s3[0], s3[0]), t49(n3(s3[1], s3[1]), n3(s3[2], s3[2]))), x2 = o3(b2, i3[0]), v2 = o3(b2, r3[0]), S2 = o3(b2, a3[0]), I2 = o3(b2, c3[0]), P2 = t49(n3(a3[0], a3[0]), t49(n3(a3[1], a3[1]), n3(a3[2], a3[2]))), M2 = o3(P2, i3[0]), C2 = o3(P2, r3[0]), N2 = o3(P2, s3[0]), w2 = o3(P2, c3[0]), T2 = t49(n3(c3[0], c3[0]), t49(n3(c3[1], c3[1]), n3(c3[2], c3[2]))), R2 = o3(T2, i3[0]), E2 = o3(T2, r3[0]), A2 = o3(T2, s3[0]), O2 = o3(T2, a3[0]), L2 = t49(t49(t49(o3(t49(o3(e3(O2, w2), s3[1]), t49(o3(e3(A2, I2), -a3[1]), o3(e3(N2, S2), c3[1]))), r3[2]), t49(o3(t49(o3(e3(O2, w2), r3[1]), t49(o3(e3(E2, y2), -a3[1]), o3(e3(C2, _2), c3[1]))), -s3[2]), o3(t49(o3(e3(A2, I2), r3[1]), t49(o3(e3(E2, y2), -s3[1]), o3(e3(v2, f2), c3[1]))), a3[2]))), t49(o3(t49(o3(e3(N2, S2), r3[1]), t49(o3(e3(C2, _2), -s3[1]), o3(e3(v2, f2), a3[1]))), -c3[2]), t49(o3(t49(o3(e3(O2, w2), r3[1]), t49(o3(e3(E2, y2), -a3[1]), o3(e3(C2, _2), c3[1]))), i3[2]), o3(t49(o3(e3(O2, w2), i3[1]), t49(o3(e3(R2, p3), -a3[1]), o3(e3(M2, u3), c3[1]))), -r3[2])))), t49(t49(o3(t49(o3(e3(E2, y2), i3[1]), t49(o3(e3(R2, p3), -r3[1]), o3(e3(g2, h3), c3[1]))), a3[2]), t49(o3(t49(o3(e3(C2, _2), i3[1]), t49(o3(e3(M2, u3), -r3[1]), o3(e3(g2, h3), a3[1]))), -c3[2]), o3(t49(o3(e3(N2, S2), r3[1]), t49(o3(e3(C2, _2), -s3[1]), o3(e3(v2, f2), a3[1]))), i3[2]))), t49(o3(t49(o3(e3(N2, S2), i3[1]), t49(o3(e3(M2, u3), -s3[1]), o3(e3(x2, d3), a3[1]))), -r3[2]), t49(o3(t49(o3(e3(C2, _2), i3[1]), t49(o3(e3(M2, u3), -r3[1]), o3(e3(g2, h3), a3[1]))), s3[2]), o3(t49(o3(e3(v2, f2), i3[1]), t49(o3(e3(x2, d3), -r3[1]), o3(e3(g2, h3), s3[1]))), -a3[2]))))), D2 = t49(t49(t49(o3(t49(o3(e3(O2, w2), s3[1]), t49(o3(e3(A2, I2), -a3[1]), o3(e3(N2, S2), c3[1]))), i3[2]), o3(t49(o3(e3(O2, w2), i3[1]), t49(o3(e3(R2, p3), -a3[1]), o3(e3(M2, u3), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(A2, I2), i3[1]), t49(o3(e3(R2, p3), -s3[1]), o3(e3(x2, d3), c3[1]))), a3[2]), o3(t49(o3(e3(N2, S2), i3[1]), t49(o3(e3(M2, u3), -s3[1]), o3(e3(x2, d3), a3[1]))), -c3[2]))), t49(t49(o3(t49(o3(e3(A2, I2), r3[1]), t49(o3(e3(E2, y2), -s3[1]), o3(e3(v2, f2), c3[1]))), i3[2]), o3(t49(o3(e3(A2, I2), i3[1]), t49(o3(e3(R2, p3), -s3[1]), o3(e3(x2, d3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(E2, y2), i3[1]), t49(o3(e3(R2, p3), -r3[1]), o3(e3(g2, h3), c3[1]))), s3[2]), o3(t49(o3(e3(v2, f2), i3[1]), t49(o3(e3(x2, d3), -r3[1]), o3(e3(g2, h3), s3[1]))), -c3[2])))), z2 = e3(L2, D2);
      return z2[z2.length - 1];
    };
  }
  function h2(t49, e3, n3, o3) {
    return function(i3, r3, s3, a3, c3, l3) {
      var h3 = t49(t49(n3(i3[0], i3[0]), n3(i3[1], i3[1])), t49(n3(i3[2], i3[2]), n3(i3[3], i3[3]))), d3 = o3(h3, r3[0]), u3 = o3(h3, s3[0]), p3 = o3(h3, a3[0]), m2 = o3(h3, c3[0]), g2 = o3(h3, l3[0]), f2 = t49(t49(n3(r3[0], r3[0]), n3(r3[1], r3[1])), t49(n3(r3[2], r3[2]), n3(r3[3], r3[3]))), _2 = o3(f2, i3[0]), y2 = o3(f2, s3[0]), b2 = o3(f2, a3[0]), x2 = o3(f2, c3[0]), v2 = o3(f2, l3[0]), S2 = t49(t49(n3(s3[0], s3[0]), n3(s3[1], s3[1])), t49(n3(s3[2], s3[2]), n3(s3[3], s3[3]))), I2 = o3(S2, i3[0]), P2 = o3(S2, r3[0]), M2 = o3(S2, a3[0]), C2 = o3(S2, c3[0]), N2 = o3(S2, l3[0]), w2 = t49(t49(n3(a3[0], a3[0]), n3(a3[1], a3[1])), t49(n3(a3[2], a3[2]), n3(a3[3], a3[3]))), T2 = o3(w2, i3[0]), R2 = o3(w2, r3[0]), E2 = o3(w2, s3[0]), A2 = o3(w2, c3[0]), O2 = o3(w2, l3[0]), L2 = t49(t49(n3(c3[0], c3[0]), n3(c3[1], c3[1])), t49(n3(c3[2], c3[2]), n3(c3[3], c3[3]))), D2 = o3(L2, i3[0]), z2 = o3(L2, r3[0]), k2 = o3(L2, s3[0]), F2 = o3(L2, a3[0]), j2 = o3(L2, l3[0]), Y2 = t49(t49(n3(l3[0], l3[0]), n3(l3[1], l3[1])), t49(n3(l3[2], l3[2]), n3(l3[3], l3[3]))), $2 = o3(Y2, i3[0]), X2 = o3(Y2, r3[0]), B2 = o3(Y2, s3[0]), H2 = o3(Y2, a3[0]), W2 = o3(Y2, c3[0]), V2 = t49(t49(t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), s3[2]), o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), -l3[2]))), r3[3]), t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), r3[2]), o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), -l3[2]))), -s3[3]), o3(t49(t49(o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), r3[2]), o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), c3[2]), o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), -l3[2]))), a3[3]))), t49(t49(o3(t49(t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), r3[2]), o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), -l3[2]))), -c3[3]), o3(t49(t49(o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), r3[2]), o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), -c3[2]))), l3[3])), t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), r3[2]), o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), -l3[2]))), i3[3]), o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -l3[2]))), -r3[3])))), t49(t49(t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), c3[2]), o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), -l3[2]))), a3[3]), o3(t49(t49(o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), i3[2]), o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), a3[2]), o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), -l3[2]))), -c3[3])), t49(o3(t49(t49(o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), i3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), a3[2]), o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), -c3[2]))), l3[3]), o3(t49(t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), r3[2]), o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), -l3[2]))), i3[3]))), t49(t49(o3(t49(t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), i3[2]), o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -l3[2]))), -r3[3]), o3(t49(t49(o3(t49(o3(e3(H2, O2), r3[1]), t49(o3(e3(X2, v2), -a3[1]), o3(e3(R2, b2), l3[1]))), i3[2]), o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), a3[2]), o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), -l3[2]))), s3[3])), t49(o3(t49(t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), i3[2]), o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -l3[2]))), -a3[3]), o3(t49(t49(o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), i3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -r3[2])), t49(o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -a3[2]))), l3[3]))))), U2 = t49(t49(t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), s3[2]), o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), -l3[2]))), i3[3]), t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), a3[1]), t49(o3(e3(H2, O2), -c3[1]), o3(e3(F2, A2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -a3[2])), t49(o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), c3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -l3[2]))), -s3[3]), o3(t49(t49(o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), c3[2]), o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), -l3[2]))), a3[3]))), t49(t49(o3(t49(t49(o3(t49(o3(e3(H2, O2), s3[1]), t49(o3(e3(B2, N2), -a3[1]), o3(e3(E2, M2), l3[1]))), i3[2]), o3(t49(o3(e3(H2, O2), i3[1]), t49(o3(e3($2, g2), -a3[1]), o3(e3(T2, p3), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -l3[2]))), -c3[3]), o3(t49(t49(o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), i3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -c3[2]))), l3[3])), t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), r3[2]), o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), c3[2]), o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), -l3[2]))), i3[3]), o3(t49(t49(o3(t49(o3(e3(W2, j2), s3[1]), t49(o3(e3(B2, N2), -c3[1]), o3(e3(k2, C2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -s3[2])), t49(o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), c3[2]), o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), -l3[2]))), -r3[3])))), t49(t49(t49(o3(t49(t49(o3(t49(o3(e3(W2, j2), r3[1]), t49(o3(e3(X2, v2), -c3[1]), o3(e3(z2, x2), l3[1]))), i3[2]), o3(t49(o3(e3(W2, j2), i3[1]), t49(o3(e3($2, g2), -c3[1]), o3(e3(D2, m2), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), c3[2]), o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), -l3[2]))), s3[3]), o3(t49(t49(o3(t49(o3(e3(B2, N2), r3[1]), t49(o3(e3(X2, v2), -s3[1]), o3(e3(P2, y2), l3[1]))), i3[2]), o3(t49(o3(e3(B2, N2), i3[1]), t49(o3(e3($2, g2), -s3[1]), o3(e3(I2, u3), l3[1]))), -r3[2])), t49(o3(t49(o3(e3(X2, v2), i3[1]), t49(o3(e3($2, g2), -r3[1]), o3(e3(_2, d3), l3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -l3[2]))), -c3[3])), t49(o3(t49(t49(o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), i3[2]), o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -c3[2]))), l3[3]), o3(t49(t49(o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), r3[2]), o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), -c3[2]))), i3[3]))), t49(t49(o3(t49(t49(o3(t49(o3(e3(F2, A2), s3[1]), t49(o3(e3(k2, C2), -a3[1]), o3(e3(E2, M2), c3[1]))), i3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -s3[2])), t49(o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), a3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -c3[2]))), -r3[3]), o3(t49(t49(o3(t49(o3(e3(F2, A2), r3[1]), t49(o3(e3(z2, x2), -a3[1]), o3(e3(R2, b2), c3[1]))), i3[2]), o3(t49(o3(e3(F2, A2), i3[1]), t49(o3(e3(D2, m2), -a3[1]), o3(e3(T2, p3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), a3[2]), o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), -c3[2]))), s3[3])), t49(o3(t49(t49(o3(t49(o3(e3(k2, C2), r3[1]), t49(o3(e3(z2, x2), -s3[1]), o3(e3(P2, y2), c3[1]))), i3[2]), o3(t49(o3(e3(k2, C2), i3[1]), t49(o3(e3(D2, m2), -s3[1]), o3(e3(I2, u3), c3[1]))), -r3[2])), t49(o3(t49(o3(e3(z2, x2), i3[1]), t49(o3(e3(D2, m2), -r3[1]), o3(e3(_2, d3), c3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -c3[2]))), -a3[3]), o3(t49(t49(o3(t49(o3(e3(E2, M2), r3[1]), t49(o3(e3(R2, b2), -s3[1]), o3(e3(P2, y2), a3[1]))), i3[2]), o3(t49(o3(e3(E2, M2), i3[1]), t49(o3(e3(T2, p3), -s3[1]), o3(e3(I2, u3), a3[1]))), -r3[2])), t49(o3(t49(o3(e3(R2, b2), i3[1]), t49(o3(e3(T2, p3), -r3[1]), o3(e3(_2, d3), a3[1]))), s3[2]), o3(t49(o3(e3(P2, y2), i3[1]), t49(o3(e3(I2, u3), -r3[1]), o3(e3(_2, d3), s3[1]))), -a3[2]))), c3[3]))))), G2 = e3(V2, U2);
      return G2[G2.length - 1];
    };
  }
  var d2 = [function() {
    return 0;
  }, function() {
    return 0;
  }, function() {
    return 0;
  }];
  function u2(t49) {
    var e3 = d2[t49.length];
    return e3 || (e3 = d2[t49.length] = s2(t49.length)), e3.apply(void 0, t49);
  }
  function p2(t49, e3, n3, o3, i3, r3, s3, a3) {
    return function(e4, n4, c3, l3, h3, d3) {
      switch (arguments.length) {
        case 0:
        case 1:
          return 0;
        case 2:
          return o3(e4, n4);
        case 3:
          return i3(e4, n4, c3);
        case 4:
          return r3(e4, n4, c3, l3);
        case 5:
          return s3(e4, n4, c3, l3, h3);
        case 6:
          return a3(e4, n4, c3, l3, h3, d3);
      }
      for (var u3 = new Array(arguments.length), p3 = 0; p3 < arguments.length; ++p3) u3[p3] = arguments[p3];
      return t49(u3);
    };
  }
  !(function() {
    for (; d2.length <= 6; ) d2.push(s2(d2.length));
    e2.exports = p2.apply(void 0, [u2].concat(d2));
    for (var t49 = 0; t49 <= 6; ++t49) e2.exports[t49] = d2[t49];
  })();
} });
var mh = oh({ "node_modules/cdt2d/lib/delaunay.js"(t48, e2) {
  var n2 = ph()[4];
  ih();
  function o2(t49, e3, o3, i2, r2, s2) {
    var a2 = e3.opposite(i2, r2);
    if (!(a2 < 0)) {
      if (r2 < i2) {
        var c2 = i2;
        i2 = r2, r2 = c2, c2 = s2, s2 = a2, a2 = c2;
      }
      e3.isConstraint(i2, r2) || n2(t49[i2], t49[r2], t49[s2], t49[a2]) < 0 && o3.push(i2, r2);
    }
  }
  e2.exports = function(t49, e3) {
    for (var i2 = [], r2 = t49.length, s2 = e3.stars, a2 = 0; a2 < r2; ++a2) for (var c2 = s2[a2], l2 = 1; l2 < c2.length; l2 += 2) {
      if (!((p2 = c2[l2]) < a2) && !e3.isConstraint(a2, p2)) {
        for (var h2 = c2[l2 - 1], d2 = -1, u2 = 1; u2 < c2.length; u2 += 2) if (c2[u2 - 1] === p2) {
          d2 = c2[u2];
          break;
        }
        d2 < 0 || n2(t49[a2], t49[p2], t49[h2], t49[d2]) < 0 && i2.push(a2, p2);
      }
    }
    for (; i2.length > 0; ) {
      for (var p2 = i2.pop(), m2 = (h2 = -1, d2 = -1, c2 = s2[a2 = i2.pop()], 1); m2 < c2.length; m2 += 2) {
        var g2 = c2[m2 - 1], f2 = c2[m2];
        g2 === p2 ? d2 = f2 : f2 === p2 && (h2 = g2);
      }
      h2 < 0 || d2 < 0 || (n2(t49[a2], t49[p2], t49[h2], t49[d2]) >= 0 || (e3.flip(a2, p2), o2(t49, e3, i2, h2, a2, d2), o2(t49, e3, i2, a2, d2, h2), o2(t49, e3, i2, d2, p2, h2), o2(t49, e3, i2, p2, h2, d2)));
    }
  };
} });
var gh = oh({ "node_modules/cdt2d/lib/filter.js"(t48, e2) {
  var n2 = ih();
  function o2(t49, e3, n3, o3, i3, r2, s2) {
    this.cells = t49, this.neighbor = e3, this.flags = o3, this.constraint = n3, this.active = i3, this.next = r2, this.boundary = s2;
  }
  function i2(t49, e3) {
    return t49[0] - e3[0] || t49[1] - e3[1] || t49[2] - e3[2];
  }
  e2.exports = function(t49, e3, n3) {
    var r2 = (function(t50, e4) {
      for (var n4 = t50.cells(), r3 = n4.length, s3 = 0; s3 < r3; ++s3) {
        var a3 = (_3 = n4[s3])[0], c3 = _3[1], l3 = _3[2];
        c3 < l3 ? c3 < a3 && (_3[0] = c3, _3[1] = l3, _3[2] = a3) : l3 < a3 && (_3[0] = l3, _3[1] = a3, _3[2] = c3);
      }
      n4.sort(i2);
      var h3 = new Array(r3);
      for (s3 = 0; s3 < h3.length; ++s3) h3[s3] = 0;
      var d3 = [], u3 = [], p3 = new Array(3 * r3), m3 = new Array(3 * r3), g3 = null;
      e4 && (g3 = []);
      var f3 = new o2(n4, p3, m3, h3, d3, u3, g3);
      for (s3 = 0; s3 < r3; ++s3) for (var _3 = n4[s3], y2 = 0; y2 < 3; ++y2) {
        a3 = _3[y2], c3 = _3[(y2 + 1) % 3];
        var b2 = p3[3 * s3 + y2] = f3.locate(c3, a3, t50.opposite(c3, a3)), x2 = m3[3 * s3 + y2] = t50.isConstraint(a3, c3);
        b2 < 0 && (x2 ? u3.push(s3) : (d3.push(s3), h3[s3] = 1), e4 && g3.push([c3, a3, -1]));
      }
      return f3;
    })(t49, n3);
    if (0 === e3) return n3 ? r2.cells.concat(r2.boundary) : r2.cells;
    var s2 = 1, a2 = r2.active, c2 = r2.next, l2 = r2.flags, h2 = r2.cells, d2 = r2.constraint, u2 = r2.neighbor;
    for (; a2.length > 0 || c2.length > 0; ) {
      for (; a2.length > 0; ) {
        var p2 = a2.pop();
        if (l2[p2] !== -s2) {
          l2[p2] = s2;
          h2[p2];
          for (var m2 = 0; m2 < 3; ++m2) {
            var g2 = u2[3 * p2 + m2];
            g2 >= 0 && 0 === l2[g2] && (d2[3 * p2 + m2] ? c2.push(g2) : (a2.push(g2), l2[g2] = s2));
          }
        }
      }
      var f2 = c2;
      c2 = a2, a2 = f2, c2.length = 0, s2 = -s2;
    }
    var _2 = (function(t50, e4, n4) {
      for (var o3 = 0, i3 = 0; i3 < t50.length; ++i3) e4[i3] === n4 && (t50[o3++] = t50[i3]);
      return t50.length = o3, t50;
    })(h2, l2, e3);
    if (n3) return _2.concat(r2.boundary);
    return _2;
  }, o2.prototype.locate = /* @__PURE__ */ (function() {
    var t49 = [0, 0, 0];
    return function(e3, o3, r2) {
      var s2 = e3, a2 = o3, c2 = r2;
      return o3 < r2 ? o3 < e3 && (s2 = o3, a2 = r2, c2 = e3) : r2 < e3 && (s2 = r2, a2 = e3, c2 = o3), s2 < 0 ? -1 : (t49[0] = s2, t49[1] = a2, t49[2] = c2, n2.eq(this.cells, t49, i2));
    };
  })();
} });
var fh = oh({ "node_modules/cdt2d/cdt2d.js"(t48, e2) {
  var n2 = dh(), o2 = uh(), i2 = mh(), r2 = gh();
  function s2(t49) {
    return [Math.min(t49[0], t49[1]), Math.max(t49[0], t49[1])];
  }
  function a2(t49, e3) {
    return t49[0] - e3[0] || t49[1] - e3[1];
  }
  function c2(t49, e3, n3) {
    return e3 in t49 ? t49[e3] : n3;
  }
  e2.exports = function(t49, e3, l2) {
    Array.isArray(e3) ? (l2 = l2 || {}, e3 = e3 || []) : (l2 = e3 || {}, e3 = []);
    var h2 = !!c2(l2, "delaunay", true), d2 = !!c2(l2, "interior", true), u2 = !!c2(l2, "exterior", true), p2 = !!c2(l2, "infinity", false);
    if (!d2 && !u2 || 0 === t49.length) return [];
    var m2 = n2(t49, e3);
    if (h2 || d2 !== u2 || p2) {
      for (var g2 = o2(t49.length, (function(t50) {
        return t50.map(s2).sort(a2);
      })(e3)), f2 = 0; f2 < m2.length; ++f2) {
        var _2 = m2[f2];
        g2.addTriangle(_2[0], _2[1], _2[2]);
      }
      return h2 && i2(t49, g2), u2 ? d2 ? p2 ? r2(g2, 0, p2) : g2.cells() : r2(g2, 1, p2) : r2(g2, -1);
    }
    return m2;
  };
} });
var { cos: Qh, sin: td, PI: ed } = Math;
var { tan: nd } = Math;
var fd = true;
var _d = { CCW: -1, CW: 1, NOT_ORIENTABLE: 0 };
var yd = 2 * Math.PI;
var bd = Object.freeze({ __proto__: null, BOUNDARY: 2, CCW: fd, CONTAINS: 3, CW: false, END_VERTEX: 2, INSIDE: 1, INTERLACE: 4, NOT_VERTEX: 0, ORIENTATION: _d, OUTSIDE: 0, OVERLAP_OPPOSITE: 2, OVERLAP_SAME: 1, PIx2: yd, START_VERTEX: 1 });
var xd = 1e-6;
function vd(t48) {
  xd = t48;
}
function Sd() {
  return xd;
}
function Id(t48) {
  return t48 < xd && t48 > -xd;
}
function Pd(t48, e2) {
  return t48 - e2 < xd && t48 - e2 > -xd;
}
function Md(t48, e2) {
  return t48 - e2 > xd;
}
function Cd(t48, e2) {
  return t48 - e2 < -xd;
}
var Nd = { Utils: Object.freeze({ __proto__: null, DECIMALS: 3, EQ: Pd, EQ_0: Id, GE: function(t48, e2) {
  return t48 - e2 > -xd;
}, GT: Md, LE: function(t48, e2) {
  return t48 - e2 < xd;
}, LT: Cd, getTolerance: Sd, setTolerance: vd }), 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 t48 in bd) Nd[t48] = bd[t48];
Object.defineProperty(Nd, "DP_TOL", { get: function() {
  return Sd();
}, set: function(t48) {
  vd(t48);
} });
var wd = 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");
  }
};
Nd.Errors = wd;
var Td = class {
  constructor(t48, e2) {
    this.first = t48, this.last = e2 || this.first;
  }
  [Symbol.iterator]() {
    let t48;
    return { next: () => (t48 = t48 ? t48.next : this.first, { value: t48, done: void 0 === t48 }) };
  }
  get size() {
    let t48 = 0;
    for (let e2 of this) t48++;
    return t48;
  }
  toArray(t48 = void 0, e2 = void 0) {
    let n2 = [], o2 = t48 || this.first, i2 = e2 || this.last, r2 = o2;
    if (void 0 === r2) return n2;
    do {
      n2.push(r2), r2 = r2.next;
    } while (r2 !== i2.next);
    return n2;
  }
  append(t48) {
    return this.isEmpty() ? this.first = t48 : (t48.prev = this.last, this.last.next = t48), this.last = t48, this.last.next = void 0, this.first.prev = void 0, this;
  }
  insert(t48, e2) {
    if (this.isEmpty()) this.first = t48, this.last = t48;
    else if (null == e2) t48.next = this.first, this.first.prev = t48, this.first = t48;
    else {
      let n2 = e2.next;
      e2.next = t48, n2 && (n2.prev = t48), t48.prev = e2, t48.next = n2, this.last === e2 && (this.last = t48);
    }
    return this.last.next = void 0, this.first.prev = void 0, this;
  }
  remove(t48) {
    return t48 === this.first && t48 === this.last ? (this.first = void 0, this.last = void 0) : (t48.prev && (t48.prev.next = t48.next), t48.next && (t48.next.prev = t48.prev), t48 === this.first && (this.first = t48.next), t48 === this.last && (this.last = t48.prev)), this;
  }
  isEmpty() {
    return void 0 === this.first;
  }
  static testInfiniteLoop(t48) {
    let e2 = t48, n2 = t48;
    do {
      if (e2 != t48 && e2 === n2) throw wd.INFINITE_LOOP;
      e2 = e2.next, n2 = n2.next.next;
    } while (e2 != t48);
  }
};
var Rd = { stroke: "black" };
var Ed = class {
  constructor(t48 = Rd) {
    for (const e2 in t48) this[e2] = t48[e2];
    this.stroke = t48.stroke ?? Rd.stroke;
  }
  toAttributesString() {
    return Object.keys(this).reduce((t48, e2) => t48 + (void 0 !== this[e2] ? this.toAttrString(e2, this[e2]) : ""), "");
  }
  toAttrString(t48, e2) {
    const n2 = "className" === t48 ? "class" : this.convertCamelToKebabCase(t48);
    return null === e2 ? `${n2} ` : `${n2}="${e2.toString()}" `;
  }
  convertCamelToKebabCase(t48) {
    return t48.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 Ad(t48) {
  return new Ed(t48).toAttributesString();
}
function Od(t48, e2) {
  let n2 = [], [o2, i2, r2] = t48.standard, [s2, a2, c2] = e2.standard, l2 = o2 * a2 - i2 * s2, h2 = r2 * a2 - i2 * c2, d2 = o2 * c2 - r2 * s2;
  if (!Nd.Utils.EQ_0(l2)) {
    let t49, e3;
    0 === i2 ? (t49 = r2 / o2, e3 = d2 / l2) : 0 === a2 ? (t49 = c2 / s2, e3 = d2 / l2) : 0 === o2 ? (t49 = h2 / l2, e3 = r2 / i2) : 0 === s2 ? (t49 = h2 / l2, e3 = c2 / a2) : (t49 = h2 / l2, e3 = d2 / l2), n2.push(new Nd.Point(t49, e3));
  }
  return n2;
}
function Ld(t48, e2) {
  let n2 = [], o2 = e2.pc.projectionOn(t48), i2 = e2.pc.distanceTo(o2)[0];
  if (Nd.Utils.EQ(i2, e2.r)) n2.push(o2);
  else if (Nd.Utils.LT(i2, e2.r)) {
    let r2, s2, a2 = Math.sqrt(e2.r * e2.r - i2 * i2);
    r2 = t48.norm.rotate90CCW().multiply(a2), s2 = o2.translate(r2), n2.push(s2), r2 = t48.norm.rotate90CW().multiply(a2), s2 = o2.translate(r2), n2.push(s2);
  }
  return n2;
}
function Dd(t48, e2) {
  let n2 = [];
  for (let o2 of e2.toSegments()) {
    let e3 = kd(o2, t48);
    for (let t49 of e3) eu(t49, n2) || n2.push(t49);
  }
  return n2;
}
function zd(t48, e2) {
  let n2 = [];
  if (0 === Dd(t48, e2.box).length) return n2;
  let o2 = Ld(t48, new Nd.Circle(e2.pc, e2.r));
  for (let t49 of o2) t49.on(e2) && n2.push(t49);
  return n2;
}
function kd(t48, e2) {
  let n2 = [];
  return t48.ps.on(e2) && n2.push(t48.ps), t48.pe.on(e2) && !t48.isZeroLength() && n2.push(t48.pe), n2.length > 0 || t48.isZeroLength() || t48.ps.leftTo(e2) && t48.pe.leftTo(e2) || !t48.ps.leftTo(e2) && !t48.pe.leftTo(e2) ? n2 : Od(new Nd.Line(t48.ps, t48.pe), e2);
}
function Fd(t48, e2) {
  let n2 = [];
  if (t48.isZeroLength()) return t48.ps.on(e2) && n2.push(t48.ps), n2;
  if (e2.isZeroLength()) return e2.ps.on(t48) && n2.push(e2.ps), n2;
  let o2 = new Nd.Line(t48.ps, t48.pe), i2 = new Nd.Line(e2.ps, e2.pe);
  if (o2.incidentTo(i2)) t48.ps.on(e2) && n2.push(t48.ps), t48.pe.on(e2) && n2.push(t48.pe), !e2.ps.on(t48) || e2.ps.equalTo(t48.ps) || e2.ps.equalTo(t48.pe) || n2.push(e2.ps), !e2.pe.on(t48) || e2.pe.equalTo(t48.ps) || e2.pe.equalTo(t48.pe) || n2.push(e2.pe);
  else {
    let r2 = Od(o2, i2);
    r2.length > 0 && jd(r2[0], t48) && jd(r2[0], e2) && n2.push(r2[0]);
  }
  return n2;
}
function jd(t48, e2) {
  const n2 = e2.box;
  return Nd.Utils.LE(t48.x, n2.xmax) && Nd.Utils.GE(t48.x, n2.xmin) && Nd.Utils.LE(t48.y, n2.ymax) && Nd.Utils.GE(t48.y, n2.ymin);
}
function Yd(t48, e2) {
  let n2 = [];
  if (t48.isZeroLength()) {
    let [o3, i2] = t48.ps.distanceTo(e2.pc);
    return Nd.Utils.EQ(o3, e2.r) && n2.push(t48.ps), n2;
  }
  let o2 = Ld(new Nd.Line(t48.ps, t48.pe), e2);
  for (let e3 of o2) e3.on(t48) && n2.push(e3);
  return n2;
}
function $d(t48, e2) {
  let n2 = [];
  if (t48.isZeroLength()) return t48.ps.on(e2) && n2.push(t48.ps), n2;
  let o2 = Ld(new Nd.Line(t48.ps, t48.pe), new Nd.Circle(e2.pc, e2.r));
  for (let i2 of o2) i2.on(t48) && i2.on(e2) && n2.push(i2);
  return n2;
}
function Xd(t48, e2) {
  let n2 = [], o2 = new Nd.Vector(t48.pc, e2.pc), i2 = t48.r, r2 = e2.r;
  if (Nd.Utils.EQ_0(i2) || Nd.Utils.EQ_0(r2)) return n2;
  if (Nd.Utils.EQ_0(o2.x) && Nd.Utils.EQ_0(o2.y) && Nd.Utils.EQ(i2, r2)) return n2.push(t48.pc.translate(-i2, 0)), n2;
  let s2, a2 = t48.pc.distanceTo(e2.pc)[0];
  if (Nd.Utils.GT(a2, i2 + r2)) return n2;
  if (Nd.Utils.LT(a2, Math.abs(i2 - r2))) return n2;
  if (o2.x /= a2, o2.y /= a2, Nd.Utils.EQ(a2, i2 + r2) || Nd.Utils.EQ(a2, Math.abs(i2 - r2))) return s2 = t48.pc.translate(i2 * o2.x, i2 * o2.y), n2.push(s2), n2;
  let c2 = i2 * i2 / (2 * a2) - r2 * r2 / (2 * a2) + a2 / 2, l2 = t48.pc.translate(c2 * o2.x, c2 * o2.y), h2 = Math.sqrt(i2 * i2 - c2 * c2);
  return s2 = l2.translate(o2.rotate90CCW().multiply(h2)), n2.push(s2), s2 = l2.translate(o2.rotate90CW().multiply(h2)), n2.push(s2), n2;
}
function Bd(t48, e2) {
  let n2 = [];
  if (t48.pc.equalTo(e2.pc) && Nd.Utils.EQ(t48.r, e2.r)) {
    let o3;
    return o3 = t48.start, o3.on(e2) && n2.push(o3), o3 = t48.end, o3.on(e2) && n2.push(o3), o3 = e2.start, o3.on(t48) && n2.push(o3), o3 = e2.end, o3.on(t48) && n2.push(o3), n2;
  }
  let o2 = new Nd.Circle(t48.pc, t48.r), i2 = new Nd.Circle(e2.pc, e2.r), r2 = o2.intersect(i2);
  for (let o3 of r2) o3.on(t48) && o3.on(e2) && n2.push(o3);
  return n2;
}
function Hd(t48, e2) {
  let n2 = [];
  if (e2.pc.equalTo(t48.pc) && Nd.Utils.EQ(e2.r, t48.r)) return n2.push(t48.start), n2.push(t48.end), n2;
  let o2 = Xd(e2, new Nd.Circle(t48.pc, t48.r));
  for (let e3 of o2) e3.on(t48) && n2.push(e3);
  return n2;
}
function Wd(t48, e2) {
  return t48.isSegment ? Fd(t48.shape, e2) : $d(e2, t48.shape);
}
function Vd(t48, e2) {
  return t48.isSegment ? $d(t48.shape, e2) : Bd(t48.shape, e2);
}
function Ud(t48, e2) {
  return t48.isSegment ? kd(t48.shape, e2) : zd(e2, t48.shape);
}
function Gd(t48, e2) {
  return t48.isSegment ? Yd(t48.shape, e2) : Hd(t48.shape, e2);
}
function Zd(t48, e2) {
  let n2 = [];
  for (let o2 of e2.edges) for (let e3 of Wd(o2, t48)) n2.push(e3);
  return n2;
}
function qd(t48, e2) {
  let n2 = [];
  for (let o2 of e2.edges) for (let e3 of Vd(o2, t48)) n2.push(e3);
  return n2;
}
function Jd(t48, e2) {
  let n2 = [];
  if (e2.isEmpty()) return n2;
  for (let o2 of e2.edges) for (let e3 of Ud(o2, t48)) eu(e3, n2) || n2.push(e3);
  return t48.sortPoints(n2);
}
function Kd(t48, e2) {
  let n2 = [];
  if (e2.isEmpty()) return n2;
  for (let o2 of e2.edges) for (let e3 of Gd(o2, t48)) n2.push(e3);
  return n2;
}
function Qd(t48, e2) {
  return t48.isSegment ? Wd(e2, t48.shape) : t48.isArc ? Vd(e2, t48.shape) : t48.isLine ? Ud(e2, t48.shape) : t48.isRay ? (n2 = e2, o2 = t48.shape, n2.isSegment ? ou(o2, n2.shape) : iu(o2, n2.shape)) : [];
  var n2, o2;
}
function tu(t48, e2) {
  let n2 = [];
  if (e2.isEmpty() || t48.shape.box.not_intersect(e2.box)) return n2;
  let o2 = e2.edges.search(t48.shape.box);
  for (let e3 of o2) n2 = [...n2, ...Qd(t48, e3)];
  return n2;
}
function eu(t48, e2) {
  return e2.some((e3) => e3.equalTo(t48));
}
function nu(t48) {
  return new Nd.Line(t48.start, t48.norm);
}
function ou(t48, e2) {
  return kd(e2, nu(t48)).filter((e3) => t48.contains(e3));
}
function iu(t48, e2) {
  return zd(nu(t48), e2).filter((e3) => t48.contains(e3));
}
function ru(t48, e2) {
  return Ld(nu(t48), e2).filter((e3) => t48.contains(e3));
}
function su(t48, e2) {
  return Od(nu(t48), e2).filter((e3) => t48.contains(e3));
}
function au(t48, e2) {
  return Jd(nu(t48), e2).filter((e3) => t48.contains(e3));
}
function cu(t48, e2) {
  if (t48.intersect && t48.intersect instanceof Function) return t48.intersect(e2);
  throw wd.UNSUPPORTED_SHAPE_TYPE;
}
function lu(t48, e2) {
  let n2 = [];
  for (let o2 of e2) n2 = [...n2, ...cu(t48, o2.shape)];
  return n2;
}
var hu = class t3 extends Td {
  constructor(...t48) {
    if (super(), this.isInfinite = false, 1 === t48.length && t48[0] instanceof Array && t48[0].length > 0) {
      const e2 = t48[0], n2 = e2.length, o2 = (t49) => t49 instanceof Nd.Segment || t49 instanceof Nd.Arc || t49 instanceof Nd.Ray, i2 = (t49) => t49 instanceof Nd.Segment || t49 instanceof Nd.Arc;
      if (!(1 === n2 && ((t49) => t49 instanceof Nd.Segment || t49 instanceof Nd.Arc || t49 instanceof Nd.Ray || t49 instanceof Nd.Line)(e2[0]) || n2 > 1 && o2(e2[0]) && o2(e2[n2 - 1]) && e2.slice(1, n2 - 1).every(i2))) throw Nd.Errors.ILLEGAL_PARAMETERS;
      this.isInfinite = e2.some((t49) => t49 instanceof Nd.Ray || t49 instanceof Nd.Line);
      for (let t49 of e2) {
        let e3 = new Nd.Edge(t49);
        this.append(e3);
      }
      this.setArcLength();
    }
  }
  get edges() {
    return [...this];
  }
  get box() {
    return this.edges.reduce((t48, e2) => t48.merge(e2.box), new Nd.Box());
  }
  get vertices() {
    let t48 = this.edges.map((t49) => t49.start);
    return t48.push(this.last.end), t48;
  }
  get length() {
    if (this.isEmpty()) return 0;
    if (this.isInfinite) return Number.POSITIVE_INFINITY;
    let t48 = 0;
    for (let e2 of this) t48 += e2.length;
    return t48;
  }
  clone() {
    return new t3(this.toShapes());
  }
  setArcLength() {
    for (let t48 of this) this.setOneEdgeArcLength(t48);
  }
  setOneEdgeArcLength(t48) {
    t48 === this.first ? t48.arc_length = 0 : t48.arc_length = t48.prev.arc_length + t48.prev.length;
  }
  pointAtLength(t48) {
    if (t48 > this.length || t48 < 0) return null;
    if (this.isInfinite) return null;
    let e2 = null;
    for (let n2 of this) if (t48 >= n2.arc_length && (n2 === this.last || t48 < n2.next.arc_length)) {
      e2 = n2.pointAtLength(t48 - n2.arc_length);
      break;
    }
    return e2;
  }
  addVertex(t48, e2) {
    let n2 = e2.shape.split(t48);
    if (null === n2[0]) return e2.prev;
    if (null === n2[1]) return e2;
    let o2 = new Nd.Edge(n2[0]), i2 = e2.prev;
    return this.insert(o2, i2), e2.shape = n2[1], o2;
  }
  getChain(t48, e2) {
    let n2 = [];
    for (let o2 = t48; o2 !== e2.next; o2 = o2.next) n2.push(o2);
    return n2;
  }
  split(t48) {
    for (let e2 of t48) {
      let t49 = this.findEdgeByPoint(e2);
      this.addVertex(e2, t49);
    }
    return this;
  }
  findEdgeByPoint(t48) {
    let e2;
    for (let n2 of this) if (n2.shape.contains(t48)) {
      e2 = n2;
      break;
    }
    return e2;
  }
  distanceTo(t48) {
    if (t48 instanceof Point) {
      const [e2, n2] = Nd.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof Nd.Line) {
      const [e2, n2] = Nd.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof Nd.Circle) {
      const [e2, n2] = Nd.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof Nd.Segment) {
      const [e2, n2] = Nd.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof Nd.Arc) {
      const [e2, n2] = Nd.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof Nd.Multiline) return Nd.Distance.multiline2multiline(this, t48);
    throw Nd.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  intersect(t48) {
    return t48 instanceof Nd.Multiline ? (function(t49, e2) {
      let n2 = [];
      for (let o2 of t49) for (let t50 of e2) n2 = [...n2, ...cu(o2.shape, t50.shape)];
      return n2;
    })(this, t48) : lu(t48, this);
  }
  contains(t48) {
    if (t48 instanceof Nd.Point) return this.edges.some((e2) => e2.shape.contains(t48));
    throw Nd.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  translate(e2) {
    return new t3(this.edges.map((t48) => t48.shape.translate(e2)));
  }
  rotate(e2 = 0, n2 = new Nd.Point()) {
    return new t3(this.edges.map((t48) => t48.shape.rotate(e2, n2)));
  }
  transform(e2 = new Nd.Matrix()) {
    return new t3(this.edges.map((t48) => t48.shape.transform(e2)));
  }
  toShapes() {
    return this.edges.map((t48) => t48.shape.clone());
  }
  toJSON() {
    return this.edges.map((t48) => t48.toJSON());
  }
  svgPoints() {
    return this.vertices.map((t48) => `${t48.x},${t48.y}`).join(" ");
  }
  dpath() {
    let t48 = `M${this.first.start.x},${this.first.start.y}`;
    for (let e2 of this) t48 += e2.svg();
    return t48;
  }
  svg(t48 = {}) {
    let e2 = `
<path ${Ad({ fill: "none", ...t48 })} d="`;
    e2 += `
M${this.first.start.x},${this.first.start.y}`;
    for (let t49 of this) e2 += t49.svg();
    return e2 += '" >\n</path>', e2;
  }
};
Nd.Multiline = hu;
function du(t48, e2, n2) {
  let o2 = n2.length, i2 = t48.shape.split(e2);
  if (0 === i2.length) return;
  let r2 = 0;
  r2 = null === i2[0] ? 0 : null === i2[1] ? t48.shape.length : i2[0].length;
  let s2, a2 = 0;
  Pd(r2, 0) && (a2 |= 1), Pd(r2, t48.shape.length) && (a2 |= 2), s2 = r2 === 1 / 0 ? i2[0].coord(e2) : 2 & a2 && t48.next && 0 === t48.next.arc_length ? 0 : t48.arc_length + r2, n2.push({ id: o2, pt: e2, arc_length: s2, edge_before: t48, edge_after: void 0, face: t48.face, is_vertex: a2 });
}
function uu(t48) {
  t48.int_points1_sorted = pu(t48.int_points1), t48.int_points2_sorted = pu(t48.int_points2);
}
function pu(t48) {
  let e2 = /* @__PURE__ */ new Map(), n2 = 0;
  for (let o2 of t48) e2.has(o2.face) || (e2.set(o2.face, n2), n2++);
  for (let n3 of t48) n3.faceId = e2.get(n3.face);
  return t48.slice().sort(mu);
}
function mu(t48, e2) {
  return t48.faceId < e2.faceId ? -1 : t48.faceId > e2.faceId ? 1 : t48.arc_length < e2.arc_length ? -1 : t48.arc_length > e2.arc_length ? 1 : 0;
}
function gu(t48) {
  if (t48.int_points1.length < 2) return;
  let e2, n2, o2, i2, r2 = false;
  for (let s2 = 0; s2 < t48.int_points1_sorted.length; s2++) if (-1 !== t48.int_points1_sorted[s2].id) {
    e2 = t48.int_points1_sorted[s2], n2 = t48.int_points2[e2.id];
    for (let a2 = s2 + 1; a2 < t48.int_points1_sorted.length && (o2 = t48.int_points1_sorted[a2], Pd(o2.arc_length, e2.arc_length)); a2++) -1 !== o2.id && (i2 = t48.int_points2[o2.id], -1 !== i2.id && o2.edge_before === e2.edge_before && o2.edge_after === e2.edge_after && i2.edge_before === n2.edge_before && i2.edge_after === n2.edge_after && (o2.id = -1, i2.id = -1, r2 = true));
  }
  n2 = t48.int_points2_sorted[0], e2 = t48.int_points1[n2.id];
  for (let o3 = 1; o3 < t48.int_points2_sorted.length; o3++) {
    let i3 = t48.int_points2_sorted[o3];
    if (-1 === i3.id) continue;
    if (-1 === n2.id || !Pd(i3.arc_length, n2.arc_length)) {
      n2 = i3, e2 = t48.int_points1[n2.id];
      continue;
    }
    let s2 = t48.int_points1[i3.id];
    s2.edge_before === e2.edge_before && s2.edge_after === e2.edge_after && i3.edge_before === n2.edge_before && i3.edge_after === n2.edge_after && (s2.id = -1, i3.id = -1, r2 = true);
  }
  r2 && (t48.int_points1 = t48.int_points1.filter((t49) => t49.id >= 0), t48.int_points2 = t48.int_points2.filter((t49) => t49.id >= 0), t48.int_points1.forEach((t49, e3) => t49.id = e3), t48.int_points2.forEach((t49, e3) => t49.id = e3));
}
function fu(t48) {
  for (let e2 of t48) e2.edge_before && (e2.edge_before.bvStart = void 0, e2.edge_before.bvEnd = void 0, e2.edge_before.bv = void 0, e2.edge_before.overlap = void 0), e2.edge_after && (e2.edge_after.bvStart = void 0, e2.edge_after.bvEnd = void 0, e2.edge_after.bv = void 0, e2.edge_after.overlap = void 0);
  for (let e2 of t48) e2.edge_before && (e2.edge_before.bvEnd = 2), e2.edge_after && (e2.edge_after.bvStart = 2);
}
function _u(t48, e2) {
  for (let n2 of t48) n2.edge_before && n2.edge_before.setInclusion(e2), n2.edge_after && n2.edge_after.setInclusion(e2);
}
function yu(t48, e2, n2) {
  let o2, i2, r2 = 1;
  if (1 === t48.length) return 1;
  o2 = t48[e2];
  for (let s2 = e2 + 1; s2 < t48.length && o2.face === n2 && (i2 = t48[s2], i2.pt.equalTo(o2.pt) && i2.edge_before === o2.edge_before && i2.edge_after === o2.edge_after); s2++) r2++;
  return r2;
}
function bu(t48, e2) {
  if (e2) {
    for (let n2 of e2) {
      let e3 = n2.edge_before;
      if (n2.is_vertex = 0, e3.shape.start && e3.shape.start.equalTo(n2.pt) && (n2.is_vertex |= 1), e3.shape.end && e3.shape.end.equalTo(n2.pt) && (n2.is_vertex |= 2), 1 & n2.is_vertex) {
        n2.edge_before = e3.prev, e3.prev && (n2.is_vertex = 2);
        continue;
      }
      if (2 & n2.is_vertex) continue;
      let o2 = t48.addVertex(n2.pt, e3);
      n2.edge_before = o2;
    }
    for (let n2 of e2) n2.edge_before ? n2.edge_after = n2.edge_before.next : t48 instanceof hu && 1 & n2.is_vertex && (n2.edge_after = t48.first);
  }
}
function xu(t48, e2, n2) {
  const o2 = t48.edge_before, i2 = e2.edge_after, r2 = n2.length;
  o2.next = n2[0], n2[0].prev = o2, n2[r2 - 1].next = i2, i2.prev = n2[r2 - 1];
}
Nd.multiline = (...t48) => new Nd.Multiline(...t48);
var { INSIDE: vu, OUTSIDE: Su, BOUNDARY: Iu, OVERLAP_SAME: Pu, OVERLAP_OPPOSITE: Mu } = bd;
var { NOT_VERTEX: Cu, START_VERTEX: Nu, END_VERTEX: wu } = bd;
function Tu(t48, e2) {
  let n2 = e2.clone().reverse(), [o2, i2] = Du(t48, n2, 3, true);
  return o2;
}
function Ru(t48, e2) {
  let [n2, o2] = Du(t48, e2, 2, true);
  return n2;
}
function Eu(t48, e2) {
  let [n2, o2] = Du(t48, e2, 2, false), i2 = [];
  for (let t49 of n2.faces) i2 = [...i2, ...[...t49.edges].map((t50) => t50.shape)];
  let r2 = [];
  for (let t49 of o2.faces) r2 = [...r2, ...[...t49.edges].map((t50) => t50.shape)];
  return [i2, r2];
}
function Au(t48, e2) {
  let [n2, o2] = Du(t48, e2, 3, false), i2 = [];
  for (let t49 of n2.faces) i2 = [...i2, ...[...t49.edges].map((t50) => t50.shape)];
  return i2;
}
function Ou(t48, e2) {
  let n2 = t48.clone(), o2 = e2.clone(), i2 = zu(n2, o2);
  return uu(i2), bu(n2, i2.int_points1_sorted), bu(o2, i2.int_points2_sorted), gu(i2), uu(i2), [i2.int_points1_sorted.map((t49) => t49.pt), i2.int_points2_sorted.map((t49) => t49.pt)];
}
function Lu(t48, e2, n2, o2) {
  let i2 = ku(t48, n2.int_points1), r2 = ku(e2, n2.int_points2);
  for (Fu(i2, e2), Fu(r2, t48), fu(n2.int_points1), fu(n2.int_points2), _u(n2.int_points1, e2), _u(n2.int_points2, t48); ju(t48, e2, n2.int_points1, n2.int_points1_sorted, n2.int_points2, n2); ) ;
  !(function(t49) {
    let e3, n3, o3, i3 = t49.int_points1.length;
    for (let r3 = 0; r3 < i3; r3++) {
      let s2 = t49.int_points1_sorted[r3];
      s2.face !== e3 && (n3 = r3, e3 = s2.face);
      let a2, c2 = r3, l2 = yu(t49.int_points1_sorted, r3, e3);
      a2 = c2 + l2 < i3 && t49.int_points1_sorted[c2 + l2].face === e3 ? c2 + l2 : n3;
      let h2 = yu(t49.int_points1_sorted, a2, e3);
      o3 = null;
      for (let n4 = a2; n4 < a2 + h2; n4++) {
        let i4 = t49.int_points1_sorted[n4];
        if (i4.face === e3 && t49.int_points2[i4.id].face === t49.int_points2[s2.id].face) {
          o3 = i4;
          break;
        }
      }
      if (null === o3) continue;
      let d2 = s2.edge_after, u2 = o3.edge_before;
      if (2 !== d2.bv || 2 !== u2.bv) continue;
      if (d2 !== u2) continue;
      let p2 = t49.int_points2[s2.id], m2 = t49.int_points2[o3.id], g2 = p2.edge_after, f2 = m2.edge_before;
      2 === g2.bv && 2 === f2.bv && g2 === f2 || (p2 = t49.int_points2[o3.id], m2 = t49.int_points2[s2.id], g2 = p2.edge_after, f2 = m2.edge_before), 2 === g2.bv && 2 === f2.bv && g2 === f2 && d2.setOverlap(g2);
    }
  })(n2), Yu(t48, o2, n2.int_points1_sorted, true), Yu(e2, o2, n2.int_points2_sorted, false), Bu(t48, i2, o2, true), Bu(e2, r2, o2, false);
}
function Du(t48, e2, n2, o2) {
  let i2 = t48.clone(), r2 = e2.clone(), s2 = zu(i2, r2);
  return uu(s2), bu(i2, s2.int_points1_sorted), bu(r2, s2.int_points2_sorted), gu(s2), uu(s2), Lu(i2, r2, s2, n2), o2 && (function(t49, e3, n3) {
    !(function(t50, e4, n4, o3) {
      for (let n5 of e4.faces) {
        for (let e5 of n5) t50.edges.add(e5);
        void 0 === o3.find((t51) => t51.face === n5) && t50.addFace(n5.first, n5.last);
      }
    })(t49, e3, 0, n3.int_points2), (function(t50, e4, n4) {
      if (0 !== n4.int_points1.length) for (let t51 = 0; t51 < n4.int_points1.length; t51++) {
        let e5 = n4.int_points1[t51], o3 = n4.int_points2[t51];
        if (void 0 !== e5.edge_before && void 0 === e5.edge_after && void 0 === o3.edge_before && void 0 !== o3.edge_after && (e5.edge_before.next = o3.edge_after, o3.edge_after.prev = e5.edge_before, e5.edge_after = o3.edge_after, o3.edge_before = e5.edge_before), void 0 !== o3.edge_before && void 0 === o3.edge_after && void 0 === e5.edge_before && void 0 !== e5.edge_after && (o3.edge_before.next = e5.edge_after, e5.edge_after.prev = o3.edge_before, o3.edge_after = e5.edge_after, e5.edge_before = o3.edge_before), void 0 !== e5.edge_before && void 0 === e5.edge_after) for (let t52 of n4.int_points1_sorted) t52 !== e5 && void 0 === t52.edge_before && void 0 !== t52.edge_after && t52.pt.equalTo(e5.pt) && (e5.edge_before.next = t52.edge_after, t52.edge_after.prev = e5.edge_before, e5.edge_after = t52.edge_after, t52.edge_before = e5.edge_before);
        if (void 0 !== o3.edge_before && void 0 === o3.edge_after) for (let t52 of n4.int_points2_sorted) t52 !== o3 && void 0 === t52.edge_before && void 0 !== t52.edge_after && t52.pt.equalTo(o3.pt) && (o3.edge_before.next = t52.edge_after, t52.edge_after.prev = o3.edge_before, o3.edge_after = t52.edge_after, t52.edge_before = o3.edge_before);
      }
    })(0, 0, n3), $u(t49, n3.int_points1), $u(e3, n3.int_points2), Xu(t49, n3.int_points1, n3.int_points2), Xu(t49, n3.int_points2, n3.int_points1);
  })(i2, r2, s2), [i2, r2];
}
function zu(t48, e2) {
  let n2 = { int_points1: [], int_points2: [] };
  for (let o2 of t48.edges) {
    let t49 = e2.edges.search(o2.box);
    for (let e3 of t49) {
      let t50 = o2.shape.intersect(e3.shape);
      for (let i2 of t50) du(o2, i2, n2.int_points1), du(e3, i2, n2.int_points2);
    }
  }
  return n2;
}
function ku(t48, e2) {
  let n2 = [];
  for (let o2 of t48.faces) e2.find((t49) => t49.face === o2) || n2.push(o2);
  return n2;
}
function Fu(t48, e2) {
  for (let n2 of t48) n2.first.bv = n2.first.bvStart = n2.first.bvEnd = void 0, n2.first.setInclusion(e2);
}
function ju(t48, e2, n2, o2, i2, r2) {
  let s2, a2, c2, l2 = o2.length, h2 = false;
  for (let d2 = 0; d2 < l2; d2++) {
    let u2 = o2[d2];
    u2.face !== s2 && (a2 = d2, s2 = u2.face);
    let p2, m2 = d2, g2 = yu(o2, d2, s2);
    p2 = m2 + g2 < l2 && o2[m2 + g2].face === s2 ? m2 + g2 : a2;
    let f2 = yu(o2, p2, s2);
    c2 = null;
    for (let t49 = p2; t49 < p2 + f2; t49++) {
      let e3 = o2[t49];
      if (e3.face === s2 && i2[e3.id].face === i2[u2.id].face) {
        c2 = e3;
        break;
      }
    }
    if (null === c2) continue;
    let _2 = u2.edge_after, y2 = c2.edge_before;
    if (_2.bv !== Iu || y2.bv == Iu) if (_2.bv == Iu || y2.bv !== Iu) {
      if (_2.bv === Iu && y2.bv === Iu && _2 != y2 || _2.bv === vu && y2.bv === Su || _2.bv === Su && y2.bv === vu) {
        let t49 = _2.next;
        for (; t49 != y2; ) t49.bvStart = void 0, t49.bvEnd = void 0, t49.bv = void 0, t49.setInclusion(e2), t49 = t49.next;
      }
      if (_2.bv === Iu && y2.bv === Iu && _2 != y2) {
        let t49, e3 = _2.next;
        for (; e3 != y2; ) {
          if (e3.bv != Iu) {
            if (void 0 === t49) t49 = e3.bv;
            else if (e3.bv != t49) throw wd.UNRESOLVED_BOUNDARY_CONFLICT;
          }
          e3 = e3.next;
        }
        null != t49 && (_2.bv = t49, y2.bv = t49);
        continue;
      }
      if (_2.bv === vu && y2.bv === Su || _2.bv === Su && y2.bv === vu) {
        let o3 = _2;
        for (; o3 != y2; ) {
          if (o3.bvStart === _2.bv && o3.bvEnd === y2.bv) {
            let [s3, a3] = o3.shape.distanceTo(e2);
            if (s3 < 10 * Nd.DP_TOL) {
              du(o3, a3.ps, n2);
              let s4 = n2[n2.length - 1];
              if (s4.is_vertex & Nu) s4.edge_after = o3, s4.edge_before = o3.prev, o3.bvStart = Iu, o3.bv = void 0, o3.setInclusion(e2);
              else if (s4.is_vertex & wu) s4.edge_after = o3.next, o3.bvEnd = Iu, o3.bv = void 0, o3.setInclusion(e2);
              else {
                let t49 = e2.addVertex(s4.pt, o3);
                s4.edge_before = t49, s4.edge_after = t49.next, t49.setInclusion(e2), t49.next.bvStart = Iu, t49.next.bvEnd = void 0, t49.next.bv = void 0, t49.next.setInclusion(e2);
              }
              let c3 = e2.findEdgeByPoint(a3.pe);
              du(c3, a3.pe, i2);
              let l3 = i2[i2.length - 1];
              if (l3.is_vertex & Nu) l3.edge_after = c3, l3.edge_before = c3.prev;
              else if (l3.is_vertex & wu) l3.edge_after = c3.next;
              else {
                let n3 = i2.find((t49) => t49.edge_after === c3), o4 = e2.addVertex(l3.pt, c3);
                l3.edge_before = o4, l3.edge_after = o4.next, n3 && (n3.edge_after = o4), o4.bvStart = void 0, o4.bvEnd = Iu, o4.bv = void 0, o4.setInclusion(t48), o4.next.bvStart = Iu, o4.next.bvEnd = void 0, o4.next.bv = void 0, o4.next.setInclusion(t48);
              }
              uu(r2), h2 = true;
              break;
            }
          }
          o3 = o3.next;
        }
        if (h2) break;
        throw wd.UNRESOLVED_BOUNDARY_CONFLICT;
      }
    } else y2.bv = _2.bv;
    else _2.bv = y2.bv;
  }
  return h2;
}
function Yu(t48, e2, n2, o2) {
  if (!n2) return;
  let i2, r2, s2, a2;
  for (let c2 = 0; c2 < n2.length; c2++) {
    if (s2 = n2[c2], s2.face !== i2 && (r2 = c2, i2 = s2.face), i2.isEmpty()) continue;
    let l2, h2 = c2, d2 = yu(n2, c2, i2);
    l2 = h2 + d2 < n2.length && n2[h2 + d2].face === s2.face ? h2 + d2 : r2, a2 = n2[l2];
    let u2 = l2, p2 = yu(n2, u2, i2), m2 = s2.edge_after, g2 = a2.edge_before;
    if (m2.bv === vu && g2.bv === vu && 1 === e2 || m2.bv === Su && g2.bv === Su && 2 === e2 || (m2.bv === Su || g2.bv === Su) && 3 === e2 && !o2 || (m2.bv === vu || g2.bv === vu) && 3 === e2 && o2 || m2.bv === Iu && g2.bv === Iu && m2.overlap & Pu && o2 || m2.bv === Iu && g2.bv === Iu && m2.overlap & Mu) {
      t48.removeChain(i2, m2, g2);
      for (let t49 = h2; t49 < h2 + d2; t49++) n2[t49].edge_after = void 0;
      for (let t49 = u2; t49 < u2 + p2; t49++) n2[t49].edge_before = void 0;
    }
    c2 += d2 - 1;
  }
}
function $u(t48, e2) {
  for (let n2 of e2) t48.faces.delete(n2.face), n2.face = void 0, n2.edge_before && (n2.edge_before.face = void 0), n2.edge_after && (n2.edge_after.face = void 0);
}
function Xu(t48, e2, n2) {
  for (let o2 of e2) {
    if (void 0 === o2.edge_before || void 0 === o2.edge_after) continue;
    if (o2.face) continue;
    if (o2.edge_after.face || o2.edge_before.face) continue;
    let i2 = o2.edge_after, r2 = o2.edge_before;
    try {
      Td.testInfiniteLoop(i2);
    } catch (t49) {
      throw wd.CANNOT_COMPLETE_BOOLEAN_OPERATION;
    }
    let s2 = t48.addFace(i2, r2);
    for (let t49 of e2) t49.edge_before && t49.edge_after && t49.edge_before.face === s2 && t49.edge_after.face === s2 && (t49.face = s2);
    for (let t49 of n2) t49.edge_before && t49.edge_after && t49.edge_before.face === s2 && t49.edge_after.face === s2 && (t49.face = s2);
  }
}
function Bu(t48, e2, n2, o2) {
  for (let i2 of e2) {
    let e3 = i2.first.bv;
    (1 === n2 && e3 === vu || 3 === n2 && e3 === vu && o2 || 3 === n2 && e3 === Su && !o2 || 2 === n2 && e3 === Su) && t48.deleteFace(i2);
  }
}
var Hu = Object.freeze({ __proto__: null, BOOLEAN_INTERSECT: 2, BOOLEAN_SUBTRACT: 3, BOOLEAN_UNION: 1, calculateIntersections: Ou, innerClip: Eu, intersect: Ru, outerClip: Au, removeNotRelevantChains: Yu, removeOldFaces: $u, restoreFaces: Xu, subtract: Tu, unify: function(t48, e2) {
  let [n2, o2] = Du(t48, e2, 1, true);
  return n2;
} });
var Wu = RegExp("T.F..FFF.|T.F...F..");
var Vu = RegExp("T........|.T.......|...T.....|....T....");
var Uu = RegExp("FT.......|F..T.....|F...T....");
var Gu = RegExp("T.F..F...");
var Zu = RegExp("T.F..F...|.TF..F...|..FT.F...|..F.TF...");
var qu = class {
  constructor() {
    this.m = new Array(9).fill(void 0);
  }
  get I2I() {
    return this.m[0];
  }
  set I2I(t48) {
    this.m[0] = t48;
  }
  get I2B() {
    return this.m[1];
  }
  set I2B(t48) {
    this.m[1] = t48;
  }
  get I2E() {
    return this.m[2];
  }
  set I2E(t48) {
    this.m[2] = t48;
  }
  get B2I() {
    return this.m[3];
  }
  set B2I(t48) {
    this.m[3] = t48;
  }
  get B2B() {
    return this.m[4];
  }
  set B2B(t48) {
    this.m[4] = t48;
  }
  get B2E() {
    return this.m[5];
  }
  set B2E(t48) {
    this.m[5] = t48;
  }
  get E2I() {
    return this.m[6];
  }
  set E2I(t48) {
    this.m[6] = t48;
  }
  get E2B() {
    return this.m[7];
  }
  set E2B(t48) {
    this.m[7] = t48;
  }
  get E2E() {
    return this.m[8];
  }
  set E2E(t48) {
    this.m[8] = t48;
  }
  toString() {
    return this.m.map((t48) => t48 instanceof Array && t48.length > 0 ? "T" : t48 instanceof Array && 0 === t48.length ? "F" : "*").join("");
  }
  equal() {
    return Wu.test(this.toString());
  }
  intersect() {
    return Vu.test(this.toString());
  }
  touch() {
    return Uu.test(this.toString());
  }
  inside() {
    return Gu.test(this.toString());
  }
  covered() {
    return Zu.test(this.toString());
  }
};
function Ju(t48, e2) {
  let n2, o2 = new Nd.Ray(e2), i2 = new Nd.Line(o2.pt, o2.norm);
  const r2 = new Nd.Box(o2.box.xmin - Nd.DP_TOL, o2.box.ymin - Nd.DP_TOL, o2.box.xmax + Nd.DP_TOL, o2.box.ymax + Nd.DP_TOL);
  if (t48.box.not_intersect(r2)) return Nd.OUTSIDE;
  let s2 = t48.edges.search(r2);
  if (0 === s2.length) return Nd.OUTSIDE;
  for (let t49 of s2) if (t49.shape.contains(e2)) return Nd.BOUNDARY;
  let a2 = [...t48.faces], c2 = [];
  for (let t49 of s2) for (let n3 of o2.intersect(t49.shape)) {
    if (n3.equalTo(e2)) return Nd.BOUNDARY;
    c2.push({ pt: n3, edge: t49, face_index: a2.indexOf(t49.face) });
  }
  c2.sort((t49, e3) => Cd(t49.pt.x, e3.pt.x) ? -1 : Md(t49.pt.x, e3.pt.x) ? 1 : t49.face_index < e3.face_index ? -1 : t49.face_index > e3.face_index ? 1 : t49.edge.arc_length < e3.edge.arc_length ? -1 : t49.edge.arc_length > e3.edge.arc_length ? 1 : 0);
  let l2 = 0;
  for (let t49 = 0; t49 < c2.length; t49++) {
    let e3 = c2[t49];
    if (e3.pt.equalTo(e3.edge.shape.start)) {
      if (t49 > 0 && e3.pt.equalTo(c2[t49 - 1].pt) && e3.face_index === c2[t49 - 1].face_index && e3.edge.prev === c2[t49 - 1].edge) continue;
      let n3 = e3.edge.prev;
      for (; Id(n3.length); ) n3 = n3.prev;
      let o3 = n3.shape.tangentInEnd(), r3 = e3.pt.translate(o3), s3 = e3.edge.shape.tangentInStart(), a3 = e3.pt.translate(s3), h2 = r3.leftTo(i2), d2 = a3.leftTo(i2);
      (h2 && !d2 || !h2 && d2) && l2++;
    } else if (e3.pt.equalTo(e3.edge.shape.end)) {
      if (t49 > 0 && e3.pt.equalTo(c2[t49 - 1].pt) && e3.face_index === c2[t49 - 1].face_index && e3.edge.next === c2[t49 - 1].edge) continue;
      let n3 = e3.edge.next;
      for (; Id(n3.length); ) n3 = n3.next;
      let o3 = n3.shape.tangentInStart(), r3 = e3.pt.translate(o3), s3 = e3.edge.shape.tangentInEnd(), a3 = e3.pt.translate(s3), h2 = r3.leftTo(i2), d2 = a3.leftTo(i2);
      (h2 && !d2 || !h2 && d2) && l2++;
    } else if (e3.edge.shape instanceof Nd.Segment) l2++;
    else {
      let t50 = e3.edge.shape.box;
      Pd(e3.pt.y, t50.ymin) || Pd(e3.pt.y, t50.ymax) || l2++;
    }
  }
  return n2 = l2 % 2 == 1 ? 1 : 0, n2;
}
function Ku(t48, e2) {
  return np(t48, e2).intersect();
}
function Qu(t48, e2) {
  return np(t48, e2).inside();
}
function tp(t48, e2) {
  return np(t48, e2).covered();
}
function ep(t48, e2) {
  return tp(e2, t48);
}
function np(t48, e2) {
  return t48 instanceof Nd.Line && e2 instanceof Nd.Line ? (function(t49, e3) {
    let n2 = new qu(), o2 = Od(t49, e3);
    0 === o2.length ? t49.contains(e3.pt) && e3.contains(t49.pt) ? (n2.I2I = [t49], n2.I2E = [], n2.E2I = []) : (n2.I2I = [], n2.I2E = [t49], n2.E2I = [e3]) : (n2.I2I = o2, n2.I2E = t49.split(o2), n2.E2I = e3.split(o2));
    return n2;
  })(t48, e2) : t48 instanceof Nd.Line && e2 instanceof Nd.Circle ? (function(t49, e3) {
    let n2 = new qu(), o2 = Ld(t49, e3);
    if (0 === o2.length) n2.I2I = [], n2.I2B = [], n2.I2E = [t49], n2.E2I = [e3];
    else if (1 === o2.length) n2.I2I = [], n2.I2B = o2, n2.I2E = t49.split(o2), n2.E2I = [e3];
    else {
      let i2 = new hu([t49]), r2 = t49.sortPoints(o2);
      i2.split(r2);
      let s2 = i2.toShapes();
      n2.I2I = [s2[1]], n2.I2B = r2, n2.I2E = [s2[0], s2[2]], n2.E2I = new Nd.Polygon([e3.toArc()]).cutWithLine(t49);
    }
    return n2;
  })(t48, e2) : t48 instanceof Nd.Line && e2 instanceof Nd.Box ? (function(t49, e3) {
    let n2 = new qu(), o2 = Dd(t49, e3);
    if (0 === o2.length) n2.I2I = [], n2.I2B = [], n2.I2E = [t49], n2.E2I = [e3];
    else if (1 === o2.length) n2.I2I = [], n2.I2B = o2, n2.I2E = t49.split(o2), n2.E2I = [e3];
    else {
      let i2 = new hu([t49]), r2 = t49.sortPoints(o2);
      i2.split(r2);
      let s2 = i2.toShapes();
      e3.toSegments().some((t50) => t50.contains(o2[0]) && t50.contains(o2[1])) ? (n2.I2I = [], n2.I2B = [s2[1]], n2.I2E = [s2[0], s2[2]], n2.E2I = [e3]) : (n2.I2I = [s2[1]], n2.I2B = r2, n2.I2E = [s2[0], s2[2]], n2.E2I = new Nd.Polygon(e3.toSegments()).cutWithLine(t49));
    }
    return n2;
  })(t48, e2) : t48 instanceof Nd.Line && e2 instanceof Nd.Polygon ? (function(t49, e3) {
    let n2 = new qu(), o2 = Jd(t49, e3), i2 = new hu([t49]), r2 = o2.length > 0 ? o2.slice() : t49.sortPoints(o2);
    return i2.split(r2), [...i2].forEach((t50) => t50.setInclusion(e3)), n2.I2I = [...i2].filter((t50) => t50.bv === Nd.INSIDE).map((t50) => t50.shape), n2.I2B = [...i2].slice(1).map((t50) => t50.bv === Nd.BOUNDARY ? t50.shape : t50.shape.start), n2.I2E = [...i2].filter((t50) => t50.bv === Nd.OUTSIDE).map((t50) => t50.shape), n2.E2I = e3.cutWithLine(t49), n2;
  })(t48, e2) : (t48 instanceof Nd.Segment || t48 instanceof Nd.Arc) && e2 instanceof Nd.Polygon ? op(t48, e2) : (t48 instanceof Nd.Segment || t48 instanceof Nd.Arc) && (e2 instanceof Nd.Circle || e2 instanceof Nd.Box) ? op(t48, new Nd.Polygon(e2)) : t48 instanceof Nd.Polygon && e2 instanceof Nd.Polygon ? ip(t48, e2) : (t48 instanceof Nd.Circle || t48 instanceof Nd.Box) && (e2 instanceof Nd.Circle || e2 instanceof Nd.Box) ? ip(new Nd.Polygon(t48), new Nd.Polygon(e2)) : (t48 instanceof Nd.Circle || t48 instanceof Nd.Box) && e2 instanceof Nd.Polygon ? ip(new Nd.Polygon(t48), e2) : t48 instanceof Nd.Polygon && (e2 instanceof Nd.Circle || e2 instanceof Nd.Box) ? ip(t48, new Nd.Polygon(e2)) : void 0;
}
function op(t48, e2) {
  let n2 = new qu(), o2 = (function(t49, e3) {
    return t49 instanceof Nd.Line ? Jd(t49, e3) : t49 instanceof Nd.Segment ? Zd(t49, e3) : t49 instanceof Nd.Arc ? qd(t49, e3) : [];
  })(t48, e2), i2 = o2.length > 0 ? o2.slice() : t48.sortPoints(o2), r2 = new hu([t48]);
  r2.split(i2), [...r2].forEach((t49) => t49.setInclusion(e2)), n2.I2I = [...r2].filter((t49) => t49.bv === Nd.INSIDE).map((t49) => t49.shape), n2.I2B = [...r2].slice(1).map((t49) => t49.bv === Nd.BOUNDARY ? t49.shape : t49.shape.start), n2.I2E = [...r2].filter((t49) => t49.bv === Nd.OUTSIDE).map((t49) => t49.shape), n2.B2I = [], n2.B2B = [], n2.B2E = [];
  for (let o3 of [t48.start, t48.end]) switch (Ju(e2, o3)) {
    case Nd.INSIDE:
      n2.B2I.push(o3);
      break;
    case Nd.BOUNDARY:
      n2.B2B.push(o3);
      break;
    case Nd.OUTSIDE:
      n2.B2E.push(o3);
  }
  return n2;
}
function ip(t48, e2) {
  let n2 = new qu(), [o2, i2] = Ou(t48, e2), r2 = Ru(t48, e2), s2 = Tu(t48, e2), a2 = Tu(e2, t48), [c2, l2] = Eu(t48, e2), h2 = Au(t48, e2), d2 = Au(e2, t48);
  return n2.I2I = r2.isEmpty() ? [] : [r2], n2.I2B = l2, n2.I2E = s2.isEmpty() ? [] : [s2], n2.B2I = c2, n2.B2B = o2, n2.B2E = h2, n2.E2I = a2.isEmpty() ? [] : [a2], n2.E2B = d2, n2;
}
var rp = Object.freeze({ __proto__: null, contain: function(t48, e2) {
  return Qu(e2, t48);
}, cover: ep, covered: tp, disjoint: function(t48, e2) {
  return !Ku(t48, e2);
}, equal: function(t48, e2) {
  return np(t48, e2).equal();
}, inside: Qu, intersect: Ku, relate: np, touch: function(t48, e2) {
  return np(t48, e2).touch();
} });
var sp = class t4 {
  constructor(t48 = 1, e2 = 0, n2 = 0, o2 = 1, i2 = 0, r2 = 0) {
    this.a = t48, this.b = e2, this.c = n2, this.d = o2, this.tx = i2, this.ty = r2;
  }
  fromMatrix3x3(e2) {
    const [n2, o2, i2] = e2[0], [r2, s2, a2] = e2[1];
    return new t4(n2, r2, o2, s2, i2, a2);
  }
  toMatrix3x3() {
    return [[this.a, this.c, this.tx], [this.b, this.d, this.ty], [0, 0, 1]];
  }
  clone() {
    return new t4(this.a, this.b, this.c, this.d, this.tx, this.ty);
  }
  transform(t48) {
    return [t48[0] * this.a + t48[1] * this.c + this.tx, t48[0] * this.b + t48[1] * this.d + this.ty];
  }
  multiply(e2) {
    return new t4(this.a * e2.a + this.c * e2.b, this.b * e2.a + this.d * e2.b, this.a * e2.c + this.c * e2.d, this.b * e2.c + this.d * e2.d, this.a * e2.tx + this.c * e2.ty + this.tx, this.b * e2.tx + this.d * e2.ty + this.ty);
  }
  translate(...e2) {
    let n2, o2;
    if (1 != e2.length || isNaN(e2[0].x) || isNaN(e2[0].y)) {
      if (2 !== e2.length || "number" != typeof e2[0] || "number" != typeof e2[1]) throw wd.ILLEGAL_PARAMETERS;
      n2 = e2[0], o2 = e2[1];
    } else n2 = e2[0].x, o2 = e2[0].y;
    return this.multiply(new t4(1, 0, 0, 1, n2, o2));
  }
  rotate(e2, n2 = 0, o2 = 0) {
    let i2 = Math.cos(e2), r2 = Math.sin(e2);
    return this.translate(n2, o2).multiply(new t4(i2, r2, -r2, i2, 0, 0)).translate(-n2, -o2);
  }
  scale(e2, n2) {
    return this.multiply(new t4(e2, 0, 0, n2, 0, 0));
  }
  equalTo(t48) {
    return !!Nd.Utils.EQ(this.tx, t48.tx) && (!!Nd.Utils.EQ(this.ty, t48.ty) && (!!Nd.Utils.EQ(this.a, t48.a) && (!!Nd.Utils.EQ(this.b, t48.b) && (!!Nd.Utils.EQ(this.c, t48.c) && !!Nd.Utils.EQ(this.d, t48.d)))));
  }
};
Nd.Matrix = sp;
Nd.matrix = (...t48) => new Nd.Matrix(...t48);
var ap = class {
  constructor(t48, e2) {
    this.low = t48, this.high = e2;
  }
  get max() {
    return this.clone();
  }
  less_than(t48) {
    return this.low < t48.low || this.low === t48.low && this.high < t48.high;
  }
  equal_to(t48) {
    return this.low === t48.low && this.high === t48.high;
  }
  intersect(t48) {
    return !this.not_intersect(t48);
  }
  not_intersect(t48) {
    return this.high < t48.low || t48.high < this.low;
  }
  merge(t48) {
    const e2 = void 0 === this.low ? t48.low : this.low < t48.low ? this.low : t48.low, n2 = void 0 === this.high ? t48.high : this.high > t48.high ? this.high : t48.high, o2 = this.clone();
    return o2.low = e2, o2.high = n2, o2;
  }
  output() {
    return [this.low, this.high];
  }
  comparable_less_than(t48, e2) {
    return t48 < e2;
  }
};
var cp = class t5 extends ap {
  clone() {
    return new t5(this.low, this.high);
  }
};
var lp = class {
  constructor(t48, e2, n2 = null, o2 = null, i2 = null, r2 = 0) {
    if (this.left = n2, this.right = o2, this.parent = i2, this.color = r2, this.item = { key: void 0, values: [] }, void 0 !== e2 && this.item.values.push(e2), void 0 !== t48) if (Array.isArray(t48)) {
      const [e3, n3] = t48;
      if (!Number.isNaN(e3) && !Number.isNaN(n3)) {
        let t49 = e3, o3 = n3;
        t49 > o3 && ([t49, o3] = [o3, t49]), this.item.key = new cp(t49, o3);
      }
    } else this.item.key = t48;
    this.max = this.item.key ? this.item.key.max : void 0;
  }
  isNil() {
    return void 0 === this.item.key && 0 === this.item.values.length && null === this.left && null === this.right && 0 === this.color;
  }
  requireKey() {
    if (!this.item.key) throw new Error("Node key is undefined (nil/sentinel). Operation is not applicable.");
    return this.item.key;
  }
  less_than(t48) {
    const e2 = this.requireKey(), n2 = t48.requireKey();
    return e2.less_than(n2);
  }
  _value_equal(t48) {
    const e2 = this.item.values[0], n2 = t48.item.values[0];
    return e2 && n2 && e2.equal_to ? e2.equal_to(n2) : e2 === n2;
  }
  equal_to(t48) {
    const e2 = this.requireKey(), n2 = t48.requireKey();
    return e2.equal_to(n2);
  }
  intersect(t48) {
    const e2 = this.requireKey(), n2 = t48.requireKey();
    return e2.intersect(n2);
  }
  copy_data(t48) {
    this.item.key = t48.item.key, this.item.values = t48.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(t48) {
    if (!this.left) return true;
    const e2 = this.left.max ? this.left.max.high : this.left.item.key.high, n2 = this.requireKey(), o2 = t48.requireKey();
    return n2.comparable_less_than(e2, o2.low);
  }
  not_intersect_right_subtree(t48) {
    if (!this.right) return true;
    const e2 = this.right.max ? this.right.max.low : this.right.item.key.low, n2 = this.requireKey(), o2 = t48.requireKey();
    return n2.comparable_less_than(o2.high, e2);
  }
};
var hp = class t6 {
  constructor() {
    this.root = null, this.nil_node = new lp();
  }
  get size() {
    let t48 = 0;
    return this.tree_walk(this.root, (e2) => t48 += e2.item.values.length), t48;
  }
  get keys() {
    const t48 = [];
    return this.tree_walk(this.root, (e2) => t48.push(e2.item.key.output())), t48;
  }
  get values() {
    const t48 = [];
    return this.tree_walk(this.root, (e2) => {
      for (const n2 of e2.item.values) t48.push(n2);
    }), t48;
  }
  get items() {
    const t48 = [];
    return this.tree_walk(this.root, (e2) => {
      const n2 = e2.item.key.output();
      for (const o2 of e2.item.values) t48.push({ key: n2, value: o2 });
    }), t48;
  }
  isEmpty() {
    return null == this.root || this.root === this.nil_node;
  }
  clear() {
    this.root = null;
  }
  insert(t48, e2 = t48) {
    if (void 0 === t48) return;
    const n2 = this.tree_search(this.root, new lp(t48));
    if (n2) return n2.item.values.push(e2), n2;
    const o2 = new lp(t48, e2, this.nil_node, this.nil_node, null, 1);
    return this.tree_insert(o2), this.recalc_max(o2), o2;
  }
  exist(t48, e2 = t48) {
    const n2 = this.tree_search(this.root, new lp(t48));
    return !!n2 && (arguments.length < 2 || e2 === t48 || n2.item.values.some((t49) => t49 && t49.equal_to ? t49.equal_to(e2) : t49 === e2));
  }
  remove(t48, e2 = t48) {
    const n2 = this.tree_search(this.root, new lp(t48));
    if (!n2) return;
    if (arguments.length < 2) return this.tree_delete(n2), n2;
    const o2 = n2.item.values.findIndex((t49) => t49 && t49.equal_to ? t49.equal_to(e2) : t49 === e2);
    return o2 >= 0 ? (n2.item.values.splice(o2, 1), 0 === n2.item.values.length && this.tree_delete(n2), n2) : void 0;
  }
  search(t48, e2 = (t49, e3) => t49 === e3 ? e3.output() : t49) {
    const n2 = new lp(t48), o2 = [];
    this.tree_search_interval(this.root, n2, o2);
    const i2 = [];
    for (const t49 of o2) for (const n3 of t49.item.values) i2.push(e2(n3, t49.item.key));
    return i2;
  }
  intersect_any(t48) {
    const e2 = new lp(t48);
    return this.tree_find_any_interval(this.root, e2);
  }
  forEach(t48) {
    this.tree_walk(this.root, (e2) => {
      for (const n2 of e2.item.values) t48(e2.item.key, n2);
    });
  }
  map(e2) {
    const n2 = new t6();
    return this.tree_walk(this.root, (t48) => {
      for (const o2 of t48.item.values) n2.insert(t48.item.key, e2(o2, t48.item.key));
    }), n2;
  }
  *iterate(t48, e2 = (t49, e3) => t49 === e3 ? e3.output() : t49) {
    let n2 = null;
    for (t48 ? n2 = this.tree_search_nearest_forward(this.root, new lp(t48)) : this.root && (n2 = this.local_minimum(this.root)); n2; ) {
      for (const t49 of n2.item.values) yield e2(t49, n2.item.key);
      n2 = this.tree_successor(n2);
    }
  }
  recalc_max(t48) {
    let e2 = t48;
    for (; null != e2.parent; ) e2.parent.update_max(), e2 = e2.parent;
  }
  tree_insert(t48) {
    let e2 = this.root, n2 = null;
    if (null == this.root || this.root === this.nil_node) this.root = t48;
    else {
      for (; e2 !== this.nil_node; ) n2 = e2, e2 = t48.less_than(e2) ? e2.left : e2.right;
      t48.parent = n2, t48.less_than(n2) ? n2.left = t48 : n2.right = t48;
    }
    this.insert_fixup(t48);
  }
  insert_fixup(t48) {
    let e2, n2;
    for (e2 = t48; e2 !== this.root && 1 === e2.parent.color; ) e2.parent === e2.parent.parent.left ? (n2 = e2.parent.parent.right, 1 === n2.color ? (e2.parent.color = 0, n2.color = 0, e2.parent.parent.color = 1, e2 = e2.parent.parent) : (e2 === e2.parent.right && (e2 = e2.parent, this.rotate_left(e2)), e2.parent.color = 0, e2.parent.parent.color = 1, this.rotate_right(e2.parent.parent))) : (n2 = e2.parent.parent.left, 1 === n2.color ? (e2.parent.color = 0, n2.color = 0, e2.parent.parent.color = 1, e2 = e2.parent.parent) : (e2 === e2.parent.left && (e2 = e2.parent, this.rotate_right(e2)), e2.parent.color = 0, e2.parent.parent.color = 1, this.rotate_left(e2.parent.parent)));
    this.root.color = 0;
  }
  tree_delete(t48) {
    let e2, n2;
    e2 = t48.left === this.nil_node || t48.right === this.nil_node ? t48 : this.tree_successor(t48), n2 = e2.left !== this.nil_node ? e2.left : e2.right, n2.parent = e2.parent, e2 === this.root ? this.root = n2 : (e2 === e2.parent.left ? e2.parent.left = n2 : e2.parent.right = n2, e2.parent.update_max()), this.recalc_max(n2), e2 !== t48 && (t48.copy_data(e2), t48.update_max(), this.recalc_max(t48)), 0 === e2.color && this.delete_fixup(n2);
  }
  delete_fixup(t48) {
    let e2, n2 = t48;
    for (; n2 !== this.root && null != n2.parent && 0 === n2.color; ) n2 === n2.parent.left ? (e2 = n2.parent.right, 1 === e2.color && (e2.color = 0, n2.parent.color = 1, this.rotate_left(n2.parent), e2 = n2.parent.right), 0 === e2.left.color && 0 === e2.right.color ? (e2.color = 1, n2 = n2.parent) : (0 === e2.right.color && (e2.color = 1, e2.left.color = 0, this.rotate_right(e2), e2 = n2.parent.right), e2.color = n2.parent.color, n2.parent.color = 0, e2.right.color = 0, this.rotate_left(n2.parent), n2 = this.root)) : (e2 = n2.parent.left, 1 === e2.color && (e2.color = 0, n2.parent.color = 1, this.rotate_right(n2.parent), e2 = n2.parent.left), 0 === e2.left.color && 0 === e2.right.color ? (e2.color = 1, n2 = n2.parent) : (0 === e2.left.color && (e2.color = 1, e2.right.color = 0, this.rotate_left(e2), e2 = n2.parent.left), e2.color = n2.parent.color, n2.parent.color = 0, e2.left.color = 0, this.rotate_right(n2.parent), n2 = this.root));
    n2.color = 0;
  }
  tree_search(t48, e2) {
    if (null != t48 && t48 !== this.nil_node) return e2.equal_to(t48) ? t48 : e2.less_than(t48) ? this.tree_search(t48.left, e2) : this.tree_search(t48.right, e2);
  }
  tree_search_nearest_forward(t48, e2) {
    let n2 = null, o2 = t48;
    for (; o2 && o2 !== this.nil_node; ) o2.less_than(e2) ? o2.intersect(e2) ? (n2 = o2, o2 = o2.left) : o2 = o2.right : (n2 && !o2.less_than(n2) || (n2 = o2), o2 = o2.left);
    return n2 || null;
  }
  tree_search_interval(t48, e2, n2) {
    null != t48 && t48 !== this.nil_node && (t48.left === this.nil_node || t48.not_intersect_left_subtree(e2) || this.tree_search_interval(t48.left, e2, n2), t48.intersect(e2) && n2.push(t48), t48.right === this.nil_node || t48.not_intersect_right_subtree(e2) || this.tree_search_interval(t48.right, e2, n2));
  }
  tree_find_any_interval(t48, e2) {
    let n2 = false;
    return null != t48 && t48 !== this.nil_node && (t48.left === this.nil_node || t48.not_intersect_left_subtree(e2) || (n2 = this.tree_find_any_interval(t48.left, e2)), n2 || (n2 = t48.intersect(e2)), n2 || t48.right === this.nil_node || t48.not_intersect_right_subtree(e2) || (n2 = this.tree_find_any_interval(t48.right, e2))), n2;
  }
  local_minimum(t48) {
    let e2 = t48;
    for (; null != e2.left && e2.left !== this.nil_node; ) e2 = e2.left;
    return e2;
  }
  local_maximum(t48) {
    let e2 = t48;
    for (; null != e2.right && e2.right !== this.nil_node; ) e2 = e2.right;
    return e2;
  }
  tree_successor(t48) {
    let e2, n2, o2;
    if (t48.right !== this.nil_node) e2 = this.local_minimum(t48.right);
    else {
      for (n2 = t48, o2 = t48.parent; null != o2 && o2.right === n2; ) n2 = o2, o2 = o2.parent;
      e2 = o2;
    }
    return e2;
  }
  rotate_left(t48) {
    const e2 = t48.right;
    t48.right = e2.left, e2.left !== this.nil_node && (e2.left.parent = t48), e2.parent = t48.parent, t48 === this.root ? this.root = e2 : t48 === t48.parent.left ? t48.parent.left = e2 : t48.parent.right = e2, e2.left = t48, t48.parent = e2, null !== t48 && t48 !== this.nil_node && t48.update_max(), null != e2 && e2 !== this.nil_node && e2.update_max();
  }
  rotate_right(t48) {
    const e2 = t48.left;
    t48.left = e2.right, e2.right !== this.nil_node && (e2.right.parent = t48), e2.parent = t48.parent, t48 === this.root ? this.root = e2 : t48 === t48.parent.left ? t48.parent.left = e2 : t48.parent.right = e2, e2.right = t48, t48.parent = e2, null !== t48 && t48 !== this.nil_node && t48.update_max(), null != e2 && e2 !== this.nil_node && e2.update_max();
  }
  tree_walk(t48, e2) {
    null != t48 && t48 !== this.nil_node && (this.tree_walk(t48.left, e2), e2(t48), this.tree_walk(t48.right, e2));
  }
  testRedBlackProperty() {
    let t48 = true;
    return this.tree_walk(this.root, function(e2) {
      1 === e2.color && (0 === e2.left.color && 0 === e2.right.color || (t48 = false));
    }), t48;
  }
  testBlackHeightProperty(t48) {
    let e2 = 0, n2 = 0, o2 = 0;
    if (0 === t48.color && e2++, n2 = t48.left !== this.nil_node ? this.testBlackHeightProperty(t48.left) : 1, o2 = t48.right !== this.nil_node ? this.testBlackHeightProperty(t48.right) : 1, n2 !== o2) throw new Error("Red-black height property violated");
    return e2 += n2, e2;
  }
};
var dp = class extends Set {
  constructor(t48) {
    super(t48), this.index = new hp(), this.forEach((t49) => this.index.insert(t49));
  }
  add(t48) {
    let e2 = this.size;
    const { key: n2, value: o2 } = t48, i2 = n2 || t48.box, r2 = o2 || t48;
    return super.add(r2), this.size > e2 && this.index.insert(i2, r2), this;
  }
  delete(t48) {
    const { key: e2, value: n2 } = t48, o2 = e2 || t48.box, i2 = n2 || t48;
    let r2 = super.delete(i2);
    return r2 && this.index.remove(o2, i2), r2;
  }
  clear() {
    super.clear(), this.index = new hp();
  }
  search(t48) {
    return this.index.search(t48);
  }
  hit(t48) {
    let e2 = new Nd.Box(t48.x - 1, t48.y - 1, t48.x + 1, t48.y + 1);
    return this.index.search(e2).filter((e3) => t48.on(e3));
  }
  svg() {
    return [...this].reduce((t48, e2) => t48 + e2.svg(), "");
  }
};
Nd.PlanarSet = dp;
var up = class {
  get name() {
    throw wd.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  get box() {
    throw wd.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  clone() {
    throw wd.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  translate(...t48) {
    return this.transform(new sp().translate(...t48));
  }
  rotate(t48, e2 = new Nd.Point()) {
    return this.transform(new sp().rotate(t48, e2.x, e2.y));
  }
  scale(t48, e2) {
    return this.transform(new sp().scale(t48, e2));
  }
  transform(...t48) {
    throw wd.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  toJSON() {
    return Object.assign({}, this, { name: this.name });
  }
  svg(t48 = {}) {
    throw wd.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
};
Nd.Point = class t7 extends up {
  constructor(...t48) {
    if (super(), this.x = 0, this.y = 0, 0 !== t48.length) {
      if (1 === t48.length && t48[0] instanceof Array && 2 === t48[0].length) {
        let e2 = t48[0];
        if ("number" == typeof e2[0] && "number" == typeof e2[1]) return this.x = e2[0], void (this.y = e2[1]);
      }
      if (1 === t48.length && t48[0] instanceof Object && "point" === t48[0].name) {
        let { x: e2, y: n2 } = t48[0];
        return this.x = e2, void (this.y = n2);
      }
      if (2 === t48.length && "number" == typeof t48[0] && "number" == typeof t48[1]) return this.x = t48[0], void (this.y = t48[1]);
      throw wd.ILLEGAL_PARAMETERS;
    }
  }
  get box() {
    return new Nd.Box(this.x, this.y, this.x, this.y);
  }
  clone() {
    return new Nd.Point(this.x, this.y);
  }
  get vertices() {
    return [this.clone()];
  }
  equalTo(t48) {
    return Nd.Utils.EQ(this.x, t48.x) && Nd.Utils.EQ(this.y, t48.y);
  }
  lessThan(t48) {
    return !!Nd.Utils.LT(this.y, t48.y) || !(!Nd.Utils.EQ(this.y, t48.y) || !Nd.Utils.LT(this.x, t48.x));
  }
  transform(t48) {
    return new Nd.Point(t48.transform([this.x, this.y]));
  }
  projectionOn(t48) {
    if (this.equalTo(t48.pt)) return this.clone();
    let e2 = new Nd.Vector(this, t48.pt);
    if (Nd.Utils.EQ_0(e2.cross(t48.norm))) return t48.pt.clone();
    let n2 = e2.dot(t48.norm), o2 = t48.norm.multiply(n2);
    return this.translate(o2);
  }
  leftTo(t48) {
    let e2 = new Nd.Vector(t48.pt, this);
    return Nd.Utils.GT(e2.dot(t48.norm), 0);
  }
  distanceTo(e2) {
    if (e2 instanceof t7) {
      let t48 = e2.x - this.x, n2 = e2.y - this.y;
      return [Math.sqrt(t48 * t48 + n2 * n2), new Nd.Segment(this, e2)];
    }
    return e2 instanceof Nd.Line ? Nd.Distance.point2line(this, e2) : e2 instanceof Nd.Circle ? Nd.Distance.point2circle(this, e2) : e2 instanceof Nd.Segment ? Nd.Distance.point2segment(this, e2) : e2 instanceof Nd.Arc ? Nd.Distance.point2arc(this, e2) : e2 instanceof Nd.Polygon ? Nd.Distance.point2polygon(this, e2) : e2 instanceof Nd.PlanarSet ? Nd.Distance.shape2planarSet(this, e2) : e2 instanceof Nd.Multiline ? Nd.Distance.shape2multiline(this, e2) : void 0;
  }
  on(t48) {
    if (t48 instanceof Nd.Point) return this.equalTo(t48);
    if (t48.contains && t48.contains instanceof Function) return t48.contains(this);
    throw Nd.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  get name() {
    return "point";
  }
  svg(t48 = {}) {
    const e2 = t48.r ?? 3;
    return `
<circle cx="${this.x}" cy="${this.y}" r="${e2}"
            ${Ad({ fill: "red", ...t48 })} />`;
  }
};
Nd.point = (...t48) => new Nd.Point(...t48);
Nd.Vector = class extends up {
  constructor(...t48) {
    if (super(), this.x = 0, this.y = 0, 0 !== t48.length) {
      if (1 === t48.length && t48[0] instanceof Array && 2 === t48[0].length) {
        let e2 = t48[0];
        if ("number" == typeof e2[0] && "number" == typeof e2[1]) return this.x = e2[0], void (this.y = e2[1]);
      }
      if (1 === t48.length && t48[0] instanceof Object && "vector" === t48[0].name) {
        let { x: e2, y: n2 } = t48[0];
        return this.x = e2, void (this.y = n2);
      }
      if (1 === t48.length && t48[0] instanceof Object && "segment" === t48[0].name) {
        let { start: e2, end: n2 } = t48[0];
        return this.x = n2.x - e2.x, void (this.y = n2.y - e2.y);
      }
      if (2 === t48.length) {
        let e2 = t48[0], n2 = t48[1];
        if ("number" == typeof e2 && "number" == typeof n2) return this.x = e2, void (this.y = n2);
        if (e2 instanceof Nd.Point && n2 instanceof Nd.Point) return this.x = n2.x - e2.x, void (this.y = n2.y - e2.y);
      }
      throw wd.ILLEGAL_PARAMETERS;
    }
  }
  clone() {
    return new Nd.Vector(this.x, this.y);
  }
  get slope() {
    let t48 = Math.atan2(this.y, this.x);
    return t48 < 0 && (t48 = 2 * Math.PI + t48), t48;
  }
  get length() {
    return Math.sqrt(this.dot(this));
  }
  isZeroLength() {
    return Nd.Utils.EQ_0(this.length);
  }
  equalTo(t48) {
    return Nd.Utils.EQ(this.x, t48.x) && Nd.Utils.EQ(this.y, t48.y);
  }
  multiply(t48) {
    return new Nd.Vector(t48 * this.x, t48 * this.y);
  }
  dot(t48) {
    return this.x * t48.x + this.y * t48.y;
  }
  cross(t48) {
    return this.x * t48.y - this.y * t48.x;
  }
  normalize() {
    if (this.isZeroLength()) throw wd.ZERO_DIVISION;
    return new Nd.Vector(this.x / this.length, this.y / this.length);
  }
  rotate(t48, e2 = new Nd.Point()) {
    if (0 === e2.x && 0 === e2.y) return this.transform(new sp().rotate(t48));
    throw wd.OPERATION_IS_NOT_SUPPORTED;
  }
  transform(t48) {
    return new Nd.Vector(t48.transform([this.x, this.y]));
  }
  rotate90CCW() {
    return new Nd.Vector(-this.y, this.x);
  }
  rotate90CW() {
    return new Nd.Vector(this.y, -this.x);
  }
  invert() {
    return new Nd.Vector(-this.x, -this.y);
  }
  add(t48) {
    return new Nd.Vector(this.x + t48.x, this.y + t48.y);
  }
  subtract(t48) {
    return new Nd.Vector(this.x - t48.x, this.y - t48.y);
  }
  angleTo(t48) {
    let e2 = this.normalize(), n2 = t48.normalize(), o2 = Math.atan2(e2.cross(n2), e2.dot(n2));
    return o2 < 0 && (o2 += 2 * Math.PI), o2;
  }
  projectionOn(t48) {
    let e2 = t48.normalize(), n2 = this.dot(e2);
    return e2.multiply(n2);
  }
  get name() {
    return "vector";
  }
};
var pp = (...t48) => new Nd.Vector(...t48);
Nd.vector = pp;
Nd.Segment = class t8 extends up {
  constructor(...t48) {
    if (super(), this.ps = new Nd.Point(), this.pe = new Nd.Point(), 0 !== t48.length) {
      if (1 === t48.length && t48[0] instanceof Array && 4 === t48[0].length) {
        let e2 = t48[0];
        return this.ps = new Nd.Point(e2[0], e2[1]), void (this.pe = new Nd.Point(e2[2], e2[3]));
      }
      if (1 === t48.length && t48[0] instanceof Object && "segment" === t48[0].name) {
        let { ps: e2, pe: n2 } = t48[0];
        return this.ps = new Nd.Point(e2.x, e2.y), void (this.pe = new Nd.Point(n2.x, n2.y));
      }
      if (!(1 === t48.length && t48[0] instanceof Nd.Point)) {
        if (2 === t48.length && t48[0] instanceof Nd.Point && t48[1] instanceof Nd.Point) return this.ps = t48[0].clone(), void (this.pe = t48[1].clone());
        if (4 === t48.length) return this.ps = new Nd.Point(t48[0], t48[1]), void (this.pe = new Nd.Point(t48[2], t48[3]));
        throw wd.ILLEGAL_PARAMETERS;
      }
      this.ps = t48[0].clone();
    }
  }
  clone() {
    return new Nd.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 Nd.Vector(this.start, this.end).slope;
  }
  get box() {
    return new Nd.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(t48) {
    return this.ps.equalTo(t48.ps) && this.pe.equalTo(t48.pe);
  }
  contains(t48) {
    return Nd.Utils.EQ_0(this.distanceToPoint(t48));
  }
  intersect(t48) {
    return t48 instanceof Nd.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof Nd.Line ? kd(this, t48) : t48 instanceof Nd.Ray ? ou(t48, this) : t48 instanceof Nd.Segment ? Fd(this, t48) : t48 instanceof Nd.Circle ? Yd(this, t48) : t48 instanceof Nd.Box ? (function(t49, e2) {
      let n2 = [];
      for (let o2 of e2.toSegments()) {
        let e3 = Fd(o2, t49);
        for (let t50 of e3) n2.push(t50);
      }
      return n2;
    })(this, t48) : t48 instanceof Nd.Arc ? $d(this, t48) : t48 instanceof Nd.Polygon ? Zd(this, t48) : t48 instanceof Nd.Multiline ? lu(this, t48) : void 0;
  }
  distanceTo(t48) {
    if (t48 instanceof Nd.Point) {
      let [e2, n2] = Nd.Distance.point2segment(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Circle) {
      let [e2, n2] = Nd.Distance.segment2circle(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Line) {
      let [e2, n2] = Nd.Distance.segment2line(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Segment) {
      let [e2, n2] = Nd.Distance.segment2segment(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Arc) {
      let [e2, n2] = Nd.Distance.segment2arc(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Polygon) {
      let [e2, n2] = Nd.Distance.shape2polygon(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.PlanarSet) {
      let [e2, n2] = Nd.Distance.shape2planarSet(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Multiline) return Nd.Distance.shape2multiline(this, t48);
  }
  tangentInStart() {
    return new Nd.Vector(this.start, this.end).normalize();
  }
  tangentInEnd() {
    return new Nd.Vector(this.end, this.start).normalize();
  }
  reverse() {
    return new t8(this.end, this.start);
  }
  split(t48) {
    return this.start.equalTo(t48) ? [null, this.clone()] : this.end.equalTo(t48) ? [this.clone(), null] : [new Nd.Segment(this.start, t48), new Nd.Segment(t48, this.end)];
  }
  middle() {
    return new Nd.Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);
  }
  pointAtLength(t48) {
    if (t48 > this.length || t48 < 0) return null;
    if (0 == t48) return this.start;
    if (t48 == this.length) return this.end;
    let e2 = t48 / this.length;
    return new Nd.Point((this.end.x - this.start.x) * e2 + this.start.x, (this.end.y - this.start.y) * e2 + this.start.y);
  }
  distanceToPoint(t48) {
    let [e2, ...n2] = Nd.Distance.point2segment(t48, this);
    return e2;
  }
  definiteIntegral(t48 = 0) {
    return (this.end.x - this.start.x) * (this.start.y - t48 + (this.end.y - t48)) / 2;
  }
  transform(e2 = new Nd.Matrix()) {
    return new t8(this.ps.transform(e2), this.pe.transform(e2));
  }
  isZeroLength() {
    return this.ps.equalTo(this.pe);
  }
  sortPoints(t48) {
    return new Nd.Line(this.start, this.end).sortPoints(t48);
  }
  get name() {
    return "segment";
  }
  svg(t48 = {}) {
    return `
<line x1="${this.start.x}" y1="${this.start.y}" x2="${this.end.x}" y2="${this.end.y}" ${Ad(t48)} />`;
  }
};
Nd.segment = (...t48) => new Nd.Segment(...t48);
var { vector: mp } = Nd;
Nd.Line = class t9 extends up {
  constructor(...e2) {
    if (super(), this.pt = new Nd.Point(), this.norm = new Nd.Vector(0, 1), 0 !== e2.length) {
      if (1 === e2.length && e2[0] instanceof Object && "line" === e2[0].name) {
        let { pt: t48, norm: n2 } = e2[0];
        return this.pt = new Nd.Point(t48), void (this.norm = new Nd.Vector(n2));
      }
      if (2 === e2.length) {
        let n2 = e2[0], o2 = e2[1];
        if (n2 instanceof Nd.Point && o2 instanceof Nd.Point) return this.pt = n2, this.norm = t9.points2norm(n2, o2), void (this.norm.dot(mp(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        if (n2 instanceof Nd.Point && o2 instanceof Nd.Vector) {
          if (Nd.Utils.EQ_0(o2.x) && Nd.Utils.EQ_0(o2.y)) throw wd.ILLEGAL_PARAMETERS;
          return this.pt = n2.clone(), this.norm = o2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(mp(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        }
        if (n2 instanceof Nd.Vector && o2 instanceof Nd.Point) {
          if (Nd.Utils.EQ_0(n2.x) && Nd.Utils.EQ_0(n2.y)) throw wd.ILLEGAL_PARAMETERS;
          return this.pt = o2.clone(), this.norm = n2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(mp(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        }
      }
      throw wd.ILLEGAL_PARAMETERS;
    }
  }
  clone() {
    return new Nd.Line(this.pt, this.norm);
  }
  get start() {
  }
  get end() {
  }
  get length() {
    return Number.POSITIVE_INFINITY;
  }
  get box() {
    return new Nd.Box(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
  }
  get middle() {
  }
  get slope() {
    return new Nd.Vector(this.norm.y, -this.norm.x).slope;
  }
  get standard() {
    return [this.norm.x, this.norm.y, this.norm.dot(mp(this.pt.x, this.pt.y))];
  }
  parallelTo(t48) {
    return Nd.Utils.EQ_0(this.norm.cross(t48.norm));
  }
  incidentTo(t48) {
    return this.parallelTo(t48) && this.pt.on(t48);
  }
  contains(t48) {
    if (this.pt.equalTo(t48)) return true;
    let e2 = new Nd.Vector(this.pt, t48);
    return Nd.Utils.EQ_0(this.norm.dot(e2));
  }
  coord(t48) {
    return mp(t48.x, t48.y).cross(this.norm);
  }
  intersect(t48) {
    return t48 instanceof Nd.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof Nd.Line ? Od(this, t48) : t48 instanceof Nd.Ray ? su(t48, this) : t48 instanceof Nd.Circle ? Ld(this, t48) : t48 instanceof Nd.Box ? Dd(this, t48) : t48 instanceof Nd.Segment ? kd(t48, this) : t48 instanceof Nd.Arc ? zd(this, t48) : t48 instanceof Nd.Polygon ? Jd(this, t48) : t48 instanceof Nd.Multiline ? lu(this, t48) : void 0;
  }
  distanceTo(t48) {
    if (t48 instanceof Nd.Point) {
      let [e2, n2] = Nd.Distance.point2line(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Circle) {
      let [e2, n2] = Nd.Distance.circle2line(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Segment) {
      let [e2, n2] = Nd.Distance.segment2line(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof Nd.Arc) {
      let [e2, n2] = Nd.Distance.arc2line(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof Nd.Polygon) {
      let [e2, n2] = Nd.Distance.shape2polygon(this, t48);
      return [e2, n2];
    }
  }
  split(t48) {
    if (t48 instanceof Nd.Point) return [new Nd.Ray(t48, this.norm), new Nd.Ray(t48, this.norm)];
    {
      let e2 = new Nd.Multiline([this]), n2 = this.sortPoints(t48);
      return e2.split(n2), e2.toShapes();
    }
  }
  rotate(t48, e2 = new Nd.Point()) {
    return new Nd.Line(this.pt.rotate(t48, e2), this.norm.rotate(t48));
  }
  transform(t48) {
    return new Nd.Line(this.pt.transform(t48), this.norm.clone());
  }
  sortPoints(t48) {
    return t48.slice().sort((t49, e2) => this.coord(t49) < this.coord(e2) ? -1 : this.coord(t49) > this.coord(e2) ? 1 : 0);
  }
  get name() {
    return "line";
  }
  svg(t48, e2 = {}) {
    let n2 = Dd(this, t48);
    if (0 === n2.length) return "";
    let o2 = n2[0], i2 = 2 === n2.length ? n2[1] : n2.find((t49) => !t49.equalTo(o2));
    return void 0 === i2 && (i2 = o2), new Nd.Segment(o2, i2).svg(e2);
  }
  static points2norm(t48, e2) {
    if (t48.equalTo(e2)) throw wd.ILLEGAL_PARAMETERS;
    return new Nd.Vector(t48, e2).normalize().rotate90CCW();
  }
};
Nd.line = (...t48) => new Nd.Line(...t48);
Nd.Circle = class extends up {
  constructor(...t48) {
    if (super(), this.pc = new Nd.Point(), this.r = 1, 1 === t48.length && t48[0] instanceof Object && "circle" === t48[0].name) {
      let { pc: e2, r: n2 } = t48[0];
      this.pc = new Nd.Point(e2), this.r = n2;
    } else {
      let [e2, n2] = [...t48];
      e2 && e2 instanceof Nd.Point && (this.pc = e2.clone()), void 0 !== n2 && (this.r = n2);
    }
  }
  clone() {
    return new Nd.Circle(this.pc.clone(), this.r);
  }
  get center() {
    return this.pc;
  }
  get box() {
    return new Nd.Box(this.pc.x - this.r, this.pc.y - this.r, this.pc.x + this.r, this.pc.y + this.r);
  }
  contains(t48) {
    return t48 instanceof Nd.Point ? Nd.Utils.LE(t48.distanceTo(this.center)[0], this.r) : t48 instanceof Nd.Segment ? Nd.Utils.LE(t48.start.distanceTo(this.center)[0], this.r) && Nd.Utils.LE(t48.end.distanceTo(this.center)[0], this.r) : t48 instanceof Nd.Arc ? 0 === this.intersect(t48).length && Nd.Utils.LE(t48.start.distanceTo(this.center)[0], this.r) && Nd.Utils.LE(t48.end.distanceTo(this.center)[0], this.r) : t48 instanceof Nd.Circle ? 0 === this.intersect(t48).length && Nd.Utils.LE(t48.r, this.r) && Nd.Utils.LE(t48.center.distanceTo(this.center)[0], this.r) : void 0;
  }
  toArc(t48 = true) {
    return new Nd.Arc(this.center, this.r, Math.PI, -Math.PI, t48);
  }
  scale(t48, e2) {
    if (t48 !== e2) throw wd.OPERATION_IS_NOT_SUPPORTED;
    if (0 !== this.pc.x || 0 !== this.pc.y) throw wd.OPERATION_IS_NOT_SUPPORTED;
    return new Nd.Circle(this.pc, this.r * t48);
  }
  transform(t48 = new Nd.Matrix()) {
    return new Nd.Circle(this.pc.transform(t48), this.r);
  }
  intersect(t48) {
    return t48 instanceof Nd.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof Nd.Line ? Ld(t48, this) : t48 instanceof Nd.Ray ? ru(t48, this) : t48 instanceof Nd.Segment ? Yd(t48, this) : t48 instanceof Nd.Circle ? Xd(t48, this) : t48 instanceof Nd.Box ? (function(t49, e2) {
      let n2 = [];
      for (let o2 of e2.toSegments()) {
        let e3 = Yd(o2, t49);
        for (let t50 of e3) n2.push(t50);
      }
      return n2;
    })(this, t48) : t48 instanceof Nd.Arc ? Hd(t48, this) : t48 instanceof Nd.Polygon ? Kd(this, t48) : t48 instanceof Nd.Multiline ? lu(this, t48) : void 0;
  }
  distanceTo(t48) {
    if (t48 instanceof Nd.Point) {
      let [e2, n2] = Nd.Distance.point2circle(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Circle) {
      let [e2, n2] = Nd.Distance.circle2circle(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Line) {
      let [e2, n2] = Nd.Distance.circle2line(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Segment) {
      let [e2, n2] = Nd.Distance.segment2circle(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Arc) {
      let [e2, n2] = Nd.Distance.arc2circle(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Polygon) {
      let [e2, n2] = Nd.Distance.shape2polygon(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.PlanarSet) {
      let [e2, n2] = Nd.Distance.shape2planarSet(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Multiline) {
      let [e2, n2] = Nd.Distance.shape2multiline(this, t48);
      return [e2, n2];
    }
  }
  get name() {
    return "circle";
  }
  svg(t48 = {}) {
    return `
<circle cx="${this.pc.x}" cy="${this.pc.y}" r="${this.r}"
                ${Ad({ fill: "none", ...t48 })} />`;
  }
};
Nd.circle = (...t48) => new Nd.Circle(...t48);
Nd.Arc = class extends up {
  constructor(...t48) {
    if (super(), this.pc = new Nd.Point(), this.r = 1, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.counterClockwise = true, 0 !== t48.length) if (1 === t48.length && t48[0] instanceof Object && "arc" === t48[0].name) {
      let { pc: e2, r: n2, startAngle: o2, endAngle: i2, counterClockwise: r2 } = t48[0];
      this.pc = new Nd.Point(e2.x, e2.y), this.r = n2, this.startAngle = o2, this.endAngle = i2, this.counterClockwise = r2;
    } else {
      let [e2, n2, o2, i2, r2] = [...t48];
      e2 && e2 instanceof Nd.Point && (this.pc = e2.clone()), void 0 !== n2 && (this.r = n2), void 0 !== o2 && (this.startAngle = o2), void 0 !== i2 && (this.endAngle = i2), void 0 !== r2 && (this.counterClockwise = r2);
    }
  }
  clone() {
    return new Nd.Arc(this.pc.clone(), this.r, this.startAngle, this.endAngle, this.counterClockwise);
  }
  get sweep() {
    let t48 = this.startAngle, e2 = this.endAngle;
    if (Nd.Utils.EQ(Math.abs(t48 - e2), Nd.PIx2)) return Nd.PIx2;
    Math.abs(t48) > Nd.PIx2 && (t48 -= Math.trunc(t48 / Nd.PIx2) * Nd.PIx2), t48 < 0 && (t48 += Nd.PIx2), Math.abs(e2) > Nd.PIx2 && (e2 -= Math.trunc(e2 / Nd.PIx2) * Nd.PIx2), e2 < 0 && (e2 += Nd.PIx2);
    let n2 = this.counterClockwise ? e2 - t48 : t48 - e2;
    return n2 < 0 && (n2 += Nd.PIx2), n2;
  }
  get start() {
    return new Nd.Point(this.pc.x + this.r, this.pc.y).rotate(this.startAngle, this.pc);
  }
  get end() {
    return new Nd.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 t48 = this.breakToFunctional().reduce((t49, e2) => t49.merge(e2.start.box), new Nd.Box());
    return t48 = t48.merge(this.end.box), t48;
  }
  contains(t48) {
    if (!Nd.Utils.EQ(this.pc.distanceTo(t48)[0], this.r)) return false;
    if (t48.equalTo(this.start)) return true;
    let e2 = new Nd.Vector(this.pc, t48).slope, n2 = new Nd.Arc(this.pc, this.r, this.startAngle, e2, this.counterClockwise);
    return Nd.Utils.LE(n2.length, this.length);
  }
  split(t48) {
    if (this.start.equalTo(t48)) return [null, this.clone()];
    if (this.end.equalTo(t48)) return [this.clone(), null];
    let e2 = new Nd.Vector(this.pc, t48).slope;
    return [new Nd.Arc(this.pc, this.r, this.startAngle, e2, this.counterClockwise), new Nd.Arc(this.pc, this.r, e2, this.endAngle, this.counterClockwise)];
  }
  middle() {
    let t48 = this.counterClockwise ? this.startAngle + this.sweep / 2 : this.startAngle - this.sweep / 2;
    return new Nd.Arc(this.pc, this.r, this.startAngle, t48, this.counterClockwise).end;
  }
  pointAtLength(t48) {
    if (t48 > this.length || t48 < 0) return null;
    if (0 === t48) return this.start;
    if (t48 === this.length) return this.end;
    let e2 = t48 / this.length, n2 = this.counterClockwise ? this.startAngle + this.sweep * e2 : this.startAngle - this.sweep * e2;
    return new Nd.Arc(this.pc, this.r, this.startAngle, n2, this.counterClockwise).end;
  }
  chordHeight() {
    return (1 - Math.cos(Math.abs(this.sweep / 2))) * this.r;
  }
  intersect(t48) {
    return t48 instanceof Nd.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof Nd.Line ? zd(t48, this) : t48 instanceof Nd.Ray ? iu(t48, this) : t48 instanceof Nd.Circle ? Hd(this, t48) : t48 instanceof Nd.Segment ? $d(t48, this) : t48 instanceof Nd.Box ? (function(t49, e2) {
      let n2 = [];
      for (let o2 of e2.toSegments()) {
        let e3 = $d(o2, t49);
        for (let t50 of e3) n2.push(t50);
      }
      return n2;
    })(this, t48) : t48 instanceof Nd.Arc ? Bd(this, t48) : t48 instanceof Nd.Polygon ? qd(this, t48) : t48 instanceof Nd.Multiline ? lu(this, t48) : void 0;
  }
  distanceTo(t48) {
    if (t48 instanceof Nd.Point) {
      let [e2, n2] = Nd.Distance.point2arc(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Circle) {
      let [e2, n2] = Nd.Distance.arc2circle(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Line) {
      let [e2, n2] = Nd.Distance.arc2line(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Segment) {
      let [e2, n2] = Nd.Distance.segment2arc(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Arc) {
      let [e2, n2] = Nd.Distance.arc2arc(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Polygon) {
      let [e2, n2] = Nd.Distance.shape2polygon(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.PlanarSet) {
      let [e2, n2] = Nd.Distance.shape2planarSet(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof Nd.Multiline) return Nd.Distance.shape2multiline(this, t48);
  }
  breakToFunctional() {
    let t48 = [], e2 = [0, Math.PI / 2, Math.PI, 3 * Math.PI / 2], n2 = this.startAngle, o2 = this.endAngle;
    Nd.Utils.EQ(Math.abs(n2 - o2), Nd.PIx2) && (o2 = n2), Math.abs(n2) > Nd.PIx2 && (n2 -= Math.trunc(n2 / Nd.PIx2) * Nd.PIx2), n2 < 0 && (n2 += Nd.PIx2), Math.abs(o2) > Nd.PIx2 && (o2 -= Math.trunc(o2 / Nd.PIx2) * Nd.PIx2), o2 < 0 && (o2 += Nd.PIx2);
    let i2, r2, s2, a2 = n2;
    this.counterClockwise ? (r2 = Math.ceil(n2 / (Math.PI / 2)) % 4, s2 = 1) : (r2 = Math.floor(n2 / (Math.PI / 2)) % 4, s2 = -1);
    for (let o3 = 0, c2 = r2; o3 < 4; o3++, c2 = (c2 + s2 + 4) % 4) {
      if (i2 = e2[c2], i2 === a2) continue;
      let o4 = this.counterClockwise ? i2 - n2 : n2 - i2;
      if (o4 < 0 && (o4 += Nd.PIx2), o4 > this.sweep) break;
      t48.push(new Nd.Arc(this.pc, this.r, a2, i2, this.counterClockwise)), a2 = i2;
    }
    return 0 === t48.length ? (t48.push(this), t48) : (i2 = o2, a2 !== i2 && t48.push(new Nd.Arc(this.pc, this.r, a2, i2, this.counterClockwise)), t48);
  }
  tangentInStart() {
    let t48 = new Nd.Vector(this.pc, this.start), e2 = this.counterClockwise ? Math.PI / 2 : -Math.PI / 2;
    return t48.rotate(e2).normalize();
  }
  tangentInEnd() {
    let t48 = new Nd.Vector(this.pc, this.end), e2 = this.counterClockwise ? -Math.PI / 2 : Math.PI / 2;
    return t48.rotate(e2).normalize();
  }
  reverse() {
    return new Nd.Arc(this.pc, this.r, this.endAngle, this.startAngle, !this.counterClockwise);
  }
  transform(t48 = new Nd.Matrix()) {
    let e2 = this.start.transform(t48), n2 = this.end.transform(t48), o2 = this.pc.transform(t48), i2 = this.counterClockwise;
    return t48.a * t48.d < 0 && (i2 = !i2), Nd.Arc.arcSE(o2, e2, n2, i2);
  }
  static arcSE(t48, e2, n2, o2) {
    let { vector: i2 } = Nd, r2 = i2(t48, e2).slope, s2 = i2(t48, n2).slope;
    Nd.Utils.EQ(r2, s2) && (s2 += 2 * Math.PI, o2 = true);
    let a2 = i2(t48, e2).length;
    return new Nd.Arc(t48, a2, r2, s2, o2);
  }
  definiteIntegral(t48 = 0) {
    return this.breakToFunctional().reduce((e2, n2) => e2 + n2.circularSegmentDefiniteIntegral(t48), 0);
  }
  circularSegmentDefiniteIntegral(t48) {
    let e2 = new Nd.Segment(this.start, this.end).definiteIntegral(t48), n2 = Nd.Utils.EQ(this.sweep, Nd.PIx2) ? 0 : this.circularSegmentArea();
    return this.counterClockwise ? e2 - n2 : e2 + n2;
  }
  circularSegmentArea() {
    return 0.5 * this.r * this.r * (this.sweep - Math.sin(this.sweep));
  }
  sortPoints(t48) {
    let { vector: e2 } = Nd;
    return t48.slice().sort((t49, n2) => {
      let o2 = e2(this.pc, t49).slope, i2 = e2(this.pc, n2).slope;
      return o2 < i2 ? -1 : o2 > i2 ? 1 : 0;
    });
  }
  get name() {
    return "arc";
  }
  svg(t48 = {}) {
    let e2 = this.sweep <= Math.PI ? "0" : "1", n2 = this.counterClockwise ? "1" : "0";
    if (Nd.Utils.EQ(this.sweep, 2 * Math.PI)) {
      return new Nd.Circle(this.pc, this.r).svg(t48);
    }
    return `
<path d="M${this.start.x},${this.start.y}
                             A${this.r},${this.r} 0 ${e2},${n2} ${this.end.x},${this.end.y}"
                    ${Ad({ fill: "none", ...t48 })} />`;
  }
};
Nd.arc = (...t48) => new Nd.Arc(...t48);
Nd.Box = class t10 extends up {
  constructor(t48 = void 0, e2 = void 0, n2 = void 0, o2 = void 0) {
    super(), this.xmin = t48, this.ymin = e2, this.xmax = n2, this.ymax = o2;
  }
  clone() {
    return new t10(this.xmin, this.ymin, this.xmax, this.ymax);
  }
  get low() {
    return new Nd.Point(this.xmin, this.ymin);
  }
  get high() {
    return new Nd.Point(this.xmax, this.ymax);
  }
  get max() {
    return this.clone();
  }
  get center() {
    return new Nd.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(t48) {
    return this.xmax < t48.xmin || this.xmin > t48.xmax || this.ymax < t48.ymin || this.ymin > t48.ymax;
  }
  intersect(t48) {
    return !this.not_intersect(t48);
  }
  merge(e2) {
    return new t10(void 0 === this.xmin ? e2.xmin : Math.min(this.xmin, e2.xmin), void 0 === this.ymin ? e2.ymin : Math.min(this.ymin, e2.ymin), void 0 === this.xmax ? e2.xmax : Math.max(this.xmax, e2.xmax), void 0 === this.ymax ? e2.ymax : Math.max(this.ymax, e2.ymax));
  }
  less_than(t48) {
    return !!this.low.lessThan(t48.low) || !(!this.low.equalTo(t48.low) || !this.high.lessThan(t48.high));
  }
  equal_to(t48) {
    return this.low.equalTo(t48.low) && this.high.equalTo(t48.high);
  }
  output() {
    return this.clone();
  }
  comparable_less_than(t48, e2) {
    return t48.lessThan(e2);
  }
  set(t48, e2, n2, o2) {
    this.xmin = t48, this.ymin = e2, this.xmax = n2, this.ymax = o2;
  }
  extend(e2) {
    return e2 <= 0 ? this.clone() : new t10(this.xmin - e2, this.ymin - e2, this.xmax + e2, this.ymax + e2);
  }
  toPoints() {
    return [new Nd.Point(this.xmin, this.ymin), new Nd.Point(this.xmax, this.ymin), new Nd.Point(this.xmax, this.ymax), new Nd.Point(this.xmin, this.ymax)];
  }
  toSegments() {
    let t48 = this.toPoints();
    return [new Nd.Segment(t48[0], t48[1]), new Nd.Segment(t48[1], t48[2]), new Nd.Segment(t48[2], t48[3]), new Nd.Segment(t48[3], t48[0])];
  }
  rotate(t48, e2 = new Nd.Point()) {
    throw wd.OPERATION_IS_NOT_SUPPORTED;
  }
  transform(e2 = new Nd.Matrix()) {
    return this.toPoints().map((t48) => t48.transform(e2)).reduce((t48, e3) => t48.merge(e3.box), new t10());
  }
  contains(t48) {
    return t48 instanceof Nd.Point ? t48.x >= this.xmin && t48.x <= this.xmax && t48.y >= this.ymin && t48.y <= this.ymax : t48 instanceof Nd.Segment ? t48.vertices.every((t49) => this.contains(t49)) : t48 instanceof Nd.Box ? t48.toSegments().every((t49) => this.contains(t49)) : t48 instanceof Nd.Circle ? this.contains(t48.box) : t48 instanceof Nd.Arc ? t48.vertices.every((t49) => this.contains(t49)) && this.toSegments().every((e2) => 0 === $d(e2, t48).length) : !(t48 instanceof Nd.Line || t48 instanceof Nd.Ray) && (t48 instanceof Nd.Multiline ? t48.toShapes().every((t49) => this.contains(t49)) : t48 instanceof Nd.Polygon ? this.contains(t48.box) : void 0);
  }
  distanceTo(t48) {
    const e2 = this.toSegments().map((e3) => e3.distanceTo(t48));
    let n2 = [Number.MAX_SAFE_INTEGER, null];
    return e2.forEach((t49) => {
      t49[0] < n2[0] && (n2 = t49);
    }), n2;
  }
  get name() {
    return "box";
  }
  svg(t48 = {}) {
    const e2 = this.xmax - this.xmin, n2 = this.ymax - this.ymin;
    return `
<rect x="${this.xmin}" y="${this.ymin}" width="${e2}" height="${n2}"
                ${Ad({ fill: "none", ...t48 })} />`;
  }
};
Nd.box = (...t48) => new Nd.Box(...t48);
Nd.Edge = class {
  constructor(t48) {
    this.shape = t48, 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 Nd.Segment;
  }
  get isArc() {
    return this.shape instanceof Nd.Arc;
  }
  get isLine() {
    return this.shape instanceof Nd.Line;
  }
  get isRay() {
    return this.shape instanceof Nd.Ray;
  }
  middle() {
    return this.shape.middle();
  }
  pointAtLength(t48) {
    return this.shape.pointAtLength(t48);
  }
  contains(t48) {
    return this.shape.contains(t48);
  }
  setInclusion(t48) {
    if (void 0 !== this.bv) return this.bv;
    if (this.shape instanceof Nd.Line || this.shape instanceof Nd.Ray) return this.bv = Nd.OUTSIDE, this.bv;
    if (void 0 === this.bvStart && (this.bvStart = Ju(t48, this.start)), void 0 === this.bvEnd && (this.bvEnd = Ju(t48, this.end)), this.bvStart === Nd.OUTSIDE || this.bvEnd == Nd.OUTSIDE) this.bv = Nd.OUTSIDE;
    else if (this.bvStart === Nd.INSIDE || this.bvEnd == Nd.INSIDE) this.bv = Nd.INSIDE;
    else {
      let e2 = Ju(t48, this.middle());
      this.bv = e2;
    }
    return this.bv;
  }
  setOverlap(t48) {
    let e2, n2 = this.shape, o2 = t48.shape;
    n2 instanceof Nd.Segment && o2 instanceof Nd.Segment ? n2.start.equalTo(o2.start) && n2.end.equalTo(o2.end) ? e2 = Nd.OVERLAP_SAME : n2.start.equalTo(o2.end) && n2.end.equalTo(o2.start) && (e2 = Nd.OVERLAP_OPPOSITE) : (n2 instanceof Nd.Arc && o2 instanceof Nd.Arc || n2 instanceof Nd.Segment && o2 instanceof Nd.Arc || n2 instanceof Nd.Arc && o2 instanceof Nd.Segment) && (n2.start.equalTo(o2.start) && n2.end.equalTo(o2.end) && n2.middle().equalTo(o2.middle()) ? e2 = Nd.OVERLAP_SAME : n2.start.equalTo(o2.end) && n2.end.equalTo(o2.start) && n2.middle().equalTo(o2.middle()) && (e2 = Nd.OVERLAP_OPPOSITE)), void 0 === this.overlap && (this.overlap = e2), void 0 === t48.overlap && (t48.overlap = e2);
  }
  svg() {
    if (this.shape instanceof Nd.Segment) return ` L${this.shape.end.x},${this.shape.end.y}`;
    if (this.shape instanceof Nd.Arc) {
      let t48, e2 = this.shape, n2 = e2.counterClockwise ? "1" : "0";
      if (Nd.Utils.EQ(e2.sweep, 2 * Math.PI)) {
        let o2 = e2.counterClockwise ? 1 : -1, i2 = new Nd.Arc(e2.pc, e2.r, e2.startAngle, e2.startAngle + o2 * Math.PI, e2.counterClockwise), r2 = new Nd.Arc(e2.pc, e2.r, e2.startAngle + o2 * Math.PI, e2.endAngle, e2.counterClockwise);
        return t48 = "0", ` A${i2.r},${i2.r} 0 ${t48},${n2} ${i2.end.x},${i2.end.y}
                    A${r2.r},${r2.r} 0 ${t48},${n2} ${r2.end.x},${r2.end.y}`;
      }
      return t48 = e2.sweep <= Math.PI ? "0" : "1", ` A${e2.r},${e2.r} 0 ${t48},${n2} ${e2.end.x},${e2.end.y}`;
    }
  }
  toJSON() {
    return this.shape.toJSON();
  }
};
var gp = class extends Td {
  constructor(t48, e2) {
    super(t48, e2), this.setCircularLinks();
  }
  setCircularLinks() {
    this.isEmpty() || (this.last.next = this.first, this.first.prev = this.last);
  }
  [Symbol.iterator]() {
    let t48;
    return { next: () => {
      let e2 = t48 || this.first, n2 = !this.first || !!t48 && t48 === this.first;
      return t48 = e2 ? e2.next : void 0, { value: e2, done: n2 };
    } };
  }
  append(t48) {
    return super.append(t48), this.setCircularLinks(), this;
  }
  insert(t48, e2) {
    return super.insert(t48, e2), this.setCircularLinks(), this;
  }
  remove(t48) {
    return super.remove(t48), this;
  }
};
Nd.Face = class t11 extends gp {
  constructor(e2, ...n2) {
    if (super(), this._box = void 0, this._orientation = void 0, 0 !== n2.length) {
      if (1 === n2.length) {
        if (n2[0] instanceof Array) {
          let o2 = n2[0];
          if (0 === o2.length) return;
          if (o2.every((t48) => t48 instanceof Nd.Point)) {
            let n3 = t11.points2segments(o2);
            this.shapes2face(e2.edges, n3);
          } else if (o2.every((t48) => t48 instanceof Array && 2 === t48.length)) {
            let n3 = o2.map((t48) => new Nd.Point(t48[0], t48[1])), i2 = t11.points2segments(n3);
            this.shapes2face(e2.edges, i2);
          } else if (o2.every((t48) => t48 instanceof Nd.Segment || t48 instanceof Nd.Arc)) this.shapes2face(e2.edges, o2);
          else if (o2.every((t48) => "segment" === t48.name || "arc" === t48.name)) {
            let t48 = [];
            for (let e3 of o2) {
              let n3;
              n3 = "segment" === e3.name ? new Nd.Segment(e3) : new Nd.Arc(e3), t48.push(n3);
            }
            this.shapes2face(e2.edges, t48);
          }
        } else if (n2[0] instanceof t11) {
          let t48 = n2[0];
          this.first = t48.first, this.last = t48.last;
          for (let n3 of t48) e2.edges.add(n3);
        } else if (n2[0] instanceof Nd.Circle) this.shapes2face(e2.edges, [n2[0].toArc(fd)]);
        else if (n2[0] instanceof Nd.Box) {
          let t48 = n2[0];
          this.shapes2face(e2.edges, [new Nd.Segment(new Nd.Point(t48.xmin, t48.ymin), new Nd.Point(t48.xmax, t48.ymin)), new Nd.Segment(new Nd.Point(t48.xmax, t48.ymin), new Nd.Point(t48.xmax, t48.ymax)), new Nd.Segment(new Nd.Point(t48.xmax, t48.ymax), new Nd.Point(t48.xmin, t48.ymax)), new Nd.Segment(new Nd.Point(t48.xmin, t48.ymax), new Nd.Point(t48.xmin, t48.ymin))]);
        }
      }
      2 === n2.length && n2[0] instanceof Nd.Edge && n2[1] instanceof Nd.Edge && (this.first = n2[0], this.last = n2[1], this.last.next = this.first, this.first.prev = this.last, this.setArcLength());
    }
  }
  get edges() {
    return this.toArray();
  }
  get vertices() {
    return this.edges.map((t48) => t48.shape.start.clone());
  }
  get shapes() {
    return this.edges.map((t48) => t48.shape.clone());
  }
  get box() {
    if (void 0 === this._box) {
      let t48 = new Nd.Box();
      for (let e2 of this) t48 = t48.merge(e2.box);
      this._box = t48;
    }
    return this._box;
  }
  get perimeter() {
    return this.last.arc_length + this.last.length;
  }
  pointAtLength(t48) {
    if (t48 > this.perimeter || t48 < 0) return null;
    let e2 = null;
    for (let n2 of this) if (t48 >= n2.arc_length && (n2 === this.last || t48 < n2.next.arc_length)) {
      e2 = n2.pointAtLength(t48 - n2.arc_length);
      break;
    }
    return e2;
  }
  static points2segments(t48) {
    let e2 = [];
    for (let n2 = 0; n2 < t48.length; n2++) t48[n2].equalTo(t48[(n2 + 1) % t48.length]) || e2.push(new Nd.Segment(t48[n2], t48[(n2 + 1) % t48.length]));
    return e2;
  }
  shapes2face(t48, e2) {
    for (let n2 of e2) {
      let e3 = new Nd.Edge(n2);
      this.append(e3), t48.add(e3);
    }
  }
  append(t48) {
    return super.append(t48), this.setOneEdgeArcLength(t48), t48.face = this, this;
  }
  insert(t48, e2) {
    return super.insert(t48, e2), this.setOneEdgeArcLength(t48), t48.face = this, this;
  }
  remove(t48) {
    return super.remove(t48), this.setArcLength(), this;
  }
  merge_with_next_edge(t48) {
    return t48.shape.end.x = t48.next.shape.end.x, t48.shape.end.y = t48.next.shape.end.y, this.remove(t48.next), this;
  }
  reverse() {
    let t48 = [], e2 = this.last;
    do {
      e2.shape = e2.shape.reverse(), t48.push(e2), e2 = e2.prev;
    } while (e2 !== this.last);
    this.first = void 0, this.last = void 0;
    for (let e3 of t48) void 0 === this.first ? (e3.prev = e3, e3.next = e3, this.first = e3, this.last = e3) : (e3.prev = this.last, this.last.next = e3, this.last = e3, this.last.next = this.first, this.first.prev = this.last), this.setOneEdgeArcLength(e3);
    void 0 !== this._orientation && (this._orientation = void 0, this._orientation = this.orientation());
  }
  setArcLength() {
    for (let t48 of this) this.setOneEdgeArcLength(t48), t48.face = this;
  }
  setOneEdgeArcLength(t48) {
    t48 === this.first ? t48.arc_length = 0 : t48.arc_length = t48.prev.arc_length + t48.prev.length;
  }
  area() {
    return Math.abs(this.signedArea());
  }
  signedArea() {
    let t48 = 0, e2 = this.box.ymin;
    for (let n2 of this) t48 += n2.shape.definiteIntegral(e2);
    return t48;
  }
  orientation() {
    if (void 0 === this._orientation) {
      let t48 = this.signedArea();
      Nd.Utils.EQ_0(t48) ? this._orientation = _d.NOT_ORIENTABLE : Nd.Utils.LT(t48, 0) ? this._orientation = _d.CCW : this._orientation = _d.CW;
    }
    return this._orientation;
  }
  isSimple(e2) {
    return 0 === t11.getSelfIntersections(this, e2, true).length;
  }
  static getSelfIntersections(t48, e2, n2 = false) {
    let o2 = [];
    for (let i2 of t48) {
      let r2 = e2.search(i2.box);
      for (let e3 of r2) {
        if (i2 === e3) continue;
        if (e3.face !== t48) continue;
        if (i2.shape instanceof Nd.Segment && e3.shape instanceof Nd.Segment && (i2.next === e3 || i2.prev === e3)) continue;
        let r3 = i2.shape.intersect(e3.shape);
        for (let t49 of r3) if ((!t49.equalTo(i2.start) || !t49.equalTo(e3.end) || e3 !== i2.prev) && (!t49.equalTo(i2.end) || !t49.equalTo(e3.start) || e3 !== i2.next) && (o2.push(t49), n2)) break;
        if (o2.length > 0 && n2) break;
      }
      if (o2.length > 0 && n2) break;
    }
    return o2;
  }
  findEdgeByPoint(t48) {
    let e2;
    for (let n2 of this) if (!t48.equalTo(n2.shape.start) && (t48.equalTo(n2.shape.end) || n2.shape.contains(t48))) {
      e2 = n2;
      break;
    }
    return e2;
  }
  toPolygon() {
    return new Nd.Polygon(this.shapes);
  }
  toJSON() {
    return this.edges.map((t48) => t48.toJSON());
  }
  svg() {
    let t48 = `M${this.first.start.x},${this.first.start.y}`;
    for (let e2 of this) t48 += e2.svg();
    return t48 += " z", t48;
  }
};
Nd.Ray = class t12 extends up {
  constructor(...t48) {
    if (super(), this.pt = new Nd.Point(), this.norm = new Nd.Vector(0, 1), 0 !== t48.length && (t48.length >= 1 && t48[0] instanceof Nd.Point && (this.pt = t48[0].clone()), 1 !== t48.length)) {
      if (!(2 === t48.length && t48[1] instanceof Nd.Vector)) throw wd.ILLEGAL_PARAMETERS;
      this.norm = t48[1].clone();
    }
  }
  clone() {
    return new t12(this.pt, this.norm);
  }
  get slope() {
    return new Nd.Vector(this.norm.y, -this.norm.x).slope;
  }
  get box() {
    let t48 = this.slope;
    return new Nd.Box(t48 > Math.PI / 2 && t48 < 3 * Math.PI / 2 ? Number.NEGATIVE_INFINITY : this.pt.x, t48 >= 0 && t48 <= Math.PI ? this.pt.y : Number.NEGATIVE_INFINITY, t48 >= Math.PI / 2 && t48 <= 3 * Math.PI / 2 ? this.pt.x : Number.POSITIVE_INFINITY, t48 >= Math.PI && t48 <= 2 * Math.PI || 0 === t48 ? this.pt.y : Number.POSITIVE_INFINITY);
  }
  get start() {
    return this.pt;
  }
  get end() {
  }
  get length() {
    return Number.POSITIVE_INFINITY;
  }
  contains(t48) {
    if (this.pt.equalTo(t48)) return true;
    let e2 = new Nd.Vector(this.pt, t48);
    return Nd.Utils.EQ_0(this.norm.dot(e2)) && Nd.Utils.GE(e2.cross(this.norm), 0);
  }
  coord(t48) {
    return pp(t48.x, t48.y).cross(this.norm);
  }
  split(t48) {
    return this.contains(t48) ? this.pt.equalTo(t48) ? [this] : [new Nd.Segment(this.pt, t48), new Nd.Ray(t48, this.norm)] : [];
  }
  intersect(t48) {
    return t48 instanceof Nd.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof Nd.Segment ? ou(this, t48) : t48 instanceof Nd.Arc ? iu(this, t48) : t48 instanceof Nd.Line ? su(this, t48) : t48 instanceof Nd.Ray ? (n2 = t48, Od(nu(e2 = this), nu(n2)).filter((t49) => e2.contains(t49)).filter((t49) => n2.contains(t49))) : t48 instanceof Nd.Circle ? ru(this, t48) : t48 instanceof Nd.Box ? (function(t49, e3) {
      return Dd(nu(t49), e3).filter((e4) => t49.contains(e4));
    })(this, t48) : t48 instanceof Nd.Polygon ? au(this, t48) : t48 instanceof Nd.Multiline ? lu(this, t48) : void 0;
    var e2, n2;
  }
  rotate(t48, e2 = new Nd.Point()) {
    return new Nd.Ray(this.pt.rotate(t48, e2), this.norm.rotate(t48));
  }
  transform(t48) {
    return new Nd.Ray(this.pt.transform(t48), this.norm.clone());
  }
  get name() {
    return "ray";
  }
  svg(t48, e2 = {}) {
    let n2 = Dd(new Nd.Line(this.pt, this.norm), t48);
    return n2 = n2.filter((t49) => this.contains(t49)), 0 === n2.length || 2 === n2.length ? "" : new Nd.Segment(this.pt, n2[0]).svg(e2);
  }
};
Nd.ray = (...t48) => new Nd.Ray(...t48);
Nd.Polygon = class t13 {
  constructor() {
    this.faces = new Nd.PlanarSet(), this.edges = new Nd.PlanarSet();
    let t48 = [...arguments];
    if (1 === t48.length && (t48[0] instanceof Array && t48[0].length > 0 || t48[0] instanceof Nd.Circle || t48[0] instanceof Nd.Box)) {
      let e2 = t48[0];
      if (t48[0] instanceof Array && t48[0].every((t49) => t49 instanceof Array)) if (e2.every((t49) => t49 instanceof Array && 2 === t49.length && "number" == typeof t49[0] && "number" == typeof t49[1])) this.faces.add(new Nd.Face(this, e2));
      else for (let t49 of e2) if (t49 instanceof Array && t49[0] instanceof Array && t49[0].every((t50) => t50 instanceof Array && 2 === t50.length && "number" == typeof t50[0] && "number" == typeof t50[1])) for (let e3 of t49) this.faces.add(new Nd.Face(this, e3));
      else this.faces.add(new Nd.Face(this, t49));
      else this.faces.add(new Nd.Face(this, e2));
    }
  }
  get box() {
    return [...this.faces].reduce((t48, e2) => t48.merge(e2.box), new Nd.Box());
  }
  get vertices() {
    return [...this.faces].flatMap((t48) => t48.vertices);
  }
  clone() {
    let e2 = new t13();
    for (let t48 of this.faces) e2.addFace(t48.shapes);
    return e2;
  }
  createFromArray(e2) {
    const n2 = new t13();
    return e2.forEach((t48) => [...t48.faces].forEach((t49) => n2.addFace(t49.shapes))), n2;
  }
  isEmpty() {
    return 0 === this.edges.size || 0 === this.faces.size;
  }
  isValid() {
    let t48 = true;
    for (let e2 of this.faces) if (!e2.isSimple(this.edges)) {
      t48 = false;
      break;
    }
    return t48;
  }
  area() {
    let t48 = [...this.faces].reduce((t49, e2) => t49 + e2.signedArea(), 0);
    return Math.abs(t48);
  }
  addFace(...t48) {
    let e2 = new Nd.Face(this, ...t48);
    return this.faces.add(e2), e2;
  }
  deleteFace(t48) {
    for (let e2 of t48) this.edges.delete(e2);
    return this.faces.delete(t48);
  }
  recreateFaces() {
    this.faces.clear();
    for (let t49 of this.edges) t49.face = null;
    let t48, e2 = true;
    for (; e2; ) {
      e2 = false;
      for (let n2 of this.edges) if (null === n2.face) {
        t48 = n2, e2 = true;
        break;
      }
      if (e2) {
        let e3 = t48;
        do {
          e3 = e3.next;
        } while (e3.next !== t48);
        this.addFace(t48, e3);
      }
    }
  }
  removeChain(t48, e2, n2) {
    if (n2.next !== e2) {
      for (let o2 = e2; o2 !== n2.next; o2 = o2.next) if (t48.remove(o2), this.edges.delete(o2), t48.isEmpty()) {
        this.deleteFace(t48);
        break;
      }
    } else this.deleteFace(t48);
  }
  addVertex(t48, e2) {
    let n2 = e2.shape.split(t48);
    if (null === n2[0]) return e2.prev;
    if (null === n2[1]) return e2;
    let o2 = new Nd.Edge(n2[0]), i2 = e2.prev;
    return e2.face.insert(o2, i2), this.edges.delete(e2), this.edges.add(o2), e2.shape = n2[1], this.edges.add(e2), o2;
  }
  removeEndVertex(t48) {
    const e2 = t48.next;
    e2 !== t48 && (t48.face.merge_with_next_edge(t48), this.edges.delete(e2));
  }
  cut(t48) {
    const e2 = this.splitToIslands().flatMap((e3) => e3._cutSingleIsland(t48)).filter((t49) => t49.isValid() && false === t49.isEmpty());
    return this.createFromArray(e2);
  }
  _cutSingleIsland(t48) {
    let e2 = this.clone();
    const n2 = t48.clone();
    let o2, i2, r2 = { int_points1: [], int_points2: [], int_points1_sorted: [], int_points2_sorted: [] };
    for (let t49 of n2.edges) for (let n3 of e2.edges) {
      let e3 = Qd(t49, n3);
      for (let o3 of e3) du(t49, o3, r2.int_points1), du(n3, o3, r2.int_points2);
    }
    if (0 === r2.int_points1.length) return e2;
    r2.int_points1_sorted = pu(r2.int_points1), r2.int_points2_sorted = pu(r2.int_points2), bu(n2, r2.int_points1_sorted), bu(e2, r2.int_points2_sorted), gu(r2), r2.int_points1_sorted = pu(r2.int_points1), r2.int_points2_sorted = pu(r2.int_points2), fu(r2.int_points1), _u(r2.int_points1, e2);
    for (let t49 of r2.int_points1_sorted) t49.edge_before && t49.edge_after && t49.edge_before.bv === t49.edge_after.bv && (r2.int_points2[t49.id] = -1, t49.id = -1);
    if (r2.int_points1 = r2.int_points1.filter((t49) => t49.id >= 0), r2.int_points2 = r2.int_points2.filter((t49) => t49.id >= 0), r2.int_points1.forEach((t49, e3) => {
      t49.id = e3;
    }), r2.int_points2.forEach((t49, e3) => {
      t49.id = e3;
    }), 0 === r2.int_points1.length) return e2;
    r2.int_points1_sorted = pu(r2.int_points1), r2.int_points2_sorted = pu(r2.int_points2);
    for (let t49 = 1; t49 < r2.int_points1_sorted.length; t49++) if (i2 = r2.int_points1_sorted[t49], o2 = r2.int_points1_sorted[t49 - 1], i2.edge_before && 1 === i2.edge_before.bv) {
      let t50 = o2.edge_after, s2 = i2.edge_before, a2 = n2.getChain(t50, s2);
      xu(r2.int_points2[o2.id], r2.int_points2[i2.id], a2), a2.forEach((t51) => e2.edges.add(t51)), a2 = a2.reverse().map((t51) => new Nd.Edge(t51.shape.reverse()));
      for (let t51 = 0; t51 < a2.length - 1; t51++) a2[t51].next = a2[t51 + 1], a2[t51 + 1].prev = a2[t51];
      xu(r2.int_points2[i2.id], r2.int_points2[o2.id], a2), a2.forEach((t51) => e2.edges.add(t51));
    }
    return e2.recreateFaces(), e2;
  }
  cutWithLine(t48) {
    let e2 = new hu([t48]);
    return this.cut(e2);
  }
  findEdgeByPoint(t48) {
    let e2;
    for (let n2 of this.faces) if (e2 = n2.findEdgeByPoint(t48), void 0 !== e2) break;
    return e2;
  }
  splitToIslands() {
    if (this.isEmpty()) return [];
    let t48 = this.toArray();
    t48.sort((t49, e3) => e3.area() - t49.area());
    let e2 = [...t48[0].faces][0].orientation(), n2 = t48.filter((t49) => [...t49.faces][0].orientation() === e2);
    for (let o2 of t48) {
      let t49 = [...o2.faces][0];
      if (t49.orientation() !== e2) {
        for (let e3 of n2) if (t49.shapes.every((t50) => e3.contains(t50))) {
          e3.addFace(t49.shapes);
          break;
        }
      }
    }
    return n2;
  }
  rearrange() {
    if (this.faces.size <= 1) return this.clone();
    const e2 = this.splitToIslands(), n2 = new t13();
    return e2.forEach((t48) => {
      t48.faces.forEach((t49) => n2.addFace(t49.shapes));
    }), n2;
  }
  orientation() {
    return this.isEmpty() ? _d.NOT_ORIENTABLE : [...this.faces][0].orientation();
  }
  isOuter(t48) {
    return t48.orientation() === this.orientation();
  }
  isMultiPolygon() {
    let t48 = 0;
    return this.faces.forEach((e2) => {
      this.isOuter(e2) && t48++;
    }), t48 > 1;
  }
  reverse() {
    for (let t48 of this.faces) t48.reverse();
    return this;
  }
  contains(t48) {
    if (t48 instanceof Nd.Point) {
      let e2 = Ju(this, t48);
      return 1 === e2 || 2 === e2;
    }
    return ep(this, t48);
  }
  distanceTo(t48) {
    if (t48 instanceof Nd.Point) {
      let [e2, n2] = Nd.Distance.point2polygon(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Circle || t48 instanceof Nd.Line || t48 instanceof Nd.Segment || t48 instanceof Nd.Arc) {
      let [e2, n2] = Nd.Distance.shape2polygon(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof Nd.Polygon) {
      let e2, n2, o2 = [Number.POSITIVE_INFINITY, new Nd.Segment()];
      for (let i2 of this.edges) {
        let r2 = o2[0];
        [e2, n2] = Nd.Distance.shape2planarSet(i2.shape, t48.edges, r2), Nd.Utils.LT(e2, r2) && (o2 = [e2, n2]);
      }
      return o2;
    }
  }
  intersect(t48) {
    return t48 instanceof Nd.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof Nd.Line ? Jd(t48, this) : t48 instanceof Nd.Ray ? au(t48, this) : t48 instanceof Nd.Circle ? Kd(t48, this) : t48 instanceof Nd.Segment ? Zd(t48, this) : t48 instanceof Nd.Arc ? qd(t48, this) : t48 instanceof Nd.Polygon ? (function(t49, e2) {
      let n2 = [];
      if (t49.isEmpty() || e2.isEmpty()) return n2;
      if (t49.box.not_intersect(e2.box)) return n2;
      for (let o2 of t49.edges) n2 = [...n2, ...tu(o2, e2)];
      return n2;
    })(t48, this) : t48 instanceof Nd.Multiline ? (function(t49, e2) {
      let n2 = [];
      if (e2.isEmpty() || 0 === t49.size) return n2;
      for (let o2 of t49) n2 = [...n2, ...tu(o2, e2)];
      return n2;
    })(t48, this) : void 0;
  }
  translate(e2) {
    let n2 = new t13();
    for (let t48 of this.faces) n2.addFace(t48.shapes.map((t49) => t49.translate(e2)));
    return n2;
  }
  rotate(e2 = 0, n2 = new Nd.Point()) {
    let o2 = new t13();
    for (let t48 of this.faces) o2.addFace(t48.shapes.map((t49) => t49.rotate(e2, n2)));
    return o2;
  }
  scale(e2, n2) {
    let o2 = new t13();
    for (let t48 of this.faces) o2.addFace(t48.shapes.map((t49) => t49.scale(e2, n2)));
    return o2;
  }
  transform(e2 = new Nd.Matrix()) {
    let n2 = new t13();
    for (let t48 of this.faces) n2.addFace(t48.shapes.map((t49) => t49.transform(e2)));
    return n2;
  }
  toJSON() {
    return [...this.faces].map((t48) => t48.toJSON());
  }
  toArray() {
    return [...this.faces].map((t48) => t48.toPolygon());
  }
  dpath() {
    return [...this.faces].reduce((t48, e2) => t48 + e2.svg(), "");
  }
  svg(t48 = {}) {
    let e2 = `
<path ${Ad({ fillRule: "evenodd", fill: "lightcyan", ...t48 })} d="`;
    for (let t49 of this.faces) e2 += `
${t49.svg()}`;
    return e2 += '" >\n</path>', e2;
  }
};
Nd.polygon = (...t48) => new Nd.Polygon(...t48);
var { Circle: fp, Line: _p, Point: yp, Vector: bp, Utils: xp } = Nd;
Nd.Inversion = class t14 {
  constructor(t48) {
    this.circle = t48;
  }
  get inversion_circle() {
    return this.circle;
  }
  static inversePoint(t48, e2) {
    const n2 = new bp(t48.pc, e2), o2 = t48.r * t48.r, i2 = n2.dot(n2);
    return xp.EQ_0(i2) ? new yp(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY) : t48.pc.translate(n2.multiply(o2 / i2));
  }
  static inverseCircle(t48, e2) {
    const n2 = t48.pc.distanceTo(e2.pc)[0];
    if (xp.EQ(n2, e2.r)) {
      let n3 = t48.r * t48.r / (2 * e2.r), o2 = new bp(t48.pc, e2.pc);
      o2 = o2.normalize();
      let i2 = t48.pc.translate(o2.multiply(n3));
      return new _p(i2, o2);
    }
    {
      let n3 = new bp(t48.pc, e2.pc), o2 = t48.r * t48.r / (n3.dot(n3) - e2.r * e2.r), i2 = t48.pc.translate(n3.multiply(o2)), r2 = Math.abs(o2) * e2.r;
      return new fp(i2, r2);
    }
  }
  static inverseLine(t48, e2) {
    const [n2, o2] = t48.pc.distanceTo(e2);
    if (xp.EQ_0(n2)) return e2.clone();
    {
      let e3 = t48.r * t48.r / (2 * n2), i2 = new bp(t48.pc, o2.end);
      return i2 = i2.multiply(e3 / n2), new fp(t48.pc.translate(i2), e3);
    }
  }
  inverse(e2) {
    return e2 instanceof yp ? t14.inversePoint(this.circle, e2) : e2 instanceof fp ? t14.inverseCircle(this.circle, e2) : e2 instanceof _p ? t14.inverseLine(this.circle, e2) : void 0;
  }
};
Nd.inversion = (t48) => new Nd.Inversion(t48);
Nd.Distance = class t15 {
  static point2point(t48, e2) {
    return t48.distanceTo(e2);
  }
  static point2line(t48, e2) {
    let n2 = t48.projectionOn(e2);
    return [new Nd.Vector(t48, n2).length, new Nd.Segment(t48, n2)];
  }
  static point2circle(t48, e2) {
    let [n2, o2] = t48.distanceTo(e2.center);
    if (Nd.Utils.EQ_0(n2)) return [e2.r, new Nd.Segment(t48, e2.toArc().start)];
    {
      let o3 = Math.abs(n2 - e2.r), i2 = new Nd.Vector(e2.pc, t48).normalize().multiply(e2.r), r2 = e2.pc.translate(i2);
      return [o3, new Nd.Segment(t48, r2)];
    }
  }
  static point2segment(e2, n2) {
    if (n2.start.equalTo(n2.end)) return t15.point2point(e2, n2.start);
    let o2, i2, r2 = new Nd.Vector(n2.start, n2.end), s2 = new Nd.Vector(n2.start, e2), a2 = new Nd.Vector(n2.end, e2), c2 = r2.dot(s2), l2 = -r2.dot(a2);
    if (Nd.Utils.GE(c2, 0) && Nd.Utils.GE(l2, 0)) {
      let t48 = n2.tangentInStart();
      return o2 = Math.abs(t48.cross(s2)), i2 = n2.start.translate(t48.multiply(t48.dot(s2))), [o2, new Nd.Segment(e2, i2)];
    }
    return c2 < 0 ? e2.distanceTo(n2.start) : e2.distanceTo(n2.end);
  }
  static point2arc(e2, n2) {
    let o2, i2, r2 = new Nd.Circle(n2.pc, n2.r), s2 = [];
    return [o2, i2] = t15.point2circle(e2, r2), i2.end.on(n2) && s2.push(t15.point2circle(e2, r2)), s2.push(t15.point2point(e2, n2.start)), s2.push(t15.point2point(e2, n2.end)), t15.sort(s2), s2[0];
  }
  static point2edge(e2, n2) {
    return n2.shape instanceof Nd.Segment ? t15.point2segment(e2, n2.shape) : t15.point2arc(e2, n2.shape);
  }
  static segment2line(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    let i2 = [];
    return i2.push(t15.point2line(e2.start, n2)), i2.push(t15.point2line(e2.end, n2)), t15.sort(i2), i2[0];
  }
  static segment2segment(e2, n2) {
    let o2 = Fd(e2, n2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    let i2, r2, s2 = [];
    return [i2, r2] = t15.point2segment(n2.start, e2), s2.push([i2, r2.reverse()]), [i2, r2] = t15.point2segment(n2.end, e2), s2.push([i2, r2.reverse()]), s2.push(t15.point2segment(e2.start, n2)), s2.push(t15.point2segment(e2.end, n2)), t15.sort(s2), s2[0];
  }
  static segment2circle(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    let i2 = new Nd.Line(e2.ps, e2.pe), [r2, s2] = t15.point2line(n2.center, i2);
    if (Nd.Utils.GE(r2, n2.r) && s2.end.on(e2)) return t15.point2circle(s2.end, n2);
    {
      let [o3, i3] = t15.point2circle(e2.start, n2), [r3, s3] = t15.point2circle(e2.end, n2);
      return Nd.Utils.LT(o3, r3) ? [o3, i3] : [r3, s3];
    }
  }
  static segment2arc(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    let i2 = new Nd.Line(e2.ps, e2.pe), r2 = new Nd.Circle(n2.pc, n2.r), [s2, a2] = t15.point2line(r2.center, i2);
    if (Nd.Utils.GE(s2, r2.r) && a2.end.on(e2)) {
      let [e3, o3] = t15.point2circle(a2.end, r2);
      if (o3.end.on(n2)) return [e3, o3];
    }
    let c2, l2, h2 = [];
    return h2.push(t15.point2arc(e2.start, n2)), h2.push(t15.point2arc(e2.end, n2)), [c2, l2] = t15.point2segment(n2.start, e2), h2.push([c2, l2.reverse()]), [c2, l2] = t15.point2segment(n2.end, e2), h2.push([c2, l2.reverse()]), t15.sort(h2), h2[0];
  }
  static circle2circle(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    if (e2.center.equalTo(n2.center)) {
      let o3 = e2.toArc(), i2 = n2.toArc();
      return t15.point2point(o3.start, i2.start);
    }
    {
      let o3 = new Nd.Line(e2.center, n2.center), i2 = o3.intersect(e2), r2 = o3.intersect(n2), s2 = [];
      return s2.push(t15.point2point(i2[0], r2[0])), s2.push(t15.point2point(i2[0], r2[1])), s2.push(t15.point2point(i2[1], r2[0])), s2.push(t15.point2point(i2[1], r2[1])), t15.sort(s2), s2[0];
    }
  }
  static circle2line(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    let [i2, r2] = t15.point2line(e2.center, n2), [s2, a2] = t15.point2circle(r2.end, e2);
    return a2 = a2.reverse(), [s2, a2];
  }
  static arc2line(e2, n2) {
    let o2 = n2.intersect(e2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    let i2 = new Nd.Circle(e2.center, e2.r), [r2, s2] = t15.point2line(i2.center, n2);
    if (!Nd.Utils.GE(r2, i2.r)) {
      let o3 = [];
      return o3.push(t15.point2line(e2.start, n2)), o3.push(t15.point2line(e2.end, n2)), t15.sort(o3), o3[0];
    }
    {
      let [n3, o3] = t15.point2circle(s2.end, i2);
      if (o3.end.on(e2)) return [n3, o3];
    }
  }
  static arc2circle(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    let i2 = new Nd.Circle(e2.center, e2.r), [r2, s2] = t15.circle2circle(i2, n2);
    if (s2.start.on(e2)) return [r2, s2];
    {
      let o3 = [];
      return o3.push(t15.point2circle(e2.start, n2)), o3.push(t15.point2circle(e2.end, n2)), t15.sort(o3), o3[0];
    }
  }
  static arc2arc(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new Nd.Segment(o2[0], o2[0])];
    let i2 = new Nd.Circle(e2.center, e2.r), r2 = new Nd.Circle(n2.center, n2.r), [s2, a2] = t15.circle2circle(i2, r2);
    if (a2.start.on(e2) && a2.end.on(n2)) return [s2, a2];
    {
      let o3, i3, r3 = [];
      return [o3, i3] = t15.point2arc(e2.start, n2), i3.end.on(n2) && r3.push([o3, i3]), [o3, i3] = t15.point2arc(e2.end, n2), i3.end.on(n2) && r3.push([o3, i3]), [o3, i3] = t15.point2arc(n2.start, e2), i3.end.on(e2) && r3.push([o3, i3.reverse()]), [o3, i3] = t15.point2arc(n2.end, e2), i3.end.on(e2) && r3.push([o3, i3.reverse()]), [o3, i3] = t15.point2point(e2.start, n2.start), r3.push([o3, i3]), [o3, i3] = t15.point2point(e2.start, n2.end), r3.push([o3, i3]), [o3, i3] = t15.point2point(e2.end, n2.start), r3.push([o3, i3]), [o3, i3] = t15.point2point(e2.end, n2.end), r3.push([o3, i3]), t15.sort(r3), r3[0];
    }
  }
  static point2polygon(e2, n2) {
    let o2 = [Number.POSITIVE_INFINITY, new Nd.Segment()];
    for (let i2 of n2.edges) {
      let [n3, r2] = t15.point2edge(e2, i2);
      Nd.Utils.LT(n3, o2[0]) && (o2 = [n3, r2]);
    }
    return o2;
  }
  static shape2polygon(t48, e2) {
    let n2 = [Number.POSITIVE_INFINITY, new Nd.Segment()];
    for (let o2 of e2.edges) {
      let [e3, i2] = t48.distanceTo(o2.shape);
      Nd.Utils.LT(e3, n2[0]) && (n2 = [e3, i2]);
    }
    return n2;
  }
  static polygon2polygon(t48, e2) {
    let n2 = [Number.POSITIVE_INFINITY, new Nd.Segment()];
    for (let o2 of t48.edges) for (let t49 of e2.edges) {
      let [e3, i2] = o2.shape.distanceTo(t49.shape);
      Nd.Utils.LT(e3, n2[0]) && (n2 = [e3, i2]);
    }
    return n2;
  }
  static box2box_minmax(t48, e2) {
    let n2 = Math.max(Math.max(t48.xmin - e2.xmax, 0), Math.max(e2.xmin - t48.xmax, 0)), o2 = Math.max(Math.max(t48.ymin - e2.ymax, 0), Math.max(e2.ymin - t48.ymax, 0)), i2 = n2 * n2 + o2 * o2, r2 = t48.merge(e2), s2 = r2.xmax - r2.xmin, a2 = r2.ymax - r2.ymin;
    return [i2, s2 * s2 + a2 * a2];
  }
  static minmax_tree_process_level(e2, n2, o2, i2) {
    let r2, s2;
    for (let a3 of n2) {
      [r2, s2] = t15.box2box_minmax(e2.box, a3.item.key);
      for (let t48 of a3.item.values) t48 instanceof Nd.Edge ? i2.insert([r2, s2], t48.shape) : i2.insert([r2, s2], t48);
      Nd.Utils.LT(s2, o2) && (o2 = s2);
    }
    if (0 === n2.length) return o2;
    let a2 = [...n2.map((t48) => t48.left.isNil() ? void 0 : t48.left).filter((t48) => void 0 !== t48), ...n2.map((t48) => t48.right.isNil() ? void 0 : t48.right).filter((t48) => void 0 !== t48)].filter((n3) => {
      let [i3, r3] = t15.box2box_minmax(e2.box, n3.max);
      return Nd.Utils.LE(i3, o2);
    });
    return o2 = t15.minmax_tree_process_level(e2, a2, o2, i2);
  }
  static minmax_tree(e2, n2, o2) {
    let i2 = new hp(), r2 = [n2.index.root], s2 = o2 < Number.POSITIVE_INFINITY ? o2 * o2 : Number.POSITIVE_INFINITY;
    return s2 = t15.minmax_tree_process_level(e2, r2, s2, i2), i2;
  }
  static minmax_tree_calc_distance(e2, n2, o2) {
    let i2, r2;
    if (null != n2 && !n2.isNil()) {
      if ([i2, r2] = t15.minmax_tree_calc_distance(e2, n2.left, o2), r2) return [i2, r2];
      if (Nd.Utils.LT(i2[0], Math.sqrt(n2.item.key.low))) return [i2, true];
      let [s2, a2] = t15.distanceToArray(e2, n2.item.values);
      return Nd.Utils.LT(s2, i2[0]) && (i2 = [s2, a2]), [i2, r2] = t15.minmax_tree_calc_distance(e2, n2.right, i2), [i2, r2];
    }
    return [o2, false];
  }
  static shape2planarSet(e2, n2, o2 = Number.POSITIVE_INFINITY) {
    let i2 = [o2, new Nd.Segment()], r2 = false;
    if (n2 instanceof Nd.PlanarSet) {
      let s2 = t15.minmax_tree(e2, n2, o2);
      [i2, r2] = t15.minmax_tree_calc_distance(e2, s2.root, i2);
    }
    return i2;
  }
  static sort(t48) {
    t48.sort((t49, e2) => Nd.Utils.LT(t49[0], e2[0]) ? -1 : Nd.Utils.GT(t49[0], e2[0]) ? 1 : 0);
  }
  static distance(t48, e2) {
    return t48.distanceTo(e2);
  }
  static distanceToArray(t48, e2) {
    let n2 = [Number.POSITIVE_INFINITY, new Nd.Segment()];
    for (let o2 of e2) {
      let [e3, i2] = t48.distanceTo(o2);
      Nd.Utils.LT(e3, n2[0]) && (n2 = [e3, i2]);
    }
    return n2;
  }
  static shape2multiline(e2, n2) {
    let o2 = [Number.POSITIVE_INFINITY, new Nd.Segment()];
    for (let i2 of n2) {
      let [n3, r2] = t15.distance(e2, i2.shape);
      Nd.Utils.LT(n3, o2[0]) && (o2 = [n3, r2]);
    }
    return o2;
  }
  static multiline2multiline(e2, n2) {
    let o2 = [Number.POSITIVE_INFINITY, new Nd.Segment()];
    for (let i2 of e2) for (let e3 of n2) {
      let [n3, r2] = t15.distance(i2.shape, e3.shape);
      Nd.Utils.LT(n3, o2[0]) && (o2 = [n3, r2]);
    }
    return o2;
  }
};
var { Multiline: vp, Point: Sp, Segment: Ip, Polygon: Pp } = Nd;
function Mp(t48) {
  return new Sp(t48.split(" ").map(Number));
}
function Cp(t48) {
  return t48.split(", ").map(Mp);
}
function Np(t48) {
  const e2 = Cp(t48);
  let n2 = [];
  for (let t49 = 0; t49 < e2.length - 1; t49++) n2.push(new Ip(e2[t49], e2[t49 + 1]));
  return new vp(n2);
}
function wp(t48) {
  const e2 = t48.replace(/\(\(/, "").replace(/\)\)$/, "").split("), ("), n2 = new Pp();
  let o2;
  return e2.forEach((t49, e3) => {
    let i2 = t49.split(", ").map((t50) => new Sp(t50.split(" ").map(Number)));
    const r2 = n2.addFace(i2);
    0 === e3 ? o2 = r2.orientation() : r2.orientation() === o2 && r2.reverse();
  }), n2;
}
function Tp(t48) {
  if (t48.startsWith("POLYGON")) {
    return wp(t48.replace(/^POLYGON /, ""));
  }
  return (function(t49) {
    const e2 = t49.split(/\)\), \(\(/).map((t50) => "((" + t50 + "))").map(wp), n2 = new Pp();
    return e2.reduce((t50, e3) => [...t50, ...e3?.faces], []).forEach((t50) => n2.addFace([...t50?.shapes])), n2;
  })(t48.replace(/^MULTIPOLYGON \(\(\((.*)\)\)\)$/, "$1"));
}
function Rp(t48) {
  return t48.split("\n")?.every((t49) => t49.includes("POINT"));
}
function Ep(t48) {
  return t48.split("\n")?.every((t49) => t49.includes("LINESTRING"));
}
Nd.isWktString = function(t48) {
  return t48.startsWith("POINT") || Rp(t48) || t48.startsWith("LINESTRING") || Ep(t48) || t48.startsWith("MULTILINESTRING") || t48.startsWith("POLYGON") || t48.startsWith("MULTIPOINT") || t48.startsWith("MULTIPOLYGON") || t48.startsWith("GEOMETRYCOLLECTION");
}, Nd.parseWKT = function t16(e2) {
  if (e2.startsWith("POINT")) {
    return Mp(e2.replace(/^POINT \(/, "").replace(/\)$/, ""));
  }
  if (e2.startsWith("MULTIPOINT")) {
    return Cp(e2.replace(/^MULTIPOINT \(/, "").replace(/\)$/, ""));
  }
  if (e2.startsWith("LINESTRING")) {
    return Np(e2.replace(/^LINESTRING \(/, "").replace(/\)$/, ""));
  }
  if (e2.startsWith("MULTILINESTRING")) {
    return (function(t48) {
      return t48.replace(/\(\(/, "").replace(/\)\)$/, "").split("), (").map(Np);
    })(e2.replace(/^MULTILINESTRING /, ""));
  }
  if (e2.startsWith("POLYGON") || e2.startsWith("MULTIPOLYGON")) return Tp(e2);
  if (e2.startsWith("GEOMETRYCOLLECTION")) {
    const n2 = /(?<type>POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \((?:[^\(\)]|\([^\)]*\))*\)/g, o2 = e2.match(n2);
    o2[0].startsWith("GEOMETRYCOLLECTION") && (o2[0] = o2[0].replace("GEOMETRYCOLLECTION (", ""));
    return o2.map(t16).map((t48) => t48 instanceof Array ? t48 : [t48]).reduce((t48, e3) => [...t48, ...e3], []);
  }
  return Rp(e2) ? (function(t48) {
    return t48.split("\n").map((t49) => t49.match(/\(([^)]+)\)/)[1]).map(Mp);
  })(e2) : Ep(e2) ? (function(t48) {
    return t48.split("\n").map((t49) => t49.match(/\(([^)]+)\)/)[1]).map(Np).reduce((t49, e3) => [...t49, ...e3], []);
  })(e2) : [];
}, Nd.BooleanOperations = Hu, Nd.Relations = rp;
Ap = fh(), Op = 1, Lp = null != Ap ? Jl(eh(Ap)) : {}, ((t48, e2, n2, o2) => {
  if (e2 && "object" == typeof e2 || "function" == typeof e2) for (let i2 of th(e2)) nh.call(t48, i2) || i2 === n2 || Kl(t48, i2, { get: () => e2[i2], enumerable: !(o2 = Ql(e2, i2)) || o2.enumerable });
})(!Op && Ap && Ap.__esModule ? Lp : Kl(Lp, "default", { value: Ap, enumerable: true }), Ap);
var Ap;
var Op;
var Lp;
var Dp = Object.create;
var zp = Object.defineProperty;
var kp = Object.getOwnPropertyDescriptor;
var Fp = Object.getOwnPropertyNames;
var jp = Object.getPrototypeOf;
var Yp = Object.prototype.hasOwnProperty;
var $p = (t48, e2) => function() {
  return e2 || (0, t48[Fp(t48)[0]])((e2 = { exports: {} }).exports, e2), e2.exports;
};
var Xp = (t48, e2, n2) => (n2 = null != t48 ? Dp(jp(t48)) : {}, ((t49, e3, n3, o2) => {
  if (e3 && "object" == typeof e3 || "function" == typeof e3) for (let i2 of Fp(e3)) Yp.call(t49, i2) || i2 === n3 || zp(t49, i2, { get: () => e3[i2], enumerable: !(o2 = kp(e3, i2)) || o2.enumerable });
  return t49;
})(!e2 && t48 && t48.__esModule ? n2 : zp(n2, "default", { value: t48, enumerable: true }), t48));
var Bp = $p({ "node_modules/is-buffer/index.js"(t48, e2) {
  function n2(t49) {
    return !!t49.constructor && "function" == typeof t49.constructor.isBuffer && t49.constructor.isBuffer(t49);
  }
  e2.exports = function(t49) {
    return null != t49 && (n2(t49) || (function(t50) {
      return "function" == typeof t50.readFloatLE && "function" == typeof t50.slice && n2(t50.slice(0, 0));
    })(t49) || !!t49._isBuffer);
  };
} });
var Hp = $p({ "node_modules/kind-of/index.js"(t48, e2) {
  var n2 = Bp(), o2 = Object.prototype.toString;
  e2.exports = function(t49) {
    if (void 0 === t49) return "undefined";
    if (null === t49) return "null";
    if (true === t49 || false === t49 || t49 instanceof Boolean) return "boolean";
    if ("string" == typeof t49 || t49 instanceof String) return "string";
    if ("number" == typeof t49 || t49 instanceof Number) return "number";
    if ("function" == typeof t49 || t49 instanceof Function) return "function";
    if (void 0 !== Array.isArray && Array.isArray(t49)) return "array";
    if (t49 instanceof RegExp) return "regexp";
    if (t49 instanceof Date) return "date";
    var e3 = o2.call(t49);
    return "[object RegExp]" === e3 ? "regexp" : "[object Date]" === e3 ? "date" : "[object Arguments]" === e3 ? "arguments" : "[object Error]" === e3 ? "error" : n2(t49) ? "buffer" : "[object Set]" === e3 ? "set" : "[object WeakSet]" === e3 ? "weakset" : "[object Map]" === e3 ? "map" : "[object WeakMap]" === e3 ? "weakmap" : "[object Symbol]" === e3 ? "symbol" : "[object Int8Array]" === e3 ? "int8array" : "[object Uint8Array]" === e3 ? "uint8array" : "[object Uint8ClampedArray]" === e3 ? "uint8clampedarray" : "[object Int16Array]" === e3 ? "int16array" : "[object Uint16Array]" === e3 ? "uint16array" : "[object Int32Array]" === e3 ? "int32array" : "[object Uint32Array]" === e3 ? "uint32array" : "[object Float32Array]" === e3 ? "float32array" : "[object Float64Array]" === e3 ? "float64array" : "object";
  };
} });
var Wp = $p({ "node_modules/rename-keys/index.js"(t48, e2) {
  !(function() {
    function t49(t50, e3) {
      if ("function" != typeof e3) return t50;
      var n2 = {};
      for (var o2 in t50) Object.prototype.hasOwnProperty.call(t50, o2) && (n2[e3(o2, t50[o2]) || o2] = t50[o2]);
      return n2;
    }
    void 0 !== e2 && e2.exports ? e2.exports = t49 : "function" == typeof define && define.amd ? define([], function() {
      return t49;
    }) : window.rename = t49;
  })();
} });
var Vp = $p({ "node_modules/deep-rename-keys/index.js"(t48, e2) {
  var n2 = Hp(), o2 = Wp();
  e2.exports = function t49(e3, i2) {
    var r2 = n2(e3);
    if ("object" !== r2 && "array" !== r2) throw new Error("expected an object");
    var s2 = [];
    for (var a2 in "object" === r2 && (e3 = o2(e3, i2), s2 = {}), e3) if (e3.hasOwnProperty(a2)) {
      var c2 = e3[a2];
      "object" === n2(c2) || "array" === n2(c2) ? s2[a2] = t49(c2, i2) : s2[a2] = c2;
    }
    return s2;
  };
} });
var Up = $p({ "node_modules/eventemitter3/index.js"(t48, e2) {
  var n2 = Object.prototype.hasOwnProperty, o2 = "~";
  function i2() {
  }
  function r2(t49, e3, n3) {
    this.fn = t49, this.context = e3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i2(), this._eventsCount = 0;
  }
  Object.create && (i2.prototype = /* @__PURE__ */ Object.create(null), new i2().__proto__ || (o2 = false)), s2.prototype.eventNames = function() {
    var t49, e3, i3 = [];
    if (0 === this._eventsCount) return i3;
    for (e3 in t49 = this._events) n2.call(t49, e3) && i3.push(o2 ? e3.slice(1) : e3);
    return Object.getOwnPropertySymbols ? i3.concat(Object.getOwnPropertySymbols(t49)) : i3;
  }, s2.prototype.listeners = function(t49, e3) {
    var n3 = o2 ? o2 + t49 : t49, i3 = this._events[n3];
    if (e3) return !!i3;
    if (!i3) return [];
    if (i3.fn) return [i3.fn];
    for (var r3 = 0, s3 = i3.length, a2 = new Array(s3); r3 < s3; r3++) a2[r3] = i3[r3].fn;
    return a2;
  }, s2.prototype.emit = function(t49, e3, n3, i3, r3, s3) {
    var a2 = o2 ? o2 + t49 : t49;
    if (!this._events[a2]) return false;
    var c2, l2, h2 = this._events[a2], d2 = arguments.length;
    if (h2.fn) {
      switch (h2.once && this.removeListener(t49, h2.fn, void 0, true), d2) {
        case 1:
          return h2.fn.call(h2.context), true;
        case 2:
          return h2.fn.call(h2.context, e3), true;
        case 3:
          return h2.fn.call(h2.context, e3, n3), true;
        case 4:
          return h2.fn.call(h2.context, e3, n3, i3), true;
        case 5:
          return h2.fn.call(h2.context, e3, n3, i3, r3), true;
        case 6:
          return h2.fn.call(h2.context, e3, n3, i3, r3, s3), true;
      }
      for (l2 = 1, c2 = new Array(d2 - 1); l2 < d2; l2++) c2[l2 - 1] = arguments[l2];
      h2.fn.apply(h2.context, c2);
    } else {
      var u2, p2 = h2.length;
      for (l2 = 0; l2 < p2; l2++) switch (h2[l2].once && this.removeListener(t49, h2[l2].fn, void 0, true), d2) {
        case 1:
          h2[l2].fn.call(h2[l2].context);
          break;
        case 2:
          h2[l2].fn.call(h2[l2].context, e3);
          break;
        case 3:
          h2[l2].fn.call(h2[l2].context, e3, n3);
          break;
        case 4:
          h2[l2].fn.call(h2[l2].context, e3, n3, i3);
          break;
        default:
          if (!c2) for (u2 = 1, c2 = new Array(d2 - 1); u2 < d2; u2++) c2[u2 - 1] = arguments[u2];
          h2[l2].fn.apply(h2[l2].context, c2);
      }
    }
    return true;
  }, s2.prototype.on = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.once = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this, true), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(t49, e3, n3, r3) {
    var s3 = o2 ? o2 + t49 : t49;
    if (!this._events[s3]) return this;
    if (!e3) return 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3], this;
    var a2 = this._events[s3];
    if (a2.fn) a2.fn !== e3 || r3 && !a2.once || n3 && a2.context !== n3 || (0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3]);
    else {
      for (var c2 = 0, l2 = [], h2 = a2.length; c2 < h2; c2++) (a2[c2].fn !== e3 || r3 && !a2[c2].once || n3 && a2[c2].context !== n3) && l2.push(a2[c2]);
      l2.length ? this._events[s3] = 1 === l2.length ? l2[0] : l2 : 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(t49) {
    var e3;
    return t49 ? (e3 = o2 ? o2 + t49 : t49, this._events[e3] && (0 === --this._eventsCount ? this._events = new i2() : delete this._events[e3])) : (this._events = new i2(), this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o2, s2.EventEmitter = s2, void 0 !== e2 && (e2.exports = s2);
} });
var Gp = $p({ "node_modules/xml-lexer/dist/lexer.js"(t48, e2) {
  function n2(t49, e3, n3) {
    return e3 in t49 ? Object.defineProperty(t49, e3, { value: n3, enumerable: true, configurable: true, writable: true }) : t49[e3] = n3, t49;
  }
  var o2 = Up(), i2 = function() {
  }, r2 = { 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" }, s2 = { lt: "action-lt", gt: "action-gt", space: "action-space", equal: "action-equal", quote: "action-quote", slash: "action-slash", char: "action-char", error: "action-error" }, a2 = { text: "text", openTag: "open-tag", closeTag: "close-tag", attributeName: "attribute-name", attributeValue: "attribute-value" }, c2 = { " ": s2.space, "	": s2.space, "\n": s2.space, "\r": s2.space, "<": s2.lt, ">": s2.gt, '"': s2.quote, "'": s2.quote, "=": s2.equal, "/": s2.slash };
  e2.exports = { State: r2, Action: s2, Type: a2, create: function(t49) {
    var e3, l2, h2, d2, u2, p2, m2, g2, f2, _2;
    t49 = Object.assign({ debug: false }, t49);
    var y2 = new o2(), b2 = r2.data, x2 = "", v2 = "", S2 = "", I2 = "", P2 = "", M2 = "", C2 = function(e4, n3) {
      if ("?" !== v2[0] && "!" !== v2[0]) {
        var o3 = { type: e4, value: n3 };
        t49.debug && console.log("emit:", o3), y2.emit("data", o3);
      }
    };
    y2.stateMachine = (n2(_2 = {}, r2.data, (n2(e3 = {}, s2.lt, function() {
      x2.trim() && C2(a2.text, x2), v2 = "", P2 = false, b2 = r2.tagBegin;
    }), n2(e3, s2.char, function(t50) {
      x2 += t50;
    }), e3)), n2(_2, r2.cdata, n2({}, s2.char, function(t50) {
      "]]>" === (x2 += t50).substr(-3) && (C2(a2.text, x2.slice(0, -3)), x2 = "", b2 = r2.data);
    })), n2(_2, r2.tagBegin, (n2(l2 = {}, s2.space, i2), n2(l2, s2.char, function(t50) {
      v2 = t50, b2 = r2.tagName;
    }), n2(l2, s2.slash, function() {
      v2 = "", P2 = true;
    }), l2)), n2(_2, r2.tagName, (n2(h2 = {}, s2.space, function() {
      P2 ? b2 = r2.tagEnd : (b2 = r2.attributeNameStart, C2(a2.openTag, v2));
    }), n2(h2, s2.gt, function() {
      C2(P2 ? a2.closeTag : a2.openTag, v2), x2 = "", b2 = r2.data;
    }), n2(h2, s2.slash, function() {
      b2 = r2.tagEnd, C2(a2.openTag, v2);
    }), n2(h2, s2.char, function(t50) {
      "![CDATA[" === (v2 += t50) && (b2 = r2.cdata, x2 = "", v2 = "");
    }), h2)), n2(_2, r2.tagEnd, (n2(d2 = {}, s2.gt, function() {
      C2(a2.closeTag, v2), x2 = "", b2 = r2.data;
    }), n2(d2, s2.char, i2), d2)), n2(_2, r2.attributeNameStart, (n2(u2 = {}, s2.char, function(t50) {
      S2 = t50, b2 = r2.attributeName;
    }), n2(u2, s2.gt, function() {
      x2 = "", b2 = r2.data;
    }), n2(u2, s2.space, i2), n2(u2, s2.slash, function() {
      P2 = true, b2 = r2.tagEnd;
    }), u2)), n2(_2, r2.attributeName, (n2(p2 = {}, s2.space, function() {
      b2 = r2.attributeNameEnd;
    }), n2(p2, s2.equal, function() {
      C2(a2.attributeName, S2), b2 = r2.attributeValueBegin;
    }), n2(p2, s2.gt, function() {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), x2 = "", b2 = r2.data;
    }), n2(p2, s2.slash, function() {
      P2 = true, I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), b2 = r2.tagEnd;
    }), n2(p2, s2.char, function(t50) {
      S2 += t50;
    }), p2)), n2(_2, r2.attributeNameEnd, (n2(m2 = {}, s2.space, i2), n2(m2, s2.equal, function() {
      C2(a2.attributeName, S2), b2 = r2.attributeValueBegin;
    }), n2(m2, s2.gt, function() {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), x2 = "", b2 = r2.data;
    }), n2(m2, s2.char, function(t50) {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), S2 = t50, b2 = r2.attributeName;
    }), m2)), n2(_2, r2.attributeValueBegin, (n2(g2 = {}, s2.space, i2), n2(g2, s2.quote, function(t50) {
      M2 = t50, I2 = "", b2 = r2.attributeValue;
    }), n2(g2, s2.gt, function() {
      C2(a2.attributeValue, I2 = ""), x2 = "", b2 = r2.data;
    }), n2(g2, s2.char, function(t50) {
      M2 = "", I2 = t50, b2 = r2.attributeValue;
    }), g2)), n2(_2, r2.attributeValue, (n2(f2 = {}, s2.space, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), b2 = r2.attributeNameStart);
    }), n2(f2, s2.quote, function(t50) {
      M2 === t50 ? (C2(a2.attributeValue, I2), b2 = r2.attributeNameStart) : I2 += t50;
    }), n2(f2, s2.gt, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), x2 = "", b2 = r2.data);
    }), n2(f2, s2.slash, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), P2 = true, b2 = r2.tagEnd);
    }), n2(f2, s2.char, function(t50) {
      I2 += t50;
    }), f2)), _2);
    var N2 = function(e4) {
      t49.debug && console.log(b2, e4);
      var n3 = y2.stateMachine[b2], o3 = n3[(function(t50) {
        return c2[t50] || s2.char;
      })(e4)] || n3[s2.error] || n3[s2.char];
      o3(e4);
    };
    return y2.write = function(t50) {
      for (var e4 = t50.length, n3 = 0; n3 < e4; n3++) N2(t50[n3]);
    }, y2;
  } };
} });
var Zp = $p({ "node_modules/xml-reader/dist/reader.js"(t48, e2) {
  var n2 = Up(), o2 = Gp(), i2 = o2.Type, r2 = { element: "element", text: "text" }, s2 = function(t49) {
    return Object.assign({ name: "", type: r2.element, value: "", parent: null, attributes: {}, children: [] }, t49);
  }, a2 = function(t49) {
    t49 = Object.assign({ stream: false, parentNodes: true, doneEvent: "done", tagPrefix: "tag:", emitTopLevelOnly: false, debug: false }, t49);
    var e3 = void 0, a3 = void 0, c2 = void 0, l2 = void 0, h2 = new n2(), d2 = function(n3) {
      switch (n3.type) {
        case i2.openTag:
          if (null === c2) (c2 = a3).name = n3.value;
          else {
            var o3 = s2({ name: n3.value, parent: c2 });
            c2.children.push(o3), c2 = o3;
          }
          break;
        case i2.closeTag:
          var d3 = c2.parent;
          if (t49.parentNodes || (c2.parent = null), c2.name !== n3.value) break;
          t49.stream && d3 === a3 && (a3.children = [], c2.parent = null), t49.emitTopLevelOnly && d3 !== a3 || (h2.emit(t49.tagPrefix + c2.name, c2), h2.emit("tag", c2.name, c2)), c2 === a3 && (e3.removeAllListeners("data"), h2.emit(t49.doneEvent, c2), a3 = null), c2 = d3;
          break;
        case i2.text:
          c2 && c2.children.push(s2({ type: r2.text, value: n3.value, parent: t49.parentNodes ? c2 : null }));
          break;
        case i2.attributeName:
          l2 = n3.value, c2.attributes[l2] = "";
          break;
        case i2.attributeValue:
          c2.attributes[l2] = n3.value;
      }
    };
    return h2.reset = function() {
      (e3 = o2.create({ debug: t49.debug })).on("data", d2), a3 = s2(), c2 = null, l2 = "", h2.parse = e3.write;
    }, h2.reset(), h2;
  };
  e2.exports = { parseSync: function(t49, e3) {
    e3 = Object.assign({}, e3, { stream: false, tagPrefix: ":" });
    var n3 = a2(e3), o3 = void 0;
    return n3.on("done", function(t50) {
      o3 = t50;
    }), n3.parse(t49), o3;
  }, create: a2, NodeType: r2 };
} });
var { cos: qp, sin: Jp, PI: Kp } = Math;
var { tan: Qp } = Math;
var tm = (Xp(Vp()), Xp(Zp()), Object.create);
var em = Object.defineProperty;
var nm = Object.getOwnPropertyDescriptor;
var om = Object.getOwnPropertyNames;
var im = Object.getPrototypeOf;
var rm = Object.prototype.hasOwnProperty;
var sm = (t48, e2) => function() {
  return e2 || (0, t48[om(t48)[0]])((e2 = { exports: {} }).exports, e2), e2.exports;
};
var am = (t48, e2, n2) => (n2 = null != t48 ? tm(im(t48)) : {}, ((t49, e3, n3, o2) => {
  if (e3 && "object" == typeof e3 || "function" == typeof e3) for (let i2 of om(e3)) rm.call(t49, i2) || i2 === n3 || em(t49, i2, { get: () => e3[i2], enumerable: !(o2 = nm(e3, i2)) || o2.enumerable });
  return t49;
})(!e2 && t48 && t48.__esModule ? n2 : em(n2, "default", { value: t48, enumerable: true }), t48));
var cm = sm({ "node_modules/is-buffer/index.js"(t48, e2) {
  function n2(t49) {
    return !!t49.constructor && "function" == typeof t49.constructor.isBuffer && t49.constructor.isBuffer(t49);
  }
  e2.exports = function(t49) {
    return null != t49 && (n2(t49) || (function(t50) {
      return "function" == typeof t50.readFloatLE && "function" == typeof t50.slice && n2(t50.slice(0, 0));
    })(t49) || !!t49._isBuffer);
  };
} });
var lm = sm({ "node_modules/kind-of/index.js"(t48, e2) {
  var n2 = cm(), o2 = Object.prototype.toString;
  e2.exports = function(t49) {
    if (void 0 === t49) return "undefined";
    if (null === t49) return "null";
    if (true === t49 || false === t49 || t49 instanceof Boolean) return "boolean";
    if ("string" == typeof t49 || t49 instanceof String) return "string";
    if ("number" == typeof t49 || t49 instanceof Number) return "number";
    if ("function" == typeof t49 || t49 instanceof Function) return "function";
    if (void 0 !== Array.isArray && Array.isArray(t49)) return "array";
    if (t49 instanceof RegExp) return "regexp";
    if (t49 instanceof Date) return "date";
    var e3 = o2.call(t49);
    return "[object RegExp]" === e3 ? "regexp" : "[object Date]" === e3 ? "date" : "[object Arguments]" === e3 ? "arguments" : "[object Error]" === e3 ? "error" : n2(t49) ? "buffer" : "[object Set]" === e3 ? "set" : "[object WeakSet]" === e3 ? "weakset" : "[object Map]" === e3 ? "map" : "[object WeakMap]" === e3 ? "weakmap" : "[object Symbol]" === e3 ? "symbol" : "[object Int8Array]" === e3 ? "int8array" : "[object Uint8Array]" === e3 ? "uint8array" : "[object Uint8ClampedArray]" === e3 ? "uint8clampedarray" : "[object Int16Array]" === e3 ? "int16array" : "[object Uint16Array]" === e3 ? "uint16array" : "[object Int32Array]" === e3 ? "int32array" : "[object Uint32Array]" === e3 ? "uint32array" : "[object Float32Array]" === e3 ? "float32array" : "[object Float64Array]" === e3 ? "float64array" : "object";
  };
} });
var hm = sm({ "node_modules/rename-keys/index.js"(t48, e2) {
  !(function() {
    function t49(t50, e3) {
      if ("function" != typeof e3) return t50;
      var n2 = {};
      for (var o2 in t50) Object.prototype.hasOwnProperty.call(t50, o2) && (n2[e3(o2, t50[o2]) || o2] = t50[o2]);
      return n2;
    }
    void 0 !== e2 && e2.exports ? e2.exports = t49 : "function" == typeof define && define.amd ? define([], function() {
      return t49;
    }) : window.rename = t49;
  })();
} });
var dm = sm({ "node_modules/deep-rename-keys/index.js"(t48, e2) {
  var n2 = lm(), o2 = hm();
  e2.exports = function t49(e3, i2) {
    var r2 = n2(e3);
    if ("object" !== r2 && "array" !== r2) throw new Error("expected an object");
    var s2 = [];
    for (var a2 in "object" === r2 && (e3 = o2(e3, i2), s2 = {}), e3) if (e3.hasOwnProperty(a2)) {
      var c2 = e3[a2];
      "object" === n2(c2) || "array" === n2(c2) ? s2[a2] = t49(c2, i2) : s2[a2] = c2;
    }
    return s2;
  };
} });
var um = sm({ "node_modules/eventemitter3/index.js"(t48, e2) {
  var n2 = Object.prototype.hasOwnProperty, o2 = "~";
  function i2() {
  }
  function r2(t49, e3, n3) {
    this.fn = t49, this.context = e3, this.once = n3 || false;
  }
  function s2() {
    this._events = new i2(), this._eventsCount = 0;
  }
  Object.create && (i2.prototype = /* @__PURE__ */ Object.create(null), new i2().__proto__ || (o2 = false)), s2.prototype.eventNames = function() {
    var t49, e3, i3 = [];
    if (0 === this._eventsCount) return i3;
    for (e3 in t49 = this._events) n2.call(t49, e3) && i3.push(o2 ? e3.slice(1) : e3);
    return Object.getOwnPropertySymbols ? i3.concat(Object.getOwnPropertySymbols(t49)) : i3;
  }, s2.prototype.listeners = function(t49, e3) {
    var n3 = o2 ? o2 + t49 : t49, i3 = this._events[n3];
    if (e3) return !!i3;
    if (!i3) return [];
    if (i3.fn) return [i3.fn];
    for (var r3 = 0, s3 = i3.length, a2 = new Array(s3); r3 < s3; r3++) a2[r3] = i3[r3].fn;
    return a2;
  }, s2.prototype.emit = function(t49, e3, n3, i3, r3, s3) {
    var a2 = o2 ? o2 + t49 : t49;
    if (!this._events[a2]) return false;
    var c2, l2, h2 = this._events[a2], d2 = arguments.length;
    if (h2.fn) {
      switch (h2.once && this.removeListener(t49, h2.fn, void 0, true), d2) {
        case 1:
          return h2.fn.call(h2.context), true;
        case 2:
          return h2.fn.call(h2.context, e3), true;
        case 3:
          return h2.fn.call(h2.context, e3, n3), true;
        case 4:
          return h2.fn.call(h2.context, e3, n3, i3), true;
        case 5:
          return h2.fn.call(h2.context, e3, n3, i3, r3), true;
        case 6:
          return h2.fn.call(h2.context, e3, n3, i3, r3, s3), true;
      }
      for (l2 = 1, c2 = new Array(d2 - 1); l2 < d2; l2++) c2[l2 - 1] = arguments[l2];
      h2.fn.apply(h2.context, c2);
    } else {
      var u2, p2 = h2.length;
      for (l2 = 0; l2 < p2; l2++) switch (h2[l2].once && this.removeListener(t49, h2[l2].fn, void 0, true), d2) {
        case 1:
          h2[l2].fn.call(h2[l2].context);
          break;
        case 2:
          h2[l2].fn.call(h2[l2].context, e3);
          break;
        case 3:
          h2[l2].fn.call(h2[l2].context, e3, n3);
          break;
        case 4:
          h2[l2].fn.call(h2[l2].context, e3, n3, i3);
          break;
        default:
          if (!c2) for (u2 = 1, c2 = new Array(d2 - 1); u2 < d2; u2++) c2[u2 - 1] = arguments[u2];
          h2[l2].fn.apply(h2[l2].context, c2);
      }
    }
    return true;
  }, s2.prototype.on = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.once = function(t49, e3, n3) {
    var i3 = new r2(e3, n3 || this, true), s3 = o2 ? o2 + t49 : t49;
    return this._events[s3] ? this._events[s3].fn ? this._events[s3] = [this._events[s3], i3] : this._events[s3].push(i3) : (this._events[s3] = i3, this._eventsCount++), this;
  }, s2.prototype.removeListener = function(t49, e3, n3, r3) {
    var s3 = o2 ? o2 + t49 : t49;
    if (!this._events[s3]) return this;
    if (!e3) return 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3], this;
    var a2 = this._events[s3];
    if (a2.fn) a2.fn !== e3 || r3 && !a2.once || n3 && a2.context !== n3 || (0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3]);
    else {
      for (var c2 = 0, l2 = [], h2 = a2.length; c2 < h2; c2++) (a2[c2].fn !== e3 || r3 && !a2[c2].once || n3 && a2[c2].context !== n3) && l2.push(a2[c2]);
      l2.length ? this._events[s3] = 1 === l2.length ? l2[0] : l2 : 0 === --this._eventsCount ? this._events = new i2() : delete this._events[s3];
    }
    return this;
  }, s2.prototype.removeAllListeners = function(t49) {
    var e3;
    return t49 ? (e3 = o2 ? o2 + t49 : t49, this._events[e3] && (0 === --this._eventsCount ? this._events = new i2() : delete this._events[e3])) : (this._events = new i2(), this._eventsCount = 0), this;
  }, s2.prototype.off = s2.prototype.removeListener, s2.prototype.addListener = s2.prototype.on, s2.prototype.setMaxListeners = function() {
    return this;
  }, s2.prefixed = o2, s2.EventEmitter = s2, void 0 !== e2 && (e2.exports = s2);
} });
var pm = sm({ "node_modules/xml-lexer/dist/lexer.js"(t48, e2) {
  function n2(t49, e3, n3) {
    return e3 in t49 ? Object.defineProperty(t49, e3, { value: n3, enumerable: true, configurable: true, writable: true }) : t49[e3] = n3, t49;
  }
  var o2 = um(), i2 = function() {
  }, r2 = { 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" }, s2 = { lt: "action-lt", gt: "action-gt", space: "action-space", equal: "action-equal", quote: "action-quote", slash: "action-slash", char: "action-char", error: "action-error" }, a2 = { text: "text", openTag: "open-tag", closeTag: "close-tag", attributeName: "attribute-name", attributeValue: "attribute-value" }, c2 = { " ": s2.space, "	": s2.space, "\n": s2.space, "\r": s2.space, "<": s2.lt, ">": s2.gt, '"': s2.quote, "'": s2.quote, "=": s2.equal, "/": s2.slash };
  e2.exports = { State: r2, Action: s2, Type: a2, create: function(t49) {
    var e3, l2, h2, d2, u2, p2, m2, g2, f2, _2;
    t49 = Object.assign({ debug: false }, t49);
    var y2 = new o2(), b2 = r2.data, x2 = "", v2 = "", S2 = "", I2 = "", P2 = "", M2 = "", C2 = function(e4, n3) {
      if ("?" !== v2[0] && "!" !== v2[0]) {
        var o3 = { type: e4, value: n3 };
        t49.debug && console.log("emit:", o3), y2.emit("data", o3);
      }
    };
    y2.stateMachine = (n2(_2 = {}, r2.data, (n2(e3 = {}, s2.lt, function() {
      x2.trim() && C2(a2.text, x2), v2 = "", P2 = false, b2 = r2.tagBegin;
    }), n2(e3, s2.char, function(t50) {
      x2 += t50;
    }), e3)), n2(_2, r2.cdata, n2({}, s2.char, function(t50) {
      "]]>" === (x2 += t50).substr(-3) && (C2(a2.text, x2.slice(0, -3)), x2 = "", b2 = r2.data);
    })), n2(_2, r2.tagBegin, (n2(l2 = {}, s2.space, i2), n2(l2, s2.char, function(t50) {
      v2 = t50, b2 = r2.tagName;
    }), n2(l2, s2.slash, function() {
      v2 = "", P2 = true;
    }), l2)), n2(_2, r2.tagName, (n2(h2 = {}, s2.space, function() {
      P2 ? b2 = r2.tagEnd : (b2 = r2.attributeNameStart, C2(a2.openTag, v2));
    }), n2(h2, s2.gt, function() {
      C2(P2 ? a2.closeTag : a2.openTag, v2), x2 = "", b2 = r2.data;
    }), n2(h2, s2.slash, function() {
      b2 = r2.tagEnd, C2(a2.openTag, v2);
    }), n2(h2, s2.char, function(t50) {
      "![CDATA[" === (v2 += t50) && (b2 = r2.cdata, x2 = "", v2 = "");
    }), h2)), n2(_2, r2.tagEnd, (n2(d2 = {}, s2.gt, function() {
      C2(a2.closeTag, v2), x2 = "", b2 = r2.data;
    }), n2(d2, s2.char, i2), d2)), n2(_2, r2.attributeNameStart, (n2(u2 = {}, s2.char, function(t50) {
      S2 = t50, b2 = r2.attributeName;
    }), n2(u2, s2.gt, function() {
      x2 = "", b2 = r2.data;
    }), n2(u2, s2.space, i2), n2(u2, s2.slash, function() {
      P2 = true, b2 = r2.tagEnd;
    }), u2)), n2(_2, r2.attributeName, (n2(p2 = {}, s2.space, function() {
      b2 = r2.attributeNameEnd;
    }), n2(p2, s2.equal, function() {
      C2(a2.attributeName, S2), b2 = r2.attributeValueBegin;
    }), n2(p2, s2.gt, function() {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), x2 = "", b2 = r2.data;
    }), n2(p2, s2.slash, function() {
      P2 = true, I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), b2 = r2.tagEnd;
    }), n2(p2, s2.char, function(t50) {
      S2 += t50;
    }), p2)), n2(_2, r2.attributeNameEnd, (n2(m2 = {}, s2.space, i2), n2(m2, s2.equal, function() {
      C2(a2.attributeName, S2), b2 = r2.attributeValueBegin;
    }), n2(m2, s2.gt, function() {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), x2 = "", b2 = r2.data;
    }), n2(m2, s2.char, function(t50) {
      I2 = "", C2(a2.attributeName, S2), C2(a2.attributeValue, I2), S2 = t50, b2 = r2.attributeName;
    }), m2)), n2(_2, r2.attributeValueBegin, (n2(g2 = {}, s2.space, i2), n2(g2, s2.quote, function(t50) {
      M2 = t50, I2 = "", b2 = r2.attributeValue;
    }), n2(g2, s2.gt, function() {
      C2(a2.attributeValue, I2 = ""), x2 = "", b2 = r2.data;
    }), n2(g2, s2.char, function(t50) {
      M2 = "", I2 = t50, b2 = r2.attributeValue;
    }), g2)), n2(_2, r2.attributeValue, (n2(f2 = {}, s2.space, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), b2 = r2.attributeNameStart);
    }), n2(f2, s2.quote, function(t50) {
      M2 === t50 ? (C2(a2.attributeValue, I2), b2 = r2.attributeNameStart) : I2 += t50;
    }), n2(f2, s2.gt, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), x2 = "", b2 = r2.data);
    }), n2(f2, s2.slash, function(t50) {
      M2 ? I2 += t50 : (C2(a2.attributeValue, I2), P2 = true, b2 = r2.tagEnd);
    }), n2(f2, s2.char, function(t50) {
      I2 += t50;
    }), f2)), _2);
    var N2 = function(e4) {
      t49.debug && console.log(b2, e4);
      var n3 = y2.stateMachine[b2], o3 = n3[(function(t50) {
        return c2[t50] || s2.char;
      })(e4)] || n3[s2.error] || n3[s2.char];
      o3(e4);
    };
    return y2.write = function(t50) {
      for (var e4 = t50.length, n3 = 0; n3 < e4; n3++) N2(t50[n3]);
    }, y2;
  } };
} });
var mm = sm({ "node_modules/xml-reader/dist/reader.js"(t48, e2) {
  var n2 = um(), o2 = pm(), i2 = o2.Type, r2 = { element: "element", text: "text" }, s2 = function(t49) {
    return Object.assign({ name: "", type: r2.element, value: "", parent: null, attributes: {}, children: [] }, t49);
  }, a2 = function(t49) {
    t49 = Object.assign({ stream: false, parentNodes: true, doneEvent: "done", tagPrefix: "tag:", emitTopLevelOnly: false, debug: false }, t49);
    var e3 = void 0, a3 = void 0, c2 = void 0, l2 = void 0, h2 = new n2(), d2 = function(n3) {
      switch (n3.type) {
        case i2.openTag:
          if (null === c2) (c2 = a3).name = n3.value;
          else {
            var o3 = s2({ name: n3.value, parent: c2 });
            c2.children.push(o3), c2 = o3;
          }
          break;
        case i2.closeTag:
          var d3 = c2.parent;
          if (t49.parentNodes || (c2.parent = null), c2.name !== n3.value) break;
          t49.stream && d3 === a3 && (a3.children = [], c2.parent = null), t49.emitTopLevelOnly && d3 !== a3 || (h2.emit(t49.tagPrefix + c2.name, c2), h2.emit("tag", c2.name, c2)), c2 === a3 && (e3.removeAllListeners("data"), h2.emit(t49.doneEvent, c2), a3 = null), c2 = d3;
          break;
        case i2.text:
          c2 && c2.children.push(s2({ type: r2.text, value: n3.value, parent: t49.parentNodes ? c2 : null }));
          break;
        case i2.attributeName:
          l2 = n3.value, c2.attributes[l2] = "";
          break;
        case i2.attributeValue:
          c2.attributes[l2] = n3.value;
      }
    };
    return h2.reset = function() {
      (e3 = o2.create({ debug: t49.debug })).on("data", d2), a3 = s2(), c2 = null, l2 = "", h2.parse = e3.write;
    }, h2.reset(), h2;
  };
  e2.exports = { parseSync: function(t49, e3) {
    e3 = Object.assign({}, e3, { stream: false, tagPrefix: ":" });
    var n3 = a2(e3), o3 = void 0;
    return n3.on("done", function(t50) {
      o3 = t50;
    }), n3.parse(t49), o3;
  }, create: a2, NodeType: r2 };
} });
var { cos: gm, sin: fm, PI: _m } = Math;
var { tan: ym } = Math;
am(dm()), am(mm());
var mf = 0.65 + 0.05;
var c_ = 8 / 3;
var v_ = {};
a(v_, { all_layers: () => Bv, any_circuit_element: () => gM, any_soup_element: () => fM, any_source_component: () => Lv, asset: () => Tx, base_circuit_json_error: () => Wx, battery_capacity: () => xx, brep_shape: () => LS, cadModelDefaultDirectionMap: () => WP, cad_component: () => VP, cad_model_axis_directions: () => HP, cad_model_formats: () => BP, capacitance: () => cx, circuit_json_footprint_load_error: () => gP, current: () => mx, distance: () => px, duration_ms: () => gx, experiment_type: () => nM, external_footprint_load_error: () => mP, frequency: () => ux, getZodPrefixedIdWithDefault: () => Cx, inductance: () => lx, kicadAt: () => Rx, kicadEffects: () => Ax, kicadFont: () => Ex, kicadFootprintAttributes: () => Dx, kicadFootprintMetadata: () => Fx, kicadFootprintModel: () => kx, kicadFootprintPad: () => zx, kicadFootprintProperties: () => Lx, kicadProperty: () => Ox, kicadSymbolEffects: () => $x, kicadSymbolMetadata: () => Hx, kicadSymbolPinNames: () => Yx, kicadSymbolPinNumbers: () => jx, kicadSymbolProperties: () => Bx, kicadSymbolProperty: () => Xx, layer_ref: () => Wv, layer_string: () => Hv, length: () => dx, manufacturing_drc_properties: () => FS, ms: () => _x, ninePointAnchor: () => Nx, parseAndConvertSiUnit: () => N_, pcbRenderLayer: () => wx, pcb_autorouting_error: () => _P, pcb_board: () => LI, pcb_breakout_point: () => SP, pcb_component: () => jS, pcb_component_invalid_layer_error: () => OP, pcb_component_not_on_board_edge_error: () => AP, pcb_component_outside_board_error: () => EP, pcb_connector_not_in_accessible_orientation_warning: () => xP, pcb_copper_pour: () => RP, pcb_copper_pour_brep: () => wP, pcb_copper_pour_polygon: () => TP, pcb_copper_pour_rect: () => NP, pcb_copper_text: () => XI, pcb_courtyard_circle: () => $P, pcb_courtyard_outline: () => jP, pcb_courtyard_overlap_error: () => rP, pcb_courtyard_pill: () => XP, pcb_courtyard_polygon: () => YP, pcb_courtyard_rect: () => FP, pcb_cutout: () => uP, pcb_cutout_circle: () => lP, pcb_cutout_path: () => dP, pcb_cutout_polygon: () => hP, pcb_cutout_rect: () => cP, pcb_fabrication_note_dimension: () => KI, pcb_fabrication_note_path: () => qI, pcb_fabrication_note_rect: () => JI, pcb_fabrication_note_text: () => ZI, pcb_footprint_overlap_error: () => iP, pcb_ground_plane: () => IP, pcb_ground_plane_region: () => PP, pcb_group: () => fP, pcb_hole: () => KS, pcb_hole_circle_or_square_shape: () => WS, pcb_hole_circle_shape: () => $S, pcb_hole_oval_shape: () => US, pcb_hole_pill_shape: () => ZS, pcb_hole_rect_shape: () => BS, pcb_hole_rotated_pill_shape: () => JS, pcb_keepout: () => sP, pcb_manual_edit_conflict_warning: () => yP, pcb_missing_footprint_error: () => pP, pcb_net: () => AI, pcb_note_dimension: () => oP, pcb_note_line: () => nP, pcb_note_path: () => eP, pcb_note_rect: () => tP, pcb_note_text: () => QI, pcb_pad_pad_clearance_error: () => zP, pcb_pad_trace_clearance_error: () => kP, pcb_panel: () => DI, pcb_panelization_placement_error: () => kI, pcb_placement_error: () => zI, pcb_plated_hole: () => rI, pcb_port: () => sI, pcb_port_not_connected_error: () => EI, pcb_port_not_matched_error: () => RI, pcb_route_hint: () => DS, pcb_route_hints: () => zS, pcb_silkscreen_circle: () => HI, pcb_silkscreen_graphic: () => UI, pcb_silkscreen_graphic_brep: () => VI, pcb_silkscreen_line: () => jI, pcb_silkscreen_oval: () => WI, pcb_silkscreen_path: () => YI, pcb_silkscreen_pill: () => GI, pcb_silkscreen_rect: () => BI, pcb_silkscreen_text: () => $I, pcb_smtpad: () => pI, pcb_smtpad_pill: () => hI, pcb_solder_paste: () => bI, pcb_text: () => xI, pcb_thermal_spoke: () => MP, pcb_trace: () => MI, pcb_trace_error: () => wI, pcb_trace_hint: () => FI, pcb_trace_missing_error: () => TI, pcb_trace_route_point: () => PI2, pcb_trace_route_point_through_pad: () => II, pcb_trace_route_point_via: () => SI, pcb_trace_route_point_wire: () => vI, pcb_trace_too_long_warning: () => NI, pcb_trace_warning: () => CI, pcb_via: () => OI, pcb_via_clearance_error: () => LP, pcb_via_trace_clearance_error: () => DP, point: () => vx, point3: () => Ix, point_with_bulge: () => AS, port_arrangement: () => sS, position: () => Sx, position3: () => Px, resistance: () => ax, ring: () => OS, rotation: () => bx, route_hint_point: () => kS, schematic_arc: () => pS, schematic_box: () => eS, schematic_circle: () => uS, schematic_component: () => aS, schematic_component_port_arrangement_by_sides: () => rS, schematic_component_port_arrangement_by_size: () => iS, schematic_debug_line: () => IS, schematic_debug_object: () => MS, schematic_debug_object_base: () => vS, schematic_debug_point: () => PS, schematic_debug_rect: () => SS, schematic_error: () => bS, schematic_group: () => wS, schematic_layout_error: () => xS, schematic_line: () => hS, schematic_manual_edit_conflict_warning: () => NS, schematic_net_label: () => yS, schematic_path: () => nS, schematic_pin_styles: () => oS, schematic_port: () => _S, schematic_rect: () => dS, schematic_sheet: () => ES, schematic_symbol: () => lS, schematic_table: () => TS, schematic_table_cell: () => RS, schematic_text: () => fS, schematic_trace: () => mS, schematic_voltage_probe: () => CS, simulation_ac_current_source: () => tM, simulation_ac_voltage_source: () => qP, simulation_current_probe: () => lM, simulation_current_source: () => eM, simulation_dc_current_source: () => QP, simulation_dc_voltage_source: () => ZP, simulation_experiment: () => iM, simulation_op_amp: () => dM, simulation_oscilloscope_trace: () => mM, simulation_spice_subcircuit: () => uM, simulation_switch: () => aM, simulation_transient_current_graph: () => sM, simulation_transient_voltage_graph: () => rM, simulation_unknown_experiment_error: () => hM, simulation_voltage_probe: () => cM, simulation_voltage_source: () => JP, size: () => Mx, source_ambiguous_port_reference: () => $v, source_board: () => Yv, source_component_base: () => Ux, source_component_internal_connection: () => zv, source_component_misconfigured_error: () => Av, source_component_pins_underspecified_warning: () => Jv, source_failed_to_create_component_error: () => Sv, source_group: () => Fv, source_i2c_misconfigured_error: () => Ev, source_interconnect: () => Rv, source_invalid_component_property_error: () => Iv, source_manually_placed_via: () => Uv, source_missing_manufacturer_part_number_warning: () => Nv, source_missing_property_error: () => vv, source_net: () => jv, source_no_ground_pin_defined_warning: () => qv, source_no_power_pin_defined_warning: () => Zv, source_part_not_found_warning: () => tS, source_pcb_ground_plane: () => Xv, source_pin_attributes: () => rv, source_pin_missing_trace_warning: () => Cv, source_pin_must_be_connected_error: () => Kv, source_port: () => Dv, source_project_metadata: () => xv, source_property_ignored_warning: () => Mv, source_refdes_convention_warning: () => wv, source_simple_ammeter: () => iv, source_simple_battery: () => sv, source_simple_capacitor: () => Gx, source_simple_chip: () => tv, source_simple_connector: () => uv, source_simple_crystal: () => hv, source_simple_current_source: () => nv, source_simple_diode: () => qx, source_simple_fiducial: () => Jx, source_simple_fuse: () => ov, source_simple_ground: () => Qx, source_simple_inductor: () => av, source_simple_led: () => Kx, source_simple_mosfet: () => _v, source_simple_op_amp: () => yv, source_simple_pin_header: () => dv, source_simple_pinout: () => pv, source_simple_potentiometer: () => lv, source_simple_power_source: () => ev, source_simple_push_button: () => cv, source_simple_resistor: () => Zx, source_simple_resonator: () => mv, source_simple_switch: () => bv, source_simple_test_point: () => fv, source_simple_transistor: () => gv, source_simple_voltage_probe: () => Tv, source_simple_voltage_source: () => Ov, source_trace: () => kv, source_trace_not_connected_error: () => Pv, source_unnamed_trace_warning: () => Gv, spice_simulation_options: () => oM, supplier_footprint_mismatch_warning: () => vP, supplier_name: () => Vx, time: () => fx, timestamp: () => yx, unknown_error_finding_part: () => Qv, visible_layer: () => Vv, voltage: () => hx, wave_shape: () => UP });
var S_ = /* @__PURE__ */ new Map([["T", 1e12], ["G", 1e9], ["M", 1e6], ["K", 1e3], ["k", 1e3], ["", 1], ["m", 1e-3], ["\xB5", 1e-6], ["u", 1e-6], ["n", 1e-9], ["p", 1e-12], ["f", 1e-15]]);
var I_ = [...S_.keys()];
function P_(t48) {
  return S_.get(t48);
}
var M_ = { Hz: { baseUnit: "Hz", variants: { MHz: 1e6, kHz: 1e3, Hz: 1 } }, g: { baseUnit: "g", variants: { kg: 1e3, g: 1 } }, "\u03A9": { baseUnit: "\u03A9", variants: { "m\u03A9": 1e-3, mohm: 1e-3, mOhm: 1e-3, milliohm: 1e-3, "\u03A9": 1, ohm: 1, Ohm: 1, "k\u03A9": 1e3, "K\u03A9": 1e3, kohm: 1e3, kOhm: 1e3, KOhm: 1e3, Kohm: 1e3, "M\u03A9": 1e6, Mohm: 1e6, MOhm: 1e6, megohm: 1e6, Megohm: 1e6, "G\u03A9": 1e9, Gohm: 1e9, GOhm: 1e9, "T\u03A9": 1e12, Tohm: 1e12, TOhm: 1e12 } }, V: { baseUnit: "V", variants: { mV: 1e-3, V: 1, kV: 1e3, KV: 1e3, MV: 1e6, GV: 1e9, TV: 1e12 } }, A: { baseUnit: "A", variants: { "\xB5A": 1e-6, mA: 1e-3, ma: 1e-3, A: 1, kA: 1e3, MA: 1e6 } }, F: { baseUnit: "F", variants: { pF: 1e-12, nF: 1e-9, "\xB5F": 1e-6, uF: 1e-6, mF: 1e-3, F: 1, kF: 1e3, KF: 1e3, MF: 1e6 } }, H: { baseUnit: "H", variants: { pH: 1e-12, nH: 1e-9, "\xB5H": 1e-6, uH: 1e-6, mH: 1e-3, 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: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3 } }, mm: { baseUnit: "mm", variants: { nm: 1e-6, "\xB5m": 1e-3, um: 1e-3, 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: 0.0254 } } };
var C_ = /* @__PURE__ */ new Set();
for (const [t48, e2] of Object.entries(M_)) {
  C_.add(t48);
  for (const t49 of Object.keys(e2.variants)) C_.add(t49);
}
function N_(t48, e2) {
  if (null == t48) return { parsedUnit: null, unitOfValue: null, value: null };
  if ("string" == typeof t48 && t48.match(/^-?[\d.]+$/)) return { value: Number.parseFloat(t48), parsedUnit: null, unitOfValue: null };
  if ("number" == typeof t48) return { value: t48, parsedUnit: null, unitOfValue: null };
  if ("object" == typeof t48 && "x" in t48 && "y" in t48) {
    const n3 = N_(t48.x, e2), o3 = N_(t48.x, e2), i3 = N_(t48.y, e2);
    return null === o3.value || null === i3.value ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: n3.parsedUnit, unitOfValue: n3.unitOfValue, value: { x: o3.value, y: i3.value } };
  }
  const n2 = t48.toString().split("").reverse().join(""), o2 = n2.match(/[^\d\s]+/)?.[0];
  if (!o2) throw new Error(`Could not determine unit: "${t48}"`);
  const i2 = o2.split("").reverse().join(""), r2 = t48.slice(0, -i2.length), s2 = P_(i2);
  if (e2 && null != s2) return { parsedUnit: null, unitOfValue: e2, value: Number.parseFloat(r2) * s2 };
  if (null != s2 && !C_.has(i2)) return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(r2) * s2 };
  const { baseUnit: a2, conversionFactor: c2 } = (function(t49) {
    for (const e3 of Object.values(M_)) {
      if (t49 in e3.variants) return { baseUnit: e3.baseUnit, conversionFactor: e3.variants[t49] };
      for (const [n3, o3] of Object.entries(e3.variants)) {
        if (!t49.endsWith(n3)) continue;
        const i3 = P_(t49.slice(0, -n3.length));
        if (null != i3) return { baseUnit: e3.baseUnit, conversionFactor: i3 * o3 };
      }
    }
    return { baseUnit: t49, conversionFactor: 1 };
  })(i2);
  return { parsedUnit: i2, unitOfValue: a2, value: c2 * Number.parseFloat(r2) };
}
var w_;
var T_;
var R_;
var E_ = I_.filter((t48) => "" !== t48).sort((t48, e2) => e2.length - t48.length).map((t48) => t48.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
var A_ = (new RegExp(`^([+-]?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:[eE][+-]?\\d+)?)(?:(${E_}))?$`), {});
a(A_, { BRAND: () => ub, DIRTY: () => Z_, EMPTY_PATH: () => B_, INVALID: () => G_, NEVER: () => sx, OK: () => q_, ParseStatus: () => U_, Schema: () => ry, ZodAny: () => ky, ZodArray: () => $y, ZodBigInt: () => Ey, ZodBoolean: () => Ay, ZodBranded: () => pb, ZodCatch: () => hb, ZodDate: () => Oy, ZodDefault: () => lb, ZodDiscriminatedUnion: () => Vy, ZodEffects: () => sb, ZodEnum: () => ob, ZodError: () => k_, ZodFirstPartyTypeKind: () => yb, ZodFunction: () => Qy, ZodIntersection: () => Gy, ZodIssueCode: () => D_, ZodLazy: () => tb, ZodLiteral: () => eb, ZodMap: () => Jy, ZodNaN: () => db, ZodNativeEnum: () => ib, ZodNever: () => jy, ZodNull: () => zy, ZodNullable: () => cb, ZodNumber: () => Ry, ZodObject: () => By, ZodOptional: () => ab, ZodParsedType: () => O_, ZodPipeline: () => mb, ZodPromise: () => rb, ZodReadonly: () => gb, ZodRecord: () => qy, ZodSchema: () => ry, ZodSet: () => Ky, ZodString: () => wy, ZodSymbol: () => Ly, ZodTransformer: () => sb, ZodTuple: () => Zy, ZodType: () => ry, ZodUndefined: () => Dy, ZodUnion: () => Hy, ZodUnknown: () => Fy, ZodVoid: () => Yy, addIssueToContext: () => H_, any: () => Eb, array: () => Db, bigint: () => Mb, boolean: () => Cb, coerce: () => rx, custom: () => _b, date: () => Nb, datetimeRegex: () => Py, defaultErrorMap: () => F_, discriminatedUnion: () => jb, effect: () => Jb, enum: () => Gb, function: () => Wb, getErrorMap: () => $_, getParsedType: () => L_, instanceof: () => vb, intersection: () => Yb, isAborted: () => J_, isAsync: () => ty, isDirty: () => K_, isValid: () => Q_, late: () => xb, lazy: () => Vb, literal: () => Ub, makeIssue: () => X_, map: () => Bb, nan: () => Pb, nativeEnum: () => Zb, never: () => Ob, null: () => Rb, nullable: () => Qb, number: () => Ib, object: () => zb, objectUtil: () => R_, oboolean: () => ix, onumber: () => ox, optional: () => Kb, ostring: () => nx, pipeline: () => ex, preprocess: () => tx, promise: () => qb, quotelessJson: () => z_, record: () => Xb, set: () => Hb, setErrorMap: () => Y_, strictObject: () => kb, string: () => Sb, symbol: () => wb, transformer: () => Jb, tuple: () => $b, undefined: () => Tb, union: () => Fb, unknown: () => Ab, util: () => w_, void: () => Lb }), (T_ = w_ || (w_ = {})).assertEqual = (t48) => {
}, T_.assertIs = function(t48) {
}, T_.assertNever = function(t48) {
  throw new Error();
}, T_.arrayToEnum = (t48) => {
  const e2 = {};
  for (const n2 of t48) e2[n2] = n2;
  return e2;
}, T_.getValidEnumValues = (t48) => {
  const e2 = T_.objectKeys(t48).filter((e3) => "number" != typeof t48[t48[e3]]), n2 = {};
  for (const o2 of e2) n2[o2] = t48[o2];
  return T_.objectValues(n2);
}, T_.objectValues = (t48) => T_.objectKeys(t48).map(function(e2) {
  return t48[e2];
}), T_.objectKeys = "function" == typeof Object.keys ? (t48) => Object.keys(t48) : (t48) => {
  const e2 = [];
  for (const n2 in t48) Object.prototype.hasOwnProperty.call(t48, n2) && e2.push(n2);
  return e2;
}, T_.find = (t48, e2) => {
  for (const n2 of t48) if (e2(n2)) return n2;
}, T_.isInteger = "function" == typeof Number.isInteger ? (t48) => Number.isInteger(t48) : (t48) => "number" == typeof t48 && Number.isFinite(t48) && Math.floor(t48) === t48, T_.joinValues = function(t48, e2 = " | ") {
  return t48.map((t49) => "string" == typeof t49 ? `'${t49}'` : t49).join(e2);
}, T_.jsonStringifyReplacer = (t48, e2) => "bigint" == typeof e2 ? e2.toString() : e2, (R_ || (R_ = {})).mergeShapes = (t48, e2) => ({ ...t48, ...e2 });
var O_ = w_.arrayToEnum(["string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set"]);
var L_ = (t48) => {
  switch (typeof t48) {
    case "undefined":
      return O_.undefined;
    case "string":
      return O_.string;
    case "number":
      return Number.isNaN(t48) ? O_.nan : O_.number;
    case "boolean":
      return O_.boolean;
    case "function":
      return O_.function;
    case "bigint":
      return O_.bigint;
    case "symbol":
      return O_.symbol;
    case "object":
      return Array.isArray(t48) ? O_.array : null === t48 ? O_.null : t48.then && "function" == typeof t48.then && t48.catch && "function" == typeof t48.catch ? O_.promise : "undefined" != typeof Map && t48 instanceof Map ? O_.map : "undefined" != typeof Set && t48 instanceof Set ? O_.set : "undefined" != typeof Date && t48 instanceof Date ? O_.date : O_.object;
    default:
      return O_.unknown;
  }
};
var D_ = w_.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"]);
var z_ = (t48) => JSON.stringify(t48, null, 2).replace(/"([^"]+)":/g, "$1:");
var k_ = class t17 extends Error {
  get errors() {
    return this.issues;
  }
  constructor(t48) {
    super(), this.issues = [], this.addIssue = (t49) => {
      this.issues = [...this.issues, t49];
    }, this.addIssues = (t49 = []) => {
      this.issues = [...this.issues, ...t49];
    };
    const e2 = new.target.prototype;
    Object.setPrototypeOf ? Object.setPrototypeOf(this, e2) : this.__proto__ = e2, this.name = "ZodError", this.issues = t48;
  }
  format(t48) {
    const e2 = t48 || function(t49) {
      return t49.message;
    }, n2 = { _errors: [] }, o2 = (t49) => {
      for (const i2 of t49.issues) if ("invalid_union" === i2.code) i2.unionErrors.map(o2);
      else if ("invalid_return_type" === i2.code) o2(i2.returnTypeError);
      else if ("invalid_arguments" === i2.code) o2(i2.argumentsError);
      else if (0 === i2.path.length) n2._errors.push(e2(i2));
      else {
        let t50 = n2, o3 = 0;
        for (; o3 < i2.path.length; ) {
          const n3 = i2.path[o3];
          o3 === i2.path.length - 1 ? (t50[n3] = t50[n3] || { _errors: [] }, t50[n3]._errors.push(e2(i2))) : t50[n3] = t50[n3] || { _errors: [] }, t50 = t50[n3], o3++;
        }
      }
    };
    return o2(this), n2;
  }
  static assert(e2) {
    if (!(e2 instanceof t17)) throw new Error(`Not a ZodError: ${e2}`);
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, w_.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return 0 === this.issues.length;
  }
  flatten(t48 = (t49) => t49.message) {
    const e2 = {}, n2 = [];
    for (const o2 of this.issues) if (o2.path.length > 0) {
      const n3 = o2.path[0];
      e2[n3] = e2[n3] || [], e2[n3].push(t48(o2));
    } else n2.push(t48(o2));
    return { formErrors: n2, fieldErrors: e2 };
  }
  get formErrors() {
    return this.flatten();
  }
};
k_.create = (t48) => new k_(t48);
var F_ = (t48, e2) => {
  let n2;
  switch (t48.code) {
    case D_.invalid_type:
      n2 = t48.received === O_.undefined ? "Required" : `Expected ${t48.expected}, received ${t48.received}`;
      break;
    case D_.invalid_literal:
      n2 = `Invalid literal value, expected ${JSON.stringify(t48.expected, w_.jsonStringifyReplacer)}`;
      break;
    case D_.unrecognized_keys:
      n2 = `Unrecognized key(s) in object: ${w_.joinValues(t48.keys, ", ")}`;
      break;
    case D_.invalid_union:
      n2 = "Invalid input";
      break;
    case D_.invalid_union_discriminator:
      n2 = `Invalid discriminator value. Expected ${w_.joinValues(t48.options)}`;
      break;
    case D_.invalid_enum_value:
      n2 = `Invalid enum value. Expected ${w_.joinValues(t48.options)}, received '${t48.received}'`;
      break;
    case D_.invalid_arguments:
      n2 = "Invalid function arguments";
      break;
    case D_.invalid_return_type:
      n2 = "Invalid function return type";
      break;
    case D_.invalid_date:
      n2 = "Invalid date";
      break;
    case D_.invalid_string:
      "object" == typeof t48.validation ? "includes" in t48.validation ? (n2 = `Invalid input: must include "${t48.validation.includes}"`, "number" == typeof t48.validation.position && (n2 = `${n2} at one or more positions greater than or equal to ${t48.validation.position}`)) : "startsWith" in t48.validation ? n2 = `Invalid input: must start with "${t48.validation.startsWith}"` : "endsWith" in t48.validation ? n2 = `Invalid input: must end with "${t48.validation.endsWith}"` : w_.assertNever(t48.validation) : n2 = "regex" !== t48.validation ? `Invalid ${t48.validation}` : "Invalid";
      break;
    case D_.too_small:
      n2 = "array" === t48.type ? `Array must contain ${t48.exact ? "exactly" : t48.inclusive ? "at least" : "more than"} ${t48.minimum} element(s)` : "string" === t48.type ? `String must contain ${t48.exact ? "exactly" : t48.inclusive ? "at least" : "over"} ${t48.minimum} character(s)` : "number" === t48.type || "bigint" === t48.type ? `Number must be ${t48.exact ? "exactly equal to " : t48.inclusive ? "greater than or equal to " : "greater than "}${t48.minimum}` : "date" === t48.type ? `Date must be ${t48.exact ? "exactly equal to " : t48.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(t48.minimum))}` : "Invalid input";
      break;
    case D_.too_big:
      n2 = "array" === t48.type ? `Array must contain ${t48.exact ? "exactly" : t48.inclusive ? "at most" : "less than"} ${t48.maximum} element(s)` : "string" === t48.type ? `String must contain ${t48.exact ? "exactly" : t48.inclusive ? "at most" : "under"} ${t48.maximum} character(s)` : "number" === t48.type ? `Number must be ${t48.exact ? "exactly" : t48.inclusive ? "less than or equal to" : "less than"} ${t48.maximum}` : "bigint" === t48.type ? `BigInt must be ${t48.exact ? "exactly" : t48.inclusive ? "less than or equal to" : "less than"} ${t48.maximum}` : "date" === t48.type ? `Date must be ${t48.exact ? "exactly" : t48.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(t48.maximum))}` : "Invalid input";
      break;
    case D_.custom:
      n2 = "Invalid input";
      break;
    case D_.invalid_intersection_types:
      n2 = "Intersection results could not be merged";
      break;
    case D_.not_multiple_of:
      n2 = `Number must be a multiple of ${t48.multipleOf}`;
      break;
    case D_.not_finite:
      n2 = "Number must be finite";
      break;
    default:
      n2 = e2.defaultError, w_.assertNever(t48);
  }
  return { message: n2 };
};
var j_ = F_;
function Y_(t48) {
  j_ = t48;
}
function $_() {
  return j_;
}
var X_ = (t48) => {
  const { data: e2, path: n2, errorMaps: o2, issueData: i2 } = t48, r2 = [...n2, ...i2.path || []], s2 = { ...i2, path: r2 };
  if (void 0 !== i2.message) return { ...i2, path: r2, message: i2.message };
  let a2 = "";
  const c2 = o2.filter((t49) => !!t49).slice().reverse();
  for (const t49 of c2) a2 = t49(s2, { data: e2, defaultError: a2 }).message;
  return { ...i2, path: r2, message: a2 };
};
var B_ = [];
function H_(t48, e2) {
  const n2 = $_(), o2 = X_({ issueData: e2, data: t48.data, path: t48.path, errorMaps: [t48.common.contextualErrorMap, t48.schemaErrorMap, n2, n2 === F_ ? void 0 : F_].filter((t49) => !!t49) });
  t48.common.issues.push(o2);
}
var W_;
var V_;
var U_ = class t18 {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    "valid" === this.value && (this.value = "dirty");
  }
  abort() {
    "aborted" !== this.value && (this.value = "aborted");
  }
  static mergeArray(t48, e2) {
    const n2 = [];
    for (const o2 of e2) {
      if ("aborted" === o2.status) return G_;
      "dirty" === o2.status && t48.dirty(), n2.push(o2.value);
    }
    return { status: t48.value, value: n2 };
  }
  static async mergeObjectAsync(e2, n2) {
    const o2 = [];
    for (const t48 of n2) {
      const e3 = await t48.key, n3 = await t48.value;
      o2.push({ key: e3, value: n3 });
    }
    return t18.mergeObjectSync(e2, o2);
  }
  static mergeObjectSync(t48, e2) {
    const n2 = {};
    for (const o2 of e2) {
      const { key: e3, value: i2 } = o2;
      if ("aborted" === e3.status) return G_;
      if ("aborted" === i2.status) return G_;
      "dirty" === e3.status && t48.dirty(), "dirty" === i2.status && t48.dirty(), "__proto__" === e3.value || void 0 === i2.value && !o2.alwaysSet || (n2[e3.value] = i2.value);
    }
    return { status: t48.value, value: n2 };
  }
};
var G_ = Object.freeze({ status: "aborted" });
var Z_ = (t48) => ({ status: "dirty", value: t48 });
var q_ = (t48) => ({ status: "valid", value: t48 });
var J_ = (t48) => "aborted" === t48.status;
var K_ = (t48) => "dirty" === t48.status;
var Q_ = (t48) => "valid" === t48.status;
var ty = (t48) => "undefined" != typeof Promise && t48 instanceof Promise;
(V_ = W_ || (W_ = {})).errToObj = (t48) => "string" == typeof t48 ? { message: t48 } : t48 || {}, V_.toString = (t48) => "string" == typeof t48 ? t48 : t48?.message;
var ey = class {
  constructor(t48, e2, n2, o2) {
    this._cachedPath = [], this.parent = t48, this.data = e2, this._path = n2, this._key = o2;
  }
  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;
  }
};
var ny = (t48, e2) => {
  if (Q_(e2)) return { success: true, data: e2.value };
  if (!t48.common.issues.length) throw new Error("Validation failed but no issues detected.");
  return { success: false, get error() {
    if (this._error) return this._error;
    const e3 = new k_(t48.common.issues);
    return this._error = e3, this._error;
  } };
};
function oy(t48) {
  if (!t48) return {};
  const { errorMap: e2, invalid_type_error: n2, required_error: o2, description: i2 } = t48;
  if (e2 && (n2 || o2)) throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  if (e2) return { errorMap: e2, description: i2 };
  return { errorMap: (e3, i3) => {
    const { message: r2 } = t48;
    return "invalid_enum_value" === e3.code ? { message: r2 ?? i3.defaultError } : void 0 === i3.data ? { message: r2 ?? o2 ?? i3.defaultError } : "invalid_type" !== e3.code ? { message: i3.defaultError } : { message: r2 ?? n2 ?? i3.defaultError };
  }, description: i2 };
}
var iy;
var ry = class {
  get description() {
    return this._def.description;
  }
  _getType(t48) {
    return L_(t48.data);
  }
  _getOrReturnCtx(t48, e2) {
    return e2 || { common: t48.parent.common, data: t48.data, parsedType: L_(t48.data), schemaErrorMap: this._def.errorMap, path: t48.path, parent: t48.parent };
  }
  _processInputParams(t48) {
    return { status: new U_(), ctx: { common: t48.parent.common, data: t48.data, parsedType: L_(t48.data), schemaErrorMap: this._def.errorMap, path: t48.path, parent: t48.parent } };
  }
  _parseSync(t48) {
    const e2 = this._parse(t48);
    if (ty(e2)) throw new Error("Synchronous parse encountered promise.");
    return e2;
  }
  _parseAsync(t48) {
    const e2 = this._parse(t48);
    return Promise.resolve(e2);
  }
  parse(t48, e2) {
    const n2 = this.safeParse(t48, e2);
    if (n2.success) return n2.data;
    throw n2.error;
  }
  safeParse(t48, e2) {
    const n2 = { common: { issues: [], async: e2?.async ?? false, contextualErrorMap: e2?.errorMap }, path: e2?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data: t48, parsedType: L_(t48) }, o2 = this._parseSync({ data: t48, path: n2.path, parent: n2 });
    return ny(n2, o2);
  }
  "~validate"(t48) {
    const e2 = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data: t48, parsedType: L_(t48) };
    if (!this["~standard"].async) try {
      const n2 = this._parseSync({ data: t48, path: [], parent: e2 });
      return Q_(n2) ? { value: n2.value } : { issues: e2.common.issues };
    } catch (t49) {
      t49?.message?.toLowerCase()?.includes("encountered") && (this["~standard"].async = true), e2.common = { issues: [], async: true };
    }
    return this._parseAsync({ data: t48, path: [], parent: e2 }).then((t49) => Q_(t49) ? { value: t49.value } : { issues: e2.common.issues });
  }
  async parseAsync(t48, e2) {
    const n2 = await this.safeParseAsync(t48, e2);
    if (n2.success) return n2.data;
    throw n2.error;
  }
  async safeParseAsync(t48, e2) {
    const n2 = { common: { issues: [], contextualErrorMap: e2?.errorMap, async: true }, path: e2?.path || [], schemaErrorMap: this._def.errorMap, parent: null, data: t48, parsedType: L_(t48) }, o2 = this._parse({ data: t48, path: n2.path, parent: n2 }), i2 = await (ty(o2) ? o2 : Promise.resolve(o2));
    return ny(n2, i2);
  }
  refine(t48, e2) {
    const n2 = (t49) => "string" == typeof e2 || void 0 === e2 ? { message: e2 } : "function" == typeof e2 ? e2(t49) : e2;
    return this._refinement((e3, o2) => {
      const i2 = t48(e3), r2 = () => o2.addIssue({ code: D_.custom, ...n2(e3) });
      return "undefined" != typeof Promise && i2 instanceof Promise ? i2.then((t49) => !!t49 || (r2(), false)) : !!i2 || (r2(), false);
    });
  }
  refinement(t48, e2) {
    return this._refinement((n2, o2) => !!t48(n2) || (o2.addIssue("function" == typeof e2 ? e2(n2, o2) : e2), false));
  }
  _refinement(t48) {
    return new sb({ schema: this, typeName: yb.ZodEffects, effect: { type: "refinement", refinement: t48 } });
  }
  superRefine(t48) {
    return this._refinement(t48);
  }
  constructor(t48) {
    this.spa = this.safeParseAsync, this._def = t48, 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: (t49) => this["~validate"](t49) };
  }
  optional() {
    return ab.create(this, this._def);
  }
  nullable() {
    return cb.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return $y.create(this);
  }
  promise() {
    return rb.create(this, this._def);
  }
  or(t48) {
    return Hy.create([this, t48], this._def);
  }
  and(t48) {
    return Gy.create(this, t48, this._def);
  }
  transform(t48) {
    return new sb({ ...oy(this._def), schema: this, typeName: yb.ZodEffects, effect: { type: "transform", transform: t48 } });
  }
  default(t48) {
    const e2 = "function" == typeof t48 ? t48 : () => t48;
    return new lb({ ...oy(this._def), innerType: this, defaultValue: e2, typeName: yb.ZodDefault });
  }
  brand() {
    return new pb({ typeName: yb.ZodBranded, type: this, ...oy(this._def) });
  }
  catch(t48) {
    const e2 = "function" == typeof t48 ? t48 : () => t48;
    return new hb({ ...oy(this._def), innerType: this, catchValue: e2, typeName: yb.ZodCatch });
  }
  describe(t48) {
    return new (0, this.constructor)({ ...this._def, description: t48 });
  }
  pipe(t48) {
    return mb.create(this, t48);
  }
  readonly() {
    return gb.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var sy = /^c[^\s-]{8,}$/i;
var ay = /^[0-9a-z]+$/;
var cy = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var ly = /^[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;
var hy = /^[a-z0-9_-]{21}$/i;
var dy = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var uy = /^[-+]?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)?)??$/;
var py = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var my = /^(?:(?: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])$/;
var gy = /^(?:(?: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])$/;
var fy = /^(([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]))$/;
var _y = /^(([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])$/;
var yy = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var by = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var xy = "((\\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])))";
var vy = new RegExp(`^${xy}$`);
function Sy(t48) {
  let e2 = "[0-5]\\d";
  t48.precision ? e2 = `${e2}\\.\\d{${t48.precision}}` : null == t48.precision && (e2 = `${e2}(\\.\\d+)?`);
  return `([01]\\d|2[0-3]):[0-5]\\d(:${e2})${t48.precision ? "+" : "?"}`;
}
function Iy(t48) {
  return new RegExp(`^${Sy(t48)}$`);
}
function Py(t48) {
  let e2 = `${xy}T${Sy(t48)}`;
  const n2 = [];
  return n2.push(t48.local ? "Z?" : "Z"), t48.offset && n2.push("([+-]\\d{2}:?\\d{2})"), e2 = `${e2}(${n2.join("|")})`, new RegExp(`^${e2}$`);
}
function My(t48, e2) {
  return !("v4" !== e2 && e2 || !my.test(t48)) || !("v6" !== e2 && e2 || !fy.test(t48));
}
function Cy(t48, e2) {
  if (!dy.test(t48)) return false;
  try {
    const [n2] = t48.split(".");
    if (!n2) return false;
    const o2 = n2.replace(/-/g, "+").replace(/_/g, "/").padEnd(n2.length + (4 - n2.length % 4) % 4, "="), i2 = JSON.parse(atob(o2));
    return "object" == typeof i2 && null !== i2 && ((!("typ" in i2) || "JWT" === i2?.typ) && (!!i2.alg && (!e2 || i2.alg === e2)));
  } catch {
    return false;
  }
}
function Ny(t48, e2) {
  return !("v4" !== e2 && e2 || !gy.test(t48)) || !("v6" !== e2 && e2 || !_y.test(t48));
}
var wy = class t19 extends ry {
  _parse(t48) {
    this._def.coerce && (t48.data = String(t48.data));
    if (this._getType(t48) !== O_.string) {
      const e3 = this._getOrReturnCtx(t48);
      return H_(e3, { code: D_.invalid_type, expected: O_.string, received: e3.parsedType }), G_;
    }
    const e2 = new U_();
    let n2;
    for (const o2 of this._def.checks) if ("min" === o2.kind) t48.data.length < o2.value && (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.too_small, minimum: o2.value, type: "string", inclusive: true, exact: false, message: o2.message }), e2.dirty());
    else if ("max" === o2.kind) t48.data.length > o2.value && (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.too_big, maximum: o2.value, type: "string", inclusive: true, exact: false, message: o2.message }), e2.dirty());
    else if ("length" === o2.kind) {
      const i2 = t48.data.length > o2.value, r2 = t48.data.length < o2.value;
      (i2 || r2) && (n2 = this._getOrReturnCtx(t48, n2), i2 ? H_(n2, { code: D_.too_big, maximum: o2.value, type: "string", inclusive: true, exact: true, message: o2.message }) : r2 && H_(n2, { code: D_.too_small, minimum: o2.value, type: "string", inclusive: true, exact: true, message: o2.message }), e2.dirty());
    } else if ("email" === o2.kind) py.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "email", code: D_.invalid_string, message: o2.message }), e2.dirty());
    else if ("emoji" === o2.kind) iy || (iy = new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u")), iy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "emoji", code: D_.invalid_string, message: o2.message }), e2.dirty());
    else if ("uuid" === o2.kind) ly.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "uuid", code: D_.invalid_string, message: o2.message }), e2.dirty());
    else if ("nanoid" === o2.kind) hy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "nanoid", code: D_.invalid_string, message: o2.message }), e2.dirty());
    else if ("cuid" === o2.kind) sy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "cuid", code: D_.invalid_string, message: o2.message }), e2.dirty());
    else if ("cuid2" === o2.kind) ay.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "cuid2", code: D_.invalid_string, message: o2.message }), e2.dirty());
    else if ("ulid" === o2.kind) cy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "ulid", code: D_.invalid_string, message: o2.message }), e2.dirty());
    else if ("url" === o2.kind) try {
      new URL(t48.data);
    } catch {
      n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "url", code: D_.invalid_string, message: o2.message }), e2.dirty();
    }
    else if ("regex" === o2.kind) {
      o2.regex.lastIndex = 0;
      o2.regex.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "regex", code: D_.invalid_string, message: o2.message }), e2.dirty());
    } else if ("trim" === o2.kind) t48.data = t48.data.trim();
    else if ("includes" === o2.kind) t48.data.includes(o2.value, o2.position) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: { includes: o2.value, position: o2.position }, message: o2.message }), e2.dirty());
    else if ("toLowerCase" === o2.kind) t48.data = t48.data.toLowerCase();
    else if ("toUpperCase" === o2.kind) t48.data = t48.data.toUpperCase();
    else if ("startsWith" === o2.kind) t48.data.startsWith(o2.value) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: { startsWith: o2.value }, message: o2.message }), e2.dirty());
    else if ("endsWith" === o2.kind) t48.data.endsWith(o2.value) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: { endsWith: o2.value }, message: o2.message }), e2.dirty());
    else if ("datetime" === o2.kind) {
      Py(o2).test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: "datetime", message: o2.message }), e2.dirty());
    } else if ("date" === o2.kind) {
      vy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: "date", message: o2.message }), e2.dirty());
    } else if ("time" === o2.kind) {
      Iy(o2).test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.invalid_string, validation: "time", message: o2.message }), e2.dirty());
    } else "duration" === o2.kind ? uy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "duration", code: D_.invalid_string, message: o2.message }), e2.dirty()) : "ip" === o2.kind ? My(t48.data, o2.version) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "ip", code: D_.invalid_string, message: o2.message }), e2.dirty()) : "jwt" === o2.kind ? Cy(t48.data, o2.alg) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "jwt", code: D_.invalid_string, message: o2.message }), e2.dirty()) : "cidr" === o2.kind ? Ny(t48.data, o2.version) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "cidr", code: D_.invalid_string, message: o2.message }), e2.dirty()) : "base64" === o2.kind ? yy.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "base64", code: D_.invalid_string, message: o2.message }), e2.dirty()) : "base64url" === o2.kind ? by.test(t48.data) || (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { validation: "base64url", code: D_.invalid_string, message: o2.message }), e2.dirty()) : w_.assertNever(o2);
    return { status: e2.value, value: t48.data };
  }
  _regex(t48, e2, n2) {
    return this.refinement((e3) => t48.test(e3), { validation: e2, code: D_.invalid_string, ...W_.errToObj(n2) });
  }
  _addCheck(e2) {
    return new t19({ ...this._def, checks: [...this._def.checks, e2] });
  }
  email(t48) {
    return this._addCheck({ kind: "email", ...W_.errToObj(t48) });
  }
  url(t48) {
    return this._addCheck({ kind: "url", ...W_.errToObj(t48) });
  }
  emoji(t48) {
    return this._addCheck({ kind: "emoji", ...W_.errToObj(t48) });
  }
  uuid(t48) {
    return this._addCheck({ kind: "uuid", ...W_.errToObj(t48) });
  }
  nanoid(t48) {
    return this._addCheck({ kind: "nanoid", ...W_.errToObj(t48) });
  }
  cuid(t48) {
    return this._addCheck({ kind: "cuid", ...W_.errToObj(t48) });
  }
  cuid2(t48) {
    return this._addCheck({ kind: "cuid2", ...W_.errToObj(t48) });
  }
  ulid(t48) {
    return this._addCheck({ kind: "ulid", ...W_.errToObj(t48) });
  }
  base64(t48) {
    return this._addCheck({ kind: "base64", ...W_.errToObj(t48) });
  }
  base64url(t48) {
    return this._addCheck({ kind: "base64url", ...W_.errToObj(t48) });
  }
  jwt(t48) {
    return this._addCheck({ kind: "jwt", ...W_.errToObj(t48) });
  }
  ip(t48) {
    return this._addCheck({ kind: "ip", ...W_.errToObj(t48) });
  }
  cidr(t48) {
    return this._addCheck({ kind: "cidr", ...W_.errToObj(t48) });
  }
  datetime(t48) {
    return "string" == typeof t48 ? this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: t48 }) : this._addCheck({ kind: "datetime", precision: void 0 === t48?.precision ? null : t48?.precision, offset: t48?.offset ?? false, local: t48?.local ?? false, ...W_.errToObj(t48?.message) });
  }
  date(t48) {
    return this._addCheck({ kind: "date", message: t48 });
  }
  time(t48) {
    return "string" == typeof t48 ? this._addCheck({ kind: "time", precision: null, message: t48 }) : this._addCheck({ kind: "time", precision: void 0 === t48?.precision ? null : t48?.precision, ...W_.errToObj(t48?.message) });
  }
  duration(t48) {
    return this._addCheck({ kind: "duration", ...W_.errToObj(t48) });
  }
  regex(t48, e2) {
    return this._addCheck({ kind: "regex", regex: t48, ...W_.errToObj(e2) });
  }
  includes(t48, e2) {
    return this._addCheck({ kind: "includes", value: t48, position: e2?.position, ...W_.errToObj(e2?.message) });
  }
  startsWith(t48, e2) {
    return this._addCheck({ kind: "startsWith", value: t48, ...W_.errToObj(e2) });
  }
  endsWith(t48, e2) {
    return this._addCheck({ kind: "endsWith", value: t48, ...W_.errToObj(e2) });
  }
  min(t48, e2) {
    return this._addCheck({ kind: "min", value: t48, ...W_.errToObj(e2) });
  }
  max(t48, e2) {
    return this._addCheck({ kind: "max", value: t48, ...W_.errToObj(e2) });
  }
  length(t48, e2) {
    return this._addCheck({ kind: "length", value: t48, ...W_.errToObj(e2) });
  }
  nonempty(t48) {
    return this.min(1, W_.errToObj(t48));
  }
  trim() {
    return new t19({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] });
  }
  toLowerCase() {
    return new t19({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] });
  }
  toUpperCase() {
    return new t19({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] });
  }
  get isDatetime() {
    return !!this._def.checks.find((t48) => "datetime" === t48.kind);
  }
  get isDate() {
    return !!this._def.checks.find((t48) => "date" === t48.kind);
  }
  get isTime() {
    return !!this._def.checks.find((t48) => "time" === t48.kind);
  }
  get isDuration() {
    return !!this._def.checks.find((t48) => "duration" === t48.kind);
  }
  get isEmail() {
    return !!this._def.checks.find((t48) => "email" === t48.kind);
  }
  get isURL() {
    return !!this._def.checks.find((t48) => "url" === t48.kind);
  }
  get isEmoji() {
    return !!this._def.checks.find((t48) => "emoji" === t48.kind);
  }
  get isUUID() {
    return !!this._def.checks.find((t48) => "uuid" === t48.kind);
  }
  get isNANOID() {
    return !!this._def.checks.find((t48) => "nanoid" === t48.kind);
  }
  get isCUID() {
    return !!this._def.checks.find((t48) => "cuid" === t48.kind);
  }
  get isCUID2() {
    return !!this._def.checks.find((t48) => "cuid2" === t48.kind);
  }
  get isULID() {
    return !!this._def.checks.find((t48) => "ulid" === t48.kind);
  }
  get isIP() {
    return !!this._def.checks.find((t48) => "ip" === t48.kind);
  }
  get isCIDR() {
    return !!this._def.checks.find((t48) => "cidr" === t48.kind);
  }
  get isBase64() {
    return !!this._def.checks.find((t48) => "base64" === t48.kind);
  }
  get isBase64url() {
    return !!this._def.checks.find((t48) => "base64url" === t48.kind);
  }
  get minLength() {
    let t48 = null;
    for (const e2 of this._def.checks) "min" === e2.kind && (null === t48 || e2.value > t48) && (t48 = e2.value);
    return t48;
  }
  get maxLength() {
    let t48 = null;
    for (const e2 of this._def.checks) "max" === e2.kind && (null === t48 || e2.value < t48) && (t48 = e2.value);
    return t48;
  }
};
function Ty(t48, e2) {
  const n2 = (t48.toString().split(".")[1] || "").length, o2 = (e2.toString().split(".")[1] || "").length, i2 = n2 > o2 ? n2 : o2;
  return Number.parseInt(t48.toFixed(i2).replace(".", "")) % Number.parseInt(e2.toFixed(i2).replace(".", "")) / 10 ** i2;
}
wy.create = (t48) => new wy({ checks: [], typeName: yb.ZodString, coerce: t48?.coerce ?? false, ...oy(t48) });
var Ry = class t20 extends ry {
  constructor() {
    super(...arguments), this.min = this.gte, this.max = this.lte, this.step = this.multipleOf;
  }
  _parse(t48) {
    this._def.coerce && (t48.data = Number(t48.data));
    if (this._getType(t48) !== O_.number) {
      const e3 = this._getOrReturnCtx(t48);
      return H_(e3, { code: D_.invalid_type, expected: O_.number, received: e3.parsedType }), G_;
    }
    let e2;
    const n2 = new U_();
    for (const o2 of this._def.checks) if ("int" === o2.kind) w_.isInteger(t48.data) || (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.invalid_type, expected: "integer", received: "float", message: o2.message }), n2.dirty());
    else if ("min" === o2.kind) {
      (o2.inclusive ? t48.data < o2.value : t48.data <= o2.value) && (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.too_small, minimum: o2.value, type: "number", inclusive: o2.inclusive, exact: false, message: o2.message }), n2.dirty());
    } else if ("max" === o2.kind) {
      (o2.inclusive ? t48.data > o2.value : t48.data >= o2.value) && (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.too_big, maximum: o2.value, type: "number", inclusive: o2.inclusive, exact: false, message: o2.message }), n2.dirty());
    } else "multipleOf" === o2.kind ? 0 !== Ty(t48.data, o2.value) && (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.not_multiple_of, multipleOf: o2.value, message: o2.message }), n2.dirty()) : "finite" === o2.kind ? Number.isFinite(t48.data) || (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.not_finite, message: o2.message }), n2.dirty()) : w_.assertNever(o2);
    return { status: n2.value, value: t48.data };
  }
  gte(t48, e2) {
    return this.setLimit("min", t48, true, W_.toString(e2));
  }
  gt(t48, e2) {
    return this.setLimit("min", t48, false, W_.toString(e2));
  }
  lte(t48, e2) {
    return this.setLimit("max", t48, true, W_.toString(e2));
  }
  lt(t48, e2) {
    return this.setLimit("max", t48, false, W_.toString(e2));
  }
  setLimit(e2, n2, o2, i2) {
    return new t20({ ...this._def, checks: [...this._def.checks, { kind: e2, value: n2, inclusive: o2, message: W_.toString(i2) }] });
  }
  _addCheck(e2) {
    return new t20({ ...this._def, checks: [...this._def.checks, e2] });
  }
  int(t48) {
    return this._addCheck({ kind: "int", message: W_.toString(t48) });
  }
  positive(t48) {
    return this._addCheck({ kind: "min", value: 0, inclusive: false, message: W_.toString(t48) });
  }
  negative(t48) {
    return this._addCheck({ kind: "max", value: 0, inclusive: false, message: W_.toString(t48) });
  }
  nonpositive(t48) {
    return this._addCheck({ kind: "max", value: 0, inclusive: true, message: W_.toString(t48) });
  }
  nonnegative(t48) {
    return this._addCheck({ kind: "min", value: 0, inclusive: true, message: W_.toString(t48) });
  }
  multipleOf(t48, e2) {
    return this._addCheck({ kind: "multipleOf", value: t48, message: W_.toString(e2) });
  }
  finite(t48) {
    return this._addCheck({ kind: "finite", message: W_.toString(t48) });
  }
  safe(t48) {
    return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: W_.toString(t48) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: W_.toString(t48) });
  }
  get minValue() {
    let t48 = null;
    for (const e2 of this._def.checks) "min" === e2.kind && (null === t48 || e2.value > t48) && (t48 = e2.value);
    return t48;
  }
  get maxValue() {
    let t48 = null;
    for (const e2 of this._def.checks) "max" === e2.kind && (null === t48 || e2.value < t48) && (t48 = e2.value);
    return t48;
  }
  get isInt() {
    return !!this._def.checks.find((t48) => "int" === t48.kind || "multipleOf" === t48.kind && w_.isInteger(t48.value));
  }
  get isFinite() {
    let t48 = null, e2 = null;
    for (const n2 of this._def.checks) {
      if ("finite" === n2.kind || "int" === n2.kind || "multipleOf" === n2.kind) return true;
      "min" === n2.kind ? (null === e2 || n2.value > e2) && (e2 = n2.value) : "max" === n2.kind && (null === t48 || n2.value < t48) && (t48 = n2.value);
    }
    return Number.isFinite(e2) && Number.isFinite(t48);
  }
};
Ry.create = (t48) => new Ry({ checks: [], typeName: yb.ZodNumber, coerce: t48?.coerce || false, ...oy(t48) });
var Ey = class t21 extends ry {
  constructor() {
    super(...arguments), this.min = this.gte, this.max = this.lte;
  }
  _parse(t48) {
    if (this._def.coerce) try {
      t48.data = BigInt(t48.data);
    } catch {
      return this._getInvalidInput(t48);
    }
    if (this._getType(t48) !== O_.bigint) return this._getInvalidInput(t48);
    let e2;
    const n2 = new U_();
    for (const o2 of this._def.checks) if ("min" === o2.kind) {
      (o2.inclusive ? t48.data < o2.value : t48.data <= o2.value) && (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.too_small, type: "bigint", minimum: o2.value, inclusive: o2.inclusive, message: o2.message }), n2.dirty());
    } else if ("max" === o2.kind) {
      (o2.inclusive ? t48.data > o2.value : t48.data >= o2.value) && (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.too_big, type: "bigint", maximum: o2.value, inclusive: o2.inclusive, message: o2.message }), n2.dirty());
    } else "multipleOf" === o2.kind ? t48.data % o2.value !== BigInt(0) && (e2 = this._getOrReturnCtx(t48, e2), H_(e2, { code: D_.not_multiple_of, multipleOf: o2.value, message: o2.message }), n2.dirty()) : w_.assertNever(o2);
    return { status: n2.value, value: t48.data };
  }
  _getInvalidInput(t48) {
    const e2 = this._getOrReturnCtx(t48);
    return H_(e2, { code: D_.invalid_type, expected: O_.bigint, received: e2.parsedType }), G_;
  }
  gte(t48, e2) {
    return this.setLimit("min", t48, true, W_.toString(e2));
  }
  gt(t48, e2) {
    return this.setLimit("min", t48, false, W_.toString(e2));
  }
  lte(t48, e2) {
    return this.setLimit("max", t48, true, W_.toString(e2));
  }
  lt(t48, e2) {
    return this.setLimit("max", t48, false, W_.toString(e2));
  }
  setLimit(e2, n2, o2, i2) {
    return new t21({ ...this._def, checks: [...this._def.checks, { kind: e2, value: n2, inclusive: o2, message: W_.toString(i2) }] });
  }
  _addCheck(e2) {
    return new t21({ ...this._def, checks: [...this._def.checks, e2] });
  }
  positive(t48) {
    return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: W_.toString(t48) });
  }
  negative(t48) {
    return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: W_.toString(t48) });
  }
  nonpositive(t48) {
    return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: W_.toString(t48) });
  }
  nonnegative(t48) {
    return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: W_.toString(t48) });
  }
  multipleOf(t48, e2) {
    return this._addCheck({ kind: "multipleOf", value: t48, message: W_.toString(e2) });
  }
  get minValue() {
    let t48 = null;
    for (const e2 of this._def.checks) "min" === e2.kind && (null === t48 || e2.value > t48) && (t48 = e2.value);
    return t48;
  }
  get maxValue() {
    let t48 = null;
    for (const e2 of this._def.checks) "max" === e2.kind && (null === t48 || e2.value < t48) && (t48 = e2.value);
    return t48;
  }
};
Ey.create = (t48) => new Ey({ checks: [], typeName: yb.ZodBigInt, coerce: t48?.coerce ?? false, ...oy(t48) });
var Ay = class extends ry {
  _parse(t48) {
    this._def.coerce && (t48.data = Boolean(t48.data));
    if (this._getType(t48) !== O_.boolean) {
      const e2 = this._getOrReturnCtx(t48);
      return H_(e2, { code: D_.invalid_type, expected: O_.boolean, received: e2.parsedType }), G_;
    }
    return q_(t48.data);
  }
};
Ay.create = (t48) => new Ay({ typeName: yb.ZodBoolean, coerce: t48?.coerce || false, ...oy(t48) });
var Oy = class t22 extends ry {
  _parse(t48) {
    this._def.coerce && (t48.data = new Date(t48.data));
    if (this._getType(t48) !== O_.date) {
      const e3 = this._getOrReturnCtx(t48);
      return H_(e3, { code: D_.invalid_type, expected: O_.date, received: e3.parsedType }), G_;
    }
    if (Number.isNaN(t48.data.getTime())) {
      return H_(this._getOrReturnCtx(t48), { code: D_.invalid_date }), G_;
    }
    const e2 = new U_();
    let n2;
    for (const o2 of this._def.checks) "min" === o2.kind ? t48.data.getTime() < o2.value && (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.too_small, message: o2.message, inclusive: true, exact: false, minimum: o2.value, type: "date" }), e2.dirty()) : "max" === o2.kind ? t48.data.getTime() > o2.value && (n2 = this._getOrReturnCtx(t48, n2), H_(n2, { code: D_.too_big, message: o2.message, inclusive: true, exact: false, maximum: o2.value, type: "date" }), e2.dirty()) : w_.assertNever(o2);
    return { status: e2.value, value: new Date(t48.data.getTime()) };
  }
  _addCheck(e2) {
    return new t22({ ...this._def, checks: [...this._def.checks, e2] });
  }
  min(t48, e2) {
    return this._addCheck({ kind: "min", value: t48.getTime(), message: W_.toString(e2) });
  }
  max(t48, e2) {
    return this._addCheck({ kind: "max", value: t48.getTime(), message: W_.toString(e2) });
  }
  get minDate() {
    let t48 = null;
    for (const e2 of this._def.checks) "min" === e2.kind && (null === t48 || e2.value > t48) && (t48 = e2.value);
    return null != t48 ? new Date(t48) : null;
  }
  get maxDate() {
    let t48 = null;
    for (const e2 of this._def.checks) "max" === e2.kind && (null === t48 || e2.value < t48) && (t48 = e2.value);
    return null != t48 ? new Date(t48) : null;
  }
};
Oy.create = (t48) => new Oy({ checks: [], coerce: t48?.coerce || false, typeName: yb.ZodDate, ...oy(t48) });
var Ly = class extends ry {
  _parse(t48) {
    if (this._getType(t48) !== O_.symbol) {
      const e2 = this._getOrReturnCtx(t48);
      return H_(e2, { code: D_.invalid_type, expected: O_.symbol, received: e2.parsedType }), G_;
    }
    return q_(t48.data);
  }
};
Ly.create = (t48) => new Ly({ typeName: yb.ZodSymbol, ...oy(t48) });
var Dy = class extends ry {
  _parse(t48) {
    if (this._getType(t48) !== O_.undefined) {
      const e2 = this._getOrReturnCtx(t48);
      return H_(e2, { code: D_.invalid_type, expected: O_.undefined, received: e2.parsedType }), G_;
    }
    return q_(t48.data);
  }
};
Dy.create = (t48) => new Dy({ typeName: yb.ZodUndefined, ...oy(t48) });
var zy = class extends ry {
  _parse(t48) {
    if (this._getType(t48) !== O_.null) {
      const e2 = this._getOrReturnCtx(t48);
      return H_(e2, { code: D_.invalid_type, expected: O_.null, received: e2.parsedType }), G_;
    }
    return q_(t48.data);
  }
};
zy.create = (t48) => new zy({ typeName: yb.ZodNull, ...oy(t48) });
var ky = class extends ry {
  constructor() {
    super(...arguments), this._any = true;
  }
  _parse(t48) {
    return q_(t48.data);
  }
};
ky.create = (t48) => new ky({ typeName: yb.ZodAny, ...oy(t48) });
var Fy = class extends ry {
  constructor() {
    super(...arguments), this._unknown = true;
  }
  _parse(t48) {
    return q_(t48.data);
  }
};
Fy.create = (t48) => new Fy({ typeName: yb.ZodUnknown, ...oy(t48) });
var jy = class extends ry {
  _parse(t48) {
    const e2 = this._getOrReturnCtx(t48);
    return H_(e2, { code: D_.invalid_type, expected: O_.never, received: e2.parsedType }), G_;
  }
};
jy.create = (t48) => new jy({ typeName: yb.ZodNever, ...oy(t48) });
var Yy = class extends ry {
  _parse(t48) {
    if (this._getType(t48) !== O_.undefined) {
      const e2 = this._getOrReturnCtx(t48);
      return H_(e2, { code: D_.invalid_type, expected: O_.void, received: e2.parsedType }), G_;
    }
    return q_(t48.data);
  }
};
Yy.create = (t48) => new Yy({ typeName: yb.ZodVoid, ...oy(t48) });
var $y = class t23 extends ry {
  _parse(t48) {
    const { ctx: e2, status: n2 } = this._processInputParams(t48), o2 = this._def;
    if (e2.parsedType !== O_.array) return H_(e2, { code: D_.invalid_type, expected: O_.array, received: e2.parsedType }), G_;
    if (null !== o2.exactLength) {
      const t49 = e2.data.length > o2.exactLength.value, i3 = e2.data.length < o2.exactLength.value;
      (t49 || i3) && (H_(e2, { code: t49 ? D_.too_big : D_.too_small, minimum: i3 ? o2.exactLength.value : void 0, maximum: t49 ? o2.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: o2.exactLength.message }), n2.dirty());
    }
    if (null !== o2.minLength && e2.data.length < o2.minLength.value && (H_(e2, { code: D_.too_small, minimum: o2.minLength.value, type: "array", inclusive: true, exact: false, message: o2.minLength.message }), n2.dirty()), null !== o2.maxLength && e2.data.length > o2.maxLength.value && (H_(e2, { code: D_.too_big, maximum: o2.maxLength.value, type: "array", inclusive: true, exact: false, message: o2.maxLength.message }), n2.dirty()), e2.common.async) return Promise.all([...e2.data].map((t49, n3) => o2.type._parseAsync(new ey(e2, t49, e2.path, n3)))).then((t49) => U_.mergeArray(n2, t49));
    const i2 = [...e2.data].map((t49, n3) => o2.type._parseSync(new ey(e2, t49, e2.path, n3)));
    return U_.mergeArray(n2, i2);
  }
  get element() {
    return this._def.type;
  }
  min(e2, n2) {
    return new t23({ ...this._def, minLength: { value: e2, message: W_.toString(n2) } });
  }
  max(e2, n2) {
    return new t23({ ...this._def, maxLength: { value: e2, message: W_.toString(n2) } });
  }
  length(e2, n2) {
    return new t23({ ...this._def, exactLength: { value: e2, message: W_.toString(n2) } });
  }
  nonempty(t48) {
    return this.min(1, t48);
  }
};
function Xy(t48) {
  if (t48 instanceof By) {
    const e2 = {};
    for (const n2 in t48.shape) {
      const o2 = t48.shape[n2];
      e2[n2] = ab.create(Xy(o2));
    }
    return new By({ ...t48._def, shape: () => e2 });
  }
  return t48 instanceof $y ? new $y({ ...t48._def, type: Xy(t48.element) }) : t48 instanceof ab ? ab.create(Xy(t48.unwrap())) : t48 instanceof cb ? cb.create(Xy(t48.unwrap())) : t48 instanceof Zy ? Zy.create(t48.items.map((t49) => Xy(t49))) : t48;
}
$y.create = (t48, e2) => new $y({ type: t48, minLength: null, maxLength: null, exactLength: null, typeName: yb.ZodArray, ...oy(e2) });
var By = class t24 extends ry {
  constructor() {
    super(...arguments), this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;
  }
  _getCached() {
    if (null !== this._cached) return this._cached;
    const t48 = this._def.shape(), e2 = w_.objectKeys(t48);
    return this._cached = { shape: t48, keys: e2 }, this._cached;
  }
  _parse(t48) {
    if (this._getType(t48) !== O_.object) {
      const e3 = this._getOrReturnCtx(t48);
      return H_(e3, { code: D_.invalid_type, expected: O_.object, received: e3.parsedType }), G_;
    }
    const { status: e2, ctx: n2 } = this._processInputParams(t48), { shape: o2, keys: i2 } = this._getCached(), r2 = [];
    if (!(this._def.catchall instanceof jy && "strip" === this._def.unknownKeys)) for (const t49 in n2.data) i2.includes(t49) || r2.push(t49);
    const s2 = [];
    for (const t49 of i2) {
      const e3 = o2[t49], i3 = n2.data[t49];
      s2.push({ key: { status: "valid", value: t49 }, value: e3._parse(new ey(n2, i3, n2.path, t49)), alwaysSet: t49 in n2.data });
    }
    if (this._def.catchall instanceof jy) {
      const t49 = this._def.unknownKeys;
      if ("passthrough" === t49) for (const t50 of r2) s2.push({ key: { status: "valid", value: t50 }, value: { status: "valid", value: n2.data[t50] } });
      else if ("strict" === t49) r2.length > 0 && (H_(n2, { code: D_.unrecognized_keys, keys: r2 }), e2.dirty());
      else if ("strip" !== t49) throw new Error("Internal ZodObject error: invalid unknownKeys value.");
    } else {
      const t49 = this._def.catchall;
      for (const e3 of r2) {
        const o3 = n2.data[e3];
        s2.push({ key: { status: "valid", value: e3 }, value: t49._parse(new ey(n2, o3, n2.path, e3)), alwaysSet: e3 in n2.data });
      }
    }
    return n2.common.async ? Promise.resolve().then(async () => {
      const t49 = [];
      for (const e3 of s2) {
        const n3 = await e3.key, o3 = await e3.value;
        t49.push({ key: n3, value: o3, alwaysSet: e3.alwaysSet });
      }
      return t49;
    }).then((t49) => U_.mergeObjectSync(e2, t49)) : U_.mergeObjectSync(e2, s2);
  }
  get shape() {
    return this._def.shape();
  }
  strict(e2) {
    return W_.errToObj, new t24({ ...this._def, unknownKeys: "strict", ...void 0 !== e2 ? { errorMap: (t48, n2) => {
      const o2 = this._def.errorMap?.(t48, n2).message ?? n2.defaultError;
      return "unrecognized_keys" === t48.code ? { message: W_.errToObj(e2).message ?? o2 } : { message: o2 };
    } } : {} });
  }
  strip() {
    return new t24({ ...this._def, unknownKeys: "strip" });
  }
  passthrough() {
    return new t24({ ...this._def, unknownKeys: "passthrough" });
  }
  extend(e2) {
    return new t24({ ...this._def, shape: () => ({ ...this._def.shape(), ...e2 }) });
  }
  merge(e2) {
    return new t24({ unknownKeys: e2._def.unknownKeys, catchall: e2._def.catchall, shape: () => ({ ...this._def.shape(), ...e2._def.shape() }), typeName: yb.ZodObject });
  }
  setKey(t48, e2) {
    return this.augment({ [t48]: e2 });
  }
  catchall(e2) {
    return new t24({ ...this._def, catchall: e2 });
  }
  pick(e2) {
    const n2 = {};
    for (const t48 of w_.objectKeys(e2)) e2[t48] && this.shape[t48] && (n2[t48] = this.shape[t48]);
    return new t24({ ...this._def, shape: () => n2 });
  }
  omit(e2) {
    const n2 = {};
    for (const t48 of w_.objectKeys(this.shape)) e2[t48] || (n2[t48] = this.shape[t48]);
    return new t24({ ...this._def, shape: () => n2 });
  }
  deepPartial() {
    return Xy(this);
  }
  partial(e2) {
    const n2 = {};
    for (const t48 of w_.objectKeys(this.shape)) {
      const o2 = this.shape[t48];
      e2 && !e2[t48] ? n2[t48] = o2 : n2[t48] = o2.optional();
    }
    return new t24({ ...this._def, shape: () => n2 });
  }
  required(e2) {
    const n2 = {};
    for (const t48 of w_.objectKeys(this.shape)) if (e2 && !e2[t48]) n2[t48] = this.shape[t48];
    else {
      let e3 = this.shape[t48];
      for (; e3 instanceof ab; ) e3 = e3._def.innerType;
      n2[t48] = e3;
    }
    return new t24({ ...this._def, shape: () => n2 });
  }
  keyof() {
    return nb(w_.objectKeys(this.shape));
  }
};
By.create = (t48, e2) => new By({ shape: () => t48, unknownKeys: "strip", catchall: jy.create(), typeName: yb.ZodObject, ...oy(e2) }), By.strictCreate = (t48, e2) => new By({ shape: () => t48, unknownKeys: "strict", catchall: jy.create(), typeName: yb.ZodObject, ...oy(e2) }), By.lazycreate = (t48, e2) => new By({ shape: t48, unknownKeys: "strip", catchall: jy.create(), typeName: yb.ZodObject, ...oy(e2) });
var Hy = class extends ry {
  _parse(t48) {
    const { ctx: e2 } = this._processInputParams(t48), n2 = this._def.options;
    if (e2.common.async) return Promise.all(n2.map(async (t49) => {
      const n3 = { ...e2, common: { ...e2.common, issues: [] }, parent: null };
      return { result: await t49._parseAsync({ data: e2.data, path: e2.path, parent: n3 }), ctx: n3 };
    })).then(function(t49) {
      for (const e3 of t49) if ("valid" === e3.result.status) return e3.result;
      for (const n4 of t49) if ("dirty" === n4.result.status) return e2.common.issues.push(...n4.ctx.common.issues), n4.result;
      const n3 = t49.map((t50) => new k_(t50.ctx.common.issues));
      return H_(e2, { code: D_.invalid_union, unionErrors: n3 }), G_;
    });
    {
      let t49;
      const o2 = [];
      for (const i3 of n2) {
        const n3 = { ...e2, common: { ...e2.common, issues: [] }, parent: null }, r2 = i3._parseSync({ data: e2.data, path: e2.path, parent: n3 });
        if ("valid" === r2.status) return r2;
        "dirty" !== r2.status || t49 || (t49 = { result: r2, ctx: n3 }), n3.common.issues.length && o2.push(n3.common.issues);
      }
      if (t49) return e2.common.issues.push(...t49.ctx.common.issues), t49.result;
      const i2 = o2.map((t50) => new k_(t50));
      return H_(e2, { code: D_.invalid_union, unionErrors: i2 }), G_;
    }
  }
  get options() {
    return this._def.options;
  }
};
Hy.create = (t48, e2) => new Hy({ options: t48, typeName: yb.ZodUnion, ...oy(e2) });
var Wy = (t48) => t48 instanceof tb ? Wy(t48.schema) : t48 instanceof sb ? Wy(t48.innerType()) : t48 instanceof eb ? [t48.value] : t48 instanceof ob ? t48.options : t48 instanceof ib ? w_.objectValues(t48.enum) : t48 instanceof lb ? Wy(t48._def.innerType) : t48 instanceof Dy ? [void 0] : t48 instanceof zy ? [null] : t48 instanceof ab ? [void 0, ...Wy(t48.unwrap())] : t48 instanceof cb ? [null, ...Wy(t48.unwrap())] : t48 instanceof pb || t48 instanceof gb ? Wy(t48.unwrap()) : t48 instanceof hb ? Wy(t48._def.innerType) : [];
var Vy = class t25 extends ry {
  _parse(t48) {
    const { ctx: e2 } = this._processInputParams(t48);
    if (e2.parsedType !== O_.object) return H_(e2, { code: D_.invalid_type, expected: O_.object, received: e2.parsedType }), G_;
    const n2 = this.discriminator, o2 = e2.data[n2], i2 = this.optionsMap.get(o2);
    return i2 ? e2.common.async ? i2._parseAsync({ data: e2.data, path: e2.path, parent: e2 }) : i2._parseSync({ data: e2.data, path: e2.path, parent: e2 }) : (H_(e2, { code: D_.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [n2] }), G_);
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  static create(e2, n2, o2) {
    const i2 = /* @__PURE__ */ new Map();
    for (const t48 of n2) {
      const n3 = Wy(t48.shape[e2]);
      if (!n3.length) throw new Error(`A discriminator value for key \`${e2}\` could not be extracted from all schema options`);
      for (const o3 of n3) {
        if (i2.has(o3)) throw new Error(`Discriminator property ${String(e2)} has duplicate value ${String(o3)}`);
        i2.set(o3, t48);
      }
    }
    return new t25({ typeName: yb.ZodDiscriminatedUnion, discriminator: e2, options: n2, optionsMap: i2, ...oy(o2) });
  }
};
function Uy(t48, e2) {
  const n2 = L_(t48), o2 = L_(e2);
  if (t48 === e2) return { valid: true, data: t48 };
  if (n2 === O_.object && o2 === O_.object) {
    const n3 = w_.objectKeys(e2), o3 = w_.objectKeys(t48).filter((t49) => -1 !== n3.indexOf(t49)), i2 = { ...t48, ...e2 };
    for (const n4 of o3) {
      const o4 = Uy(t48[n4], e2[n4]);
      if (!o4.valid) return { valid: false };
      i2[n4] = o4.data;
    }
    return { valid: true, data: i2 };
  }
  if (n2 === O_.array && o2 === O_.array) {
    if (t48.length !== e2.length) return { valid: false };
    const n3 = [];
    for (let o3 = 0; o3 < t48.length; o3++) {
      const i2 = Uy(t48[o3], e2[o3]);
      if (!i2.valid) return { valid: false };
      n3.push(i2.data);
    }
    return { valid: true, data: n3 };
  }
  return n2 === O_.date && o2 === O_.date && +t48 === +e2 ? { valid: true, data: t48 } : { valid: false };
}
var Gy = class extends ry {
  _parse(t48) {
    const { status: e2, ctx: n2 } = this._processInputParams(t48), o2 = (t49, o3) => {
      if (J_(t49) || J_(o3)) return G_;
      const i2 = Uy(t49.value, o3.value);
      return i2.valid ? ((K_(t49) || K_(o3)) && e2.dirty(), { status: e2.value, value: i2.data }) : (H_(n2, { code: D_.invalid_intersection_types }), G_);
    };
    return n2.common.async ? Promise.all([this._def.left._parseAsync({ data: n2.data, path: n2.path, parent: n2 }), this._def.right._parseAsync({ data: n2.data, path: n2.path, parent: n2 })]).then(([t49, e3]) => o2(t49, e3)) : o2(this._def.left._parseSync({ data: n2.data, path: n2.path, parent: n2 }), this._def.right._parseSync({ data: n2.data, path: n2.path, parent: n2 }));
  }
};
Gy.create = (t48, e2, n2) => new Gy({ left: t48, right: e2, typeName: yb.ZodIntersection, ...oy(n2) });
var Zy = class t26 extends ry {
  _parse(t48) {
    const { status: e2, ctx: n2 } = this._processInputParams(t48);
    if (n2.parsedType !== O_.array) return H_(n2, { code: D_.invalid_type, expected: O_.array, received: n2.parsedType }), G_;
    if (n2.data.length < this._def.items.length) return H_(n2, { code: D_.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }), G_;
    !this._def.rest && n2.data.length > this._def.items.length && (H_(n2, { code: D_.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }), e2.dirty());
    const o2 = [...n2.data].map((t49, e3) => {
      const o3 = this._def.items[e3] || this._def.rest;
      return o3 ? o3._parse(new ey(n2, t49, n2.path, e3)) : null;
    }).filter((t49) => !!t49);
    return n2.common.async ? Promise.all(o2).then((t49) => U_.mergeArray(e2, t49)) : U_.mergeArray(e2, o2);
  }
  get items() {
    return this._def.items;
  }
  rest(e2) {
    return new t26({ ...this._def, rest: e2 });
  }
};
Zy.create = (t48, e2) => {
  if (!Array.isArray(t48)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  return new Zy({ items: t48, typeName: yb.ZodTuple, rest: null, ...oy(e2) });
};
var qy = class t27 extends ry {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(t48) {
    const { status: e2, ctx: n2 } = this._processInputParams(t48);
    if (n2.parsedType !== O_.object) return H_(n2, { code: D_.invalid_type, expected: O_.object, received: n2.parsedType }), G_;
    const o2 = [], i2 = this._def.keyType, r2 = this._def.valueType;
    for (const t49 in n2.data) o2.push({ key: i2._parse(new ey(n2, t49, n2.path, t49)), value: r2._parse(new ey(n2, n2.data[t49], n2.path, t49)), alwaysSet: t49 in n2.data });
    return n2.common.async ? U_.mergeObjectAsync(e2, o2) : U_.mergeObjectSync(e2, o2);
  }
  get element() {
    return this._def.valueType;
  }
  static create(e2, n2, o2) {
    return new t27(n2 instanceof ry ? { keyType: e2, valueType: n2, typeName: yb.ZodRecord, ...oy(o2) } : { keyType: wy.create(), valueType: e2, typeName: yb.ZodRecord, ...oy(n2) });
  }
};
var Jy = class extends ry {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(t48) {
    const { status: e2, ctx: n2 } = this._processInputParams(t48);
    if (n2.parsedType !== O_.map) return H_(n2, { code: D_.invalid_type, expected: O_.map, received: n2.parsedType }), G_;
    const o2 = this._def.keyType, i2 = this._def.valueType, r2 = [...n2.data.entries()].map(([t49, e3], r3) => ({ key: o2._parse(new ey(n2, t49, n2.path, [r3, "key"])), value: i2._parse(new ey(n2, e3, n2.path, [r3, "value"])) }));
    if (n2.common.async) {
      const t49 = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const n3 of r2) {
          const o3 = await n3.key, i3 = await n3.value;
          if ("aborted" === o3.status || "aborted" === i3.status) return G_;
          "dirty" !== o3.status && "dirty" !== i3.status || e2.dirty(), t49.set(o3.value, i3.value);
        }
        return { status: e2.value, value: t49 };
      });
    }
    {
      const t49 = /* @__PURE__ */ new Map();
      for (const n3 of r2) {
        const o3 = n3.key, i3 = n3.value;
        if ("aborted" === o3.status || "aborted" === i3.status) return G_;
        "dirty" !== o3.status && "dirty" !== i3.status || e2.dirty(), t49.set(o3.value, i3.value);
      }
      return { status: e2.value, value: t49 };
    }
  }
};
Jy.create = (t48, e2, n2) => new Jy({ valueType: e2, keyType: t48, typeName: yb.ZodMap, ...oy(n2) });
var Ky = class t28 extends ry {
  _parse(t48) {
    const { status: e2, ctx: n2 } = this._processInputParams(t48);
    if (n2.parsedType !== O_.set) return H_(n2, { code: D_.invalid_type, expected: O_.set, received: n2.parsedType }), G_;
    const o2 = this._def;
    null !== o2.minSize && n2.data.size < o2.minSize.value && (H_(n2, { code: D_.too_small, minimum: o2.minSize.value, type: "set", inclusive: true, exact: false, message: o2.minSize.message }), e2.dirty()), null !== o2.maxSize && n2.data.size > o2.maxSize.value && (H_(n2, { code: D_.too_big, maximum: o2.maxSize.value, type: "set", inclusive: true, exact: false, message: o2.maxSize.message }), e2.dirty());
    const i2 = this._def.valueType;
    function r2(t49) {
      const n3 = /* @__PURE__ */ new Set();
      for (const o3 of t49) {
        if ("aborted" === o3.status) return G_;
        "dirty" === o3.status && e2.dirty(), n3.add(o3.value);
      }
      return { status: e2.value, value: n3 };
    }
    const s2 = [...n2.data.values()].map((t49, e3) => i2._parse(new ey(n2, t49, n2.path, e3)));
    return n2.common.async ? Promise.all(s2).then((t49) => r2(t49)) : r2(s2);
  }
  min(e2, n2) {
    return new t28({ ...this._def, minSize: { value: e2, message: W_.toString(n2) } });
  }
  max(e2, n2) {
    return new t28({ ...this._def, maxSize: { value: e2, message: W_.toString(n2) } });
  }
  size(t48, e2) {
    return this.min(t48, e2).max(t48, e2);
  }
  nonempty(t48) {
    return this.min(1, t48);
  }
};
Ky.create = (t48, e2) => new Ky({ valueType: t48, minSize: null, maxSize: null, typeName: yb.ZodSet, ...oy(e2) });
var Qy = class t29 extends ry {
  constructor() {
    super(...arguments), this.validate = this.implement;
  }
  _parse(t48) {
    const { ctx: e2 } = this._processInputParams(t48);
    if (e2.parsedType !== O_.function) return H_(e2, { code: D_.invalid_type, expected: O_.function, received: e2.parsedType }), G_;
    function n2(t49, n3) {
      return X_({ data: t49, path: e2.path, errorMaps: [e2.common.contextualErrorMap, e2.schemaErrorMap, $_(), F_].filter((t50) => !!t50), issueData: { code: D_.invalid_arguments, argumentsError: n3 } });
    }
    function o2(t49, n3) {
      return X_({ data: t49, path: e2.path, errorMaps: [e2.common.contextualErrorMap, e2.schemaErrorMap, $_(), F_].filter((t50) => !!t50), issueData: { code: D_.invalid_return_type, returnTypeError: n3 } });
    }
    const i2 = { errorMap: e2.common.contextualErrorMap }, r2 = e2.data;
    if (this._def.returns instanceof rb) {
      const t49 = this;
      return q_(async function(...e3) {
        const s2 = new k_([]), a2 = await t49._def.args.parseAsync(e3, i2).catch((t50) => {
          throw s2.addIssue(n2(e3, t50)), s2;
        }), c2 = await Reflect.apply(r2, this, a2);
        return await t49._def.returns._def.type.parseAsync(c2, i2).catch((t50) => {
          throw s2.addIssue(o2(c2, t50)), s2;
        });
      });
    }
    {
      const t49 = this;
      return q_(function(...e3) {
        const s2 = t49._def.args.safeParse(e3, i2);
        if (!s2.success) throw new k_([n2(e3, s2.error)]);
        const a2 = Reflect.apply(r2, this, s2.data), c2 = t49._def.returns.safeParse(a2, i2);
        if (!c2.success) throw new k_([o2(a2, c2.error)]);
        return c2.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...e2) {
    return new t29({ ...this._def, args: Zy.create(e2).rest(Fy.create()) });
  }
  returns(e2) {
    return new t29({ ...this._def, returns: e2 });
  }
  implement(t48) {
    return this.parse(t48);
  }
  strictImplement(t48) {
    return this.parse(t48);
  }
  static create(e2, n2, o2) {
    return new t29({ args: e2 || Zy.create([]).rest(Fy.create()), returns: n2 || Fy.create(), typeName: yb.ZodFunction, ...oy(o2) });
  }
};
var tb = class extends ry {
  get schema() {
    return this._def.getter();
  }
  _parse(t48) {
    const { ctx: e2 } = this._processInputParams(t48);
    return this._def.getter()._parse({ data: e2.data, path: e2.path, parent: e2 });
  }
};
tb.create = (t48, e2) => new tb({ getter: t48, typeName: yb.ZodLazy, ...oy(e2) });
var eb = class extends ry {
  _parse(t48) {
    if (t48.data !== this._def.value) {
      const e2 = this._getOrReturnCtx(t48);
      return H_(e2, { received: e2.data, code: D_.invalid_literal, expected: this._def.value }), G_;
    }
    return { status: "valid", value: t48.data };
  }
  get value() {
    return this._def.value;
  }
};
function nb(t48, e2) {
  return new ob({ values: t48, typeName: yb.ZodEnum, ...oy(e2) });
}
eb.create = (t48, e2) => new eb({ value: t48, typeName: yb.ZodLiteral, ...oy(e2) });
var ob = class t30 extends ry {
  _parse(t48) {
    if ("string" != typeof t48.data) {
      const e2 = this._getOrReturnCtx(t48), n2 = this._def.values;
      return H_(e2, { expected: w_.joinValues(n2), received: e2.parsedType, code: D_.invalid_type }), G_;
    }
    if (this._cache || (this._cache = new Set(this._def.values)), !this._cache.has(t48.data)) {
      const e2 = this._getOrReturnCtx(t48), n2 = this._def.values;
      return H_(e2, { received: e2.data, code: D_.invalid_enum_value, options: n2 }), G_;
    }
    return q_(t48.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const t48 = {};
    for (const e2 of this._def.values) t48[e2] = e2;
    return t48;
  }
  get Values() {
    const t48 = {};
    for (const e2 of this._def.values) t48[e2] = e2;
    return t48;
  }
  get Enum() {
    const t48 = {};
    for (const e2 of this._def.values) t48[e2] = e2;
    return t48;
  }
  extract(e2, n2 = this._def) {
    return t30.create(e2, { ...this._def, ...n2 });
  }
  exclude(e2, n2 = this._def) {
    return t30.create(this.options.filter((t48) => !e2.includes(t48)), { ...this._def, ...n2 });
  }
};
ob.create = nb;
var ib = class extends ry {
  _parse(t48) {
    const e2 = w_.getValidEnumValues(this._def.values), n2 = this._getOrReturnCtx(t48);
    if (n2.parsedType !== O_.string && n2.parsedType !== O_.number) {
      const t49 = w_.objectValues(e2);
      return H_(n2, { expected: w_.joinValues(t49), received: n2.parsedType, code: D_.invalid_type }), G_;
    }
    if (this._cache || (this._cache = new Set(w_.getValidEnumValues(this._def.values))), !this._cache.has(t48.data)) {
      const t49 = w_.objectValues(e2);
      return H_(n2, { received: n2.data, code: D_.invalid_enum_value, options: t49 }), G_;
    }
    return q_(t48.data);
  }
  get enum() {
    return this._def.values;
  }
};
ib.create = (t48, e2) => new ib({ values: t48, typeName: yb.ZodNativeEnum, ...oy(e2) });
var rb = class extends ry {
  unwrap() {
    return this._def.type;
  }
  _parse(t48) {
    const { ctx: e2 } = this._processInputParams(t48);
    if (e2.parsedType !== O_.promise && false === e2.common.async) return H_(e2, { code: D_.invalid_type, expected: O_.promise, received: e2.parsedType }), G_;
    const n2 = e2.parsedType === O_.promise ? e2.data : Promise.resolve(e2.data);
    return q_(n2.then((t49) => this._def.type.parseAsync(t49, { path: e2.path, errorMap: e2.common.contextualErrorMap })));
  }
};
rb.create = (t48, e2) => new rb({ type: t48, typeName: yb.ZodPromise, ...oy(e2) });
var sb = class extends ry {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === yb.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(t48) {
    const { status: e2, ctx: n2 } = this._processInputParams(t48), o2 = this._def.effect || null, i2 = { addIssue: (t49) => {
      H_(n2, t49), t49.fatal ? e2.abort() : e2.dirty();
    }, get path() {
      return n2.path;
    } };
    if (i2.addIssue = i2.addIssue.bind(i2), "preprocess" === o2.type) {
      const t49 = o2.transform(n2.data, i2);
      if (n2.common.async) return Promise.resolve(t49).then(async (t50) => {
        if ("aborted" === e2.value) return G_;
        const o3 = await this._def.schema._parseAsync({ data: t50, path: n2.path, parent: n2 });
        return "aborted" === o3.status ? G_ : "dirty" === o3.status || "dirty" === e2.value ? Z_(o3.value) : o3;
      });
      {
        if ("aborted" === e2.value) return G_;
        const o3 = this._def.schema._parseSync({ data: t49, path: n2.path, parent: n2 });
        return "aborted" === o3.status ? G_ : "dirty" === o3.status || "dirty" === e2.value ? Z_(o3.value) : o3;
      }
    }
    if ("refinement" === o2.type) {
      const t49 = (t50) => {
        const e3 = o2.refinement(t50, i2);
        if (n2.common.async) return Promise.resolve(e3);
        if (e3 instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        return t50;
      };
      if (false === n2.common.async) {
        const o3 = this._def.schema._parseSync({ data: n2.data, path: n2.path, parent: n2 });
        return "aborted" === o3.status ? G_ : ("dirty" === o3.status && e2.dirty(), t49(o3.value), { status: e2.value, value: o3.value });
      }
      return this._def.schema._parseAsync({ data: n2.data, path: n2.path, parent: n2 }).then((n3) => "aborted" === n3.status ? G_ : ("dirty" === n3.status && e2.dirty(), t49(n3.value).then(() => ({ status: e2.value, value: n3.value }))));
    }
    if ("transform" === o2.type) {
      if (false === n2.common.async) {
        const t49 = this._def.schema._parseSync({ data: n2.data, path: n2.path, parent: n2 });
        if (!Q_(t49)) return G_;
        const r2 = o2.transform(t49.value, i2);
        if (r2 instanceof Promise) throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");
        return { status: e2.value, value: r2 };
      }
      return this._def.schema._parseAsync({ data: n2.data, path: n2.path, parent: n2 }).then((t49) => Q_(t49) ? Promise.resolve(o2.transform(t49.value, i2)).then((t50) => ({ status: e2.value, value: t50 })) : G_);
    }
    w_.assertNever(o2);
  }
};
sb.create = (t48, e2, n2) => new sb({ schema: t48, typeName: yb.ZodEffects, effect: e2, ...oy(n2) }), sb.createWithPreprocess = (t48, e2, n2) => new sb({ schema: e2, effect: { type: "preprocess", transform: t48 }, typeName: yb.ZodEffects, ...oy(n2) });
var ab = class extends ry {
  _parse(t48) {
    return this._getType(t48) === O_.undefined ? q_(void 0) : this._def.innerType._parse(t48);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ab.create = (t48, e2) => new ab({ innerType: t48, typeName: yb.ZodOptional, ...oy(e2) });
var cb = class extends ry {
  _parse(t48) {
    return this._getType(t48) === O_.null ? q_(null) : this._def.innerType._parse(t48);
  }
  unwrap() {
    return this._def.innerType;
  }
};
cb.create = (t48, e2) => new cb({ innerType: t48, typeName: yb.ZodNullable, ...oy(e2) });
var lb = class extends ry {
  _parse(t48) {
    const { ctx: e2 } = this._processInputParams(t48);
    let n2 = e2.data;
    return e2.parsedType === O_.undefined && (n2 = this._def.defaultValue()), this._def.innerType._parse({ data: n2, path: e2.path, parent: e2 });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
lb.create = (t48, e2) => new lb({ innerType: t48, typeName: yb.ZodDefault, defaultValue: "function" == typeof e2.default ? e2.default : () => e2.default, ...oy(e2) });
var hb = class extends ry {
  _parse(t48) {
    const { ctx: e2 } = this._processInputParams(t48), n2 = { ...e2, common: { ...e2.common, issues: [] } }, o2 = this._def.innerType._parse({ data: n2.data, path: n2.path, parent: { ...n2 } });
    return ty(o2) ? o2.then((t49) => ({ status: "valid", value: "valid" === t49.status ? t49.value : this._def.catchValue({ get error() {
      return new k_(n2.common.issues);
    }, input: n2.data }) })) : { status: "valid", value: "valid" === o2.status ? o2.value : this._def.catchValue({ get error() {
      return new k_(n2.common.issues);
    }, input: n2.data }) };
  }
  removeCatch() {
    return this._def.innerType;
  }
};
hb.create = (t48, e2) => new hb({ innerType: t48, typeName: yb.ZodCatch, catchValue: "function" == typeof e2.catch ? e2.catch : () => e2.catch, ...oy(e2) });
var db = class extends ry {
  _parse(t48) {
    if (this._getType(t48) !== O_.nan) {
      const e2 = this._getOrReturnCtx(t48);
      return H_(e2, { code: D_.invalid_type, expected: O_.nan, received: e2.parsedType }), G_;
    }
    return { status: "valid", value: t48.data };
  }
};
db.create = (t48) => new db({ typeName: yb.ZodNaN, ...oy(t48) });
var ub = /* @__PURE__ */ Symbol("zod_brand");
var pb = class extends ry {
  _parse(t48) {
    const { ctx: e2 } = this._processInputParams(t48), n2 = e2.data;
    return this._def.type._parse({ data: n2, path: e2.path, parent: e2 });
  }
  unwrap() {
    return this._def.type;
  }
};
var mb = class t31 extends ry {
  _parse(t48) {
    const { status: e2, ctx: n2 } = this._processInputParams(t48);
    if (n2.common.async) {
      return (async () => {
        const t49 = await this._def.in._parseAsync({ data: n2.data, path: n2.path, parent: n2 });
        return "aborted" === t49.status ? G_ : "dirty" === t49.status ? (e2.dirty(), Z_(t49.value)) : this._def.out._parseAsync({ data: t49.value, path: n2.path, parent: n2 });
      })();
    }
    {
      const t49 = this._def.in._parseSync({ data: n2.data, path: n2.path, parent: n2 });
      return "aborted" === t49.status ? G_ : "dirty" === t49.status ? (e2.dirty(), { status: "dirty", value: t49.value }) : this._def.out._parseSync({ data: t49.value, path: n2.path, parent: n2 });
    }
  }
  static create(e2, n2) {
    return new t31({ in: e2, out: n2, typeName: yb.ZodPipeline });
  }
};
var gb = class extends ry {
  _parse(t48) {
    const e2 = this._def.innerType._parse(t48), n2 = (t49) => (Q_(t49) && (t49.value = Object.freeze(t49.value)), t49);
    return ty(e2) ? e2.then((t49) => n2(t49)) : n2(e2);
  }
  unwrap() {
    return this._def.innerType;
  }
};
function fb(t48, e2) {
  const n2 = "function" == typeof t48 ? t48(e2) : "string" == typeof t48 ? { message: t48 } : t48;
  return "string" == typeof n2 ? { message: n2 } : n2;
}
function _b(t48, e2 = {}, n2) {
  return t48 ? ky.create().superRefine((o2, i2) => {
    const r2 = t48(o2);
    if (r2 instanceof Promise) return r2.then((t49) => {
      if (!t49) {
        const t50 = fb(e2, o2), r3 = t50.fatal ?? n2 ?? true;
        i2.addIssue({ code: "custom", ...t50, fatal: r3 });
      }
    });
    if (!r2) {
      const t49 = fb(e2, o2), r3 = t49.fatal ?? n2 ?? true;
      i2.addIssue({ code: "custom", ...t49, fatal: r3 });
    }
  }) : ky.create();
}
gb.create = (t48, e2) => new gb({ innerType: t48, typeName: yb.ZodReadonly, ...oy(e2) });
var yb;
var bb;
var xb = { object: By.lazycreate };
(bb = yb || (yb = {})).ZodString = "ZodString", bb.ZodNumber = "ZodNumber", bb.ZodNaN = "ZodNaN", bb.ZodBigInt = "ZodBigInt", bb.ZodBoolean = "ZodBoolean", bb.ZodDate = "ZodDate", bb.ZodSymbol = "ZodSymbol", bb.ZodUndefined = "ZodUndefined", bb.ZodNull = "ZodNull", bb.ZodAny = "ZodAny", bb.ZodUnknown = "ZodUnknown", bb.ZodNever = "ZodNever", bb.ZodVoid = "ZodVoid", bb.ZodArray = "ZodArray", bb.ZodObject = "ZodObject", bb.ZodUnion = "ZodUnion", bb.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", bb.ZodIntersection = "ZodIntersection", bb.ZodTuple = "ZodTuple", bb.ZodRecord = "ZodRecord", bb.ZodMap = "ZodMap", bb.ZodSet = "ZodSet", bb.ZodFunction = "ZodFunction", bb.ZodLazy = "ZodLazy", bb.ZodLiteral = "ZodLiteral", bb.ZodEnum = "ZodEnum", bb.ZodEffects = "ZodEffects", bb.ZodNativeEnum = "ZodNativeEnum", bb.ZodOptional = "ZodOptional", bb.ZodNullable = "ZodNullable", bb.ZodDefault = "ZodDefault", bb.ZodCatch = "ZodCatch", bb.ZodPromise = "ZodPromise", bb.ZodBranded = "ZodBranded", bb.ZodPipeline = "ZodPipeline", bb.ZodReadonly = "ZodReadonly";
var vb = (t48, e2 = { message: `Input not instance of ${t48.name}` }) => _b((e3) => e3 instanceof t48, e2);
var Sb = wy.create;
var Ib = Ry.create;
var Pb = db.create;
var Mb = Ey.create;
var Cb = Ay.create;
var Nb = Oy.create;
var wb = Ly.create;
var Tb = Dy.create;
var Rb = zy.create;
var Eb = ky.create;
var Ab = Fy.create;
var Ob = jy.create;
var Lb = Yy.create;
var Db = $y.create;
var zb = By.create;
var kb = By.strictCreate;
var Fb = Hy.create;
var jb = Vy.create;
var Yb = Gy.create;
var $b = Zy.create;
var Xb = qy.create;
var Bb = Jy.create;
var Hb = Ky.create;
var Wb = Qy.create;
var Vb = tb.create;
var Ub = eb.create;
var Gb = ob.create;
var Zb = ib.create;
var qb = rb.create;
var Jb = sb.create;
var Kb = ab.create;
var Qb = cb.create;
var tx = sb.createWithPreprocess;
var ex = mb.create;
var nx = () => Sb().optional();
var ox = () => Ib().optional();
var ix = () => Cb().optional();
var rx = { string: (t48) => wy.create({ ...t48, coerce: true }), number: (t48) => Ry.create({ ...t48, coerce: true }), boolean: (t48) => Ay.create({ ...t48, coerce: true }), bigint: (t48) => Ey.create({ ...t48, coerce: true }), date: (t48) => Oy.create({ ...t48, coerce: true }) };
var sx = G_;
var ax = A_.string().or(A_.number()).transform((t48) => N_(t48, "\u03A9").value);
var cx = A_.string().or(A_.number()).transform((t48) => N_(t48, "F").value).transform((t48) => Number.parseFloat(t48.toPrecision(12)));
var lx = A_.string().or(A_.number()).transform((t48) => N_(t48, "H").value);
var hx = A_.string().or(A_.number()).transform((t48) => N_(t48, "V").value);
var dx = A_.string().or(A_.number()).transform((t48) => N_(t48).value);
var ux = A_.string().or(A_.number()).transform((t48) => N_(t48, "Hz").value);
var px = dx;
var mx = A_.string().or(A_.number()).transform((t48) => N_(t48, "A").value);
var gx = A_.string().or(A_.number()).transform((t48) => N_(t48).value);
var fx = gx;
var _x = gx;
var yx = A_.string().datetime();
var bx = A_.string().or(A_.number()).transform((t48) => "number" == typeof t48 ? t48 : t48.endsWith("deg") ? Number.parseFloat(t48.split("deg")[0]) : t48.endsWith("rad") ? 180 * Number.parseFloat(t48.split("rad")[0]) / Math.PI : Number.parseFloat(t48));
var xx = A_.number().or(A_.string().endsWith("mAh")).transform((t48) => {
  if ("string" == typeof t48) {
    const e2 = t48.replace("mAh", ""), n2 = Number.parseFloat(e2);
    if (Number.isNaN(n2)) throw new Error("Invalid capacity");
    return n2;
  }
  return t48;
}).describe("Battery capacity in mAh");
var vx = A_.object({ x: px, y: px });
var Sx = vx;
var Ix = A_.object({ x: px, y: px, z: px });
var Px = Ix;
var Mx = A_.object({ width: A_.number(), height: A_.number() });
var Cx = (t48) => A_.string().optional().default(() => `${t48}_${((t49) => {
  const e2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  return Array.from({ length: t49 }, () => e2[Math.floor(62 * Math.random())]).join("");
})(10)}`);
var Nx = A_.enum(["top_left", "top_center", "top_right", "center_left", "center", "center_right", "bottom_left", "bottom_center", "bottom_right"]);
var wx = A_.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"]);
var Tx = A_.object({ project_relative_path: A_.string(), url: A_.string(), mimetype: A_.string() });
var Rx = vx.extend({ rotation: bx.optional() });
var Ex = A_.object({ size: vx.optional(), thickness: px.optional() });
var Ax = A_.object({ font: Ex.optional() });
var Ox = A_.object({ value: A_.string(), at: Rx.optional(), layer: A_.string().optional(), uuid: A_.string().optional(), hide: A_.boolean().optional(), effects: Ax.optional() });
var Lx = A_.object({ Reference: Ox.optional(), Value: Ox.optional(), Datasheet: Ox.optional(), Description: Ox.optional() });
var Dx = A_.object({ through_hole: A_.boolean().optional(), smd: A_.boolean().optional(), exclude_from_pos_files: A_.boolean().optional(), exclude_from_bom: A_.boolean().optional() });
var zx = A_.object({ name: A_.string(), type: A_.string(), shape: A_.string().optional(), at: Rx.optional(), size: vx.optional(), drill: px.optional(), layers: A_.array(A_.string()).optional(), removeUnusedLayers: A_.boolean().optional(), uuid: A_.string().optional() });
var kx = A_.object({ path: A_.string(), offset: Ix.optional(), scale: Ix.optional(), rotate: Ix.optional() });
var Fx = A_.object({ footprintName: A_.string().optional(), version: A_.union([A_.number(), A_.string()]).optional(), generator: A_.string().optional(), generatorVersion: A_.union([A_.number(), A_.string()]).optional(), layer: A_.string().optional(), properties: Lx.optional(), attributes: Dx.optional(), pads: A_.array(zx).optional(), embeddedFonts: A_.boolean().optional(), model: kx.optional() });
var jx = A_.object({ hide: A_.boolean().optional() });
var Yx = A_.object({ offset: px.optional(), hide: A_.boolean().optional() });
var $x = A_.object({ font: Ex.optional(), justify: A_.union([A_.string(), A_.array(A_.string())]).optional(), hide: A_.boolean().optional() });
var Xx = A_.object({ value: A_.string(), id: A_.union([A_.number(), A_.string()]).optional(), at: Rx.optional(), effects: $x.optional() });
var Bx = A_.object({ Reference: Xx.optional(), Value: Xx.optional(), Footprint: Xx.optional(), Datasheet: Xx.optional(), Description: Xx.optional(), ki_keywords: Xx.optional(), ki_fp_filters: Xx.optional() });
var Hx = A_.object({ symbolName: A_.string().optional(), extends: A_.string().optional(), pinNumbers: jx.optional(), pinNames: Yx.optional(), excludeFromSim: A_.boolean().optional(), inBom: A_.boolean().optional(), onBoard: A_.boolean().optional(), properties: Bx.optional(), embeddedFonts: A_.boolean().optional() });
var Wx = A_.object({ error_type: A_.string(), message: A_.string(), is_fatal: A_.boolean().optional() });
var Vx = A_.enum(["jlcpcb", "macrofab", "pcbway", "digikey", "mouser", "lcsc"]);
var Ux = A_.object({ type: A_.literal("source_component"), ftype: A_.string().optional(), source_component_id: A_.string(), name: A_.string(), manufacturer_part_number: A_.string().optional(), supplier_part_numbers: A_.record(Vx, A_.array(A_.string())).optional(), display_value: A_.string().optional(), display_name: A_.string().optional(), are_pins_interchangeable: A_.boolean().optional(), internally_connected_source_port_ids: A_.array(A_.array(A_.string())).optional(), source_group_id: A_.string().optional(), subcircuit_id: A_.string().optional() });
var Gx = Ux.extend({ ftype: A_.literal("simple_capacitor"), capacitance: cx, max_voltage_rating: hx.optional(), display_capacitance: A_.string().optional(), max_decoupling_trace_length: px.optional() });
var Zx = Ux.extend({ ftype: A_.literal("simple_resistor"), resistance: ax, display_resistance: A_.string().optional() });
var qx = Ux.extend({ ftype: A_.literal("simple_diode") });
var Jx = Ux.extend({ ftype: A_.literal("simple_fiducial") });
var Kx = qx.extend({ ftype: A_.literal("simple_led"), color: A_.string().optional(), wavelength: A_.string().optional() });
var Qx = Ux.extend({ ftype: A_.literal("simple_ground") });
var tv = Ux.extend({ ftype: A_.literal("simple_chip") });
var ev = Ux.extend({ ftype: A_.literal("simple_power_source"), voltage: hx });
var nv = Ux.extend({ ftype: A_.literal("simple_current_source"), current: mx, frequency: ux.optional(), peak_to_peak_current: mx.optional(), wave_shape: A_.enum(["sine", "square", "triangle", "sawtooth", "dc"]).optional().default("dc"), phase: A_.number().optional(), duty_cycle: A_.number().min(0).max(1).optional() });
var ov = Ux.extend({ ftype: A_.literal("simple_fuse"), current_rating_amps: A_.number().describe("Nominal current in amps the fuse is rated for"), voltage_rating_volts: A_.number().describe("Voltage rating in volts, e.g. \xB15V would be 5") });
var iv = Ux.extend({ ftype: A_.literal("simple_ammeter") });
var rv = A_.object({ must_be_connected: A_.boolean().optional(), provides_power: A_.boolean().optional(), requires_power: A_.boolean().optional(), provides_ground: A_.boolean().optional(), requires_ground: A_.boolean().optional(), provides_voltage: A_.union([A_.string(), A_.number()]).optional(), requires_voltage: A_.union([A_.string(), A_.number()]).optional(), do_not_connect: A_.boolean().optional(), include_in_board_pinout: A_.boolean().optional(), can_use_internal_pullup: A_.boolean().optional(), is_using_internal_pullup: A_.boolean().optional(), needs_external_pullup: A_.boolean().optional(), can_use_internal_pulldown: A_.boolean().optional(), is_using_internal_pulldown: A_.boolean().optional(), needs_external_pulldown: A_.boolean().optional(), can_use_open_drain: A_.boolean().optional(), is_using_open_drain: A_.boolean().optional(), can_use_push_pull: A_.boolean().optional(), is_using_push_pull: A_.boolean().optional(), should_have_decoupling_capacitor: A_.boolean().optional(), recommended_decoupling_capacitor_capacitance: A_.union([A_.string(), A_.number()]).optional(), is_configured_for_i2c_sda: A_.boolean().optional(), is_configured_for_i2c_scl: A_.boolean().optional(), is_configured_for_spi_mosi: A_.boolean().optional(), is_configured_for_spi_miso: A_.boolean().optional(), is_configured_for_spi_sck: A_.boolean().optional(), is_configured_for_spi_cs: A_.boolean().optional(), is_configured_for_uart_tx: A_.boolean().optional(), is_configured_for_uart_rx: A_.boolean().optional(), supports_i2c_sda: A_.boolean().optional(), supports_i2c_scl: A_.boolean().optional(), supports_spi_mosi: A_.boolean().optional(), supports_spi_miso: A_.boolean().optional(), supports_spi_sck: A_.boolean().optional(), supports_spi_cs: A_.boolean().optional(), supports_uart_tx: A_.boolean().optional(), supports_uart_rx: A_.boolean().optional() });
var sv = Ux.extend({ ftype: A_.literal("simple_battery"), capacity: xx });
var av = Ux.extend({ ftype: A_.literal("simple_inductor"), inductance: lx, display_inductance: A_.string().optional(), max_current_rating: A_.number().optional() });
var cv = Ux.extend({ ftype: A_.literal("simple_push_button") });
var lv = Ux.extend({ ftype: A_.literal("simple_potentiometer"), max_resistance: ax, display_max_resistance: A_.string().optional() });
var hv = Ux.extend({ ftype: A_.literal("simple_crystal"), frequency: A_.number().describe("Frequency in Hz"), load_capacitance: A_.number().optional().describe("Load capacitance in pF"), pin_variant: A_.enum(["two_pin", "four_pin"]).optional() });
var dv = Ux.extend({ ftype: A_.literal("simple_pin_header"), pin_count: A_.number(), gender: A_.enum(["male", "female"]).optional().default("male") });
var uv = Ux.extend({ ftype: A_.literal("simple_connector"), standard: A_.enum(["usb_c", "m2"]).optional() });
var pv = Ux.extend({ ftype: A_.literal("simple_pinout") });
var mv = Ux.extend({ ftype: A_.literal("simple_resonator"), load_capacitance: cx, equivalent_series_resistance: ax.optional(), frequency: ux });
var gv = Ux.extend({ ftype: A_.literal("simple_transistor"), transistor_type: A_.enum(["npn", "pnp"]) });
var fv = Ux.extend({ ftype: A_.literal("simple_test_point"), footprint_variant: A_.enum(["pad", "through_hole"]).optional(), pad_shape: A_.enum(["rect", "circle"]).optional(), pad_diameter: A_.union([A_.number(), A_.string()]).optional(), hole_diameter: A_.union([A_.number(), A_.string()]).optional(), width: A_.union([A_.number(), A_.string()]).optional(), height: A_.union([A_.number(), A_.string()]).optional() });
var _v = Ux.extend({ ftype: A_.literal("simple_mosfet"), channel_type: A_.enum(["n", "p"]), mosfet_mode: A_.enum(["enhancement", "depletion"]) });
var yv = Ux.extend({ ftype: A_.literal("simple_op_amp") });
var bv = Ux.extend({ ftype: A_.literal("simple_switch") });
var xv = A_.object({ type: A_.literal("source_project_metadata"), name: A_.string().optional(), software_used_string: A_.string().optional(), project_url: A_.string().optional(), source_filesystem_md5_hash: A_.string().optional(), created_at: yx.optional() });
var vv = Wx.extend({ type: A_.literal("source_missing_property_error"), source_missing_property_error_id: Cx("source_missing_property_error"), source_component_id: A_.string(), property_name: A_.string(), subcircuit_id: A_.string().optional(), error_type: A_.literal("source_missing_property_error").default("source_missing_property_error") }).describe("The source code is missing a property");
var Sv = Wx.extend({ type: A_.literal("source_failed_to_create_component_error"), source_failed_to_create_component_error_id: Cx("source_failed_to_create_component_error"), error_type: A_.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"), component_name: A_.string().optional(), subcircuit_id: A_.string().optional(), parent_source_component_id: A_.string().optional(), pcb_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), schematic_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional() }).describe("Error emitted when a component fails to be constructed");
var Iv = Wx.extend({ type: A_.literal("source_invalid_component_property_error"), source_invalid_component_property_error_id: Cx("source_invalid_component_property_error"), source_component_id: A_.string(), property_name: A_.string(), property_value: A_.unknown().optional(), expected_format: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal("source_invalid_component_property_error").default("source_invalid_component_property_error") }).describe("The source component property is invalid");
var Pv = Wx.extend({ type: A_.literal("source_trace_not_connected_error"), source_trace_not_connected_error_id: Cx("source_trace_not_connected_error"), error_type: A_.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"), subcircuit_id: A_.string().optional(), source_group_id: A_.string().optional(), source_trace_id: A_.string().optional(), connected_source_port_ids: A_.array(A_.string()).optional(), selectors_not_found: A_.array(A_.string()).optional() }).describe("Occurs when a source trace selector does not match any ports");
var Mv = A_.object({ type: A_.literal("source_property_ignored_warning"), source_property_ignored_warning_id: Cx("source_property_ignored_warning"), source_component_id: A_.string(), property_name: A_.string(), subcircuit_id: A_.string().optional(), error_type: A_.literal("source_property_ignored_warning").default("source_property_ignored_warning"), message: A_.string() }).describe("The source property was ignored");
var Cv = A_.object({ type: A_.literal("source_pin_missing_trace_warning"), source_pin_missing_trace_warning_id: Cx("source_pin_missing_trace_warning"), warning_type: A_.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"), message: A_.string(), source_component_id: A_.string(), source_port_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a source component pin is missing a trace connection");
var Nv = A_.object({ type: A_.literal("source_missing_manufacturer_part_number_warning"), source_missing_manufacturer_part_number_warning_id: Cx("source_missing_manufacturer_part_number_warning"), warning_type: A_.literal("source_missing_manufacturer_part_number_warning").default("source_missing_manufacturer_part_number_warning"), message: A_.string(), source_component_id: A_.string(), standard: A_.string(), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a standard connector is missing manufacturer part number");
var wv = A_.object({ type: A_.literal("source_refdes_convention_warning"), source_refdes_convention_warning_id: Cx("source_refdes_convention_warning"), warning_type: A_.literal("source_refdes_convention_warning").default("source_refdes_convention_warning"), message: A_.string(), source_component_id: A_.string(), refdes: A_.string(), source_component_ftype: A_.string(), expected_prefixes: A_.array(A_.string()), actual_prefix: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a source component reference designator does not match the component type convention");
var Tv = Ux.extend({ ftype: A_.literal("simple_voltage_probe") });
var Rv = Ux.extend({ ftype: A_.literal("interconnect") });
var Ev = Wx.extend({ type: A_.literal("source_i2c_misconfigured_error"), source_i2c_misconfigured_error_id: Cx("source_i2c_misconfigured_error"), error_type: A_.literal("source_i2c_misconfigured_error").default("source_i2c_misconfigured_error"), source_port_ids: A_.array(A_.string()) }).describe("Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net");
var Av = Wx.extend({ type: A_.literal("source_component_misconfigured_error"), source_component_misconfigured_error_id: Cx("source_component_misconfigured_error"), error_type: A_.literal("source_component_misconfigured_error").default("source_component_misconfigured_error"), source_component_ids: A_.array(A_.string()), source_port_ids: A_.array(A_.string()).optional() }).describe("Error emitted when one or more source components have an invalid or conflicting configuration");
var Ov = Ux.extend({ ftype: A_.literal("simple_voltage_source"), voltage: hx, frequency: ux.optional(), peak_to_peak_voltage: hx.optional(), wave_shape: A_.enum(["sinewave", "square", "triangle", "sawtooth"]).optional(), phase: bx.optional(), duty_cycle: A_.number().optional().describe("Duty cycle as a fraction (0 to 1)"), pulse_delay: _x.optional(), rise_time: _x.optional(), fall_time: _x.optional(), pulse_width: _x.optional(), period: _x.optional() });
var Lv = A_.union([Zx, Gx, qx, Jx, Kx, Qx, tv, ev, nv, iv, sv, av, cv, lv, hv, dv, uv, pv, mv, bv, gv, fv, _v, yv, ov, Tv, Rv, Ov, xv, vv, Iv, Sv, Pv, Mv, Cv, Nv, wv, Ev, Av]);
var Dv = A_.object({ type: A_.literal("source_port"), pin_number: A_.number().optional(), port_hints: A_.array(A_.string()).optional(), name: A_.string(), source_port_id: A_.string(), source_component_id: A_.string().optional(), source_group_id: A_.string().optional(), most_frequently_referenced_by_name: A_.string().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() }).merge(rv);
var zv = A_.object({ type: A_.literal("source_component_internal_connection"), source_component_internal_connection_id: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() });
var kv = A_.object({ type: A_.literal("source_trace"), source_trace_id: A_.string(), connected_source_port_ids: A_.array(A_.string()), connected_source_net_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), max_length: A_.number().optional(), name: A_.string().optional(), min_trace_thickness: A_.number().optional(), display_name: A_.string().optional() });
var Fv = A_.object({ type: A_.literal("source_group"), source_group_id: A_.string(), subcircuit_id: A_.string().optional(), parent_subcircuit_id: A_.string().optional(), parent_source_group_id: A_.string().optional(), is_subcircuit: A_.boolean().optional(), show_as_schematic_box: A_.boolean().optional(), name: A_.string().optional(), was_automatically_named: A_.boolean().optional() });
var jv = A_.object({ type: A_.literal("source_net"), source_net_id: A_.string(), name: A_.string(), member_source_group_ids: A_.array(A_.string()), is_power: A_.boolean().optional(), is_ground: A_.boolean().optional(), is_digital_signal: A_.boolean().optional(), is_analog_signal: A_.boolean().optional(), is_positive_voltage_source: A_.boolean().optional(), trace_width: A_.number().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() });
var Yv = A_.object({ type: A_.literal("source_board"), source_board_id: A_.string(), source_group_id: A_.string(), title: A_.string().optional() }).describe("Defines a board in the source domain");
var $v = Wx.extend({ type: A_.literal("source_ambiguous_port_reference"), source_ambiguous_port_reference_id: Cx("source_ambiguous_port_reference"), error_type: A_.literal("source_ambiguous_port_reference").default("source_ambiguous_port_reference"), source_port_id: A_.string().optional(), source_component_id: A_.string().optional() }).describe("Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous");
var Xv = A_.object({ type: A_.literal("source_pcb_ground_plane"), source_pcb_ground_plane_id: A_.string(), source_group_id: A_.string(), source_net_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Defines a ground plane in the source domain");
var Bv = ["top", "bottom", "inner1", "inner2", "inner3", "inner4", "inner5", "inner6", "inner7", "inner8"];
var Hv = A_.enum(Bv);
var Wv = Hv.or(A_.object({ name: Hv })).transform((t48) => "string" == typeof t48 ? t48 : t48.name);
var Vv = A_.enum(["top", "bottom"]);
var Uv = A_.object({ type: A_.literal("source_manually_placed_via"), source_manually_placed_via_id: A_.string(), source_group_id: A_.string(), source_net_id: A_.string(), subcircuit_id: A_.string().optional(), source_trace_id: A_.string().optional() }).describe("Defines a via that is manually placed in the source domain");
var Gv = A_.object({ type: A_.literal("source_unnamed_trace_warning"), source_unnamed_trace_warning_id: Cx("source_unnamed_trace_warning"), warning_type: A_.literal("source_unnamed_trace_warning").default("source_unnamed_trace_warning"), message: A_.string(), source_trace_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a source trace is missing a name");
var Zv = A_.object({ type: A_.literal("source_no_power_pin_defined_warning"), source_no_power_pin_defined_warning_id: Cx("source_no_power_pin_defined_warning"), warning_type: A_.literal("source_no_power_pin_defined_warning").default("source_no_power_pin_defined_warning"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a chip has no source ports with requires_power=true");
var qv = A_.object({ type: A_.literal("source_no_ground_pin_defined_warning"), source_no_ground_pin_defined_warning_id: Cx("source_no_ground_pin_defined_warning"), warning_type: A_.literal("source_no_ground_pin_defined_warning").default("source_no_ground_pin_defined_warning"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a chip has no source ports marked as ground pins");
var Jv = A_.object({ type: A_.literal("source_component_pins_underspecified_warning"), source_component_pins_underspecified_warning_id: Cx("source_component_pins_underspecified_warning"), warning_type: A_.literal("source_component_pins_underspecified_warning").default("source_component_pins_underspecified_warning"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Warning emitted when all ports on a source component are underspecified");
var Kv = Wx.extend({ type: A_.literal("source_pin_must_be_connected_error"), source_pin_must_be_connected_error_id: Cx("source_pin_must_be_connected_error"), error_type: A_.literal("source_pin_must_be_connected_error").default("source_pin_must_be_connected_error"), source_component_id: A_.string(), source_port_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Error emitted when a pin with mustBeConnected attribute is not connected to any trace");
var Qv = Wx.extend({ type: A_.literal("unknown_error_finding_part"), unknown_error_finding_part_id: Cx("unknown_error_finding_part"), error_type: A_.literal("unknown_error_finding_part").default("unknown_error_finding_part"), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when an unexpected error occurs while finding a part");
var tS = A_.object({ type: A_.literal("source_part_not_found_warning"), source_part_not_found_warning_id: Cx("source_part_not_found_warning"), warning_type: A_.literal("source_part_not_found_warning").default("source_part_not_found_warning"), message: A_.string(), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional(), supplier_name: Vx.optional(), manufacturer_part_number: A_.string().optional(), supplier_part_number: A_.string().optional(), part_name: A_.string().optional() }).describe("Warning emitted when a requested part can not be found");
var eS = A_.object({ type: A_.literal("schematic_box"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), width: px, height: px, is_dashed: A_.boolean().default(false), x: px, y: px, subcircuit_id: A_.string().optional() }).describe("Draws a box on the schematic");
var nS = A_.object({ type: A_.literal("schematic_path"), schematic_path_id: Cx("schematic_path"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), fill_color: A_.string().optional(), is_filled: A_.boolean().optional(), is_dashed: A_.boolean().default(false), stroke_width: px.nullable().optional(), stroke_color: A_.string().optional(), dash_length: px.optional(), dash_gap: px.optional(), points: A_.array(vx), subcircuit_id: A_.string().optional() });
var oS = A_.record(A_.object({ left_margin: dx.optional(), right_margin: dx.optional(), top_margin: dx.optional(), bottom_margin: dx.optional() }));
var iS = A_.object({ left_size: A_.number(), right_size: A_.number(), top_size: A_.number().optional(), bottom_size: A_.number().optional() });
var rS = A_.object({ left_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), right_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), top_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum(["left-to-right", "right-to-left"]).optional() }).optional(), bottom_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum(["left-to-right", "right-to-left"]).optional() }).optional() });
var sS = A_.union([iS, rS]);
var aS = A_.object({ type: A_.literal("schematic_component"), size: Mx, center: vx, source_component_id: A_.string().optional(), schematic_component_id: A_.string(), schematic_sheet_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), pin_spacing: dx.optional(), pin_styles: oS.optional(), box_width: dx.optional(), symbol_name: A_.string().optional(), port_arrangement: sS.optional(), port_labels: A_.record(A_.string()).optional(), symbol_display_value: A_.string().optional(), subcircuit_id: A_.string().optional(), schematic_group_id: A_.string().optional(), is_schematic_group: A_.boolean().optional(), source_group_id: A_.string().optional(), is_box_with_pins: A_.boolean().optional().default(true) });
var cS = A_.object({ kicad_symbol: Hx.optional() }).catchall(A_.unknown());
var lS = A_.object({ type: A_.literal("schematic_symbol"), schematic_symbol_id: A_.string(), name: A_.string().optional(), metadata: cS.optional() }).describe("Defines a named schematic symbol that can be referenced by components.");
var hS = A_.object({ type: A_.literal("schematic_line"), schematic_line_id: Cx("schematic_line"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), x1: px, y1: px, x2: px, y2: px, stroke_width: px.nullable().optional(), color: A_.string().default("#000000"), is_dashed: A_.boolean().default(false), dash_length: px.optional(), dash_gap: px.optional(), subcircuit_id: A_.string().optional() }).describe("Draws a styled line on the schematic");
var dS = A_.object({ type: A_.literal("schematic_rect"), schematic_rect_id: Cx("schematic_rect"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: vx, width: px, height: px, rotation: bx.default(0), stroke_width: px.nullable().optional(), color: A_.string().default("#000000"), is_filled: A_.boolean().default(false), fill_color: A_.string().optional(), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe("Draws a styled rectangle on the schematic");
var uS = A_.object({ type: A_.literal("schematic_circle"), schematic_circle_id: Cx("schematic_circle"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: vx, radius: px, stroke_width: px.nullable().optional(), color: A_.string().default("#000000"), is_filled: A_.boolean().default(false), fill_color: A_.string().optional(), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe("Draws a styled circle on the schematic");
var pS = A_.object({ type: A_.literal("schematic_arc"), schematic_arc_id: Cx("schematic_arc"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: vx, radius: px, start_angle_degrees: bx, end_angle_degrees: bx, direction: A_.enum(["clockwise", "counterclockwise"]).default("counterclockwise"), stroke_width: px.nullable().optional(), color: A_.string().default("#000000"), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe("Draws a styled arc on the schematic");
var mS = A_.object({ type: A_.literal("schematic_trace"), schematic_trace_id: A_.string(), schematic_sheet_id: A_.string().optional(), source_trace_id: A_.string().optional(), junctions: A_.array(A_.object({ x: A_.number(), y: A_.number() })), edges: A_.array(A_.object({ from: A_.object({ x: A_.number(), y: A_.number() }), to: A_.object({ x: A_.number(), y: A_.number() }), is_crossing: A_.boolean().optional(), from_schematic_port_id: A_.string().optional(), to_schematic_port_id: A_.string().optional() })), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() });
var gS = A_.enum(["center", "left", "right", "top", "bottom"]);
var fS = A_.object({ type: A_.literal("schematic_text"), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), schematic_text_id: A_.string(), text: A_.string(), font_size: A_.number().default(0.18), position: A_.object({ x: px, y: px }), rotation: A_.number().default(0), anchor: A_.union([gS.describe("legacy"), Nx]).default("center"), color: A_.string().default("#000000"), subcircuit_id: A_.string().optional() });
var _S = A_.object({ type: A_.literal("schematic_port"), schematic_port_id: A_.string(), source_port_id: A_.string(), schematic_sheet_id: A_.string().optional(), schematic_component_id: A_.string().optional(), center: vx, facing_direction: A_.enum(["up", "down", "left", "right"]).optional(), distance_from_component_edge: A_.number().optional(), side_of_component: A_.enum(["top", "bottom", "left", "right"]).optional(), true_ccw_index: A_.number().optional(), pin_number: A_.number().optional(), display_pin_label: A_.string().optional(), subcircuit_id: A_.string().optional(), is_connected: A_.boolean().optional(), has_input_arrow: A_.boolean().optional(), has_output_arrow: A_.boolean().optional(), is_drawn_with_inversion_circle: A_.boolean().optional() }).describe("Defines a port on a schematic component");
var yS = A_.object({ type: A_.literal("schematic_net_label"), schematic_net_label_id: Cx("schematic_net_label"), schematic_sheet_id: A_.string().optional(), schematic_trace_id: A_.string().optional(), source_trace_id: A_.string().optional(), source_net_id: A_.string(), center: vx, anchor_position: vx.optional(), anchor_side: A_.enum(["top", "bottom", "left", "right"]), text: A_.string(), symbol_name: A_.string().optional(), is_movable: A_.boolean().optional(), subcircuit_id: A_.string().optional() });
var bS = Wx.extend({ type: A_.literal("schematic_error"), schematic_error_id: A_.string(), error_type: A_.literal("schematic_port_not_found").default("schematic_port_not_found"), subcircuit_id: A_.string().optional() }).describe("Defines a schematic error on the schematic");
var xS = Wx.extend({ type: A_.literal("schematic_layout_error"), schematic_layout_error_id: Cx("schematic_layout_error"), error_type: A_.literal("schematic_layout_error").default("schematic_layout_error"), source_group_id: A_.string(), schematic_group_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Error emitted when schematic layout fails for a group");
var vS = A_.object({ type: A_.literal("schematic_debug_object"), label: A_.string().optional(), subcircuit_id: A_.string().optional() });
var SS = vS.extend({ shape: A_.literal("rect"), center: vx, size: Mx });
var IS = vS.extend({ shape: A_.literal("line"), start: vx, end: vx });
var PS = vS.extend({ shape: A_.literal("point"), center: vx });
var MS = A_.discriminatedUnion("shape", [SS, IS, PS]);
var CS = A_.object({ type: A_.literal("schematic_voltage_probe"), schematic_voltage_probe_id: A_.string(), schematic_sheet_id: A_.string().optional(), source_component_id: A_.string().optional(), name: A_.string().optional(), position: vx, schematic_trace_id: A_.string(), voltage: hx.optional(), subcircuit_id: A_.string().optional(), color: A_.string().optional(), label_alignment: Nx.optional() }).describe("Defines a voltage probe measurement point on a schematic trace");
var NS = A_.object({ type: A_.literal("schematic_manual_edit_conflict_warning"), schematic_manual_edit_conflict_warning_id: Cx("schematic_manual_edit_conflict_warning"), warning_type: A_.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"), message: A_.string(), schematic_component_id: A_.string(), schematic_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_component_id: A_.string() }).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");
var wS = A_.object({ type: A_.literal("schematic_group"), schematic_group_id: Cx("schematic_group"), schematic_sheet_id: A_.string().optional(), source_group_id: A_.string(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), width: dx, height: dx, center: vx, schematic_component_ids: A_.array(A_.string()), show_as_schematic_box: A_.boolean().optional(), name: A_.string().optional(), description: A_.string().optional() }).describe("Defines a group of components on the schematic");
var TS = A_.object({ type: A_.literal("schematic_table"), schematic_table_id: Cx("schematic_table"), schematic_sheet_id: A_.string().optional(), anchor_position: vx, column_widths: A_.array(px), row_heights: A_.array(px), cell_padding: px.optional(), border_width: px.optional(), subcircuit_id: A_.string().optional(), schematic_component_id: A_.string().optional(), anchor: Nx.optional() }).describe("Defines a table on the schematic");
var RS = A_.object({ type: A_.literal("schematic_table_cell"), schematic_table_cell_id: Cx("schematic_table_cell"), schematic_sheet_id: A_.string().optional(), schematic_table_id: A_.string(), start_row_index: A_.number(), end_row_index: A_.number(), start_column_index: A_.number(), end_column_index: A_.number(), text: A_.string().optional(), center: vx, width: px, height: px, horizontal_align: A_.enum(["left", "center", "right"]).optional(), vertical_align: A_.enum(["top", "middle", "bottom"]).optional(), font_size: px.optional(), subcircuit_id: A_.string().optional() }).describe("Defines a cell within a schematic_table");
var ES = A_.object({ type: A_.literal("schematic_sheet"), schematic_sheet_id: Cx("schematic_sheet"), name: A_.string().optional(), sheet_index: A_.number().optional(), subcircuit_id: A_.string().optional(), outline_color: A_.string().optional() }).describe("Defines a schematic sheet or page that components can be placed on");
var AS = A_.object({ x: px, y: px, bulge: A_.number().optional() });
var OS = A_.object({ vertices: A_.array(AS) });
var LS = A_.object({ outer_ring: OS, inner_rings: A_.array(OS).default([]) });
var DS = A_.object({ x: px, y: px, via: A_.boolean().optional(), via_to_layer: Wv.optional() });
var zS = A_.array(DS);
var kS = A_.object({ x: px, y: px, via: A_.boolean().optional(), to_layer: Wv.optional(), trace_width: px.optional() });
var FS = A_.object({ min_trace_width: dx.optional(), min_board_edge_clearance: dx.optional(), min_via_hole_edge_to_via_hole_edge_clearance: dx.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: dx.optional(), min_trace_to_pad_edge_clearance: dx.optional(), min_pad_edge_to_pad_edge_clearance: dx.optional(), min_same_net_trace_edge_to_trace_edge_clearance: dx.optional(), min_different_net_trace_edge_to_trace_edge_clearance: dx.optional(), min_via_edge_to_pad_edge_clearance: dx.optional(), min_via_hole_diameter: dx.optional(), min_via_pad_diameter: dx.optional() });
var jS = A_.object({ type: A_.literal("pcb_component"), pcb_component_id: Cx("pcb_component"), source_component_id: A_.string(), center: vx, layer: Wv, rotation: bx, display_offset_x: A_.string().optional().describe("How to display the x offset for this part, usually corresponding with how the user specified it"), display_offset_y: A_.string().optional().describe("How to display the y offset for this part, usually corresponding with how the user specified it"), width: dx, height: dx, do_not_place: A_.boolean().optional(), is_allowed_to_be_off_board: A_.boolean().optional(), subcircuit_id: A_.string().optional(), pcb_group_id: A_.string().optional(), position_mode: A_.enum(["packed", "relative_to_group_anchor", "relative_to_another_component", "none"]).optional(), anchor_position: vx.optional(), anchor_alignment: Nx.optional(), positioned_relative_to_pcb_group_id: A_.string().optional(), positioned_relative_to_pcb_board_id: A_.string().optional(), cable_insertion_center: vx.optional(), insertion_direction: A_.enum(["from_above", "from_left", "from_right", "from_front", "from_back"]).optional(), metadata: A_.object({ kicad_footprint: Fx.optional() }).optional(), obstructs_within_bounds: A_.boolean().default(true).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");
var YS = A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: Cx("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("circle"), hole_diameter: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var $S = YS.describe("Defines a circular hole on the PCB");
var XS = A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: Cx("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("rect"), hole_width: A_.number(), hole_height: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var BS = XS.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square.");
var HS = A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: Cx("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.enum(["circle", "square"]), hole_diameter: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var WS = HS.describe("Defines a circular or square hole on the PCB");
var VS = A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: Cx("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("oval"), hole_width: A_.number(), hole_height: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var US = VS.describe("Defines an oval hole on the PCB");
var GS = A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: Cx("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("pill"), hole_width: A_.number(), hole_height: A_.number(), x: px, y: px, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var ZS = GS.describe("Defines a pill-shaped hole on the PCB");
var qS = A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: Cx("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("rotated_pill"), hole_width: A_.number(), hole_height: A_.number(), x: px, y: px, ccw_rotation: bx, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var JS = qS.describe("Defines a rotated pill-shaped hole on the PCB");
var KS = HS.or(VS).or(GS).or(qS).or(YS).or(XS);
var QS = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("circle"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), outer_diameter: A_.number(), hole_diameter: A_.number(), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx("pcb_plated_hole"), soldermask_margin: A_.number().optional() });
var tI = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.enum(["oval", "pill"]), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), outer_width: A_.number(), outer_height: A_.number(), hole_width: A_.number(), hole_height: A_.number(), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, ccw_rotation: bx, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx("pcb_plated_hole"), soldermask_margin: A_.number().optional() });
var eI = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("circular_hole_with_rect_pad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal("circle"), pad_shape: A_.literal("rect"), hole_diameter: A_.number(), rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), hole_offset_x: px.default(0), hole_offset_y: px.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx("pcb_plated_hole"), soldermask_margin: A_.number().optional(), rect_ccw_rotation: bx.optional() });
var nI = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("pill_hole_with_rect_pad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal("pill"), pad_shape: A_.literal("rect"), hole_width: A_.number(), hole_height: A_.number(), rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), hole_offset_x: px.default(0), hole_offset_y: px.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx("pcb_plated_hole"), soldermask_margin: A_.number().optional() });
var oI = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("rotated_pill_hole_with_rect_pad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal("rotated_pill"), pad_shape: A_.literal("rect"), hole_width: A_.number(), hole_height: A_.number(), hole_ccw_rotation: bx, rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), rect_ccw_rotation: bx, hole_offset_x: px.default(0), hole_offset_y: px.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx("pcb_plated_hole"), soldermask_margin: A_.number().optional() });
var iI = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("hole_with_polygon_pad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.enum(["circle", "oval", "pill", "rotated_pill"]), hole_diameter: A_.number().optional(), hole_width: A_.number().optional(), hole_height: A_.number().optional(), pad_outline: A_.array(A_.object({ x: px, y: px })).min(3), hole_offset_x: px.default(0), hole_offset_y: px.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: px, y: px, layers: A_.array(Wv), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: Cx("pcb_plated_hole"), soldermask_margin: A_.number().optional(), ccw_rotation: bx.optional() });
var rI = A_.union([QS, tI, eI, nI, oI, iI]);
var sI = A_.object({ type: A_.literal("pcb_port"), pcb_port_id: Cx("pcb_port"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_port_id: A_.string(), pcb_component_id: A_.string().optional(), x: px, y: px, layers: A_.array(Wv), is_board_pinout: A_.boolean().optional() }).describe("Defines a port on the PCB");
var aI = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("circle"), pcb_smtpad_id: Cx("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, radius: A_.number(), layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var cI = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("rect"), pcb_smtpad_id: Cx("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), rect_border_radius: A_.number().optional(), corner_radius: A_.number().optional(), layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional(), soldermask_margin_left: A_.number().optional(), soldermask_margin_top: A_.number().optional(), soldermask_margin_right: A_.number().optional(), soldermask_margin_bottom: A_.number().optional() });
var lI = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("rotated_rect"), pcb_smtpad_id: Cx("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), rect_border_radius: A_.number().optional(), corner_radius: A_.number().optional(), ccw_rotation: bx, layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional(), soldermask_margin_left: A_.number().optional(), soldermask_margin_top: A_.number().optional(), soldermask_margin_right: A_.number().optional(), soldermask_margin_bottom: A_.number().optional() });
var hI = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("pill"), pcb_smtpad_id: Cx("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), radius: A_.number(), layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var dI = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("rotated_pill"), pcb_smtpad_id: Cx("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), radius: A_.number(), ccw_rotation: bx, layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var uI = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("polygon"), pcb_smtpad_id: Cx("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), points: A_.array(vx), layer: Wv, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var pI = A_.discriminatedUnion("shape", [aI, cI, lI, dI, hI, uI]).describe("Defines an SMT pad on the PCB");
var mI = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("circle"), pcb_solder_paste_id: Cx("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, radius: A_.number(), layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var gI = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("rect"), pcb_solder_paste_id: Cx("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var fI = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("pill"), pcb_solder_paste_id: Cx("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), radius: A_.number(), layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var _I = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("rotated_rect"), pcb_solder_paste_id: Cx("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), ccw_rotation: px, layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var yI = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("oval"), pcb_solder_paste_id: Cx("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: px, y: px, width: A_.number(), height: A_.number(), layer: Wv, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var bI = A_.union([mI, gI, fI, _I, yI]).describe("Defines solderpaste on the PCB");
var xI = A_.object({ type: A_.literal("pcb_text"), pcb_text_id: Cx("pcb_text"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), text: A_.string(), center: vx, layer: Wv, width: dx, height: dx, lines: A_.number(), align: A_.enum(["bottom-left"]) }).describe("Defines text on the PCB");
var vI = A_.object({ route_type: A_.literal("wire"), x: px, y: px, width: px, copper_pour_id: A_.string().optional(), is_inside_copper_pour: A_.boolean().optional(), start_pcb_port_id: A_.string().optional(), end_pcb_port_id: A_.string().optional(), layer: Wv });
var SI = A_.object({ route_type: A_.literal("via"), x: px, y: px, copper_pour_id: A_.string().optional(), is_inside_copper_pour: A_.boolean().optional(), hole_diameter: px.optional(), outer_diameter: px.optional(), from_layer: Wv, to_layer: Wv });
var II = A_.object({ route_type: A_.literal("through_pad"), start: vx, end: vx, width: px, start_layer: Wv, end_layer: Wv, pcb_smtpad_id: A_.string().optional(), pcb_plated_hole_id: A_.string().optional() });
var PI2 = A_.union([vI, SI, II]);
var MI = A_.object({ type: A_.literal("pcb_trace"), source_trace_id: A_.string().optional(), pcb_component_id: A_.string().optional(), pcb_trace_id: Cx("pcb_trace"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), route_thickness_mode: A_.enum(["constant", "interpolated"]).default("constant").optional(), route_order_index: A_.number().optional(), should_round_corners: A_.boolean().optional(), trace_length: A_.number().optional(), highlight_color: A_.string().optional(), route: A_.array(PI2) }).describe("Defines a trace on the PCB");
var CI = A_.object({ type: A_.literal("pcb_trace_warning"), pcb_trace_warning_id: Cx("pcb_trace_warning"), warning_type: A_.literal("pcb_trace_warning").default("pcb_trace_warning"), message: A_.string(), center: vx.optional(), pcb_trace_id: A_.string(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines a trace warning on the PCB");
var NI = A_.object({ type: A_.literal("pcb_trace_too_long_warning"), pcb_trace_too_long_warning_id: Cx("pcb_trace_too_long_warning"), warning_type: A_.literal("pcb_trace_too_long_warning").default("pcb_trace_too_long_warning"), message: A_.string(), pcb_trace_id: A_.string(), source_net_id: A_.string().optional(), source_trace_id: A_.string().optional(), actual_trace_length: px, maximum_trace_length: px, subcircuit_id: A_.string().optional() }).describe("Warning emitted when a PCB trace is longer than its maximum allowed length");
var wI = Wx.extend({ type: A_.literal("pcb_trace_error"), pcb_trace_error_id: Cx("pcb_trace_error"), error_type: A_.literal("pcb_trace_error").default("pcb_trace_error"), center: vx.optional(), pcb_trace_id: A_.string(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines a trace error on the PCB");
var TI = Wx.extend({ type: A_.literal("pcb_trace_missing_error"), pcb_trace_missing_error_id: Cx("pcb_trace_missing_error"), error_type: A_.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"), center: vx.optional(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines an error when a source trace has no corresponding PCB trace");
var RI = Wx.extend({ type: A_.literal("pcb_port_not_matched_error"), pcb_error_id: Cx("pcb_error"), error_type: A_.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"), pcb_component_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines a trace error on the PCB where a port is not matched");
var EI = Wx.extend({ type: A_.literal("pcb_port_not_connected_error"), pcb_port_not_connected_error_id: Cx("pcb_port_not_connected_error"), error_type: A_.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"), pcb_port_ids: A_.array(A_.string()), pcb_component_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines an error when a pcb port is not connected to any trace");
var AI = A_.object({ type: A_.literal("pcb_net"), pcb_net_id: Cx("pcb_net"), source_net_id: A_.string().optional(), highlight_color: A_.string().optional() }).describe("Defines a net on the PCB");
var OI = A_.object({ type: A_.literal("pcb_via"), pcb_via_id: Cx("pcb_via"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), x: px, y: px, outer_diameter: px.default("0.6mm"), hole_diameter: px.default("0.25mm"), from_layer: Wv.optional(), to_layer: Wv.optional(), layers: A_.array(Wv), pcb_trace_id: A_.string().optional(), net_is_assignable: A_.boolean().optional(), net_assigned: A_.boolean().optional(), is_tented: A_.boolean().optional() }).describe("Defines a via on the PCB");
var LI = A_.object({ type: A_.literal("pcb_board"), pcb_board_id: Cx("pcb_board"), pcb_panel_id: A_.string().optional(), carrier_pcb_board_id: A_.string().optional(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), is_mounted_to_carrier_board: A_.boolean().optional(), width: dx.optional(), height: dx.optional(), center: vx, display_offset_x: A_.string().optional().describe("How to display the x offset for this board, usually corresponding with how the user specified it"), display_offset_y: A_.string().optional().describe("How to display the y offset for this board, usually corresponding with how the user specified it"), thickness: dx.optional().default(1.4), num_layers: A_.number().optional().default(4), outline: A_.array(vx).optional(), shape: A_.enum(["rect", "polygon"]).optional(), material: A_.enum(["fr4", "fr1"]).default("fr4"), solder_mask_color: A_.string().optional(), silkscreen_color: A_.string().optional(), anchor_position: vx.optional(), anchor_alignment: Nx.optional(), position_mode: A_.enum(["relative_to_panel_anchor", "none"]).optional() }).merge(FS).describe("Defines the board outline of the PCB");
var DI = A_.object({ type: A_.literal("pcb_panel"), pcb_panel_id: Cx("pcb_panel"), width: dx, height: dx, center: vx, thickness: dx.optional().default(1.4), covered_with_solder_mask: A_.boolean().optional().default(true) }).describe("Defines a PCB panel that can contain multiple boards");
var zI = Wx.extend({ type: A_.literal("pcb_placement_error"), pcb_placement_error_id: Cx("pcb_placement_error"), error_type: A_.literal("pcb_placement_error").default("pcb_placement_error"), subcircuit_id: A_.string().optional() }).describe("Defines a placement error on the PCB");
var kI = Wx.extend({ type: A_.literal("pcb_panelization_placement_error"), pcb_panelization_placement_error_id: Cx("pcb_panelization_placement_error"), error_type: A_.literal("pcb_panelization_placement_error").default("pcb_panelization_placement_error"), pcb_panel_id: A_.string().optional(), pcb_board_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Defines a panelization placement error on the PCB");
var FI = A_.object({ type: A_.literal("pcb_trace_hint"), pcb_trace_hint_id: Cx("pcb_trace_hint"), pcb_port_id: A_.string(), pcb_component_id: A_.string(), route: A_.array(kS), subcircuit_id: A_.string().optional() }).describe("A hint that can be used during generation of a PCB trace");
var jI = A_.object({ type: A_.literal("pcb_silkscreen_line"), pcb_silkscreen_line_id: Cx("pcb_silkscreen_line"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), stroke_width: px.default("0.1mm"), x1: px, y1: px, x2: px, y2: px, layer: Vv }).describe("Defines a silkscreen line on the PCB");
var YI = A_.object({ type: A_.literal("pcb_silkscreen_path"), pcb_silkscreen_path_id: Cx("pcb_silkscreen_path"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, route: A_.array(vx), stroke_width: dx }).describe("Defines a silkscreen path on the PCB");
var $I = A_.object({ type: A_.literal("pcb_silkscreen_text"), pcb_silkscreen_text_id: Cx("pcb_silkscreen_text"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: px.default("0.2mm"), pcb_component_id: A_.string(), text: A_.string(), is_knockout: A_.boolean().default(false).optional(), knockout_padding: A_.object({ left: dx, top: dx, bottom: dx, right: dx }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: A_.number().optional(), layer: Wv, is_mirrored: A_.boolean().default(false).optional(), anchor_position: vx.default({ x: 0, y: 0 }), anchor_alignment: Nx.default("center") }).describe("Defines silkscreen text on the PCB");
var XI = A_.object({ type: A_.literal("pcb_copper_text"), pcb_copper_text_id: Cx("pcb_copper_text"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: px.default("0.2mm"), pcb_component_id: A_.string(), text: A_.string(), is_knockout: A_.boolean().default(false).optional(), knockout_padding: A_.object({ left: dx, top: dx, bottom: dx, right: dx }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: A_.number().optional(), layer: Wv, is_mirrored: A_.boolean().default(false).optional(), anchor_position: vx.default({ x: 0, y: 0 }), anchor_alignment: Nx.default("center") }).describe("Defines copper text on the PCB");
var BI = A_.object({ type: A_.literal("pcb_silkscreen_rect"), pcb_silkscreen_rect_id: Cx("pcb_silkscreen_rect"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, layer: Wv, stroke_width: dx.default("1mm"), corner_radius: dx.optional(), is_filled: A_.boolean().default(true).optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), ccw_rotation: A_.number().optional() }).describe("Defines a silkscreen rect on the PCB");
var HI = A_.object({ type: A_.literal("pcb_silkscreen_circle"), pcb_silkscreen_circle_id: Cx("pcb_silkscreen_circle"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, radius: dx, layer: Vv, stroke_width: dx.default("1mm"), is_filled: A_.boolean().optional() }).describe("Defines a silkscreen circle on the PCB");
var WI = A_.object({ type: A_.literal("pcb_silkscreen_oval"), pcb_silkscreen_oval_id: Cx("pcb_silkscreen_oval"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, radius_x: px, radius_y: px, layer: Vv, ccw_rotation: bx.optional() }).describe("Defines a silkscreen oval on the PCB");
var VI = A_.object({ type: A_.literal("pcb_silkscreen_graphic"), pcb_silkscreen_graphic_id: Cx("pcb_silkscreen_graphic"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, image_asset: Tx.optional() }).extend({ shape: A_.literal("brep"), brep_shape: LS }).describe("Defines a BRep silkscreen graphic on the PCB");
var UI = A_.discriminatedUnion("shape", [VI]).describe("Defines a silkscreen graphic on the PCB");
var GI = A_.object({ type: A_.literal("pcb_silkscreen_pill"), pcb_silkscreen_pill_id: Cx("pcb_silkscreen_pill"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, layer: Wv, ccw_rotation: A_.number().optional() }).describe("Defines a silkscreen pill on the PCB");
var ZI = A_.object({ type: A_.literal("pcb_fabrication_note_text"), pcb_fabrication_note_text_id: Cx("pcb_fabrication_note_text"), subcircuit_id: A_.string().optional(), pcb_group_id: A_.string().optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: px.default("1mm"), pcb_component_id: A_.string(), text: A_.string(), ccw_rotation: A_.number().optional(), layer: Vv, anchor_position: vx.default({ x: 0, y: 0 }), anchor_alignment: A_.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), color: A_.string().optional() }).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");
var qI = A_.object({ type: A_.literal("pcb_fabrication_note_path"), pcb_fabrication_note_path_id: Cx("pcb_fabrication_note_path"), pcb_component_id: A_.string(), subcircuit_id: A_.string().optional(), layer: Wv, route: A_.array(vx), stroke_width: dx, color: A_.string().optional() }).describe("Defines a fabrication path on the PCB for fabricators or assemblers");
var JI = A_.object({ type: A_.literal("pcb_fabrication_note_rect"), pcb_fabrication_note_rect_id: Cx("pcb_fabrication_note_rect"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, layer: Vv, stroke_width: dx.default("0.1mm"), corner_radius: dx.optional(), is_filled: A_.boolean().optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), color: A_.string().optional() }).describe("Defines a fabrication note rectangle on the PCB");
var KI = A_.object({ type: A_.literal("pcb_fabrication_note_dimension"), pcb_fabrication_note_dimension_id: Cx("pcb_fabrication_note_dimension"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, from: vx, to: vx, text: A_.string().optional(), text_ccw_rotation: A_.number().optional(), offset: dx.optional(), offset_distance: dx.optional(), offset_direction: A_.object({ x: A_.number(), y: A_.number() }).optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: dx.default("1mm"), color: A_.string().optional(), arrow_size: dx.default("1mm") }).describe("Defines a measurement annotation within PCB fabrication notes");
var QI = A_.object({ type: A_.literal("pcb_note_text"), pcb_note_text_id: Cx("pcb_note_text"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: px.default("1mm"), text: A_.string().optional(), anchor_position: vx.default({ x: 0, y: 0 }), anchor_alignment: A_.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), layer: Vv.default("top"), is_mirrored_from_top_view: A_.boolean().optional(), color: A_.string().optional() }).describe("Defines a documentation note in text on the PCB");
var tP = A_.object({ type: A_.literal("pcb_note_rect"), pcb_note_rect_id: Cx("pcb_note_rect"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), center: vx, width: dx, height: dx, layer: Vv.default("top"), stroke_width: dx.default("0.1mm"), corner_radius: dx.optional(), is_filled: A_.boolean().optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), color: A_.string().optional() }).describe("Defines a rectangular documentation note on the PCB");
var eP = A_.object({ type: A_.literal("pcb_note_path"), pcb_note_path_id: Cx("pcb_note_path"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), route: A_.array(vx), layer: Vv.default("top"), stroke_width: dx.default("0.1mm"), color: A_.string().optional() }).describe("Defines a polyline documentation note on the PCB");
var nP = A_.object({ type: A_.literal("pcb_note_line"), pcb_note_line_id: Cx("pcb_note_line"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), x1: px, y1: px, x2: px, y2: px, layer: Vv.default("top"), stroke_width: px.default("0.1mm"), color: A_.string().optional(), is_dashed: A_.boolean().optional() }).describe("Defines a straight documentation note line on the PCB");
var oP = A_.object({ type: A_.literal("pcb_note_dimension"), pcb_note_dimension_id: Cx("pcb_note_dimension"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), from: vx, to: vx, text: A_.string().optional(), text_ccw_rotation: A_.number().optional(), offset_distance: dx.optional(), offset_direction: A_.object({ x: A_.number(), y: A_.number() }).optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: dx.default("1mm"), layer: Vv.default("top"), color: A_.string().optional(), arrow_size: dx.default("1mm") }).describe("Defines a measurement annotation within PCB documentation notes");
var iP = Wx.extend({ type: A_.literal("pcb_footprint_overlap_error"), pcb_error_id: Cx("pcb_error"), error_type: A_.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"), pcb_smtpad_ids: A_.array(A_.string()).optional(), pcb_plated_hole_ids: A_.array(A_.string()).optional(), pcb_hole_ids: A_.array(A_.string()).optional(), pcb_keepout_ids: A_.array(A_.string()).optional() }).describe("Error emitted when a pcb footprint overlaps with another element");
var rP = Wx.extend({ type: A_.literal("pcb_courtyard_overlap_error"), pcb_error_id: Cx("pcb_error"), error_type: A_.literal("pcb_courtyard_overlap_error").default("pcb_courtyard_overlap_error"), pcb_component_ids: A_.tuple([A_.string(), A_.string()]) }).describe("Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another");
var sP = A_.object({ type: A_.literal("pcb_keepout"), shape: A_.literal("rect"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: px, height: px, pcb_keepout_id: A_.string(), layers: A_.array(A_.string()), description: A_.string().optional() }).or(A_.object({ type: A_.literal("pcb_keepout"), shape: A_.literal("circle"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, radius: px, pcb_keepout_id: A_.string(), layers: A_.array(A_.string()), description: A_.string().optional() }));
var aP = A_.object({ type: A_.literal("pcb_cutout"), pcb_cutout_id: Cx("pcb_cutout"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_board_id: A_.string().optional(), pcb_panel_id: A_.string().optional() });
var cP = aP.extend({ shape: A_.literal("rect"), center: vx, width: dx, height: dx, rotation: bx.optional(), corner_radius: dx.optional() });
var lP = aP.extend({ shape: A_.literal("circle"), center: vx, radius: dx });
var hP = aP.extend({ shape: A_.literal("polygon"), points: A_.array(vx) });
var dP = aP.extend({ shape: A_.literal("path"), route: A_.array(vx), slot_width: dx, slot_length: dx.optional(), space_between_slots: dx.optional(), slot_corner_radius: dx.optional() });
var uP = A_.discriminatedUnion("shape", [cP, lP, hP, dP]).describe("Defines a cutout on the PCB, removing board material.");
var pP = Wx.extend({ type: A_.literal("pcb_missing_footprint_error"), pcb_missing_footprint_error_id: Cx("pcb_missing_footprint_error"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"), source_component_id: A_.string() }).describe("Defines a missing footprint error on the PCB");
var mP = Wx.extend({ type: A_.literal("external_footprint_load_error"), external_footprint_load_error_id: Cx("external_footprint_load_error"), pcb_component_id: A_.string(), source_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), footprinter_string: A_.string().optional(), error_type: A_.literal("external_footprint_load_error").default("external_footprint_load_error") }).describe("Defines an error when an external footprint fails to load");
var gP = Wx.extend({ type: A_.literal("circuit_json_footprint_load_error"), circuit_json_footprint_load_error_id: Cx("circuit_json_footprint_load_error"), pcb_component_id: A_.string(), source_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"), circuit_json: A_.array(A_.any()).optional() }).describe("Defines an error when a circuit JSON footprint fails to load");
var fP = A_.object({ type: A_.literal("pcb_group"), pcb_group_id: Cx("pcb_group"), source_group_id: A_.string(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), width: dx.optional(), height: dx.optional(), center: vx, display_offset_x: A_.string().optional().describe("How to display the x offset for this group, usually corresponding with how the user specified it"), display_offset_y: A_.string().optional().describe("How to display the y offset for this group, usually corresponding with how the user specified it"), outline: A_.array(vx).optional(), anchor_position: vx.optional(), anchor_alignment: Nx.default("center"), position_mode: A_.enum(["packed", "relative_to_group_anchor", "none"]).optional(), positioned_relative_to_pcb_group_id: A_.string().optional(), positioned_relative_to_pcb_board_id: A_.string().optional(), pcb_component_ids: A_.array(A_.string()), child_layout_mode: A_.enum(["packed", "none"]).optional(), name: A_.string().optional(), description: A_.string().optional(), layout_mode: A_.string().optional(), autorouter_configuration: A_.object({ trace_clearance: dx }).optional(), autorouter_used_string: A_.string().optional() }).describe("Defines a group of components on the PCB");
var _P = Wx.extend({ type: A_.literal("pcb_autorouting_error"), pcb_error_id: Cx("pcb_autorouting_error"), error_type: A_.literal("pcb_autorouting_error").default("pcb_autorouting_error"), subcircuit_id: A_.string().optional() }).describe("The autorouting has failed to route a portion of the board");
var yP = A_.object({ type: A_.literal("pcb_manual_edit_conflict_warning"), pcb_manual_edit_conflict_warning_id: Cx("pcb_manual_edit_conflict_warning"), warning_type: A_.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"), message: A_.string(), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_component_id: A_.string() }).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");
var bP = A_.enum(["x-", "x+", "y+", "y-"]);
var xP = A_.object({ type: A_.literal("pcb_connector_not_in_accessible_orientation_warning"), pcb_connector_not_in_accessible_orientation_warning_id: Cx("pcb_connector_not_in_accessible_orientation_warning"), warning_type: A_.literal("pcb_connector_not_in_accessible_orientation_warning").default("pcb_connector_not_in_accessible_orientation_warning"), message: A_.string(), pcb_component_id: A_.string(), source_component_id: A_.string().optional(), pcb_board_id: A_.string().optional(), facing_direction: bP, recommended_facing_direction: bP, subcircuit_id: A_.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");
var vP = A_.object({ type: A_.literal("supplier_footprint_mismatch_warning"), supplier_footprint_mismatch_warning_id: Cx("supplier_footprint_mismatch_warning"), warning_type: A_.literal("supplier_footprint_mismatch_warning").default("supplier_footprint_mismatch_warning"), message: A_.string(), source_component_id: A_.string(), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), supplier_name: Vx.optional(), supplier_part_number: A_.string().optional(), supplier_footprint_url: A_.string().optional(), footprint_copper_intersection_over_union: A_.number() }).describe("Warning emitted when a supplier part footprint does not match the expected footprint");
var SP = A_.object({ type: A_.literal("pcb_breakout_point"), pcb_breakout_point_id: Cx("pcb_breakout_point"), pcb_group_id: A_.string(), subcircuit_id: A_.string().optional(), source_trace_id: A_.string().optional(), source_port_id: A_.string().optional(), source_net_id: A_.string().optional(), x: px, y: px }).describe("Defines a routing target within a pcb_group for a source_trace or source_net");
var IP = A_.object({ type: A_.literal("pcb_ground_plane"), pcb_ground_plane_id: Cx("pcb_ground_plane"), source_pcb_ground_plane_id: A_.string(), source_net_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Defines a ground plane on the PCB");
var PP = A_.object({ type: A_.literal("pcb_ground_plane_region"), pcb_ground_plane_region_id: Cx("pcb_ground_plane_region"), pcb_ground_plane_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Wv, points: A_.array(vx) }).describe("Defines a polygon region of a ground plane");
var MP = A_.object({ type: A_.literal("pcb_thermal_spoke"), pcb_thermal_spoke_id: Cx("pcb_thermal_spoke"), pcb_ground_plane_id: A_.string(), shape: A_.string(), spoke_count: A_.number(), spoke_thickness: px, spoke_inner_diameter: px, spoke_outer_diameter: px, pcb_plated_hole_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Pattern for connecting a ground plane to a plated hole");
var CP = A_.object({ type: A_.literal("pcb_copper_pour"), pcb_copper_pour_id: Cx("pcb_copper_pour"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Wv, source_net_id: A_.string().optional(), covered_with_solder_mask: A_.boolean().optional().default(true) });
var NP = CP.extend({ shape: A_.literal("rect"), center: vx, width: dx, height: dx, rotation: bx.optional() });
var wP = CP.extend({ shape: A_.literal("brep"), brep_shape: LS });
var TP = CP.extend({ shape: A_.literal("polygon"), points: A_.array(vx) });
var RP = A_.discriminatedUnion("shape", [NP, wP, TP]).describe("Defines a copper pour on the PCB.");
var EP = Wx.extend({ type: A_.literal("pcb_component_outside_board_error"), pcb_component_outside_board_error_id: Cx("pcb_component_outside_board_error"), error_type: A_.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"), pcb_component_id: A_.string(), pcb_board_id: A_.string(), component_center: vx, component_bounds: A_.object({ min_x: A_.number(), max_x: A_.number(), min_y: A_.number(), max_y: A_.number() }), subcircuit_id: A_.string().optional(), source_component_id: A_.string().optional() }).describe("Error emitted when a PCB component is placed outside the board boundaries");
var AP = Wx.extend({ type: A_.literal("pcb_component_not_on_board_edge_error"), pcb_component_not_on_board_edge_error_id: Cx("pcb_component_not_on_board_edge_error"), error_type: A_.literal("pcb_component_not_on_board_edge_error").default("pcb_component_not_on_board_edge_error"), pcb_component_id: A_.string(), pcb_board_id: A_.string(), component_center: vx, pad_to_nearest_board_edge_distance: A_.number(), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when a component that must be placed on the board edge is centered away from the edge");
var OP = Wx.extend({ type: A_.literal("pcb_component_invalid_layer_error"), pcb_component_invalid_layer_error_id: Cx("pcb_component_invalid_layer_error"), error_type: A_.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"), pcb_component_id: A_.string().optional(), source_component_id: A_.string(), layer: Wv, subcircuit_id: A_.string().optional() }).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");
var LP = Wx.extend({ type: A_.literal("pcb_via_clearance_error"), pcb_error_id: Cx("pcb_error"), error_type: A_.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"), pcb_via_ids: A_.array(A_.string()).min(2), minimum_clearance: px.optional(), actual_clearance: px.optional(), pcb_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when vias are closer than the allowed clearance");
var DP = Wx.extend({ type: A_.literal("pcb_via_trace_clearance_error"), pcb_via_trace_clearance_error_id: Cx("pcb_via_trace_clearance_error"), error_type: A_.literal("pcb_via_trace_clearance_error").default("pcb_via_trace_clearance_error"), pcb_via_id: A_.string(), pcb_trace_id: A_.string(), minimum_clearance: px.optional(), actual_clearance: px.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when a via and trace are closer than the allowed clearance");
var zP = Wx.extend({ type: A_.literal("pcb_pad_pad_clearance_error"), pcb_pad_pad_clearance_error_id: Cx("pcb_pad_pad_clearance_error"), error_type: A_.literal("pcb_pad_pad_clearance_error").default("pcb_pad_pad_clearance_error"), pcb_pad_ids: A_.array(A_.string()).min(2), minimum_clearance: px.optional(), actual_clearance: px.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when pads are closer than the allowed clearance");
var kP = Wx.extend({ type: A_.literal("pcb_pad_trace_clearance_error"), pcb_pad_trace_clearance_error_id: Cx("pcb_pad_trace_clearance_error"), error_type: A_.literal("pcb_pad_trace_clearance_error").default("pcb_pad_trace_clearance_error"), pcb_pad_id: A_.string(), pcb_trace_id: A_.string(), minimum_clearance: px.optional(), actual_clearance: px.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when a pad and trace are closer than allowed clearance");
var FP = A_.object({ type: A_.literal("pcb_courtyard_rect"), pcb_courtyard_rect_id: Cx("pcb_courtyard_rect"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, layer: Vv, ccw_rotation: bx.optional(), color: A_.string().optional() }).describe("Defines a courtyard rectangle on the PCB");
var jP = A_.object({ type: A_.literal("pcb_courtyard_outline"), pcb_courtyard_outline_id: Cx("pcb_courtyard_outline"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, outline: A_.array(vx).min(2) }).describe("Defines a courtyard outline on the PCB");
var YP = A_.object({ type: A_.literal("pcb_courtyard_polygon"), pcb_courtyard_polygon_id: Cx("pcb_courtyard_polygon"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: Vv, points: A_.array(vx).min(3), color: A_.string().optional() }).describe("Defines a courtyard polygon on the PCB");
var $P = A_.object({ type: A_.literal("pcb_courtyard_circle"), pcb_courtyard_circle_id: Cx("pcb_courtyard_circle"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, radius: dx, layer: Vv, color: A_.string().optional() }).describe("Defines a courtyard circle on the PCB");
var XP = A_.object({ type: A_.literal("pcb_courtyard_pill"), pcb_courtyard_pill_id: Cx("pcb_courtyard_pill"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: vx, width: dx, height: dx, radius: dx, layer: Vv, color: A_.string().optional() }).describe("Defines a courtyard pill on the PCB");
var BP = ["obj", "stl", "3mf", "gltf", "glb", "step", "wrl"];
var HP = ["x+", "x-", "y+", "y-", "z+", "z-"];
var WP = { obj: "z+", stl: "z+", "3mf": "z+", gltf: "y+", glb: "y+", step: "z+", wrl: "y+" };
var VP = A_.object({ type: A_.literal("cad_component"), cad_component_id: A_.string(), pcb_component_id: A_.string(), source_component_id: A_.string(), position: Ix, rotation: Ix.optional(), size: Ix.optional(), layer: Wv.optional(), subcircuit_id: A_.string().optional(), footprinter_string: A_.string().optional(), model_obj_url: A_.string().optional(), model_stl_url: A_.string().optional(), model_3mf_url: A_.string().optional(), model_gltf_url: A_.string().optional(), model_glb_url: A_.string().optional(), model_step_url: A_.string().optional(), model_wrl_url: A_.string().optional(), model_asset: Tx.optional(), model_unit_to_mm_scale_factor: A_.number().optional(), model_board_normal_direction: A_.enum(HP).optional().describe(`The direction in the model's coordinate space that is considered "up" or "coming out of the board surface"`), model_origin_position: Ix.optional(), model_origin_alignment: A_.enum(["unknown", "center", "center_of_component_on_board_surface", "bottom_center_of_component"]).optional(), model_object_fit: A_.enum(["contain_within_bounds", "fill_bounds"]).optional().default("contain_within_bounds"), model_jscad: A_.any().optional(), show_as_translucent_model: A_.boolean().optional(), show_as_bounding_box: A_.boolean().optional(), anchor_alignment: A_.enum(["center", "center_of_component_on_board_surface"]).optional().default("center") }).describe("Defines a component on the PCB");
var UP = A_.enum(["sinewave", "square", "triangle", "sawtooth"]);
var GP = A_.union([A_.string(), A_.number()]).transform((t48) => "string" == typeof t48 ? t48.endsWith("%") ? parseFloat(t48.slice(0, -1)) / 100 : parseFloat(t48) : t48).pipe(A_.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var ZP = A_.object({ type: A_.literal("simulation_voltage_source"), simulation_voltage_source_id: Cx("simulation_voltage_source"), is_dc_source: A_.literal(true).optional().default(true), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), voltage: hx }).describe("Defines a DC voltage source for simulation");
var qP = A_.object({ type: A_.literal("simulation_voltage_source"), simulation_voltage_source_id: Cx("simulation_voltage_source"), is_dc_source: A_.literal(false), terminal1_source_port_id: A_.string().optional(), terminal2_source_port_id: A_.string().optional(), terminal1_source_net_id: A_.string().optional(), terminal2_source_net_id: A_.string().optional(), voltage: hx.optional(), frequency: ux.optional(), peak_to_peak_voltage: hx.optional(), wave_shape: UP.optional(), phase: bx.optional(), duty_cycle: GP.optional(), pulse_delay: _x.optional(), rise_time: _x.optional(), fall_time: _x.optional(), pulse_width: _x.optional(), period: _x.optional() }).describe("Defines an AC voltage source for simulation");
var JP = A_.union([ZP, qP]).describe("Defines a voltage source for simulation");
var KP = A_.union([A_.string(), A_.number()]).transform((t48) => "string" == typeof t48 ? t48.endsWith("%") ? parseFloat(t48.slice(0, -1)) / 100 : parseFloat(t48) : t48).pipe(A_.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var QP = A_.object({ type: A_.literal("simulation_current_source"), simulation_current_source_id: Cx("simulation_current_source"), is_dc_source: A_.literal(true).optional().default(true), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), current: mx }).describe("Defines a DC current source for simulation");
var tM = A_.object({ type: A_.literal("simulation_current_source"), simulation_current_source_id: Cx("simulation_current_source"), is_dc_source: A_.literal(false), terminal1_source_port_id: A_.string().optional(), terminal2_source_port_id: A_.string().optional(), terminal1_source_net_id: A_.string().optional(), terminal2_source_net_id: A_.string().optional(), current: mx.optional(), frequency: ux.optional(), peak_to_peak_current: mx.optional(), wave_shape: UP.optional(), phase: bx.optional(), duty_cycle: KP.optional() }).describe("Defines an AC current source for simulation");
var eM = A_.union([QP, tM]).describe("Defines a current source for simulation");
var nM = A_.union([A_.literal("spice_dc_sweep"), A_.literal("spice_dc_operating_point"), A_.literal("spice_transient_analysis"), A_.literal("spice_ac_analysis")]);
var oM = A_.object({ method: A_.enum(["trap", "gear"]).optional(), reltol: A_.union([A_.number(), A_.string()]).optional(), abstol: A_.union([A_.number(), A_.string()]).optional(), vntol: A_.union([A_.number(), A_.string()]).optional() }).describe("SPICE solver options for a simulation experiment");
var iM = A_.object({ type: A_.literal("simulation_experiment"), simulation_experiment_id: Cx("simulation_experiment"), name: A_.string(), experiment_type: nM, time_per_step: gx.optional(), start_time_ms: _x.optional(), end_time_ms: _x.optional(), spice_options: oM.optional() }).describe("Defines a simulation experiment configuration");
var rM = A_.object({ type: A_.literal("simulation_transient_voltage_graph"), simulation_transient_voltage_graph_id: Cx("simulation_transient_voltage_graph"), simulation_experiment_id: A_.string(), timestamps_ms: A_.array(A_.number()).optional(), voltage_levels: A_.array(A_.number()), source_component_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), time_per_step: gx, start_time_ms: _x, end_time_ms: _x, name: A_.string().optional(), color: A_.string().optional() }).describe("Stores voltage measurements over time for a simulation");
var sM = A_.object({ type: A_.literal("simulation_transient_current_graph"), simulation_transient_current_graph_id: Cx("simulation_transient_current_graph"), simulation_experiment_id: A_.string(), timestamps_ms: A_.array(A_.number()).optional(), current_levels: A_.array(A_.number()), source_component_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), time_per_step: gx, start_time_ms: _x, end_time_ms: _x, name: A_.string().optional(), color: A_.string().optional() }).describe("Stores current measurements over time for a simulation");
var aM = A_.object({ type: A_.literal("simulation_switch"), simulation_switch_id: Cx("simulation_switch"), source_component_id: A_.string().optional(), closes_at: _x.optional(), opens_at: _x.optional(), starts_closed: A_.boolean().optional(), switching_frequency: ux.optional() }).describe("Defines a switch for simulation timing control");
var cM = A_.object({ type: A_.literal("simulation_voltage_probe"), simulation_voltage_probe_id: Cx("simulation_voltage_probe"), source_component_id: A_.string().optional(), name: A_.string().optional(), signal_input_source_port_id: A_.string().optional(), signal_input_source_net_id: A_.string().optional(), reference_input_source_port_id: A_.string().optional(), reference_input_source_net_id: A_.string().optional(), subcircuit_id: A_.string().optional(), color: A_.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((t48, e2) => {
  if (t48.reference_input_source_port_id || t48.reference_input_source_net_id) {
    const n2 = !!t48.signal_input_source_port_id || !!t48.reference_input_source_port_id, o2 = !!t48.signal_input_source_net_id || !!t48.reference_input_source_net_id;
    n2 && o2 ? e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Cannot mix port and net connections in a differential probe." }) : n2 ? t48.signal_input_source_port_id && t48.reference_input_source_port_id || e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id." }) : o2 && (t48.signal_input_source_net_id && t48.reference_input_source_net_id || e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id." }));
  } else !!t48.signal_input_source_port_id == !!t48.signal_input_source_net_id && e2.addIssue({ code: A_.ZodIssueCode.custom, message: "A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id." });
});
var lM = A_.object({ type: A_.literal("simulation_current_probe"), simulation_current_probe_id: Cx("simulation_current_probe"), source_component_id: A_.string().optional(), name: A_.string().optional(), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), subcircuit_id: A_.string().optional(), color: A_.string().optional() }).describe("Defines a current probe for simulation. It measures current flowing from the positive endpoint to the negative endpoint.").superRefine((t48, e2) => {
  const n2 = !!t48.positive_source_port_id, o2 = !!t48.negative_source_port_id, i2 = !!t48.positive_source_net_id, r2 = !!t48.negative_source_net_id, s2 = n2 || o2, a2 = i2 || r2;
  s2 && a2 ? e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Cannot mix port and net connections in a current probe." }) : s2 ? n2 && o2 || e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Current probe using source ports requires both positive_source_port_id and negative_source_port_id." }) : a2 ? i2 && r2 || e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Current probe using source nets requires both positive_source_net_id and negative_source_net_id." }) : e2.addIssue({ code: A_.ZodIssueCode.custom, message: "A current probe must have either positive/negative source port ids or positive/negative source net ids." });
});
var hM = Wx.extend({ type: A_.literal("simulation_unknown_experiment_error"), simulation_unknown_experiment_error_id: Cx("simulation_unknown_experiment_error"), error_type: A_.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"), simulation_experiment_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("An unknown error occurred during the simulation experiment.");
var dM = A_.object({ type: A_.literal("simulation_op_amp"), simulation_op_amp_id: Cx("simulation_op_amp"), source_component_id: A_.string().optional(), inverting_input_source_port_id: A_.string(), non_inverting_input_source_port_id: A_.string(), output_source_port_id: A_.string(), positive_supply_source_port_id: A_.string(), negative_supply_source_port_id: A_.string() }).describe("Defines a simple ideal operational amplifier for simulation");
var uM = A_.object({ type: A_.literal("simulation_spice_subcircuit"), simulation_spice_subcircuit_id: Cx("simulation_spice_subcircuit"), source_component_id: A_.string(), spice_pin_to_source_port_map: A_.record(A_.string(), A_.string()), subcircuit_source: A_.string() }).describe("Defines a custom SPICE subcircuit model for simulation");
var pM = (t48) => void 0 !== t48;
var mM = A_.object({ type: A_.literal("simulation_oscilloscope_trace"), simulation_oscilloscope_trace_id: Cx("simulation_oscilloscope_trace"), simulation_transient_voltage_graph_id: A_.string().optional(), simulation_transient_current_graph_id: A_.string().optional(), simulation_voltage_probe_id: A_.string().optional(), simulation_current_probe_id: A_.string().optional(), display_name: A_.string().optional(), color: A_.string().optional(), display_center_value: A_.number().optional(), display_center_offset_divs: A_.number().optional(), volts_per_div: A_.number().positive().optional(), amps_per_div: A_.number().positive().optional() }).describe("Defines how a simulation measurement is rendered as an oscilloscope-style trace.").superRefine((t48, e2) => {
  const n2 = [t48.simulation_transient_voltage_graph_id, t48.simulation_voltage_probe_id].filter(pM).length, o2 = [t48.simulation_transient_current_graph_id, t48.simulation_current_probe_id].filter(pM).length;
  n2 + o2 !== 1 && e2.addIssue({ code: A_.ZodIssueCode.custom, message: "An oscilloscope trace must reference exactly one voltage graph, current graph, voltage probe, or current probe." }), n2 > 0 && void 0 !== t48.amps_per_div && e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Voltage oscilloscope traces must use volts_per_div, not amps_per_div." }), o2 > 0 && void 0 !== t48.volts_per_div && e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Current oscilloscope traces must use amps_per_div, not volts_per_div." });
});
var gM = A_.union([kv, Dv, zv, Lv, jv, Fv, tv, Gx, qx, Kx, Zx, ev, sv, av, dv, pv, mv, bv, gv, fv, _v, yv, lv, cv, Xv, Uv, Yv, xv, Iv, Pv, Cv, Gv, Nv, wv, Zv, qv, Jv, Kv, Qv, tS, Ev, Av, $v, jS, KS, pP, mP, gP, yP, xP, vP, rI, sP, sI, AI, xI, MI, CI, NI, OI, pI, bI, LI, DI, fP, FI, jI, YI, $I, GI, XI, BI, HI, WI, UI, wI, TI, zI, kI, RI, EI, LP, DP, zP, kP, qI, ZI, JI, KI, QI, tP, eP, nP, oP, _P, iP, rP, SP, uP, IP, PP, MP, RP, EP, AP, OP, FP, jP, YP, $P, XP, eS, fS, hS, dS, uS, pS, aS, lS, _S, mS, nS, bS, xS, yS, MS, CS, NS, wS, ES, TS, RS, VP, JP, eM, iM, rM, sM, aM, cM, lM, mM, hM, dM, uM]);
var fM = gM;
function _M(t48, e2, n2) {
  if (!e2 || !n2) return;
  let o2 = t48.get(e2);
  o2 || (o2 = /* @__PURE__ */ new Set(), t48.set(e2, o2)), o2.add(n2);
  let i2 = t48.get(n2);
  i2 || (i2 = /* @__PURE__ */ new Set(), t48.set(n2, i2)), i2.add(e2);
}
var yM = (t48, e2 = {}) => {
  const n2 = t48;
  let o2 = n2._internal_store;
  if (!o2) {
    o2 = { counts: {}, editCount: 0 }, n2._internal_store = o2;
    for (const t49 of n2) {
      const e3 = t49.type, n3 = t49[`${e3}_id`];
      if (!n3) continue;
      const i3 = Number.parseInt(n3.split("_").pop());
      Number.isNaN(i3) || (o2.counts[e3] = Math.max(o2.counts[e3] ?? 0, i3));
    }
  }
  const i2 = new Proxy({}, { get: (t49, r2) => {
    if ("toArray" === r2) return () => (n2.editCount = o2.editCount, n2);
    if ("editCount" === r2) return o2.editCount;
    if ("subtree" === r2) return (t50) => yM((function(t51, e3) {
      if (!e3.subcircuit_id && !e3.source_group_id) return [...t51];
      let n3 = e3;
      if (e3.subcircuit_id) {
        const o4 = /* @__PURE__ */ new Set([e3.subcircuit_id]), i4 = /* @__PURE__ */ new Map(), r4 = /* @__PURE__ */ new Map();
        for (const e4 of t51) if ("source_group" === e4.type) {
          const t52 = e4.source_group_id, n4 = e4.subcircuit_id;
          n4 && r4.set(t52, n4);
          const o5 = e4.parent_source_group_id;
          o5 && (i4.has(o5) || i4.set(o5, []), i4.get(o5).push(t52));
        }
        let s4;
        for (const [t52, n4] of r4) if (n4 === e3.subcircuit_id) {
          s4 = t52;
          break;
        }
        if (s4) {
          const t52 = (e4) => {
            const n4 = i4.get(e4) || [];
            for (const e5 of n4) {
              const n5 = r4.get(e5);
              n5 && o4.add(n5), t52(e5);
            }
          };
          t52(s4), n3 = { ...e3, subcircuit_ids: Array.from(o4) };
        }
      }
      const o3 = /* @__PURE__ */ new Map();
      for (const e4 of t51) {
        const t52 = e4[`${e4.type}_id`];
        "string" == typeof t52 && o3.set(t52, e4);
      }
      const i3 = /* @__PURE__ */ new Map();
      for (const e4 of t51) {
        const t52 = Object.entries(e4);
        for (const [n4, r4] of t52) if ("parent_source_group_id" !== n4) {
          if (n4.endsWith("_id") && "string" == typeof r4) _M(i3, e4, o3.get(r4));
          else if (n4.endsWith("_ids") && Array.isArray(r4)) for (const t53 of r4) "string" == typeof t53 && _M(i3, e4, o3.get(t53));
        }
      }
      const r3 = [], s3 = /* @__PURE__ */ new Set();
      for (const e4 of t51) {
        let t52 = false;
        (n3.subcircuit_id && "subcircuit_id" in e4 && e4.subcircuit_id === n3.subcircuit_id || n3.subcircuit_ids && "subcircuit_id" in e4 && e4.subcircuit_id && n3.subcircuit_ids.includes(e4.subcircuit_id) || n3.source_group_id && "source_group_id" in e4 && e4.source_group_id === n3.source_group_id || n3.source_group_id && "member_source_group_ids" in e4 && Array.isArray(e4.member_source_group_ids) && e4.member_source_group_ids.includes(n3.source_group_id)) && (t52 = true), t52 && (r3.push(e4), s3.add(e4));
      }
      for (; r3.length > 0; ) {
        const t52 = r3.shift(), e4 = i3.get(t52);
        if (e4) for (const t53 of e4) s3.has(t53) || (s3.add(t53), r3.push(t53));
      }
      return t51.filter((t52) => s3.has(t52));
    })(n2, t50), e2);
    if ("insert" === r2) return (t50) => {
      const i3 = t50.type;
      if (!i3) throw new Error("insert requires an element with a type");
      o2.counts[i3] ??= -1, o2.counts[i3]++;
      const r3 = o2.counts[i3], s3 = { ...t50, type: i3, [`${i3}_id`]: `${i3}_${r3}` };
      if (e2.validateInserts) {
        (v_[i3] ?? fM).parse(s3);
      }
      return n2.push(s3), o2.editCount++, s3;
    };
    if ("insertAll" === r2) return (t50) => t50.map((t51) => i2.insert(t51));
    const s2 = r2;
    return { get: (t50) => n2.find((e3) => e3.type === s2 && e3[`${s2}_id`] === t50), getUsing: (t50) => {
      const e3 = Object.keys(t50);
      if (1 !== e3.length) throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");
      const o3 = e3[0], i3 = o3.replace("_id", ""), r3 = n2.find((e4) => e4.type === i3 && e4[o3] === t50[o3]);
      return r3 ? n2.find((t51) => t51.type === s2 && t51[`${s2}_id`] === r3[`${s2}_id`]) : null;
    }, getWhere: (t50) => {
      const e3 = Object.keys(t50);
      return n2.find((n3) => n3.type === s2 && e3.every((e4) => n3[e4] === t50[e4]));
    }, list: (t50) => {
      const e3 = t50 ? Object.keys(t50) : [];
      return n2.filter((n3) => n3.type === s2 && e3.every((e4) => n3[e4] === t50[e4]));
    }, insert: (t50) => {
      o2.counts[s2] ??= -1, o2.counts[s2]++;
      const i3 = o2.counts[s2], r3 = { type: s2, [`${s2}_id`]: `${s2}_${i3}`, ...t50 };
      if (e2.validateInserts) {
        (v_[s2] ?? fM).parse(r3);
      }
      return n2.push(r3), o2.editCount++, r3;
    }, delete: (t50) => {
      const e3 = n2.find((e4) => e4[`${s2}_id`] === t50);
      e3 && (n2.splice(n2.indexOf(e3), 1), o2.editCount++);
    }, update: (t50, e3) => {
      const i3 = n2.find((e4) => e4.type === s2 && e4[`${s2}_id`] === t50);
      return i3 ? (Object.assign(i3, e3), o2.editCount++, i3) : null;
    }, select: (t50) => {
      if ("source_component" === s2) return n2.find((e3) => "source_component" === e3.type && e3.name === t50.replace(/\./g, ""));
      if ("pcb_port" === s2 || "source_port" === s2 || "schematic_port" === s2) {
        const [e3, o3] = t50.replace(/\./g, "").split(/[\s\>]+/), i3 = n2.find((t51) => "source_component" === t51.type && t51.name === e3);
        if (!i3) return null;
        const r3 = n2.find((t51) => "source_port" === t51.type && t51.source_component_id === i3.source_component_id && (t51.name === o3 || (t51.port_hints ?? []).includes(o3)));
        if (!r3) return null;
        if ("source_port" === s2) return r3;
        if ("pcb_port" === s2) return n2.find((t51) => "pcb_port" === t51.type && t51.source_port_id === r3.source_port_id);
        if ("schematic_port" === s2) return n2.find((t51) => "schematic_port" === t51.type && t51.source_port_id === r3.source_port_id);
      }
    } };
  } });
  return i2;
};
yM.unparsed = yM;
function xM(t48) {
  const e2 = t48.type;
  return `${e2}:${t48[`${e2}_id`]}`;
}
var vM = (t48, e2 = {}) => {
  let n2 = t48._internal_store_indexed;
  if (!n2) {
    n2 = { counts: {}, editCount: 0, indexes: {} };
    for (const e3 of t48) {
      const t49 = e3.type, o3 = e3[`${t49}_id`];
      if (!o3) continue;
      const i3 = Number.parseInt(o3.split("_").pop() || "");
      Number.isNaN(i3) || (n2.counts[t49] = Math.max(n2.counts[t49] ?? 0, i3));
    }
    const o2 = e2.indexConfig || {}, i2 = n2.indexes;
    if (o2.byId && (i2.byId = /* @__PURE__ */ new Map()), o2.byType && (i2.byType = /* @__PURE__ */ new Map()), o2.byRelation && (i2.byRelation = /* @__PURE__ */ new Map()), o2.bySubcircuit && (i2.bySubcircuit = /* @__PURE__ */ new Map()), o2.byCustomField && o2.byCustomField.length > 0) {
      i2.byCustomField = /* @__PURE__ */ new Map();
      for (const t49 of o2.byCustomField) i2.byCustomField.set(t49, /* @__PURE__ */ new Map());
    }
    for (const e3 of t48) {
      if (o2.byId) {
        const t49 = xM(e3);
        i2.byId.set(t49, e3);
      }
      if (o2.byType) {
        const t49 = i2.byType.get(e3.type) || [];
        t49.push(e3), i2.byType.set(e3.type, t49);
      }
      if (o2.byRelation) {
        const t49 = Object.entries(e3);
        for (const [n3, o3] of t49) if (n3.endsWith("_id") && n3 !== `${e3.type}_id` && "string" == typeof o3) {
          const t50 = i2.byRelation.get(n3) || /* @__PURE__ */ new Map(), r2 = t50.get(o3) || [];
          r2.push(e3), t50.set(o3, r2), i2.byRelation.set(n3, t50);
        }
      }
      if (o2.bySubcircuit && "subcircuit_id" in e3) {
        const t49 = e3.subcircuit_id;
        if (t49 && "string" == typeof t49) {
          const n3 = i2.bySubcircuit.get(t49) || [];
          n3.push(e3), i2.bySubcircuit.set(t49, n3);
        }
      }
      if (o2.byCustomField && i2.byCustomField) {
        for (const t49 of o2.byCustomField) if (t49 in e3) {
          const n3 = e3[t49];
          if (void 0 !== n3 && ("string" == typeof n3 || "number" == typeof n3)) {
            const o3 = String(n3), r2 = i2.byCustomField.get(t49), s2 = r2.get(o3) || [];
            s2.push(e3), r2.set(o3, s2);
          }
        }
      }
    }
    t48._internal_store_indexed = n2;
  }
  return new Proxy({}, { get: (o2, i2) => {
    if ("toArray" === i2) return () => (t48.editCount = n2.editCount, t48);
    if ("editCount" === i2) return n2.editCount;
    const r2 = i2;
    return { get: (o3) => {
      const i3 = e2.indexConfig || {};
      if (i3.byId && n2.indexes.byId) return n2.indexes.byId.get(`${r2}:${o3}`) || null;
      if (i3.byType && n2.indexes.byType) {
        return (n2.indexes.byType.get(r2) || []).find((t49) => t49[`${r2}_id`] === o3) || null;
      }
      return t48.find((t49) => t49.type === r2 && t49[`${r2}_id`] === o3) || null;
    }, getUsing: (o3) => {
      const i3 = e2.indexConfig || {}, s2 = Object.keys(o3);
      if (1 !== s2.length) throw new Error("getUsing requires exactly one key, e.g. { pcb_component_id }");
      const a2 = s2[0], c2 = a2.replace("_id", "");
      if (i3.byRelation && n2.indexes.byRelation) {
        const e3 = n2.indexes.byRelation.get(a2);
        if (e3) {
          const s3 = (e3.get(o3[a2]) || []).find((t49) => t49.type === c2);
          if (!s3) return null;
          const l3 = s3[`${r2}_id`];
          if (i3.byId && n2.indexes.byId) return n2.indexes.byId.get(`${r2}:${l3}`) || null;
          if (i3.byType && n2.indexes.byType) {
            return (n2.indexes.byType.get(r2) || []).find((t49) => t49[`${r2}_id`] === l3) || null;
          }
          return t48.find((t49) => t49.type === r2 && t49[`${r2}_id`] === l3) || null;
        }
      }
      const l2 = t48.find((t49) => t49.type === c2 && t49[a2] === o3[a2]);
      return l2 && t48.find((t49) => t49.type === r2 && t49[`${r2}_id`] === l2[`${r2}_id`]) || null;
    }, getWhere: (o3) => {
      const i3 = e2.indexConfig || {}, s2 = Object.keys(o3);
      if (1 === s2.length && i3.byCustomField && n2.indexes.byCustomField) {
        const t49 = s2[0], e3 = n2.indexes.byCustomField.get(t49);
        if (e3) {
          const n3 = String(o3[t49]);
          return (e3.get(n3) || []).find((t50) => t50.type === r2) || null;
        }
      }
      if ("subcircuit_id" in o3 && i3.bySubcircuit && n2.indexes.bySubcircuit) {
        const t49 = o3.subcircuit_id;
        return (n2.indexes.bySubcircuit.get(t49) || []).find((t50) => t50.type === r2 && s2.every((e3) => t50[e3] === o3[e3])) || null;
      }
      if (i3.byType && n2.indexes.byType) {
        return (n2.indexes.byType.get(r2) || []).find((t49) => s2.every((e3) => t49[e3] === o3[e3])) || null;
      }
      return t48.find((t49) => t49.type === r2 && s2.every((e3) => t49[e3] === o3[e3])) || null;
    }, list: (o3) => {
      const i3 = e2.indexConfig || {}, s2 = o3 ? Object.keys(o3) : [];
      if (0 === s2.length && i3.byType && n2.indexes.byType) return n2.indexes.byType.get(r2) || [];
      if (1 === s2.length && "subcircuit_id" === s2[0] && i3.bySubcircuit && n2.indexes.bySubcircuit) {
        const t49 = o3.subcircuit_id;
        return (n2.indexes.bySubcircuit.get(t49) || []).filter((t50) => t50.type === r2);
      }
      let a2;
      return a2 = i3.byType && n2.indexes.byType ? n2.indexes.byType.get(r2) || [] : t48.filter((t49) => t49.type === r2), s2.length > 0 ? a2.filter((t49) => s2.every((e3) => t49[e3] === o3[e3])) : a2;
    }, insert: (o3) => {
      n2.counts[r2] ??= -1, n2.counts[r2]++;
      const i3 = n2.counts[r2], s2 = { type: r2, [`${r2}_id`]: `${r2}_${i3}`, ...o3 };
      if (e2.validateInserts) {
        (v_[r2] ?? fM).parse(s2);
      }
      t48.push(s2), n2.editCount++;
      const a2 = e2.indexConfig || {};
      if (a2.byId && n2.indexes.byId) {
        const t49 = xM(s2);
        n2.indexes.byId.set(t49, s2);
      }
      if (a2.byType && n2.indexes.byType) {
        const t49 = n2.indexes.byType.get(r2) || [];
        t49.push(s2), n2.indexes.byType.set(r2, t49);
      }
      if (a2.byRelation && n2.indexes.byRelation) {
        const t49 = Object.entries(s2);
        for (const [e3, o4] of t49) if (e3.endsWith("_id") && e3 !== `${s2.type}_id` && "string" == typeof o4) {
          const t50 = n2.indexes.byRelation.get(e3) || /* @__PURE__ */ new Map(), i4 = t50.get(o4) || [];
          i4.push(s2), t50.set(o4, i4), n2.indexes.byRelation.set(e3, t50);
        }
      }
      if (a2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in s2) {
        const t49 = s2.subcircuit_id;
        if (t49 && "string" == typeof t49) {
          const e3 = n2.indexes.bySubcircuit.get(t49) || [];
          e3.push(s2), n2.indexes.bySubcircuit.set(t49, e3);
        }
      }
      if (a2.byCustomField && n2.indexes.byCustomField) {
        for (const t49 of a2.byCustomField) if (t49 in s2) {
          const e3 = s2[t49];
          if (void 0 !== e3 && ("string" == typeof e3 || "number" == typeof e3)) {
            const o4 = String(e3), i4 = n2.indexes.byCustomField.get(t49), r3 = i4.get(o4) || [];
            r3.push(s2), i4.set(o4, r3);
          }
        }
      }
      return s2;
    }, delete: (o3) => {
      const i3 = e2.indexConfig || {};
      let s2;
      if (i3.byId && n2.indexes.byId) s2 = n2.indexes.byId.get(`${r2}:${o3}`);
      else if (i3.byType && n2.indexes.byType) {
        const t49 = n2.indexes.byType.get(r2) || [];
        s2 = t49.find((t50) => t50[`${r2}_id`] === o3);
      } else s2 = t48.find((t49) => t49[`${r2}_id`] === o3);
      if (!s2) return;
      const a2 = t48.indexOf(s2);
      if (a2 >= 0 && (t48.splice(a2, 1), n2.editCount++), i3.byId && n2.indexes.byId) {
        const t49 = xM(s2);
        n2.indexes.byId.delete(t49);
      }
      if (i3.byType && n2.indexes.byType) {
        const t49 = (n2.indexes.byType.get(r2) || []).filter((t50) => t50[`${r2}_id`] !== o3);
        n2.indexes.byType.set(r2, t49);
      }
      if (i3.byRelation && n2.indexes.byRelation) for (const [t49, e3] of n2.indexes.byRelation.entries()) for (const [t50, n3] of e3.entries()) {
        const o4 = n3.filter((t51) => t51 !== s2);
        0 === o4.length ? e3.delete(t50) : e3.set(t50, o4);
      }
      if (i3.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in s2) {
        const t49 = s2.subcircuit_id;
        if (t49) {
          const e3 = (n2.indexes.bySubcircuit.get(t49) || []).filter((t50) => t50 !== s2);
          0 === e3.length ? n2.indexes.bySubcircuit.delete(t49) : n2.indexes.bySubcircuit.set(t49, e3);
        }
      }
      if (i3.byCustomField && n2.indexes.byCustomField) for (const t49 of n2.indexes.byCustomField.values()) for (const [e3, n3] of t49.entries()) {
        const o4 = n3.filter((t50) => t50 !== s2);
        0 === o4.length ? t49.delete(e3) : t49.set(e3, o4);
      }
    }, update: (o3, i3) => {
      const s2 = e2.indexConfig || {};
      let a2;
      if (s2.byId && n2.indexes.byId) a2 = n2.indexes.byId.get(`${r2}:${o3}`);
      else if (s2.byType && n2.indexes.byType) {
        const t49 = n2.indexes.byType.get(r2) || [];
        a2 = t49.find((t50) => t50[`${r2}_id`] === o3);
      } else a2 = t48.find((t49) => t49.type === r2 && t49[`${r2}_id`] === o3);
      if (!a2) return null;
      if (s2.byRelation && n2.indexes.byRelation) {
        const t49 = Object.entries(a2);
        for (const [e3, o4] of t49) if (e3.endsWith("_id") && e3 !== `${a2.type}_id` && "string" == typeof o4 && e3 in i3 && i3[e3] !== o4) {
          const t50 = n2.indexes.byRelation.get(e3);
          if (t50) {
            const e4 = (t50.get(o4) || []).filter((t51) => t51 !== a2);
            0 === e4.length ? t50.delete(o4) : t50.set(o4, e4);
          }
        }
      }
      if (s2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in a2 && "subcircuit_id" in i3) {
        const t49 = a2.subcircuit_id;
        if (t49 !== i3.subcircuit_id) {
          const e3 = (n2.indexes.bySubcircuit.get(t49) || []).filter((t50) => t50 !== a2);
          0 === e3.length ? n2.indexes.bySubcircuit.delete(t49) : n2.indexes.bySubcircuit.set(t49, e3);
        }
      }
      if (s2.byCustomField && n2.indexes.byCustomField) {
        for (const t49 of s2.byCustomField) if (t49 in a2 && t49 in i3 && a2[t49] !== i3[t49]) {
          const e3 = n2.indexes.byCustomField.get(t49);
          if (e3) {
            const n3 = String(a2[t49]), o4 = (e3.get(n3) || []).filter((t50) => t50 !== a2);
            0 === o4.length ? e3.delete(n3) : e3.set(n3, o4);
          }
        }
      }
      if (Object.assign(a2, i3), n2.editCount++, s2.byRelation && n2.indexes.byRelation) {
        const t49 = Object.entries(a2);
        for (const [e3, o4] of t49) if (e3.endsWith("_id") && e3 !== `${a2.type}_id` && "string" == typeof o4 && e3 in i3) {
          const t50 = n2.indexes.byRelation.get(e3) || /* @__PURE__ */ new Map(), i4 = t50.get(o4) || [];
          i4.includes(a2) || (i4.push(a2), t50.set(o4, i4), n2.indexes.byRelation.set(e3, t50));
        }
      }
      if (s2.bySubcircuit && n2.indexes.bySubcircuit && "subcircuit_id" in a2 && "subcircuit_id" in i3) {
        const t49 = a2.subcircuit_id;
        if (t49 && "string" == typeof t49) {
          const e3 = n2.indexes.bySubcircuit.get(t49) || [];
          e3.includes(a2) || (e3.push(a2), n2.indexes.bySubcircuit.set(t49, e3));
        }
      }
      if (s2.byCustomField && n2.indexes.byCustomField) {
        for (const t49 of s2.byCustomField) if (t49 in a2 && t49 in i3) {
          const e3 = a2[t49];
          if (void 0 !== e3 && ("string" == typeof e3 || "number" == typeof e3)) {
            const o4 = String(e3), i4 = n2.indexes.byCustomField.get(t49), r3 = i4.get(o4) || [];
            r3.includes(a2) || (r3.push(a2), i4.set(o4, r3));
          }
        }
      }
      return a2;
    }, select: (e3) => {
      if ("source_component" === r2) return t48.find((t49) => "source_component" === t49.type && t49.name === e3.replace(/\./g, "")) || null;
      if ("pcb_port" === r2 || "source_port" === r2 || "schematic_port" === r2) {
        const [n3, o3] = e3.replace(/\./g, "").split(/[\s\>]+/), i3 = t48.find((t49) => "source_component" === t49.type && t49.name === n3);
        if (!i3) return null;
        const s2 = t48.find((t49) => "source_port" === t49.type && t49.source_component_id === i3.source_component_id && (t49.name === o3 || (t49.port_hints ?? []).includes(o3)));
        if (!s2) return null;
        if ("source_port" === r2) return s2;
        if ("pcb_port" === r2) return t48.find((t49) => "pcb_port" === t49.type && t49.source_port_id === s2.source_port_id) || null;
        if ("schematic_port" === r2) return t48.find((t49) => "schematic_port" === t49.type && t49.source_port_id === s2.source_port_id) || null;
      }
      return null;
    } };
  } });
};
vM.unparsed = vM;
var EM = { Hz: { baseUnit: "Hz", variants: { MHz: 1e6, kHz: 1e3, Hz: 1 } }, g: { baseUnit: "g", variants: { kg: 1e3, g: 1 } }, "\u03A9": { baseUnit: "\u03A9", variants: { "m\u03A9": 1e-3, "\u03A9": 1, "k\u03A9": 1e3, "K\u03A9": 1e3, kohm: 1e3, "M\u03A9": 1e6, "G\u03A9": 1e9, "T\u03A9": 1e12 } }, V: { baseUnit: "V", variants: { mV: 1e-3, V: 1, kV: 1e3, KV: 1e3, MV: 1e6, GV: 1e9, TV: 1e12 } }, A: { baseUnit: "A", variants: { "\xB5A": 1e-6, mA: 1e-3, ma: 1e-3, A: 1, kA: 1e3, MA: 1e6 } }, F: { baseUnit: "F", variants: { pF: 1e-12, nF: 1e-9, "\xB5F": 1e-6, uF: 1e-6, mF: 1e-3, 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: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3 } }, mm: { baseUnit: "mm", variants: { nm: 1e-6, "\xB5m": 1e-3, um: 1e-3, 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: 0.0254 } } };
var AM = /* @__PURE__ */ new Set();
for (const [t48, e2] of Object.entries(EM)) {
  AM.add(t48);
  for (const t49 of Object.keys(e2.variants)) AM.add(t49);
}
var OM = { tera: 1e12, T: 1e12, giga: 1e9, G: 1e9, mega: 1e6, M: 1e6, kilo: 1e3, k: 1e3, deci: 0.1, d: 0.1, centi: 0.01, c: 0.01, milli: 1e-3, m: 1e-3, micro: 1e-6, u: 1e-6, "\xB5": 1e-6, nano: 1e-9, n: 1e-9, pico: 1e-12, p: 1e-12 };
function LM(t48) {
  if (null == t48) return { parsedUnit: null, unitOfValue: null, value: null };
  if ("string" == typeof t48 && t48.match(/^-?[\d\.]+$/)) return { value: Number.parseFloat(t48), parsedUnit: null, unitOfValue: null };
  if ("number" == typeof t48) return { value: t48, parsedUnit: null, unitOfValue: null };
  if ("object" == typeof t48 && "x" in t48 && "y" in t48) {
    const { parsedUnit: e3, unitOfValue: n3 } = LM(t48.x), o3 = LM(t48.x), i3 = LM(t48.y);
    return null === o3.value || null === i3.value ? { parsedUnit: null, unitOfValue: null, value: null } : { parsedUnit: e3, unitOfValue: n3, value: { x: o3.value, y: i3.value } };
  }
  const e2 = t48.toString().split("").reverse().join(""), n2 = e2.match(/[^\d\s]+/)?.[0];
  if (!n2) throw new Error(`Could not determine unit: "${t48}"`);
  const o2 = n2.split("").reverse().join(""), i2 = t48.slice(0, -o2.length);
  if (o2 in OM && !AM.has(o2)) {
    const t49 = OM[o2];
    return { parsedUnit: null, unitOfValue: null, value: Number.parseFloat(i2) * t49 };
  }
  const { baseUnit: r2, conversionFactor: s2 } = (function(t49) {
    for (const [e3, n3] of Object.entries(EM)) if (t49 in n3.variants) return { baseUnit: n3.baseUnit, conversionFactor: n3.variants[t49] };
    return { baseUnit: t49, conversionFactor: 1 };
  })(o2);
  return { parsedUnit: o2, unitOfValue: r2, value: s2 * Number.parseFloat(i2) };
}
var DM = A_.string().or(A_.number()).transform((t48) => LM(t48).value);
var zM = A_.string().or(A_.number()).transform((t48) => LM(t48).value).transform((t48) => Number.parseFloat(t48.toPrecision(12)));
var kM = A_.string().or(A_.number()).transform((t48) => LM(t48).value);
var FM = A_.string().or(A_.number()).transform((t48) => LM(t48).value);
var jM = A_.string().or(A_.number()).transform((t48) => LM(t48).value);
var YM = A_.string().or(A_.number()).transform((t48) => LM(t48).value);
var $M = jM;
var XM = A_.string().or(A_.number()).transform((t48) => LM(t48).value);
var BM = A_.string().or(A_.number()).transform((t48) => LM(t48).value);
var HM = BM;
var WM = A_.string().datetime();
var VM = A_.string().or(A_.number()).transform((t48) => "number" == typeof t48 ? t48 : t48.endsWith("deg") ? Number.parseFloat(t48.split("deg")[0]) : t48.endsWith("rad") ? 180 * Number.parseFloat(t48.split("rad")[0]) / Math.PI : Number.parseFloat(t48));
var UM = A_.number().or(A_.string().endsWith("mAh")).transform((t48) => {
  if ("string" == typeof t48) {
    const e2 = t48.replace("mAh", ""), n2 = Number.parseFloat(e2);
    if (Number.isNaN(n2)) throw new Error("Invalid capacity");
    return n2;
  }
  return t48;
}).describe("Battery capacity in mAh");
var GM = A_.object({ x: $M, y: $M });
var ZM = A_.object({ x: $M, y: $M, z: $M });
var qM = A_.object({ width: A_.number(), height: A_.number() });
var JM = (t48) => A_.string().optional().default(() => `${t48}_${((t49) => {
  const e2 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  return Array.from({ length: t49 }, () => e2[Math.floor(62 * Math.random())]).join("");
})(10)}`);
var KM = A_.enum(["top_left", "top_center", "top_right", "center_left", "center", "center_right", "bottom_left", "bottom_center", "bottom_right"]);
var QM = (A_.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"]), A_.object({ project_relative_path: A_.string(), url: A_.string(), mimetype: A_.string() }));
var tC = GM.extend({ rotation: VM.optional() });
var eC = A_.object({ size: GM.optional(), thickness: $M.optional() });
var nC = A_.object({ font: eC.optional() });
var oC = A_.object({ value: A_.string(), at: tC.optional(), layer: A_.string().optional(), uuid: A_.string().optional(), hide: A_.boolean().optional(), effects: nC.optional() });
var iC = A_.object({ Reference: oC.optional(), Value: oC.optional(), Datasheet: oC.optional(), Description: oC.optional() });
var rC = A_.object({ through_hole: A_.boolean().optional(), smd: A_.boolean().optional(), exclude_from_pos_files: A_.boolean().optional(), exclude_from_bom: A_.boolean().optional() });
var sC = A_.object({ name: A_.string(), type: A_.string(), shape: A_.string().optional(), at: tC.optional(), size: GM.optional(), drill: $M.optional(), layers: A_.array(A_.string()).optional(), removeUnusedLayers: A_.boolean().optional(), uuid: A_.string().optional() });
var aC = A_.object({ path: A_.string(), offset: ZM.optional(), scale: ZM.optional(), rotate: ZM.optional() });
var cC = A_.object({ footprintName: A_.string().optional(), version: A_.union([A_.number(), A_.string()]).optional(), generator: A_.string().optional(), generatorVersion: A_.union([A_.number(), A_.string()]).optional(), layer: A_.string().optional(), properties: iC.optional(), attributes: rC.optional(), pads: A_.array(sC).optional(), embeddedFonts: A_.boolean().optional(), model: aC.optional() });
var lC = A_.object({ hide: A_.boolean().optional() });
var hC = A_.object({ offset: $M.optional(), hide: A_.boolean().optional() });
var dC = A_.object({ font: eC.optional(), justify: A_.union([A_.string(), A_.array(A_.string())]).optional(), hide: A_.boolean().optional() });
var uC = A_.object({ value: A_.string(), id: A_.union([A_.number(), A_.string()]).optional(), at: tC.optional(), effects: dC.optional() });
var pC = A_.object({ Reference: uC.optional(), Value: uC.optional(), Footprint: uC.optional(), Datasheet: uC.optional(), Description: uC.optional(), ki_keywords: uC.optional(), ki_fp_filters: uC.optional() });
var mC = A_.object({ symbolName: A_.string().optional(), extends: A_.string().optional(), pinNumbers: lC.optional(), pinNames: hC.optional(), excludeFromSim: A_.boolean().optional(), inBom: A_.boolean().optional(), onBoard: A_.boolean().optional(), properties: pC.optional(), embeddedFonts: A_.boolean().optional() });
var gC = A_.object({ error_type: A_.string(), message: A_.string(), is_fatal: A_.boolean().optional() });
var fC = A_.enum(["jlcpcb", "macrofab", "pcbway", "digikey", "mouser", "lcsc"]);
var _C = A_.object({ type: A_.literal("source_component"), ftype: A_.string().optional(), source_component_id: A_.string(), name: A_.string(), manufacturer_part_number: A_.string().optional(), supplier_part_numbers: A_.record(fC, A_.array(A_.string())).optional(), display_value: A_.string().optional(), display_name: A_.string().optional(), are_pins_interchangeable: A_.boolean().optional(), internally_connected_source_port_ids: A_.array(A_.array(A_.string())).optional(), source_group_id: A_.string().optional(), subcircuit_id: A_.string().optional() });
var yC = _C.extend({ ftype: A_.literal("simple_capacitor"), capacitance: zM, max_voltage_rating: FM.optional(), display_capacitance: A_.string().optional(), max_decoupling_trace_length: $M.optional() });
var bC = _C.extend({ ftype: A_.literal("simple_resistor"), resistance: DM, display_resistance: A_.string().optional() });
var xC = _C.extend({ ftype: A_.literal("simple_diode") });
var vC = _C.extend({ ftype: A_.literal("simple_fiducial") });
var SC = xC.extend({ ftype: A_.literal("simple_led"), color: A_.string().optional(), wavelength: A_.string().optional() });
var IC = _C.extend({ ftype: A_.literal("simple_ground") });
var PC = _C.extend({ ftype: A_.literal("simple_chip") });
var MC = _C.extend({ ftype: A_.literal("simple_power_source"), voltage: FM });
var CC = _C.extend({ ftype: A_.literal("simple_current_source"), current: XM, frequency: YM.optional(), peak_to_peak_current: XM.optional(), wave_shape: A_.enum(["sine", "square", "triangle", "sawtooth", "dc"]).optional().default("dc"), phase: A_.number().optional(), duty_cycle: A_.number().min(0).max(1).optional() });
var NC = A_.object({ must_be_connected: A_.boolean().optional(), provides_power: A_.boolean().optional(), requires_power: A_.boolean().optional(), provides_ground: A_.boolean().optional(), requires_ground: A_.boolean().optional(), provides_voltage: A_.union([A_.string(), A_.number()]).optional(), requires_voltage: A_.union([A_.string(), A_.number()]).optional(), do_not_connect: A_.boolean().optional(), include_in_board_pinout: A_.boolean().optional(), can_use_internal_pullup: A_.boolean().optional(), is_using_internal_pullup: A_.boolean().optional(), needs_external_pullup: A_.boolean().optional(), can_use_internal_pulldown: A_.boolean().optional(), is_using_internal_pulldown: A_.boolean().optional(), needs_external_pulldown: A_.boolean().optional(), can_use_open_drain: A_.boolean().optional(), is_using_open_drain: A_.boolean().optional(), can_use_push_pull: A_.boolean().optional(), is_using_push_pull: A_.boolean().optional(), should_have_decoupling_capacitor: A_.boolean().optional(), recommended_decoupling_capacitor_capacitance: A_.union([A_.string(), A_.number()]).optional(), is_configured_for_i2c_sda: A_.boolean().optional(), is_configured_for_i2c_scl: A_.boolean().optional(), is_configured_for_spi_mosi: A_.boolean().optional(), is_configured_for_spi_miso: A_.boolean().optional(), is_configured_for_spi_sck: A_.boolean().optional(), is_configured_for_spi_cs: A_.boolean().optional(), is_configured_for_uart_tx: A_.boolean().optional(), is_configured_for_uart_rx: A_.boolean().optional(), supports_i2c_sda: A_.boolean().optional(), supports_i2c_scl: A_.boolean().optional(), supports_spi_mosi: A_.boolean().optional(), supports_spi_miso: A_.boolean().optional(), supports_spi_sck: A_.boolean().optional(), supports_spi_cs: A_.boolean().optional(), supports_uart_tx: A_.boolean().optional(), supports_uart_rx: A_.boolean().optional() });
var wC = _C.extend({ ftype: A_.literal("simple_fuse"), current_rating_amps: A_.number().describe("Nominal current in amps the fuse is rated for"), voltage_rating_volts: A_.number().describe("Voltage rating in volts, e.g. \xB15V would be 5") });
var TC = _C.extend({ ftype: A_.literal("simple_battery"), capacity: UM });
var RC = _C.extend({ ftype: A_.literal("simple_inductor"), inductance: kM, display_inductance: A_.string().optional(), max_current_rating: A_.number().optional() });
var EC = _C.extend({ ftype: A_.literal("simple_push_button") });
var AC = _C.extend({ ftype: A_.literal("simple_potentiometer"), max_resistance: DM, display_max_resistance: A_.string().optional() });
var OC = _C.extend({ ftype: A_.literal("simple_crystal"), frequency: A_.number().describe("Frequency in Hz"), load_capacitance: A_.number().optional().describe("Load capacitance in pF"), pin_variant: A_.enum(["two_pin", "four_pin"]).optional() });
var LC = _C.extend({ ftype: A_.literal("simple_pin_header"), pin_count: A_.number(), gender: A_.enum(["male", "female"]).optional().default("male") });
var DC = _C.extend({ ftype: A_.literal("simple_connector"), standard: A_.enum(["usb_c", "m2"]).optional() });
var zC = _C.extend({ ftype: A_.literal("simple_pinout") });
var kC = _C.extend({ ftype: A_.literal("simple_resonator"), load_capacitance: zM, equivalent_series_resistance: DM.optional(), frequency: YM });
var FC = _C.extend({ ftype: A_.literal("simple_transistor"), transistor_type: A_.enum(["npn", "pnp"]) });
var jC = _C.extend({ ftype: A_.literal("simple_test_point"), footprint_variant: A_.enum(["pad", "through_hole"]).optional(), pad_shape: A_.enum(["rect", "circle"]).optional(), pad_diameter: A_.union([A_.number(), A_.string()]).optional(), hole_diameter: A_.union([A_.number(), A_.string()]).optional(), width: A_.union([A_.number(), A_.string()]).optional(), height: A_.union([A_.number(), A_.string()]).optional() });
var YC = _C.extend({ ftype: A_.literal("simple_mosfet"), channel_type: A_.enum(["n", "p"]), mosfet_mode: A_.enum(["enhancement", "depletion"]) });
var $C = _C.extend({ ftype: A_.literal("simple_op_amp") });
var XC = _C.extend({ ftype: A_.literal("simple_switch") });
var BC = A_.object({ type: A_.literal("source_project_metadata"), name: A_.string().optional(), software_used_string: A_.string().optional(), project_url: A_.string().optional(), created_at: WM.optional() });
var HC = gC.extend({ type: A_.literal("source_missing_property_error"), source_missing_property_error_id: JM("source_missing_property_error"), source_component_id: A_.string(), property_name: A_.string(), subcircuit_id: A_.string().optional(), error_type: A_.literal("source_missing_property_error").default("source_missing_property_error") }).describe("The source code is missing a property");
var WC = gC.extend({ type: A_.literal("source_failed_to_create_component_error"), source_failed_to_create_component_error_id: JM("source_failed_to_create_component_error"), error_type: A_.literal("source_failed_to_create_component_error").default("source_failed_to_create_component_error"), component_name: A_.string().optional(), subcircuit_id: A_.string().optional(), parent_source_component_id: A_.string().optional(), pcb_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), schematic_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional() }).describe("Error emitted when a component fails to be constructed");
var VC = gC.extend({ type: A_.literal("source_invalid_component_property_error"), source_invalid_component_property_error_id: JM("source_invalid_component_property_error"), source_component_id: A_.string(), property_name: A_.string(), property_value: A_.unknown().optional(), expected_format: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal("source_invalid_component_property_error").default("source_invalid_component_property_error") }).describe("The source component property is invalid");
var UC = gC.extend({ type: A_.literal("source_trace_not_connected_error"), source_trace_not_connected_error_id: JM("source_trace_not_connected_error"), error_type: A_.literal("source_trace_not_connected_error").default("source_trace_not_connected_error"), subcircuit_id: A_.string().optional(), source_group_id: A_.string().optional(), source_trace_id: A_.string().optional(), connected_source_port_ids: A_.array(A_.string()).optional(), selectors_not_found: A_.array(A_.string()).optional() }).describe("Occurs when a source trace selector does not match any ports");
var GC = A_.object({ type: A_.literal("source_property_ignored_warning"), source_property_ignored_warning_id: JM("source_property_ignored_warning"), source_component_id: A_.string(), property_name: A_.string(), subcircuit_id: A_.string().optional(), error_type: A_.literal("source_property_ignored_warning").default("source_property_ignored_warning"), message: A_.string() }).describe("The source property was ignored");
var ZC = A_.object({ type: A_.literal("source_pin_missing_trace_warning"), source_pin_missing_trace_warning_id: JM("source_pin_missing_trace_warning"), warning_type: A_.literal("source_pin_missing_trace_warning").default("source_pin_missing_trace_warning"), message: A_.string(), source_component_id: A_.string(), source_port_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a source component pin is missing a trace connection");
var qC = A_.object({ type: A_.literal("source_missing_manufacturer_part_number_warning"), source_missing_manufacturer_part_number_warning_id: JM("source_missing_manufacturer_part_number_warning"), warning_type: A_.literal("source_missing_manufacturer_part_number_warning").default("source_missing_manufacturer_part_number_warning"), message: A_.string(), source_component_id: A_.string(), standard: A_.string(), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a standard connector is missing manufacturer part number");
var JC = _C.extend({ ftype: A_.literal("simple_voltage_probe") });
var KC = _C.extend({ ftype: A_.literal("interconnect") });
var QC = gC.extend({ type: A_.literal("source_i2c_misconfigured_error"), source_i2c_misconfigured_error_id: JM("source_i2c_misconfigured_error"), error_type: A_.literal("source_i2c_misconfigured_error").default("source_i2c_misconfigured_error"), source_port_ids: A_.array(A_.string()) }).describe("Error emitted when incompatible I2C pins (e.g. SDA and SCL) are connected to the same net");
var tN = _C.extend({ ftype: A_.literal("simple_voltage_source"), voltage: FM, frequency: YM.optional(), peak_to_peak_voltage: FM.optional(), wave_shape: A_.enum(["sinewave", "square", "triangle", "sawtooth"]).optional(), phase: VM.optional(), duty_cycle: A_.number().optional().describe("Duty cycle as a fraction (0 to 1)") });
var eN = A_.union([bC, yC, xC, vC, SC, IC, PC, MC, CC, TC, RC, EC, AC, OC, LC, DC, zC, kC, XC, FC, jC, YC, $C, wC, JC, KC, tN, BC, HC, VC, WC, UC, GC, ZC, qC, QC]);
var nN = A_.object({ type: A_.literal("source_port"), pin_number: A_.number().optional(), port_hints: A_.array(A_.string()).optional(), name: A_.string(), source_port_id: A_.string(), source_component_id: A_.string().optional(), source_group_id: A_.string().optional(), most_frequently_referenced_by_name: A_.string().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() }).merge(NC);
var oN = A_.object({ type: A_.literal("source_component_internal_connection"), source_component_internal_connection_id: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() });
var iN = A_.object({ type: A_.literal("source_trace"), source_trace_id: A_.string(), connected_source_port_ids: A_.array(A_.string()), connected_source_net_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), max_length: A_.number().optional(), min_trace_thickness: A_.number().optional(), display_name: A_.string().optional() });
var rN = A_.object({ type: A_.literal("source_group"), source_group_id: A_.string(), subcircuit_id: A_.string().optional(), parent_subcircuit_id: A_.string().optional(), parent_source_group_id: A_.string().optional(), is_subcircuit: A_.boolean().optional(), show_as_schematic_box: A_.boolean().optional(), name: A_.string().optional(), was_automatically_named: A_.boolean().optional() });
var sN = A_.object({ type: A_.literal("source_net"), source_net_id: A_.string(), name: A_.string(), member_source_group_ids: A_.array(A_.string()), is_power: A_.boolean().optional(), is_ground: A_.boolean().optional(), is_digital_signal: A_.boolean().optional(), is_analog_signal: A_.boolean().optional(), is_positive_voltage_source: A_.boolean().optional(), trace_width: A_.number().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() });
var aN = A_.object({ type: A_.literal("source_board"), source_board_id: A_.string(), source_group_id: A_.string(), title: A_.string().optional() }).describe("Defines a board in the source domain");
var cN = gC.extend({ type: A_.literal("source_ambiguous_port_reference"), source_ambiguous_port_reference_id: JM("source_ambiguous_port_reference"), error_type: A_.literal("source_ambiguous_port_reference").default("source_ambiguous_port_reference"), source_port_id: A_.string().optional(), source_component_id: A_.string().optional() }).describe("Error emitted when a port hint matches multiple non-overlapping pads, making the port reference ambiguous");
var lN = A_.object({ type: A_.literal("source_pcb_ground_plane"), source_pcb_ground_plane_id: A_.string(), source_group_id: A_.string(), source_net_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Defines a ground plane in the source domain");
var hN = ["top", "bottom", "inner1", "inner2", "inner3", "inner4", "inner5", "inner6"];
var dN = A_.enum(hN);
var uN = dN.or(A_.object({ name: dN })).transform((t48) => "string" == typeof t48 ? t48 : t48.name);
var pN = A_.enum(["top", "bottom"]);
var mN = A_.object({ type: A_.literal("source_manually_placed_via"), source_manually_placed_via_id: A_.string(), source_group_id: A_.string(), source_net_id: A_.string(), subcircuit_id: A_.string().optional(), source_trace_id: A_.string().optional() }).describe("Defines a via that is manually placed in the source domain");
var gN = A_.object({ type: A_.literal("source_no_power_pin_defined_warning"), source_no_power_pin_defined_warning_id: JM("source_no_power_pin_defined_warning"), warning_type: A_.literal("source_no_power_pin_defined_warning").default("source_no_power_pin_defined_warning"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a chip has no source ports with requires_power=true");
var fN = A_.object({ type: A_.literal("source_no_ground_pin_defined_warning"), source_no_ground_pin_defined_warning_id: JM("source_no_ground_pin_defined_warning"), warning_type: A_.literal("source_no_ground_pin_defined_warning").default("source_no_ground_pin_defined_warning"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Warning emitted when a chip has no source ports marked as ground pins");
var _N = A_.object({ type: A_.literal("source_component_pins_underspecified_warning"), source_component_pins_underspecified_warning_id: JM("source_component_pins_underspecified_warning"), warning_type: A_.literal("source_component_pins_underspecified_warning").default("source_component_pins_underspecified_warning"), message: A_.string(), source_component_id: A_.string(), source_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Warning emitted when all ports on a source component are underspecified");
var yN = gC.extend({ type: A_.literal("source_pin_must_be_connected_error"), source_pin_must_be_connected_error_id: JM("source_pin_must_be_connected_error"), error_type: A_.literal("source_pin_must_be_connected_error").default("source_pin_must_be_connected_error"), source_component_id: A_.string(), source_port_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Error emitted when a pin with mustBeConnected attribute is not connected to any trace");
var bN = gC.extend({ type: A_.literal("unknown_error_finding_part"), unknown_error_finding_part_id: JM("unknown_error_finding_part"), error_type: A_.literal("unknown_error_finding_part").default("unknown_error_finding_part"), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when an unexpected error occurs while finding a part");
var xN = A_.object({ type: A_.literal("schematic_box"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), width: $M, height: $M, is_dashed: A_.boolean().default(false), x: $M, y: $M, subcircuit_id: A_.string().optional() }).describe("Draws a box on the schematic");
var vN = A_.object({ type: A_.literal("schematic_path"), schematic_path_id: JM("schematic_path"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), fill_color: A_.string().optional(), is_filled: A_.boolean().optional(), stroke_width: $M.nullable().optional(), stroke_color: A_.string().optional(), points: A_.array(GM), subcircuit_id: A_.string().optional() });
var SN = A_.record(A_.object({ left_margin: jM.optional(), right_margin: jM.optional(), top_margin: jM.optional(), bottom_margin: jM.optional() }));
var IN = A_.object({ left_size: A_.number(), right_size: A_.number(), top_size: A_.number().optional(), bottom_size: A_.number().optional() });
var PN = A_.object({ left_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), right_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum(["top-to-bottom", "bottom-to-top"]).optional() }).optional(), top_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum(["left-to-right", "right-to-left"]).optional() }).optional(), bottom_side: A_.object({ pins: A_.array(A_.number()), direction: A_.enum(["left-to-right", "right-to-left"]).optional() }).optional() });
var MN = A_.union([IN, PN]);
var CN = A_.object({ type: A_.literal("schematic_component"), size: qM, center: GM, source_component_id: A_.string().optional(), schematic_component_id: A_.string(), schematic_symbol_id: A_.string().optional(), pin_spacing: jM.optional(), pin_styles: SN.optional(), box_width: jM.optional(), symbol_name: A_.string().optional(), port_arrangement: MN.optional(), port_labels: A_.record(A_.string()).optional(), symbol_display_value: A_.string().optional(), subcircuit_id: A_.string().optional(), schematic_group_id: A_.string().optional(), is_schematic_group: A_.boolean().optional(), source_group_id: A_.string().optional(), is_box_with_pins: A_.boolean().optional().default(true) });
var NN = A_.object({ kicad_symbol: mC.optional() }).catchall(A_.unknown());
var wN = A_.object({ type: A_.literal("schematic_symbol"), schematic_symbol_id: A_.string(), name: A_.string().optional(), metadata: NN.optional() }).describe("Defines a named schematic symbol that can be referenced by components.");
var TN = A_.object({ type: A_.literal("schematic_line"), schematic_line_id: JM("schematic_line"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), x1: $M, y1: $M, x2: $M, y2: $M, stroke_width: $M.nullable().optional(), color: A_.string().default("#000000"), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe("Draws a styled line on the schematic");
var RN = A_.object({ type: A_.literal("schematic_rect"), schematic_rect_id: JM("schematic_rect"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: GM, width: $M, height: $M, rotation: VM.default(0), stroke_width: $M.nullable().optional(), color: A_.string().default("#000000"), is_filled: A_.boolean().default(false), fill_color: A_.string().optional(), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe("Draws a styled rectangle on the schematic");
var EN = A_.object({ type: A_.literal("schematic_circle"), schematic_circle_id: JM("schematic_circle"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: GM, radius: $M, stroke_width: $M.nullable().optional(), color: A_.string().default("#000000"), is_filled: A_.boolean().default(false), fill_color: A_.string().optional(), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe("Draws a styled circle on the schematic");
var AN = A_.object({ type: A_.literal("schematic_arc"), schematic_arc_id: JM("schematic_arc"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), center: GM, radius: $M, start_angle_degrees: VM, end_angle_degrees: VM, direction: A_.enum(["clockwise", "counterclockwise"]).default("counterclockwise"), stroke_width: $M.nullable().optional(), color: A_.string().default("#000000"), is_dashed: A_.boolean().default(false), subcircuit_id: A_.string().optional() }).describe("Draws a styled arc on the schematic");
var ON = A_.object({ type: A_.literal("schematic_trace"), schematic_trace_id: A_.string(), source_trace_id: A_.string().optional(), junctions: A_.array(A_.object({ x: A_.number(), y: A_.number() })), edges: A_.array(A_.object({ from: A_.object({ x: A_.number(), y: A_.number() }), to: A_.object({ x: A_.number(), y: A_.number() }), is_crossing: A_.boolean().optional(), from_schematic_port_id: A_.string().optional(), to_schematic_port_id: A_.string().optional() })), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional() });
var LN = A_.enum(["center", "left", "right", "top", "bottom"]);
var DN = A_.object({ type: A_.literal("schematic_text"), schematic_component_id: A_.string().optional(), schematic_symbol_id: A_.string().optional(), schematic_text_id: A_.string(), text: A_.string(), font_size: A_.number().default(0.18), position: A_.object({ x: $M, y: $M }), rotation: A_.number().default(0), anchor: A_.union([LN.describe("legacy"), KM]).default("center"), color: A_.string().default("#000000"), subcircuit_id: A_.string().optional() });
var zN = A_.object({ type: A_.literal("schematic_port"), schematic_port_id: A_.string(), source_port_id: A_.string(), schematic_component_id: A_.string().optional(), center: GM, facing_direction: A_.enum(["up", "down", "left", "right"]).optional(), distance_from_component_edge: A_.number().optional(), side_of_component: A_.enum(["top", "bottom", "left", "right"]).optional(), true_ccw_index: A_.number().optional(), pin_number: A_.number().optional(), display_pin_label: A_.string().optional(), subcircuit_id: A_.string().optional(), is_connected: A_.boolean().optional(), has_input_arrow: A_.boolean().optional(), has_output_arrow: A_.boolean().optional(), is_drawn_with_inversion_circle: A_.boolean().optional() }).describe("Defines a port on a schematic component");
var kN = A_.object({ type: A_.literal("schematic_net_label"), schematic_net_label_id: JM("schematic_net_label"), schematic_trace_id: A_.string().optional(), source_trace_id: A_.string().optional(), source_net_id: A_.string(), center: GM, anchor_position: GM.optional(), anchor_side: A_.enum(["top", "bottom", "left", "right"]), text: A_.string(), symbol_name: A_.string().optional(), is_movable: A_.boolean().optional(), subcircuit_id: A_.string().optional() });
var FN = gC.extend({ type: A_.literal("schematic_error"), schematic_error_id: A_.string(), error_type: A_.literal("schematic_port_not_found").default("schematic_port_not_found"), subcircuit_id: A_.string().optional() }).describe("Defines a schematic error on the schematic");
var jN = gC.extend({ type: A_.literal("schematic_layout_error"), schematic_layout_error_id: JM("schematic_layout_error"), error_type: A_.literal("schematic_layout_error").default("schematic_layout_error"), source_group_id: A_.string(), schematic_group_id: A_.string(), subcircuit_id: A_.string().optional() }).describe("Error emitted when schematic layout fails for a group");
var YN = A_.object({ type: A_.literal("schematic_debug_object"), label: A_.string().optional(), subcircuit_id: A_.string().optional() });
var $N = YN.extend({ shape: A_.literal("rect"), center: GM, size: qM });
var XN = YN.extend({ shape: A_.literal("line"), start: GM, end: GM });
var BN = YN.extend({ shape: A_.literal("point"), center: GM });
var HN = A_.discriminatedUnion("shape", [$N, XN, BN]);
var WN = A_.object({ type: A_.literal("schematic_voltage_probe"), schematic_voltage_probe_id: A_.string(), source_component_id: A_.string().optional(), name: A_.string().optional(), position: GM, schematic_trace_id: A_.string(), voltage: FM.optional(), subcircuit_id: A_.string().optional(), color: A_.string().optional(), label_alignment: KM.optional() }).describe("Defines a voltage probe measurement point on a schematic trace");
var VN = A_.object({ type: A_.literal("schematic_manual_edit_conflict_warning"), schematic_manual_edit_conflict_warning_id: JM("schematic_manual_edit_conflict_warning"), warning_type: A_.literal("schematic_manual_edit_conflict_warning").default("schematic_manual_edit_conflict_warning"), message: A_.string(), schematic_component_id: A_.string(), schematic_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_component_id: A_.string() }).describe("Warning emitted when a component has both manual placement and explicit schX/schY coordinates");
var UN = A_.object({ type: A_.literal("schematic_group"), schematic_group_id: JM("schematic_group"), source_group_id: A_.string(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), width: jM, height: jM, center: GM, schematic_component_ids: A_.array(A_.string()), show_as_schematic_box: A_.boolean().optional(), name: A_.string().optional(), description: A_.string().optional() }).describe("Defines a group of components on the schematic");
var GN = A_.object({ type: A_.literal("schematic_table"), schematic_table_id: JM("schematic_table"), anchor_position: GM, column_widths: A_.array($M), row_heights: A_.array($M), cell_padding: $M.optional(), border_width: $M.optional(), subcircuit_id: A_.string().optional(), schematic_component_id: A_.string().optional(), anchor: KM.optional() }).describe("Defines a table on the schematic");
var ZN = A_.object({ type: A_.literal("schematic_table_cell"), schematic_table_cell_id: JM("schematic_table_cell"), schematic_table_id: A_.string(), start_row_index: A_.number(), end_row_index: A_.number(), start_column_index: A_.number(), end_column_index: A_.number(), text: A_.string().optional(), center: GM, width: $M, height: $M, horizontal_align: A_.enum(["left", "center", "right"]).optional(), vertical_align: A_.enum(["top", "middle", "bottom"]).optional(), font_size: $M.optional(), subcircuit_id: A_.string().optional() }).describe("Defines a cell within a schematic_table");
var qN = A_.object({ type: A_.literal("schematic_sheet"), schematic_sheet_id: JM("schematic_sheet"), name: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Defines a schematic sheet or page that components can be placed on");
var JN = A_.object({ x: $M, y: $M, bulge: A_.number().optional() });
var KN = A_.object({ vertices: A_.array(JN) });
var QN = A_.object({ outer_ring: KN, inner_rings: A_.array(KN).default([]) });
var tw = A_.object({ x: $M, y: $M, via: A_.boolean().optional(), via_to_layer: uN.optional() });
var ew = (A_.array(tw), A_.object({ x: $M, y: $M, via: A_.boolean().optional(), to_layer: uN.optional(), trace_width: $M.optional() }));
var nw = A_.object({ min_trace_width: jM.optional(), min_board_edge_clearance: jM.optional(), min_via_hole_edge_to_via_hole_edge_clearance: jM.optional(), min_plated_hole_drill_edge_to_drill_edge_clearance: jM.optional(), min_trace_to_pad_edge_clearance: jM.optional(), min_pad_edge_to_pad_edge_clearance: jM.optional(), min_same_net_trace_edge_to_trace_edge_clearance: jM.optional(), min_different_net_trace_edge_to_trace_edge_clearance: jM.optional(), min_via_hole_diameter: jM.optional(), min_via_pad_diameter: jM.optional() });
var ow = A_.object({ type: A_.literal("pcb_component"), pcb_component_id: JM("pcb_component"), source_component_id: A_.string(), center: GM, layer: uN, rotation: VM, display_offset_x: A_.string().optional().describe("How to display the x offset for this part, usually corresponding with how the user specified it"), display_offset_y: A_.string().optional().describe("How to display the y offset for this part, usually corresponding with how the user specified it"), width: jM, height: jM, do_not_place: A_.boolean().optional(), is_allowed_to_be_off_board: A_.boolean().optional(), subcircuit_id: A_.string().optional(), pcb_group_id: A_.string().optional(), position_mode: A_.enum(["packed", "relative_to_group_anchor", "relative_to_another_component", "none"]).optional(), anchor_position: GM.optional(), anchor_alignment: KM.optional(), positioned_relative_to_pcb_group_id: A_.string().optional(), positioned_relative_to_pcb_board_id: A_.string().optional(), cable_insertion_center: GM.optional(), insertion_direction: A_.enum(["from_above", "from_left", "from_right", "from_front", "from_back"]).optional(), metadata: A_.object({ kicad_footprint: cC.optional() }).optional(), obstructs_within_bounds: A_.boolean().default(true).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");
var iw = A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: JM("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("circle"), hole_diameter: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var rw = (iw.describe("Defines a circular hole on the PCB"), A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: JM("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("rect"), hole_width: A_.number(), hole_height: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));
var sw = (rw.describe("Defines a rectangular (square-capable) hole on the PCB. Use equal width/height for square."), A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: JM("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.enum(["circle", "square"]), hole_diameter: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));
var aw = (sw.describe("Defines a circular or square hole on the PCB"), A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: JM("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("oval"), hole_width: A_.number(), hole_height: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));
var cw = (aw.describe("Defines an oval hole on the PCB"), A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: JM("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("pill"), hole_width: A_.number(), hole_height: A_.number(), x: $M, y: $M, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));
var lw = (cw.describe("Defines a pill-shaped hole on the PCB"), A_.object({ type: A_.literal("pcb_hole"), pcb_hole_id: JM("pcb_hole"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_component_id: A_.string().optional(), hole_shape: A_.literal("rotated_pill"), hole_width: A_.number(), hole_height: A_.number(), x: $M, y: $M, ccw_rotation: VM, is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() }));
var hw = (lw.describe("Defines a rotated pill-shaped hole on the PCB"), sw.or(aw).or(cw).or(lw).or(iw).or(rw));
var dw = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("circle"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), outer_diameter: A_.number(), hole_diameter: A_.number(), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM("pcb_plated_hole"), soldermask_margin: A_.number().optional() });
var uw = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.enum(["oval", "pill"]), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), outer_width: A_.number(), outer_height: A_.number(), hole_width: A_.number(), hole_height: A_.number(), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, ccw_rotation: VM, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM("pcb_plated_hole"), soldermask_margin: A_.number().optional() });
var pw = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("circular_hole_with_rect_pad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal("circle"), pad_shape: A_.literal("rect"), hole_diameter: A_.number(), rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), hole_offset_x: $M.default(0), hole_offset_y: $M.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM("pcb_plated_hole"), soldermask_margin: A_.number().optional(), rect_ccw_rotation: VM.optional() });
var mw = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("pill_hole_with_rect_pad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal("pill"), pad_shape: A_.literal("rect"), hole_width: A_.number(), hole_height: A_.number(), rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), hole_offset_x: $M.default(0), hole_offset_y: $M.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM("pcb_plated_hole"), soldermask_margin: A_.number().optional() });
var gw = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("rotated_pill_hole_with_rect_pad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.literal("rotated_pill"), pad_shape: A_.literal("rect"), hole_width: A_.number(), hole_height: A_.number(), hole_ccw_rotation: VM, rect_pad_width: A_.number(), rect_pad_height: A_.number(), rect_border_radius: A_.number().optional(), rect_ccw_rotation: VM, hole_offset_x: $M.default(0), hole_offset_y: $M.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM("pcb_plated_hole"), soldermask_margin: A_.number().optional() });
var fw = A_.object({ type: A_.literal("pcb_plated_hole"), shape: A_.literal("hole_with_polygon_pad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), hole_shape: A_.enum(["circle", "oval", "pill", "rotated_pill"]), hole_diameter: A_.number().optional(), hole_width: A_.number().optional(), hole_height: A_.number().optional(), pad_outline: A_.array(A_.object({ x: $M, y: $M })).min(3), hole_offset_x: $M.default(0), hole_offset_y: $M.default(0), is_covered_with_solder_mask: A_.boolean().optional(), x: $M, y: $M, layers: A_.array(uN), port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), pcb_plated_hole_id: JM("pcb_plated_hole"), soldermask_margin: A_.number().optional(), ccw_rotation: VM.optional() });
var _w = A_.union([dw, uw, pw, mw, gw, fw]);
var yw = A_.object({ type: A_.literal("pcb_port"), pcb_port_id: JM("pcb_port"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_port_id: A_.string(), pcb_component_id: A_.string().optional(), x: $M, y: $M, layers: A_.array(uN), is_board_pinout: A_.boolean().optional() }).describe("Defines a port on the PCB");
var bw = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("circle"), pcb_smtpad_id: JM("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, radius: A_.number(), layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var xw = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("rect"), pcb_smtpad_id: JM("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), rect_border_radius: A_.number().optional(), corner_radius: A_.number().optional(), layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional(), soldermask_margin_left: A_.number().optional(), soldermask_margin_top: A_.number().optional(), soldermask_margin_right: A_.number().optional(), soldermask_margin_bottom: A_.number().optional() });
var vw = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("rotated_rect"), pcb_smtpad_id: JM("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), rect_border_radius: A_.number().optional(), corner_radius: A_.number().optional(), ccw_rotation: VM, layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional(), soldermask_margin_left: A_.number().optional(), soldermask_margin_top: A_.number().optional(), soldermask_margin_right: A_.number().optional(), soldermask_margin_bottom: A_.number().optional() });
var Sw = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("pill"), pcb_smtpad_id: JM("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), radius: A_.number(), layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var Iw = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("rotated_pill"), pcb_smtpad_id: JM("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), radius: A_.number(), ccw_rotation: VM, layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var Pw = A_.object({ type: A_.literal("pcb_smtpad"), shape: A_.literal("polygon"), pcb_smtpad_id: JM("pcb_smtpad"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), points: A_.array(GM), layer: uN, port_hints: A_.array(A_.string()).optional(), pcb_component_id: A_.string().optional(), pcb_port_id: A_.string().optional(), is_covered_with_solder_mask: A_.boolean().optional(), soldermask_margin: A_.number().optional() });
var Mw = A_.discriminatedUnion("shape", [bw, xw, vw, Iw, Sw, Pw]).describe("Defines an SMT pad on the PCB");
var Cw = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("circle"), pcb_solder_paste_id: JM("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, radius: A_.number(), layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var Nw = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("rect"), pcb_solder_paste_id: JM("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var ww = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("pill"), pcb_solder_paste_id: JM("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), radius: A_.number(), layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var Tw = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("rotated_rect"), pcb_solder_paste_id: JM("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), ccw_rotation: $M, layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var Rw = A_.object({ type: A_.literal("pcb_solder_paste"), shape: A_.literal("oval"), pcb_solder_paste_id: JM("pcb_solder_paste"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), x: $M, y: $M, width: A_.number(), height: A_.number(), layer: uN, pcb_component_id: A_.string().optional(), pcb_smtpad_id: A_.string().optional() });
var Ew = A_.union([Cw, Nw, ww, Tw, Rw]).describe("Defines solderpaste on the PCB");
var Aw = A_.object({ type: A_.literal("pcb_text"), pcb_text_id: JM("pcb_text"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), text: A_.string(), center: GM, layer: uN, width: jM, height: jM, lines: A_.number(), align: A_.enum(["bottom-left"]) }).describe("Defines text on the PCB");
var Ow = A_.object({ route_type: A_.literal("wire"), x: $M, y: $M, width: $M, copper_pour_id: A_.string().optional(), is_inside_copper_pour: A_.boolean().optional(), start_pcb_port_id: A_.string().optional(), end_pcb_port_id: A_.string().optional(), layer: uN });
var Lw = A_.object({ route_type: A_.literal("via"), x: $M, y: $M, copper_pour_id: A_.string().optional(), is_inside_copper_pour: A_.boolean().optional(), hole_diameter: $M.optional(), outer_diameter: $M.optional(), from_layer: uN, to_layer: uN });
var Dw = A_.union([Ow, Lw]);
var zw = A_.object({ type: A_.literal("pcb_trace"), source_trace_id: A_.string().optional(), pcb_component_id: A_.string().optional(), pcb_trace_id: JM("pcb_trace"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), route_thickness_mode: A_.enum(["constant", "interpolated"]).default("constant").optional(), route_order_index: A_.number().optional(), should_round_corners: A_.boolean().optional(), trace_length: A_.number().optional(), highlight_color: A_.string().optional(), route: A_.array(Dw) }).describe("Defines a trace on the PCB");
var kw = A_.object({ type: A_.literal("pcb_trace_warning"), pcb_trace_warning_id: JM("pcb_trace_warning"), warning_type: A_.literal("pcb_trace_warning").default("pcb_trace_warning"), message: A_.string(), center: GM.optional(), pcb_trace_id: A_.string(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines a trace warning on the PCB");
var Fw = gC.extend({ type: A_.literal("pcb_trace_error"), pcb_trace_error_id: JM("pcb_trace_error"), error_type: A_.literal("pcb_trace_error").default("pcb_trace_error"), center: GM.optional(), pcb_trace_id: A_.string(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines a trace error on the PCB");
var jw = gC.extend({ type: A_.literal("pcb_trace_missing_error"), pcb_trace_missing_error_id: JM("pcb_trace_missing_error"), error_type: A_.literal("pcb_trace_missing_error").default("pcb_trace_missing_error"), center: GM.optional(), source_trace_id: A_.string(), pcb_component_ids: A_.array(A_.string()), pcb_port_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines an error when a source trace has no corresponding PCB trace");
var Yw = gC.extend({ type: A_.literal("pcb_port_not_matched_error"), pcb_error_id: JM("pcb_error"), error_type: A_.literal("pcb_port_not_matched_error").default("pcb_port_not_matched_error"), pcb_component_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines a trace error on the PCB where a port is not matched");
var $w = gC.extend({ type: A_.literal("pcb_port_not_connected_error"), pcb_port_not_connected_error_id: JM("pcb_port_not_connected_error"), error_type: A_.literal("pcb_port_not_connected_error").default("pcb_port_not_connected_error"), pcb_port_ids: A_.array(A_.string()), pcb_component_ids: A_.array(A_.string()), subcircuit_id: A_.string().optional() }).describe("Defines an error when a pcb port is not connected to any trace");
var Xw = A_.object({ type: A_.literal("pcb_net"), pcb_net_id: JM("pcb_net"), source_net_id: A_.string().optional(), highlight_color: A_.string().optional() }).describe("Defines a net on the PCB");
var Bw = A_.object({ type: A_.literal("pcb_via"), pcb_via_id: JM("pcb_via"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), x: $M, y: $M, outer_diameter: $M.default("0.6mm"), hole_diameter: $M.default("0.25mm"), from_layer: uN.optional(), to_layer: uN.optional(), layers: A_.array(uN), pcb_trace_id: A_.string().optional(), net_is_assignable: A_.boolean().optional(), net_assigned: A_.boolean().optional(), is_tented: A_.boolean().optional() }).describe("Defines a via on the PCB");
var Hw = A_.object({ type: A_.literal("pcb_board"), pcb_board_id: JM("pcb_board"), pcb_panel_id: A_.string().optional(), carrier_pcb_board_id: A_.string().optional(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), is_mounted_to_carrier_board: A_.boolean().optional(), width: jM.optional(), height: jM.optional(), center: GM, display_offset_x: A_.string().optional().describe("How to display the x offset for this board, usually corresponding with how the user specified it"), display_offset_y: A_.string().optional().describe("How to display the y offset for this board, usually corresponding with how the user specified it"), thickness: jM.optional().default(1.4), num_layers: A_.number().optional().default(4), outline: A_.array(GM).optional(), shape: A_.enum(["rect", "polygon"]).optional(), material: A_.enum(["fr4", "fr1"]).default("fr4"), anchor_position: GM.optional(), anchor_alignment: KM.optional(), position_mode: A_.enum(["relative_to_panel_anchor", "none"]).optional() }).merge(nw).describe("Defines the board outline of the PCB");
var Ww = A_.object({ type: A_.literal("pcb_panel"), pcb_panel_id: JM("pcb_panel"), width: jM, height: jM, center: GM, thickness: jM.optional().default(1.4), covered_with_solder_mask: A_.boolean().optional().default(true) }).describe("Defines a PCB panel that can contain multiple boards");
var Vw = gC.extend({ type: A_.literal("pcb_placement_error"), pcb_placement_error_id: JM("pcb_placement_error"), error_type: A_.literal("pcb_placement_error").default("pcb_placement_error"), subcircuit_id: A_.string().optional() }).describe("Defines a placement error on the PCB");
var Uw = gC.extend({ type: A_.literal("pcb_panelization_placement_error"), pcb_panelization_placement_error_id: JM("pcb_panelization_placement_error"), error_type: A_.literal("pcb_panelization_placement_error").default("pcb_panelization_placement_error"), pcb_panel_id: A_.string().optional(), pcb_board_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Defines a panelization placement error on the PCB");
var Gw = A_.object({ type: A_.literal("pcb_trace_hint"), pcb_trace_hint_id: JM("pcb_trace_hint"), pcb_port_id: A_.string(), pcb_component_id: A_.string(), route: A_.array(ew), subcircuit_id: A_.string().optional() }).describe("A hint that can be used during generation of a PCB trace");
var Zw = A_.object({ type: A_.literal("pcb_silkscreen_line"), pcb_silkscreen_line_id: JM("pcb_silkscreen_line"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), stroke_width: $M.default("0.1mm"), x1: $M, y1: $M, x2: $M, y2: $M, layer: pN }).describe("Defines a silkscreen line on the PCB");
var qw = A_.object({ type: A_.literal("pcb_silkscreen_path"), pcb_silkscreen_path_id: JM("pcb_silkscreen_path"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: pN, route: A_.array(GM), stroke_width: jM }).describe("Defines a silkscreen path on the PCB");
var Jw = A_.object({ type: A_.literal("pcb_silkscreen_text"), pcb_silkscreen_text_id: JM("pcb_silkscreen_text"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: $M.default("0.2mm"), pcb_component_id: A_.string(), text: A_.string(), is_knockout: A_.boolean().default(false).optional(), knockout_padding: A_.object({ left: jM, top: jM, bottom: jM, right: jM }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: A_.number().optional(), layer: uN, is_mirrored: A_.boolean().default(false).optional(), anchor_position: GM.default({ x: 0, y: 0 }), anchor_alignment: KM.default("center") }).describe("Defines silkscreen text on the PCB");
var Kw = A_.object({ type: A_.literal("pcb_copper_text"), pcb_copper_text_id: JM("pcb_copper_text"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: $M.default("0.2mm"), pcb_component_id: A_.string(), text: A_.string(), is_knockout: A_.boolean().default(false).optional(), knockout_padding: A_.object({ left: jM, top: jM, bottom: jM, right: jM }).default({ left: "0.2mm", top: "0.2mm", bottom: "0.2mm", right: "0.2mm" }).optional(), ccw_rotation: A_.number().optional(), layer: uN, is_mirrored: A_.boolean().default(false).optional(), anchor_position: GM.default({ x: 0, y: 0 }), anchor_alignment: KM.default("center") }).describe("Defines copper text on the PCB");
var Qw = A_.object({ type: A_.literal("pcb_silkscreen_rect"), pcb_silkscreen_rect_id: JM("pcb_silkscreen_rect"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: jM, height: jM, layer: uN, stroke_width: jM.default("1mm"), corner_radius: jM.optional(), is_filled: A_.boolean().default(true).optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), ccw_rotation: A_.number().optional() }).describe("Defines a silkscreen rect on the PCB");
var tT = A_.object({ type: A_.literal("pcb_silkscreen_circle"), pcb_silkscreen_circle_id: JM("pcb_silkscreen_circle"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, radius: jM, layer: pN, stroke_width: jM.default("1mm"), is_filled: A_.boolean().optional() }).describe("Defines a silkscreen circle on the PCB");
var eT = A_.object({ type: A_.literal("pcb_silkscreen_oval"), pcb_silkscreen_oval_id: JM("pcb_silkscreen_oval"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, radius_x: $M, radius_y: $M, layer: pN, ccw_rotation: VM.optional() }).describe("Defines a silkscreen oval on the PCB");
var nT = A_.object({ type: A_.literal("pcb_silkscreen_pill"), pcb_silkscreen_pill_id: JM("pcb_silkscreen_pill"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: jM, height: jM, layer: uN, ccw_rotation: A_.number().optional() }).describe("Defines a silkscreen pill on the PCB");
var oT = A_.object({ type: A_.literal("pcb_fabrication_note_text"), pcb_fabrication_note_text_id: JM("pcb_fabrication_note_text"), subcircuit_id: A_.string().optional(), pcb_group_id: A_.string().optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: $M.default("1mm"), pcb_component_id: A_.string(), text: A_.string(), layer: pN, anchor_position: GM.default({ x: 0, y: 0 }), anchor_alignment: A_.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), color: A_.string().optional() }).describe("Defines a fabrication note in text on the PCB, useful for leaving notes for assemblers or fabricators");
var iT = A_.object({ type: A_.literal("pcb_fabrication_note_path"), pcb_fabrication_note_path_id: JM("pcb_fabrication_note_path"), pcb_component_id: A_.string(), subcircuit_id: A_.string().optional(), layer: uN, route: A_.array(GM), stroke_width: jM, color: A_.string().optional() }).describe("Defines a fabrication path on the PCB for fabricators or assemblers");
var rT = A_.object({ type: A_.literal("pcb_fabrication_note_rect"), pcb_fabrication_note_rect_id: JM("pcb_fabrication_note_rect"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: jM, height: jM, layer: pN, stroke_width: jM.default("0.1mm"), corner_radius: jM.optional(), is_filled: A_.boolean().optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), color: A_.string().optional() }).describe("Defines a fabrication note rectangle on the PCB");
var sT = A_.object({ type: A_.literal("pcb_fabrication_note_dimension"), pcb_fabrication_note_dimension_id: JM("pcb_fabrication_note_dimension"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: pN, from: GM, to: GM, text: A_.string().optional(), text_ccw_rotation: A_.number().optional(), offset: jM.optional(), offset_distance: jM.optional(), offset_direction: A_.object({ x: A_.number(), y: A_.number() }).optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: jM.default("1mm"), color: A_.string().optional(), arrow_size: jM.default("1mm") }).describe("Defines a measurement annotation within PCB fabrication notes");
var aT = A_.object({ type: A_.literal("pcb_note_text"), pcb_note_text_id: JM("pcb_note_text"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: $M.default("1mm"), text: A_.string().optional(), anchor_position: GM.default({ x: 0, y: 0 }), anchor_alignment: A_.enum(["center", "top_left", "top_right", "bottom_left", "bottom_right"]).default("center"), layer: pN.default("top"), is_mirrored_from_top_view: A_.boolean().optional(), color: A_.string().optional() }).describe("Defines a documentation note in text on the PCB");
var cT = A_.object({ type: A_.literal("pcb_note_rect"), pcb_note_rect_id: JM("pcb_note_rect"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), center: GM, width: jM, height: jM, layer: pN.default("top"), stroke_width: jM.default("0.1mm"), corner_radius: jM.optional(), is_filled: A_.boolean().optional(), has_stroke: A_.boolean().optional(), is_stroke_dashed: A_.boolean().optional(), color: A_.string().optional() }).describe("Defines a rectangular documentation note on the PCB");
var lT = A_.object({ type: A_.literal("pcb_note_path"), pcb_note_path_id: JM("pcb_note_path"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), route: A_.array(GM), layer: pN.default("top"), stroke_width: jM.default("0.1mm"), color: A_.string().optional() }).describe("Defines a polyline documentation note on the PCB");
var hT = A_.object({ type: A_.literal("pcb_note_line"), pcb_note_line_id: JM("pcb_note_line"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), text: A_.string().optional(), x1: $M, y1: $M, x2: $M, y2: $M, layer: pN.default("top"), stroke_width: $M.default("0.1mm"), color: A_.string().optional(), is_dashed: A_.boolean().optional() }).describe("Defines a straight documentation note line on the PCB");
var dT = A_.object({ type: A_.literal("pcb_note_dimension"), pcb_note_dimension_id: JM("pcb_note_dimension"), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), name: A_.string().optional(), from: GM, to: GM, text: A_.string().optional(), text_ccw_rotation: A_.number().optional(), offset_distance: jM.optional(), offset_direction: A_.object({ x: A_.number(), y: A_.number() }).optional(), font: A_.literal("tscircuit2024").default("tscircuit2024"), font_size: jM.default("1mm"), layer: pN.default("top"), color: A_.string().optional(), arrow_size: jM.default("1mm") }).describe("Defines a measurement annotation within PCB documentation notes");
var uT = gC.extend({ type: A_.literal("pcb_footprint_overlap_error"), pcb_error_id: JM("pcb_error"), error_type: A_.literal("pcb_footprint_overlap_error").default("pcb_footprint_overlap_error"), pcb_smtpad_ids: A_.array(A_.string()).optional(), pcb_plated_hole_ids: A_.array(A_.string()).optional(), pcb_hole_ids: A_.array(A_.string()).optional(), pcb_keepout_ids: A_.array(A_.string()).optional() }).describe("Error emitted when a pcb footprint overlaps with another element");
var pT = gC.extend({ type: A_.literal("pcb_courtyard_overlap_error"), pcb_error_id: JM("pcb_error"), error_type: A_.literal("pcb_courtyard_overlap_error").default("pcb_courtyard_overlap_error"), pcb_component_ids: A_.tuple([A_.string(), A_.string()]) }).describe("Error emitted when the courtyard (CrtYd) of one PCB component overlaps with the courtyard of another");
var mT = A_.object({ type: A_.literal("pcb_keepout"), shape: A_.literal("rect"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: $M, height: $M, pcb_keepout_id: A_.string(), layers: A_.array(A_.string()), description: A_.string().optional() }).or(A_.object({ type: A_.literal("pcb_keepout"), shape: A_.literal("circle"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, radius: $M, pcb_keepout_id: A_.string(), layers: A_.array(A_.string()), description: A_.string().optional() }));
var gT = A_.object({ type: A_.literal("pcb_cutout"), pcb_cutout_id: JM("pcb_cutout"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), pcb_board_id: A_.string().optional(), pcb_panel_id: A_.string().optional() });
var fT = gT.extend({ shape: A_.literal("rect"), center: GM, width: jM, height: jM, rotation: VM.optional(), corner_radius: jM.optional() });
var _T = gT.extend({ shape: A_.literal("circle"), center: GM, radius: jM });
var yT = gT.extend({ shape: A_.literal("polygon"), points: A_.array(GM) });
var bT = gT.extend({ shape: A_.literal("path"), route: A_.array(GM), slot_width: jM, slot_length: jM.optional(), space_between_slots: jM.optional(), slot_corner_radius: jM.optional() });
var xT = A_.discriminatedUnion("shape", [fT, _T, yT, bT]).describe("Defines a cutout on the PCB, removing board material.");
var vT = gC.extend({ type: A_.literal("pcb_missing_footprint_error"), pcb_missing_footprint_error_id: JM("pcb_missing_footprint_error"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal("pcb_missing_footprint_error").default("pcb_missing_footprint_error"), source_component_id: A_.string() }).describe("Defines a missing footprint error on the PCB");
var ST = gC.extend({ type: A_.literal("external_footprint_load_error"), external_footprint_load_error_id: JM("external_footprint_load_error"), pcb_component_id: A_.string(), source_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), footprinter_string: A_.string().optional(), error_type: A_.literal("external_footprint_load_error").default("external_footprint_load_error") }).describe("Defines an error when an external footprint fails to load");
var IT = gC.extend({ type: A_.literal("circuit_json_footprint_load_error"), circuit_json_footprint_load_error_id: JM("circuit_json_footprint_load_error"), pcb_component_id: A_.string(), source_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), error_type: A_.literal("circuit_json_footprint_load_error").default("circuit_json_footprint_load_error"), circuit_json: A_.array(A_.any()).optional() }).describe("Defines an error when a circuit JSON footprint fails to load");
var PT = A_.object({ type: A_.literal("pcb_group"), pcb_group_id: JM("pcb_group"), source_group_id: A_.string(), is_subcircuit: A_.boolean().optional(), subcircuit_id: A_.string().optional(), width: jM.optional(), height: jM.optional(), center: GM, display_offset_x: A_.string().optional().describe("How to display the x offset for this group, usually corresponding with how the user specified it"), display_offset_y: A_.string().optional().describe("How to display the y offset for this group, usually corresponding with how the user specified it"), outline: A_.array(GM).optional(), anchor_position: GM.optional(), anchor_alignment: KM.default("center"), position_mode: A_.enum(["packed", "relative_to_group_anchor", "none"]).optional(), positioned_relative_to_pcb_group_id: A_.string().optional(), positioned_relative_to_pcb_board_id: A_.string().optional(), pcb_component_ids: A_.array(A_.string()), child_layout_mode: A_.enum(["packed", "none"]).optional(), name: A_.string().optional(), description: A_.string().optional(), layout_mode: A_.string().optional(), autorouter_configuration: A_.object({ trace_clearance: jM }).optional(), autorouter_used_string: A_.string().optional() }).describe("Defines a group of components on the PCB");
var MT = gC.extend({ type: A_.literal("pcb_autorouting_error"), pcb_error_id: JM("pcb_autorouting_error"), error_type: A_.literal("pcb_autorouting_error").default("pcb_autorouting_error"), subcircuit_id: A_.string().optional() }).describe("The autorouting has failed to route a portion of the board");
var CT = A_.object({ type: A_.literal("pcb_manual_edit_conflict_warning"), pcb_manual_edit_conflict_warning_id: JM("pcb_manual_edit_conflict_warning"), warning_type: A_.literal("pcb_manual_edit_conflict_warning").default("pcb_manual_edit_conflict_warning"), message: A_.string(), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), source_component_id: A_.string() }).describe("Warning emitted when a component has both manual placement and explicit pcbX/pcbY coordinates");
var NT = A_.enum(["x-", "x+", "y+", "y-"]);
var wT = A_.object({ type: A_.literal("pcb_connector_not_in_accessible_orientation_warning"), pcb_connector_not_in_accessible_orientation_warning_id: JM("pcb_connector_not_in_accessible_orientation_warning"), warning_type: A_.literal("pcb_connector_not_in_accessible_orientation_warning").default("pcb_connector_not_in_accessible_orientation_warning"), message: A_.string(), pcb_component_id: A_.string(), source_component_id: A_.string().optional(), pcb_board_id: A_.string().optional(), facing_direction: NT, recommended_facing_direction: NT, subcircuit_id: A_.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");
var TT = A_.object({ type: A_.literal("supplier_footprint_mismatch_warning"), supplier_footprint_mismatch_warning_id: JM("supplier_footprint_mismatch_warning"), warning_type: A_.literal("supplier_footprint_mismatch_warning").default("supplier_footprint_mismatch_warning"), message: A_.string(), source_component_id: A_.string(), pcb_component_id: A_.string().optional(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), supplier_name: fC.optional(), supplier_part_number: A_.string().optional(), supplier_footprint_url: A_.string().optional(), footprint_copper_intersection_over_union: A_.number() }).describe("Warning emitted when a supplier part footprint does not match the expected footprint");
var RT = A_.object({ type: A_.literal("pcb_breakout_point"), pcb_breakout_point_id: JM("pcb_breakout_point"), pcb_group_id: A_.string(), subcircuit_id: A_.string().optional(), source_trace_id: A_.string().optional(), source_port_id: A_.string().optional(), source_net_id: A_.string().optional(), x: $M, y: $M }).describe("Defines a routing target within a pcb_group for a source_trace or source_net");
var ET = A_.object({ type: A_.literal("pcb_ground_plane"), pcb_ground_plane_id: JM("pcb_ground_plane"), source_pcb_ground_plane_id: A_.string(), source_net_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Defines a ground plane on the PCB");
var AT = A_.object({ type: A_.literal("pcb_ground_plane_region"), pcb_ground_plane_region_id: JM("pcb_ground_plane_region"), pcb_ground_plane_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: uN, points: A_.array(GM) }).describe("Defines a polygon region of a ground plane");
var OT = A_.object({ type: A_.literal("pcb_thermal_spoke"), pcb_thermal_spoke_id: JM("pcb_thermal_spoke"), pcb_ground_plane_id: A_.string(), shape: A_.string(), spoke_count: A_.number(), spoke_thickness: $M, spoke_inner_diameter: $M, spoke_outer_diameter: $M, pcb_plated_hole_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Pattern for connecting a ground plane to a plated hole");
var LT = A_.object({ type: A_.literal("pcb_copper_pour"), pcb_copper_pour_id: JM("pcb_copper_pour"), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: uN, source_net_id: A_.string().optional(), covered_with_solder_mask: A_.boolean().optional().default(true) });
var DT = LT.extend({ shape: A_.literal("rect"), center: GM, width: jM, height: jM, rotation: VM.optional() });
var zT = LT.extend({ shape: A_.literal("brep"), brep_shape: QN });
var kT = LT.extend({ shape: A_.literal("polygon"), points: A_.array(GM) });
var FT = A_.discriminatedUnion("shape", [DT, zT, kT]).describe("Defines a copper pour on the PCB.");
var jT = gC.extend({ type: A_.literal("pcb_component_outside_board_error"), pcb_component_outside_board_error_id: JM("pcb_component_outside_board_error"), error_type: A_.literal("pcb_component_outside_board_error").default("pcb_component_outside_board_error"), pcb_component_id: A_.string(), pcb_board_id: A_.string(), component_center: GM, component_bounds: A_.object({ min_x: A_.number(), max_x: A_.number(), min_y: A_.number(), max_y: A_.number() }), subcircuit_id: A_.string().optional(), source_component_id: A_.string().optional() }).describe("Error emitted when a PCB component is placed outside the board boundaries");
var YT = gC.extend({ type: A_.literal("pcb_component_not_on_board_edge_error"), pcb_component_not_on_board_edge_error_id: JM("pcb_component_not_on_board_edge_error"), error_type: A_.literal("pcb_component_not_on_board_edge_error").default("pcb_component_not_on_board_edge_error"), pcb_component_id: A_.string(), pcb_board_id: A_.string(), component_center: GM, pad_to_nearest_board_edge_distance: A_.number(), source_component_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when a component that must be placed on the board edge is centered away from the edge");
var $T = gC.extend({ type: A_.literal("pcb_component_invalid_layer_error"), pcb_component_invalid_layer_error_id: JM("pcb_component_invalid_layer_error"), error_type: A_.literal("pcb_component_invalid_layer_error").default("pcb_component_invalid_layer_error"), pcb_component_id: A_.string().optional(), source_component_id: A_.string(), layer: uN, subcircuit_id: A_.string().optional() }).describe("Error emitted when a component is placed on an invalid layer (components can only be on 'top' or 'bottom' layers)");
var XT = gC.extend({ type: A_.literal("pcb_via_clearance_error"), pcb_error_id: JM("pcb_error"), error_type: A_.literal("pcb_via_clearance_error").default("pcb_via_clearance_error"), pcb_via_ids: A_.array(A_.string()).min(2), minimum_clearance: $M.optional(), actual_clearance: $M.optional(), pcb_center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when vias are closer than the allowed clearance");
var BT = gC.extend({ type: A_.literal("pcb_via_trace_clearance_error"), pcb_via_trace_clearance_error_id: JM("pcb_via_trace_clearance_error"), error_type: A_.literal("pcb_via_trace_clearance_error").default("pcb_via_trace_clearance_error"), pcb_via_id: A_.string(), pcb_trace_id: A_.string(), minimum_clearance: $M.optional(), actual_clearance: $M.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when a via and trace are closer than the allowed clearance");
var HT = gC.extend({ type: A_.literal("pcb_pad_pad_clearance_error"), pcb_pad_pad_clearance_error_id: JM("pcb_pad_pad_clearance_error"), error_type: A_.literal("pcb_pad_pad_clearance_error").default("pcb_pad_pad_clearance_error"), pcb_pad_ids: A_.array(A_.string()).min(2), minimum_clearance: $M.optional(), actual_clearance: $M.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when pads are closer than the allowed clearance");
var WT = gC.extend({ type: A_.literal("pcb_pad_trace_clearance_error"), pcb_pad_trace_clearance_error_id: JM("pcb_pad_trace_clearance_error"), error_type: A_.literal("pcb_pad_trace_clearance_error").default("pcb_pad_trace_clearance_error"), pcb_pad_id: A_.string(), pcb_trace_id: A_.string(), minimum_clearance: $M.optional(), actual_clearance: $M.optional(), center: A_.object({ x: A_.number().optional(), y: A_.number().optional() }).optional(), subcircuit_id: A_.string().optional() }).describe("Error emitted when a pad and trace are closer than allowed clearance");
var VT = A_.object({ type: A_.literal("pcb_courtyard_rect"), pcb_courtyard_rect_id: JM("pcb_courtyard_rect"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, width: jM, height: jM, layer: pN, ccw_rotation: VM.optional(), color: A_.string().optional() }).describe("Defines a courtyard rectangle on the PCB");
var UT = A_.object({ type: A_.literal("pcb_courtyard_outline"), pcb_courtyard_outline_id: JM("pcb_courtyard_outline"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: pN, outline: A_.array(GM).min(2) }).describe("Defines a courtyard outline on the PCB");
var GT = A_.object({ type: A_.literal("pcb_courtyard_polygon"), pcb_courtyard_polygon_id: JM("pcb_courtyard_polygon"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), layer: pN, points: A_.array(GM).min(3), color: A_.string().optional() }).describe("Defines a courtyard polygon on the PCB");
var ZT = A_.object({ type: A_.literal("pcb_courtyard_circle"), pcb_courtyard_circle_id: JM("pcb_courtyard_circle"), pcb_component_id: A_.string(), pcb_group_id: A_.string().optional(), subcircuit_id: A_.string().optional(), center: GM, radius: jM, layer: pN, color: A_.string().optional() }).describe("Defines a courtyard circle on the PCB");
var qT = A_.object({ type: A_.literal("cad_component"), cad_component_id: A_.string(), pcb_component_id: A_.string(), source_component_id: A_.string(), position: ZM, rotation: ZM.optional(), size: ZM.optional(), layer: uN.optional(), subcircuit_id: A_.string().optional(), footprinter_string: A_.string().optional(), model_obj_url: A_.string().optional(), model_stl_url: A_.string().optional(), model_3mf_url: A_.string().optional(), model_gltf_url: A_.string().optional(), model_glb_url: A_.string().optional(), model_step_url: A_.string().optional(), model_wrl_url: A_.string().optional(), model_asset: QM.optional(), model_unit_to_mm_scale_factor: A_.number().optional(), model_board_normal_direction: A_.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: ZM.optional(), model_origin_alignment: A_.enum(["unknown", "center", "center_of_component_on_board_surface", "bottom_center_of_component"]).optional(), model_object_fit: A_.enum(["contain_within_bounds", "fill_bounds"]).optional().default("contain_within_bounds"), model_jscad: A_.any().optional(), show_as_translucent_model: A_.boolean().optional(), anchor_alignment: A_.enum(["center", "center_of_component_on_board_surface"]).optional().default("center") }).describe("Defines a component on the PCB");
var JT = A_.enum(["sinewave", "square", "triangle", "sawtooth"]);
var KT = A_.union([A_.string(), A_.number()]).transform((t48) => "string" == typeof t48 ? t48.endsWith("%") ? parseFloat(t48.slice(0, -1)) / 100 : parseFloat(t48) : t48).pipe(A_.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var QT = A_.object({ type: A_.literal("simulation_voltage_source"), simulation_voltage_source_id: JM("simulation_voltage_source"), is_dc_source: A_.literal(true).optional().default(true), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), voltage: FM }).describe("Defines a DC voltage source for simulation");
var tR = A_.object({ type: A_.literal("simulation_voltage_source"), simulation_voltage_source_id: JM("simulation_voltage_source"), is_dc_source: A_.literal(false), terminal1_source_port_id: A_.string().optional(), terminal2_source_port_id: A_.string().optional(), terminal1_source_net_id: A_.string().optional(), terminal2_source_net_id: A_.string().optional(), voltage: FM.optional(), frequency: YM.optional(), peak_to_peak_voltage: FM.optional(), wave_shape: JT.optional(), phase: VM.optional(), duty_cycle: KT.optional() }).describe("Defines an AC voltage source for simulation");
var eR = A_.union([QT, tR]).describe("Defines a voltage source for simulation");
var nR = A_.union([A_.string(), A_.number()]).transform((t48) => "string" == typeof t48 ? t48.endsWith("%") ? parseFloat(t48.slice(0, -1)) / 100 : parseFloat(t48) : t48).pipe(A_.number().min(0, "Duty cycle must be non-negative").max(1, "Duty cycle cannot be greater than 100%"));
var oR = A_.object({ type: A_.literal("simulation_current_source"), simulation_current_source_id: JM("simulation_current_source"), is_dc_source: A_.literal(true).optional().default(true), positive_source_port_id: A_.string().optional(), negative_source_port_id: A_.string().optional(), positive_source_net_id: A_.string().optional(), negative_source_net_id: A_.string().optional(), current: XM }).describe("Defines a DC current source for simulation");
var iR = A_.object({ type: A_.literal("simulation_current_source"), simulation_current_source_id: JM("simulation_current_source"), is_dc_source: A_.literal(false), terminal1_source_port_id: A_.string().optional(), terminal2_source_port_id: A_.string().optional(), terminal1_source_net_id: A_.string().optional(), terminal2_source_net_id: A_.string().optional(), current: XM.optional(), frequency: YM.optional(), peak_to_peak_current: XM.optional(), wave_shape: JT.optional(), phase: VM.optional(), duty_cycle: nR.optional() }).describe("Defines an AC current source for simulation");
var rR = A_.union([oR, iR]).describe("Defines a current source for simulation");
var sR = A_.union([A_.literal("spice_dc_sweep"), A_.literal("spice_dc_operating_point"), A_.literal("spice_transient_analysis"), A_.literal("spice_ac_analysis")]);
var aR = A_.object({ type: A_.literal("simulation_experiment"), simulation_experiment_id: JM("simulation_experiment"), name: A_.string(), experiment_type: sR, time_per_step: BM.optional(), start_time_ms: HM.optional(), end_time_ms: HM.optional() }).describe("Defines a simulation experiment configuration");
var cR = A_.object({ type: A_.literal("simulation_transient_voltage_graph"), simulation_transient_voltage_graph_id: JM("simulation_transient_voltage_graph"), simulation_experiment_id: A_.string(), timestamps_ms: A_.array(A_.number()).optional(), voltage_levels: A_.array(A_.number()), source_component_id: A_.string().optional(), subcircuit_connectivity_map_key: A_.string().optional(), time_per_step: BM, start_time_ms: HM, end_time_ms: HM, name: A_.string().optional(), color: A_.string().optional() }).describe("Stores voltage measurements over time for a simulation");
var lR = A_.object({ type: A_.literal("simulation_switch"), simulation_switch_id: JM("simulation_switch"), source_component_id: A_.string().optional(), closes_at: HM.optional(), opens_at: HM.optional(), starts_closed: A_.boolean().optional(), switching_frequency: YM.optional() }).describe("Defines a switch for simulation timing control");
var hR = A_.object({ type: A_.literal("simulation_voltage_probe"), simulation_voltage_probe_id: JM("simulation_voltage_probe"), source_component_id: A_.string().optional(), name: A_.string().optional(), signal_input_source_port_id: A_.string().optional(), signal_input_source_net_id: A_.string().optional(), reference_input_source_port_id: A_.string().optional(), reference_input_source_net_id: A_.string().optional(), subcircuit_id: A_.string().optional(), color: A_.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((t48, e2) => {
  if (t48.reference_input_source_port_id || t48.reference_input_source_net_id) {
    const n2 = !!t48.signal_input_source_port_id || !!t48.reference_input_source_port_id, o2 = !!t48.signal_input_source_net_id || !!t48.reference_input_source_net_id;
    n2 && o2 ? e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Cannot mix port and net connections in a differential probe." }) : n2 ? t48.signal_input_source_port_id && t48.reference_input_source_port_id || e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Differential port probe requires both signal_input_source_port_id and reference_input_source_port_id." }) : o2 && (t48.signal_input_source_net_id && t48.reference_input_source_net_id || e2.addIssue({ code: A_.ZodIssueCode.custom, message: "Differential net probe requires both signal_input_source_net_id and reference_input_source_net_id." }));
  } else !!t48.signal_input_source_port_id == !!t48.signal_input_source_net_id && e2.addIssue({ code: A_.ZodIssueCode.custom, message: "A voltage probe must have exactly one of signal_input_source_port_id or signal_input_source_net_id." });
});
var dR = gC.extend({ type: A_.literal("simulation_unknown_experiment_error"), simulation_unknown_experiment_error_id: JM("simulation_unknown_experiment_error"), error_type: A_.literal("simulation_unknown_experiment_error").default("simulation_unknown_experiment_error"), simulation_experiment_id: A_.string().optional(), subcircuit_id: A_.string().optional() }).describe("An unknown error occurred during the simulation experiment.");
var uR = A_.object({ type: A_.literal("simulation_op_amp"), simulation_op_amp_id: JM("simulation_op_amp"), source_component_id: A_.string().optional(), inverting_input_source_port_id: A_.string(), non_inverting_input_source_port_id: A_.string(), output_source_port_id: A_.string(), positive_supply_source_port_id: A_.string(), negative_supply_source_port_id: A_.string() }).describe("Defines a simple ideal operational amplifier for simulation");
var pR = (A_.union([iN, nN, oN, eN, sN, rN, PC, yC, xC, SC, bC, MC, TC, RC, LC, zC, kC, XC, FC, jC, YC, $C, AC, EC, lN, mN, aN, BC, VC, UC, ZC, qC, gN, fN, _N, yN, bN, QC, cN, ow, hw, vT, ST, IT, CT, wT, TT, _w, mT, yw, Xw, Aw, zw, kw, Bw, Mw, Ew, Hw, Ww, PT, Gw, Zw, qw, Jw, nT, Kw, Qw, tT, eT, Fw, jw, Vw, Uw, Yw, $w, XT, BT, HT, WT, iT, oT, rT, sT, aT, cT, lT, hT, dT, MT, uT, pT, RT, xT, ET, AT, OT, FT, jT, YT, $T, VT, UT, GT, ZT, xN, DN, TN, RN, EN, AN, CN, wN, zN, ON, vN, FN, jN, kN, HN, WN, VN, UN, qN, GN, ZN, qT, eR, rR, aR, cR, lR, hR, dR, uR]), true);
var mR = { CCW: -1, CW: 1, NOT_ORIENTABLE: 0 };
var gR = 2 * Math.PI;
var fR = Object.freeze({ __proto__: null, BOUNDARY: 2, CCW: pR, CONTAINS: 3, CW: false, END_VERTEX: 2, INSIDE: 1, INTERLACE: 4, NOT_VERTEX: 0, ORIENTATION: mR, OUTSIDE: 0, OVERLAP_OPPOSITE: 2, OVERLAP_SAME: 1, PIx2: gR, START_VERTEX: 1 });
var _R = 1e-6;
function yR(t48) {
  _R = t48;
}
function bR() {
  return _R;
}
function xR(t48) {
  return t48 < _R && t48 > -_R;
}
function vR(t48, e2) {
  return t48 - e2 < _R && t48 - e2 > -_R;
}
function SR(t48, e2) {
  return t48 - e2 > _R;
}
function IR(t48, e2) {
  return t48 - e2 < -_R;
}
var PR = { Utils: Object.freeze({ __proto__: null, DECIMALS: 3, EQ: vR, EQ_0: xR, GE: function(t48, e2) {
  return t48 - e2 > -_R;
}, GT: SR, LE: function(t48, e2) {
  return t48 - e2 < _R;
}, LT: IR, getTolerance: bR, setTolerance: yR }), 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 t48 in fR) PR[t48] = fR[t48];
Object.defineProperty(PR, "DP_TOL", { get: function() {
  return bR();
}, set: function(t48) {
  yR(t48);
} });
var MR = 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");
  }
};
PR.Errors = MR;
var CR = class {
  constructor(t48, e2) {
    this.first = t48, this.last = e2 || this.first;
  }
  [Symbol.iterator]() {
    let t48;
    return { next: () => (t48 = t48 ? t48.next : this.first, { value: t48, done: void 0 === t48 }) };
  }
  get size() {
    let t48 = 0;
    for (let e2 of this) t48++;
    return t48;
  }
  toArray(t48 = void 0, e2 = void 0) {
    let n2 = [], o2 = t48 || this.first, i2 = e2 || this.last, r2 = o2;
    if (void 0 === r2) return n2;
    do {
      n2.push(r2), r2 = r2.next;
    } while (r2 !== i2.next);
    return n2;
  }
  append(t48) {
    return this.isEmpty() ? this.first = t48 : (t48.prev = this.last, this.last.next = t48), this.last = t48, this.last.next = void 0, this.first.prev = void 0, this;
  }
  insert(t48, e2) {
    if (this.isEmpty()) this.first = t48, this.last = t48;
    else if (null == e2) t48.next = this.first, this.first.prev = t48, this.first = t48;
    else {
      let n2 = e2.next;
      e2.next = t48, n2 && (n2.prev = t48), t48.prev = e2, t48.next = n2, this.last === e2 && (this.last = t48);
    }
    return this.last.next = void 0, this.first.prev = void 0, this;
  }
  remove(t48) {
    return t48 === this.first && t48 === this.last ? (this.first = void 0, this.last = void 0) : (t48.prev && (t48.prev.next = t48.next), t48.next && (t48.next.prev = t48.prev), t48 === this.first && (this.first = t48.next), t48 === this.last && (this.last = t48.prev)), this;
  }
  isEmpty() {
    return void 0 === this.first;
  }
  static testInfiniteLoop(t48) {
    let e2 = t48, n2 = t48;
    do {
      if (e2 != t48 && e2 === n2) throw MR.INFINITE_LOOP;
      e2 = e2.next, n2 = n2.next.next;
    } while (e2 != t48);
  }
};
var NR = { stroke: "black" };
var wR = class {
  constructor(t48 = NR) {
    for (const e2 in t48) this[e2] = t48[e2];
    this.stroke = t48.stroke ?? NR.stroke;
  }
  toAttributesString() {
    return Object.keys(this).reduce((t48, e2) => t48 + (void 0 !== this[e2] ? this.toAttrString(e2, this[e2]) : ""), "");
  }
  toAttrString(t48, e2) {
    const n2 = "className" === t48 ? "class" : this.convertCamelToKebabCase(t48);
    return null === e2 ? `${n2} ` : `${n2}="${e2.toString()}" `;
  }
  convertCamelToKebabCase(t48) {
    return t48.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 TR(t48) {
  return new wR(t48).toAttributesString();
}
function RR(t48, e2) {
  let n2 = [], [o2, i2, r2] = t48.standard, [s2, a2, c2] = e2.standard, l2 = o2 * a2 - i2 * s2, h2 = r2 * a2 - i2 * c2, d2 = o2 * c2 - r2 * s2;
  if (!PR.Utils.EQ_0(l2)) {
    let t49, e3;
    0 === i2 ? (t49 = r2 / o2, e3 = d2 / l2) : 0 === a2 ? (t49 = c2 / s2, e3 = d2 / l2) : 0 === o2 ? (t49 = h2 / l2, e3 = r2 / i2) : 0 === s2 ? (t49 = h2 / l2, e3 = c2 / a2) : (t49 = h2 / l2, e3 = d2 / l2), n2.push(new PR.Point(t49, e3));
  }
  return n2;
}
function ER(t48, e2) {
  let n2 = [], o2 = e2.pc.projectionOn(t48), i2 = e2.pc.distanceTo(o2)[0];
  if (PR.Utils.EQ(i2, e2.r)) n2.push(o2);
  else if (PR.Utils.LT(i2, e2.r)) {
    let r2, s2, a2 = Math.sqrt(e2.r * e2.r - i2 * i2);
    r2 = t48.norm.rotate90CCW().multiply(a2), s2 = o2.translate(r2), n2.push(s2), r2 = t48.norm.rotate90CW().multiply(a2), s2 = o2.translate(r2), n2.push(s2);
  }
  return n2;
}
function AR(t48, e2) {
  let n2 = [];
  for (let o2 of e2.toSegments()) {
    let e3 = LR(o2, t48);
    for (let t49 of e3) QR(t49, n2) || n2.push(t49);
  }
  return n2;
}
function OR(t48, e2) {
  let n2 = [];
  if (0 === AR(t48, e2.box).length) return n2;
  let o2 = ER(t48, new PR.Circle(e2.pc, e2.r));
  for (let t49 of o2) t49.on(e2) && n2.push(t49);
  return n2;
}
function LR(t48, e2) {
  let n2 = [];
  return t48.ps.on(e2) && n2.push(t48.ps), t48.pe.on(e2) && !t48.isZeroLength() && n2.push(t48.pe), n2.length > 0 || t48.isZeroLength() || t48.ps.leftTo(e2) && t48.pe.leftTo(e2) || !t48.ps.leftTo(e2) && !t48.pe.leftTo(e2) ? n2 : RR(new PR.Line(t48.ps, t48.pe), e2);
}
function DR(t48, e2) {
  let n2 = [];
  if (t48.isZeroLength()) return t48.ps.on(e2) && n2.push(t48.ps), n2;
  if (e2.isZeroLength()) return e2.ps.on(t48) && n2.push(e2.ps), n2;
  let o2 = new PR.Line(t48.ps, t48.pe), i2 = new PR.Line(e2.ps, e2.pe);
  if (o2.incidentTo(i2)) t48.ps.on(e2) && n2.push(t48.ps), t48.pe.on(e2) && n2.push(t48.pe), !e2.ps.on(t48) || e2.ps.equalTo(t48.ps) || e2.ps.equalTo(t48.pe) || n2.push(e2.ps), !e2.pe.on(t48) || e2.pe.equalTo(t48.ps) || e2.pe.equalTo(t48.pe) || n2.push(e2.pe);
  else if (o2.parallelTo(i2)) {
    const o3 = new PR.Vector(t48.ps, t48.pe), i3 = new PR.Vector(e2.ps, e2.pe), r2 = new PR.Vector(t48.ps, e2.ps), s2 = o3.cross(i3);
    if (!PR.Utils.EQ_0(s2)) {
      const a2 = r2.cross(i3) / s2, c2 = r2.cross(o3) / s2;
      PR.Utils.GE(a2, 0) && PR.Utils.LE(a2, 1) && PR.Utils.GE(c2, 0) && PR.Utils.LE(c2, 1) && n2.push(zR(t48.ps.translate(o3.multiply(a2)), t48, e2));
    }
  } else {
    let r2 = RR(o2, i2);
    r2.length > 0 && kR(r2[0], t48) && kR(r2[0], e2) && n2.push(zR(r2[0], t48, e2));
  }
  return n2;
}
function zR(t48, e2, n2) {
  for (const o2 of [e2.ps, e2.pe, n2.ps, n2.pe]) if (t48.equalTo(o2)) return o2;
  return t48;
}
function kR(t48, e2) {
  const n2 = e2.box;
  return PR.Utils.LE(t48.x, n2.xmax) && PR.Utils.GE(t48.x, n2.xmin) && PR.Utils.LE(t48.y, n2.ymax) && PR.Utils.GE(t48.y, n2.ymin);
}
function FR(t48, e2) {
  let n2 = [];
  if (t48.isZeroLength()) {
    let [o3, i2] = t48.ps.distanceTo(e2.pc);
    return PR.Utils.EQ(o3, e2.r) && n2.push(t48.ps), n2;
  }
  let o2 = ER(new PR.Line(t48.ps, t48.pe), e2);
  for (let e3 of o2) e3.on(t48) && n2.push(e3);
  return n2;
}
function jR(t48, e2) {
  let n2 = [];
  if (t48.isZeroLength()) return t48.ps.on(e2) && n2.push(t48.ps), n2;
  let o2 = ER(new PR.Line(t48.ps, t48.pe), new PR.Circle(e2.pc, e2.r));
  for (let i2 of o2) i2.on(t48) && i2.on(e2) && n2.push(i2);
  return n2;
}
function YR(t48, e2) {
  let n2 = [], o2 = new PR.Vector(t48.pc, e2.pc), i2 = t48.r, r2 = e2.r;
  if (PR.Utils.EQ_0(i2) || PR.Utils.EQ_0(r2)) return n2;
  if (PR.Utils.EQ_0(o2.x) && PR.Utils.EQ_0(o2.y) && PR.Utils.EQ(i2, r2)) return n2.push(t48.pc.translate(-i2, 0)), n2;
  let s2, a2 = t48.pc.distanceTo(e2.pc)[0];
  if (PR.Utils.GT(a2, i2 + r2)) return n2;
  if (PR.Utils.LT(a2, Math.abs(i2 - r2))) return n2;
  if (o2.x /= a2, o2.y /= a2, PR.Utils.EQ(a2, i2 + r2) || PR.Utils.EQ(a2, Math.abs(i2 - r2))) return s2 = t48.pc.translate(i2 * o2.x, i2 * o2.y), n2.push(s2), n2;
  let c2 = i2 * i2 / (2 * a2) - r2 * r2 / (2 * a2) + a2 / 2, l2 = t48.pc.translate(c2 * o2.x, c2 * o2.y), h2 = Math.sqrt(i2 * i2 - c2 * c2);
  return s2 = l2.translate(o2.rotate90CCW().multiply(h2)), n2.push(s2), s2 = l2.translate(o2.rotate90CW().multiply(h2)), n2.push(s2), n2;
}
function $R(t48, e2) {
  let n2 = [];
  if (t48.pc.equalTo(e2.pc) && PR.Utils.EQ(t48.r, e2.r)) {
    let o3;
    return o3 = t48.start, o3.on(e2) && n2.push(o3), o3 = t48.end, o3.on(e2) && n2.push(o3), o3 = e2.start, o3.on(t48) && n2.push(o3), o3 = e2.end, o3.on(t48) && n2.push(o3), n2;
  }
  let o2 = new PR.Circle(t48.pc, t48.r), i2 = new PR.Circle(e2.pc, e2.r), r2 = o2.intersect(i2);
  for (let o3 of r2) o3.on(t48) && o3.on(e2) && n2.push(o3);
  return n2;
}
function XR(t48, e2) {
  let n2 = [];
  if (e2.pc.equalTo(t48.pc) && PR.Utils.EQ(e2.r, t48.r)) return n2.push(t48.start), n2.push(t48.end), n2;
  let o2 = YR(e2, new PR.Circle(t48.pc, t48.r));
  for (let e3 of o2) e3.on(t48) && n2.push(e3);
  return n2;
}
function BR(t48, e2) {
  return t48.isSegment ? DR(t48.shape, e2) : jR(e2, t48.shape);
}
function HR(t48, e2) {
  return t48.isSegment ? jR(t48.shape, e2) : $R(t48.shape, e2);
}
function WR(t48, e2) {
  return t48.isSegment ? LR(t48.shape, e2) : OR(e2, t48.shape);
}
function VR(t48, e2) {
  return t48.isSegment ? FR(t48.shape, e2) : XR(t48.shape, e2);
}
function UR(t48, e2) {
  let n2 = [];
  for (let o2 of e2.edges) for (let e3 of BR(o2, t48)) n2.push(e3);
  return n2;
}
function GR(t48, e2) {
  let n2 = [];
  for (let o2 of e2.edges) for (let e3 of HR(o2, t48)) n2.push(e3);
  return n2;
}
function ZR(t48, e2) {
  let n2 = [];
  if (e2.isEmpty()) return n2;
  for (let o2 of e2.edges) for (let e3 of WR(o2, t48)) QR(e3, n2) || n2.push(e3);
  return t48.sortPoints(n2);
}
function qR(t48, e2) {
  let n2 = [];
  if (e2.isEmpty()) return n2;
  for (let o2 of e2.edges) for (let e3 of VR(o2, t48)) n2.push(e3);
  return n2;
}
function JR(t48, e2) {
  return t48.isSegment ? BR(e2, t48.shape) : t48.isArc ? HR(e2, t48.shape) : t48.isLine ? WR(e2, t48.shape) : t48.isRay ? (n2 = e2, o2 = t48.shape, n2.isSegment ? eE(o2, n2.shape) : nE(o2, n2.shape)) : [];
  var n2, o2;
}
function KR(t48, e2) {
  let n2 = [];
  if (e2.isEmpty() || t48.shape.box.not_intersect(e2.box)) return n2;
  let o2 = e2.edges.search(t48.shape.box);
  for (let e3 of o2) n2 = [...n2, ...JR(t48, e3)];
  return n2;
}
function QR(t48, e2) {
  return e2.some((e3) => e3.equalTo(t48));
}
function tE(t48) {
  return new PR.Line(t48.start, t48.norm);
}
function eE(t48, e2) {
  return LR(e2, tE(t48)).filter((e3) => t48.contains(e3));
}
function nE(t48, e2) {
  return OR(tE(t48), e2).filter((e3) => t48.contains(e3));
}
function oE(t48, e2) {
  return ER(tE(t48), e2).filter((e3) => t48.contains(e3));
}
function iE(t48, e2) {
  return RR(tE(t48), e2).filter((e3) => t48.contains(e3));
}
function rE(t48, e2) {
  return ZR(tE(t48), e2).filter((e3) => t48.contains(e3));
}
function sE(t48, e2) {
  if (t48.intersect && t48.intersect instanceof Function) return t48.intersect(e2);
  throw MR.UNSUPPORTED_SHAPE_TYPE;
}
function aE(t48, e2) {
  let n2 = [];
  for (let o2 of e2) n2 = [...n2, ...sE(t48, o2.shape)];
  return n2;
}
var cE = class t32 extends CR {
  constructor(...t48) {
    if (super(), this.isInfinite = false, 1 === t48.length && t48[0] instanceof Array && t48[0].length > 0) {
      const e2 = t48[0], n2 = e2.length, o2 = (t49) => t49 instanceof PR.Segment || t49 instanceof PR.Arc || t49 instanceof PR.Ray, i2 = (t49) => t49 instanceof PR.Segment || t49 instanceof PR.Arc;
      if (!(1 === n2 && ((t49) => t49 instanceof PR.Segment || t49 instanceof PR.Arc || t49 instanceof PR.Ray || t49 instanceof PR.Line)(e2[0]) || n2 > 1 && o2(e2[0]) && o2(e2[n2 - 1]) && e2.slice(1, n2 - 1).every(i2))) throw PR.Errors.ILLEGAL_PARAMETERS;
      this.isInfinite = e2.some((t49) => t49 instanceof PR.Ray || t49 instanceof PR.Line);
      for (let t49 of e2) {
        let e3 = new PR.Edge(t49);
        this.append(e3);
      }
      this.setArcLength();
    }
  }
  get edges() {
    return [...this];
  }
  get box() {
    return this.edges.reduce((t48, e2) => t48.merge(e2.box), new PR.Box());
  }
  get vertices() {
    let t48 = this.edges.map((t49) => t49.start);
    return t48.push(this.last.end), t48;
  }
  get length() {
    if (this.isEmpty()) return 0;
    if (this.isInfinite) return Number.POSITIVE_INFINITY;
    let t48 = 0;
    for (let e2 of this) t48 += e2.length;
    return t48;
  }
  clone() {
    return new t32(this.toShapes());
  }
  setArcLength() {
    for (let t48 of this) this.setOneEdgeArcLength(t48);
  }
  setOneEdgeArcLength(t48) {
    t48 === this.first ? t48.arc_length = 0 : t48.arc_length = t48.prev.arc_length + t48.prev.length;
  }
  pointAtLength(t48) {
    if (t48 > this.length || t48 < 0) return null;
    if (this.isInfinite) return null;
    let e2 = null;
    for (let n2 of this) if (t48 >= n2.arc_length && (n2 === this.last || t48 < n2.next.arc_length)) {
      e2 = n2.pointAtLength(t48 - n2.arc_length);
      break;
    }
    return e2;
  }
  addVertex(t48, e2) {
    let n2 = e2.shape.split(t48);
    if (null === n2[0]) return e2.prev;
    if (null === n2[1]) return e2;
    let o2 = new PR.Edge(n2[0]), i2 = e2.prev;
    return this.insert(o2, i2), e2.shape = n2[1], o2;
  }
  getChain(t48, e2) {
    let n2 = [];
    for (let o2 = t48; o2 !== e2.next; o2 = o2.next) n2.push(o2);
    return n2;
  }
  split(t48) {
    for (let e2 of t48) {
      let t49 = this.findEdgeByPoint(e2);
      this.addVertex(e2, t49);
    }
    return this;
  }
  findEdgeByPoint(t48) {
    let e2;
    for (let n2 of this) if (n2.shape.contains(t48)) {
      e2 = n2;
      break;
    }
    return e2;
  }
  distanceTo(t48) {
    if (t48 instanceof Point) {
      const [e2, n2] = PR.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof PR.Line) {
      const [e2, n2] = PR.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof PR.Circle) {
      const [e2, n2] = PR.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof PR.Segment) {
      const [e2, n2] = PR.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof PR.Arc) {
      const [e2, n2] = PR.Distance.shape2multiline(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof PR.Multiline) return PR.Distance.multiline2multiline(this, t48);
    throw PR.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  intersect(t48) {
    return t48 instanceof PR.Multiline ? (function(t49, e2) {
      let n2 = [];
      for (let o2 of t49) for (let t50 of e2) n2 = [...n2, ...sE(o2.shape, t50.shape)];
      return n2;
    })(this, t48) : aE(t48, this);
  }
  contains(t48) {
    if (t48 instanceof PR.Point) return this.edges.some((e2) => e2.shape.contains(t48));
    throw PR.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  translate(e2) {
    return new t32(this.edges.map((t48) => t48.shape.translate(e2)));
  }
  rotate(e2 = 0, n2 = new PR.Point()) {
    return new t32(this.edges.map((t48) => t48.shape.rotate(e2, n2)));
  }
  transform(e2 = new PR.Matrix()) {
    return new t32(this.edges.map((t48) => t48.shape.transform(e2)));
  }
  toShapes() {
    return this.edges.map((t48) => t48.shape.clone());
  }
  toJSON() {
    return this.edges.map((t48) => t48.toJSON());
  }
  svgPoints() {
    return this.vertices.map((t48) => `${t48.x},${t48.y}`).join(" ");
  }
  dpath() {
    let t48 = `M${this.first.start.x},${this.first.start.y}`;
    for (let e2 of this) t48 += e2.svg();
    return t48;
  }
  svg(t48 = {}) {
    let e2 = `
<path ${TR({ fill: "none", ...t48 })} d="`;
    e2 += `
M${this.first.start.x},${this.first.start.y}`;
    for (let t49 of this) e2 += t49.svg();
    return e2 += '" >\n</path>', e2;
  }
};
PR.Multiline = cE;
function lE(t48, e2, n2) {
  let o2 = n2.length, i2 = t48.shape.split(e2);
  if (0 === i2.length) return;
  let r2 = 0;
  r2 = null === i2[0] ? 0 : null === i2[1] ? t48.shape.length : i2[0].length;
  let s2, a2 = 0;
  vR(r2, 0) && (a2 |= 1), vR(r2, t48.shape.length) && (a2 |= 2), s2 = r2 === 1 / 0 ? i2[0].coord(e2) : 2 & a2 && t48.next && 0 === t48.next.arc_length ? 0 : t48.arc_length + r2, n2.push({ id: o2, pt: e2, arc_length: s2, edge_before: t48, edge_after: void 0, face: t48.face, is_vertex: a2 });
}
function hE(t48) {
  t48.int_points1_sorted = dE(t48.int_points1), t48.int_points2_sorted = dE(t48.int_points2);
}
function dE(t48) {
  let e2 = /* @__PURE__ */ new Map(), n2 = 0;
  for (let o2 of t48) e2.has(o2.face) || (e2.set(o2.face, n2), n2++);
  for (let n3 of t48) n3.faceId = e2.get(n3.face);
  return t48.slice().sort(uE);
}
function uE(t48, e2) {
  return t48.faceId < e2.faceId ? -1 : t48.faceId > e2.faceId ? 1 : t48.arc_length < e2.arc_length ? -1 : t48.arc_length > e2.arc_length ? 1 : 0;
}
function pE(t48) {
  if (t48.int_points1.length < 2) return;
  let e2, n2, o2, i2, r2 = false;
  for (let s2 = 0; s2 < t48.int_points1_sorted.length; s2++) if (-1 !== t48.int_points1_sorted[s2].id) {
    e2 = t48.int_points1_sorted[s2], n2 = t48.int_points2[e2.id];
    for (let a2 = s2 + 1; a2 < t48.int_points1_sorted.length && (o2 = t48.int_points1_sorted[a2], vR(o2.arc_length, e2.arc_length)); a2++) -1 !== o2.id && (i2 = t48.int_points2[o2.id], -1 !== i2.id && o2.edge_before === e2.edge_before && o2.edge_after === e2.edge_after && i2.edge_before === n2.edge_before && i2.edge_after === n2.edge_after && (o2.id = -1, i2.id = -1, r2 = true));
  }
  n2 = t48.int_points2_sorted[0], e2 = t48.int_points1[n2.id];
  for (let o3 = 1; o3 < t48.int_points2_sorted.length; o3++) {
    let i3 = t48.int_points2_sorted[o3];
    if (-1 === i3.id) continue;
    if (-1 === n2.id || !vR(i3.arc_length, n2.arc_length)) {
      n2 = i3, e2 = t48.int_points1[n2.id];
      continue;
    }
    let s2 = t48.int_points1[i3.id];
    s2.edge_before === e2.edge_before && s2.edge_after === e2.edge_after && i3.edge_before === n2.edge_before && i3.edge_after === n2.edge_after && (s2.id = -1, i3.id = -1, r2 = true);
  }
  r2 && (t48.int_points1 = t48.int_points1.filter((t49) => t49.id >= 0), t48.int_points2 = t48.int_points2.filter((t49) => t49.id >= 0), t48.int_points1.forEach((t49, e3) => t49.id = e3), t48.int_points2.forEach((t49, e3) => t49.id = e3));
}
function mE(t48) {
  for (let e2 of t48) e2.edge_before && (e2.edge_before.bvStart = void 0, e2.edge_before.bvEnd = void 0, e2.edge_before.bv = void 0, e2.edge_before.overlap = void 0), e2.edge_after && (e2.edge_after.bvStart = void 0, e2.edge_after.bvEnd = void 0, e2.edge_after.bv = void 0, e2.edge_after.overlap = void 0);
  for (let e2 of t48) e2.edge_before && (e2.edge_before.bvEnd = 2), e2.edge_after && (e2.edge_after.bvStart = 2);
}
function gE(t48, e2) {
  for (let n2 of t48) n2.edge_before && n2.edge_before.setInclusion(e2), n2.edge_after && n2.edge_after.setInclusion(e2);
}
function fE(t48, e2, n2) {
  let o2, i2, r2 = 1;
  if (1 === t48.length) return 1;
  o2 = t48[e2];
  for (let s2 = e2 + 1; s2 < t48.length && o2.face === n2 && (i2 = t48[s2], i2.pt.equalTo(o2.pt) && i2.edge_before === o2.edge_before && i2.edge_after === o2.edge_after); s2++) r2++;
  return r2;
}
function _E(t48, e2) {
  if (e2) {
    for (let n2 of e2) {
      let e3 = n2.edge_before;
      if (n2.is_vertex = 0, e3.shape.start && e3.shape.start.equalTo(n2.pt) && (n2.is_vertex |= 1), e3.shape.end && e3.shape.end.equalTo(n2.pt) && (n2.is_vertex |= 2), 1 & n2.is_vertex) {
        n2.edge_before = e3.prev, e3.prev && (n2.is_vertex = 2);
        continue;
      }
      if (2 & n2.is_vertex) continue;
      let o2 = t48.addVertex(n2.pt, e3);
      n2.edge_before = o2;
    }
    for (let n2 of e2) n2.edge_before ? n2.edge_after = n2.edge_before.next : t48 instanceof cE && 1 & n2.is_vertex && (n2.edge_after = t48.first);
  }
}
function yE(t48, e2, n2) {
  const o2 = t48.edge_before, i2 = e2.edge_after, r2 = n2.length;
  o2.next = n2[0], n2[0].prev = o2, n2[r2 - 1].next = i2, i2.prev = n2[r2 - 1];
}
PR.multiline = (...t48) => new PR.Multiline(...t48);
var { INSIDE: bE, OUTSIDE: xE, BOUNDARY: vE, OVERLAP_SAME: SE, OVERLAP_OPPOSITE: IE } = fR;
var { NOT_VERTEX: PE, START_VERTEX: ME, END_VERTEX: CE } = fR;
function NE(t48, e2) {
  let n2 = e2.clone().reverse(), [o2, i2] = OE(t48, n2, 3, true);
  return o2;
}
function wE(t48, e2) {
  let [n2, o2] = OE(t48, e2, 2, true);
  return n2;
}
function TE(t48, e2) {
  let [n2, o2] = OE(t48, e2, 2, false), i2 = [];
  for (let t49 of n2.faces) i2 = [...i2, ...[...t49.edges].map((t50) => t50.shape)];
  let r2 = [];
  for (let t49 of o2.faces) r2 = [...r2, ...[...t49.edges].map((t50) => t50.shape)];
  return [i2, r2];
}
function RE(t48, e2) {
  let [n2, o2] = OE(t48, e2, 3, false), i2 = [];
  for (let t49 of n2.faces) i2 = [...i2, ...[...t49.edges].map((t50) => t50.shape)];
  return i2;
}
function EE(t48, e2) {
  let n2 = t48.clone(), o2 = e2.clone(), i2 = LE(n2, o2);
  return hE(i2), _E(n2, i2.int_points1_sorted), _E(o2, i2.int_points2_sorted), pE(i2), hE(i2), [i2.int_points1_sorted.map((t49) => t49.pt), i2.int_points2_sorted.map((t49) => t49.pt)];
}
function AE(t48, e2, n2, o2) {
  let i2 = DE(t48, n2.int_points1), r2 = DE(e2, n2.int_points2);
  for (zE(i2, e2), zE(r2, t48), mE(n2.int_points1), mE(n2.int_points2), gE(n2.int_points1, e2), gE(n2.int_points2, t48); kE(t48, e2, n2.int_points1, n2.int_points1_sorted, n2.int_points2, n2); ) ;
  !(function(t49) {
    let e3, n3, o3, i3 = t49.int_points1.length;
    for (let r3 = 0; r3 < i3; r3++) {
      let s2 = t49.int_points1_sorted[r3];
      s2.face !== e3 && (n3 = r3, e3 = s2.face);
      let a2, c2 = r3, l2 = fE(t49.int_points1_sorted, r3, e3);
      a2 = c2 + l2 < i3 && t49.int_points1_sorted[c2 + l2].face === e3 ? c2 + l2 : n3;
      let h2 = fE(t49.int_points1_sorted, a2, e3);
      o3 = null;
      for (let n4 = a2; n4 < a2 + h2; n4++) {
        let i4 = t49.int_points1_sorted[n4];
        if (i4.face === e3 && t49.int_points2[i4.id].face === t49.int_points2[s2.id].face) {
          o3 = i4;
          break;
        }
      }
      if (null === o3) continue;
      let d2 = s2.edge_after, u2 = o3.edge_before;
      if (2 !== d2.bv || 2 !== u2.bv) continue;
      if (d2 !== u2) continue;
      let p2 = t49.int_points2[s2.id], m2 = t49.int_points2[o3.id], g2 = p2.edge_after, f2 = m2.edge_before;
      2 === g2.bv && 2 === f2.bv && g2 === f2 || (p2 = t49.int_points2[o3.id], m2 = t49.int_points2[s2.id], g2 = p2.edge_after, f2 = m2.edge_before), 2 === g2.bv && 2 === f2.bv && g2 === f2 && d2.setOverlap(g2);
    }
  })(n2), FE(t48, o2, n2.int_points1_sorted, true), FE(e2, o2, n2.int_points2_sorted, false), $E(t48, i2, o2, true), $E(e2, r2, o2, false);
}
function OE(t48, e2, n2, o2) {
  let i2 = t48.clone(), r2 = e2.clone(), s2 = LE(i2, r2);
  return hE(s2), _E(i2, s2.int_points1_sorted), _E(r2, s2.int_points2_sorted), pE(s2), hE(s2), AE(i2, r2, s2, n2), o2 && (function(t49, e3, n3) {
    !(function(t50, e4, n4, o3) {
      for (let n5 of e4.faces) {
        for (let e5 of n5) t50.edges.add(e5);
        void 0 === o3.find((t51) => t51.face === n5) && t50.addFace(n5.first, n5.last);
      }
    })(t49, e3, 0, n3.int_points2), (function(t50, e4, n4) {
      if (0 !== n4.int_points1.length) for (let t51 = 0; t51 < n4.int_points1.length; t51++) {
        let e5 = n4.int_points1[t51], o3 = n4.int_points2[t51];
        if (void 0 !== e5.edge_before && void 0 === e5.edge_after && void 0 === o3.edge_before && void 0 !== o3.edge_after && (e5.edge_before.next = o3.edge_after, o3.edge_after.prev = e5.edge_before, e5.edge_after = o3.edge_after, o3.edge_before = e5.edge_before), void 0 !== o3.edge_before && void 0 === o3.edge_after && void 0 === e5.edge_before && void 0 !== e5.edge_after && (o3.edge_before.next = e5.edge_after, e5.edge_after.prev = o3.edge_before, o3.edge_after = e5.edge_after, e5.edge_before = o3.edge_before), void 0 !== e5.edge_before && void 0 === e5.edge_after) for (let t52 of n4.int_points1_sorted) t52 !== e5 && void 0 === t52.edge_before && void 0 !== t52.edge_after && t52.pt.equalTo(e5.pt) && (e5.edge_before.next = t52.edge_after, t52.edge_after.prev = e5.edge_before, e5.edge_after = t52.edge_after, t52.edge_before = e5.edge_before);
        if (void 0 !== o3.edge_before && void 0 === o3.edge_after) for (let t52 of n4.int_points2_sorted) t52 !== o3 && void 0 === t52.edge_before && void 0 !== t52.edge_after && t52.pt.equalTo(o3.pt) && (o3.edge_before.next = t52.edge_after, t52.edge_after.prev = o3.edge_before, o3.edge_after = t52.edge_after, t52.edge_before = o3.edge_before);
      }
    })(0, 0, n3), jE(t49, n3.int_points1), jE(e3, n3.int_points2), YE(t49, n3.int_points1, n3.int_points2), YE(t49, n3.int_points2, n3.int_points1), XE(t49), XE(e3);
  })(i2, r2, s2), [i2, r2];
}
function LE(t48, e2) {
  let n2 = { int_points1: [], int_points2: [] };
  for (let o2 of t48.edges) {
    let t49 = e2.edges.search(o2.box);
    for (let e3 of t49) {
      let t50 = o2.shape.intersect(e3.shape);
      for (let i2 of t50) lE(o2, i2, n2.int_points1), lE(e3, i2, n2.int_points2);
    }
  }
  return n2;
}
function DE(t48, e2) {
  let n2 = [];
  for (let o2 of t48.faces) e2.find((t49) => t49.face === o2) || n2.push(o2);
  return n2;
}
function zE(t48, e2) {
  for (let n2 of t48) n2.first.bv = n2.first.bvStart = n2.first.bvEnd = void 0, n2.first.setInclusion(e2);
}
function kE(t48, e2, n2, o2, i2, r2) {
  let s2, a2, c2, l2 = o2.length, h2 = false;
  for (let d2 = 0; d2 < l2; d2++) {
    let u2 = o2[d2];
    u2.face !== s2 && (a2 = d2, s2 = u2.face);
    let p2, m2 = d2, g2 = fE(o2, d2, s2);
    p2 = m2 + g2 < l2 && o2[m2 + g2].face === s2 ? m2 + g2 : a2;
    let f2 = fE(o2, p2, s2);
    c2 = null;
    for (let t49 = p2; t49 < p2 + f2; t49++) {
      let e3 = o2[t49];
      if (e3.face === s2 && i2[e3.id].face === i2[u2.id].face) {
        c2 = e3;
        break;
      }
    }
    if (null === c2) continue;
    let _2 = u2.edge_after, y2 = c2.edge_before;
    if (_2.bv !== vE || y2.bv == vE) if (_2.bv == vE || y2.bv !== vE) {
      if (_2.bv === vE && y2.bv === vE && _2 != y2 || _2.bv === bE && y2.bv === xE || _2.bv === xE && y2.bv === bE) {
        let t49 = _2.next;
        for (; t49 != y2; ) t49.bvStart = void 0, t49.bvEnd = void 0, t49.bv = void 0, t49.setInclusion(e2), t49 = t49.next;
      }
      if (_2.bv === vE && y2.bv === vE && _2 != y2) {
        let t49, e3 = _2.next;
        for (; e3 != y2; ) {
          if (e3.bv != vE) {
            if (void 0 === t49) t49 = e3.bv;
            else if (e3.bv != t49) throw MR.UNRESOLVED_BOUNDARY_CONFLICT;
          }
          e3 = e3.next;
        }
        null != t49 && (_2.bv = t49, y2.bv = t49);
        continue;
      }
      if (_2.bv === bE && y2.bv === xE || _2.bv === xE && y2.bv === bE) {
        let o3 = _2;
        for (; o3 != y2; ) {
          if (o3.bvStart === _2.bv && o3.bvEnd === y2.bv) {
            let [s3, a3] = o3.shape.distanceTo(e2);
            if (s3 < 10 * PR.DP_TOL) {
              lE(o3, a3.ps, n2);
              let s4 = n2[n2.length - 1];
              if (s4.is_vertex & ME) s4.edge_after = o3, s4.edge_before = o3.prev, o3.bvStart = vE, o3.bv = void 0, o3.setInclusion(e2);
              else if (s4.is_vertex & CE) s4.edge_after = o3.next, o3.bvEnd = vE, o3.bv = void 0, o3.setInclusion(e2);
              else {
                let t49 = e2.addVertex(s4.pt, o3);
                s4.edge_before = t49, s4.edge_after = t49.next, t49.setInclusion(e2), t49.next.bvStart = vE, t49.next.bvEnd = void 0, t49.next.bv = void 0, t49.next.setInclusion(e2);
              }
              let c3 = e2.findEdgeByPoint(a3.pe);
              lE(c3, a3.pe, i2);
              let l3 = i2[i2.length - 1];
              if (l3.is_vertex & ME) l3.edge_after = c3, l3.edge_before = c3.prev;
              else if (l3.is_vertex & CE) l3.edge_after = c3.next;
              else {
                let n3 = i2.find((t49) => t49.edge_after === c3), o4 = e2.addVertex(l3.pt, c3);
                l3.edge_before = o4, l3.edge_after = o4.next, n3 && (n3.edge_after = o4), o4.bvStart = void 0, o4.bvEnd = vE, o4.bv = void 0, o4.setInclusion(t48), o4.next.bvStart = vE, o4.next.bvEnd = void 0, o4.next.bv = void 0, o4.next.setInclusion(t48);
              }
              hE(r2), h2 = true;
              break;
            }
          }
          o3 = o3.next;
        }
        if (h2) break;
        throw MR.UNRESOLVED_BOUNDARY_CONFLICT;
      }
    } else y2.bv = _2.bv;
    else _2.bv = y2.bv;
  }
  return h2;
}
function FE(t48, e2, n2, o2) {
  if (!n2) return;
  let i2, r2, s2, a2;
  for (let c2 = 0; c2 < n2.length; c2++) {
    if (s2 = n2[c2], s2.face !== i2 && (r2 = c2, i2 = s2.face), i2.isEmpty()) continue;
    let l2, h2 = c2, d2 = fE(n2, c2, i2);
    l2 = h2 + d2 < n2.length && n2[h2 + d2].face === s2.face ? h2 + d2 : r2, a2 = n2[l2];
    let u2 = l2, p2 = fE(n2, u2, i2), m2 = s2.edge_after, g2 = a2.edge_before;
    if (m2.bv === bE && g2.bv === bE && 1 === e2 || m2.bv === xE && g2.bv === xE && 2 === e2 || (m2.bv === xE || g2.bv === xE) && 3 === e2 && !o2 || (m2.bv === bE || g2.bv === bE) && 3 === e2 && o2 || m2.bv === vE && g2.bv === vE && m2.overlap & SE && o2 || m2.bv === vE && g2.bv === vE && m2.overlap & IE) {
      t48.removeChain(i2, m2, g2);
      for (let t49 = h2; t49 < h2 + d2; t49++) n2[t49].edge_after = void 0;
      for (let t49 = u2; t49 < u2 + p2; t49++) n2[t49].edge_before = void 0;
    }
    c2 += d2 - 1;
  }
}
function jE(t48, e2) {
  for (let n2 of e2) t48.faces.delete(n2.face), n2.face = void 0, n2.edge_before && (n2.edge_before.face = void 0), n2.edge_after && (n2.edge_after.face = void 0);
}
function YE(t48, e2, n2) {
  for (let o2 of e2) {
    if (void 0 === o2.edge_before || void 0 === o2.edge_after) continue;
    if (o2.face) continue;
    if (o2.edge_after.face || o2.edge_before.face) continue;
    let i2 = o2.edge_after, r2 = o2.edge_before;
    try {
      CR.testInfiniteLoop(i2);
    } catch (t49) {
      throw MR.CANNOT_COMPLETE_BOOLEAN_OPERATION;
    }
    let s2 = t48.addFace(i2, r2);
    for (let t49 of e2) t49.edge_before && t49.edge_after && t49.edge_before.face === s2 && t49.edge_after.face === s2 && (t49.face = s2);
    for (let t49 of n2) t49.edge_before && t49.edge_after && t49.edge_before.face === s2 && t49.edge_after.face === s2 && (t49.face = s2);
  }
}
function $E(t48, e2, n2, o2) {
  for (let i2 of e2) {
    let e3 = i2.first.bv;
    (1 === n2 && e3 === bE || 3 === n2 && e3 === bE && o2 || 3 === n2 && e3 === xE && !o2 || 2 === n2 && e3 === xE) && t48.deleteFace(i2);
  }
}
function XE(t48) {
  const e2 = [];
  for (const n2 of t48.edges) n2.face && t48.faces.has(n2.face) || e2.push(n2);
  for (const n2 of e2) t48.edges.delete(n2);
}
var BE = Object.freeze({ __proto__: null, BOOLEAN_INTERSECT: 2, BOOLEAN_SUBTRACT: 3, BOOLEAN_UNION: 1, calculateIntersections: EE, innerClip: TE, intersect: wE, outerClip: RE, removeNotRelevantChains: FE, removeOldFaces: jE, restoreFaces: YE, subtract: NE, unify: function(t48, e2) {
  let [n2, o2] = OE(t48, e2, 1, true);
  return n2;
} });
var HE = RegExp("T.F..FFF.|T.F...F..");
var WE = RegExp("T........|.T.......|...T.....|....T....");
var VE = RegExp("FT.......|F..T.....|F...T....");
var UE = RegExp("T.F..F...");
var GE = RegExp("T.F..F...|.TF..F...|..FT.F...|..F.TF...");
var ZE = class {
  constructor() {
    this.m = new Array(9).fill(void 0);
  }
  get I2I() {
    return this.m[0];
  }
  set I2I(t48) {
    this.m[0] = t48;
  }
  get I2B() {
    return this.m[1];
  }
  set I2B(t48) {
    this.m[1] = t48;
  }
  get I2E() {
    return this.m[2];
  }
  set I2E(t48) {
    this.m[2] = t48;
  }
  get B2I() {
    return this.m[3];
  }
  set B2I(t48) {
    this.m[3] = t48;
  }
  get B2B() {
    return this.m[4];
  }
  set B2B(t48) {
    this.m[4] = t48;
  }
  get B2E() {
    return this.m[5];
  }
  set B2E(t48) {
    this.m[5] = t48;
  }
  get E2I() {
    return this.m[6];
  }
  set E2I(t48) {
    this.m[6] = t48;
  }
  get E2B() {
    return this.m[7];
  }
  set E2B(t48) {
    this.m[7] = t48;
  }
  get E2E() {
    return this.m[8];
  }
  set E2E(t48) {
    this.m[8] = t48;
  }
  toString() {
    return this.m.map((t48) => t48 instanceof Array && t48.length > 0 ? "T" : t48 instanceof Array && 0 === t48.length ? "F" : "*").join("");
  }
  equal() {
    return HE.test(this.toString());
  }
  intersect() {
    return WE.test(this.toString());
  }
  touch() {
    return VE.test(this.toString());
  }
  inside() {
    return UE.test(this.toString());
  }
  covered() {
    return GE.test(this.toString());
  }
};
function qE(t48, e2) {
  let n2, o2 = new PR.Ray(e2), i2 = new PR.Line(o2.pt, o2.norm);
  const r2 = new PR.Box(o2.box.xmin - PR.DP_TOL, o2.box.ymin - PR.DP_TOL, o2.box.xmax + PR.DP_TOL, o2.box.ymax + PR.DP_TOL);
  if (t48.box.not_intersect(r2)) return PR.OUTSIDE;
  let s2 = t48.edges.search(r2);
  if (0 === s2.length) return PR.OUTSIDE;
  for (let t49 of s2) if (t49.shape.contains(e2)) return PR.BOUNDARY;
  let a2 = [...t48.faces], c2 = [];
  for (let t49 of s2) for (let n3 of o2.intersect(t49.shape)) {
    if (n3.equalTo(e2)) return PR.BOUNDARY;
    c2.push({ pt: n3, edge: t49, face_index: a2.indexOf(t49.face) });
  }
  c2.sort((t49, e3) => IR(t49.pt.x, e3.pt.x) ? -1 : SR(t49.pt.x, e3.pt.x) ? 1 : t49.face_index < e3.face_index ? -1 : t49.face_index > e3.face_index ? 1 : t49.edge.arc_length < e3.edge.arc_length ? -1 : t49.edge.arc_length > e3.edge.arc_length ? 1 : 0);
  let l2 = 0;
  for (let t49 = 0; t49 < c2.length; t49++) {
    let e3 = c2[t49];
    if (e3.pt.equalTo(e3.edge.shape.start)) {
      if (t49 > 0 && e3.pt.equalTo(c2[t49 - 1].pt) && e3.face_index === c2[t49 - 1].face_index && e3.edge.prev === c2[t49 - 1].edge) continue;
      let n3 = e3.edge.prev;
      for (; xR(n3.length); ) n3 = n3.prev;
      let o3 = n3.shape.tangentInEnd(), r3 = e3.pt.translate(o3), s3 = e3.edge.shape.tangentInStart(), a3 = e3.pt.translate(s3), h2 = r3.leftTo(i2), d2 = a3.leftTo(i2);
      (h2 && !d2 || !h2 && d2) && l2++;
    } else if (e3.pt.equalTo(e3.edge.shape.end)) {
      if (t49 > 0 && e3.pt.equalTo(c2[t49 - 1].pt) && e3.face_index === c2[t49 - 1].face_index && e3.edge.next === c2[t49 - 1].edge) continue;
      let n3 = e3.edge.next;
      for (; xR(n3.length); ) n3 = n3.next;
      let o3 = n3.shape.tangentInStart(), r3 = e3.pt.translate(o3), s3 = e3.edge.shape.tangentInEnd(), a3 = e3.pt.translate(s3), h2 = r3.leftTo(i2), d2 = a3.leftTo(i2);
      (h2 && !d2 || !h2 && d2) && l2++;
    } else if (e3.edge.shape instanceof PR.Segment) l2++;
    else {
      let t50 = e3.edge.shape.box;
      vR(e3.pt.y, t50.ymin) || vR(e3.pt.y, t50.ymax) || l2++;
    }
  }
  return n2 = l2 % 2 == 1 ? 1 : 0, n2;
}
function JE(t48, e2) {
  return eA(t48, e2).intersect();
}
function KE(t48, e2) {
  return eA(t48, e2).inside();
}
function QE(t48, e2) {
  return eA(t48, e2).covered();
}
function tA(t48, e2) {
  return QE(e2, t48);
}
function eA(t48, e2) {
  return t48 instanceof PR.Line && e2 instanceof PR.Line ? (function(t49, e3) {
    let n2 = new ZE(), o2 = RR(t49, e3);
    0 === o2.length ? t49.contains(e3.pt) && e3.contains(t49.pt) ? (n2.I2I = [t49], n2.I2E = [], n2.E2I = []) : (n2.I2I = [], n2.I2E = [t49], n2.E2I = [e3]) : (n2.I2I = o2, n2.I2E = t49.split(o2), n2.E2I = e3.split(o2));
    return n2;
  })(t48, e2) : t48 instanceof PR.Line && e2 instanceof PR.Circle ? (function(t49, e3) {
    let n2 = new ZE(), o2 = ER(t49, e3);
    if (0 === o2.length) n2.I2I = [], n2.I2B = [], n2.I2E = [t49], n2.E2I = [e3];
    else if (1 === o2.length) n2.I2I = [], n2.I2B = o2, n2.I2E = t49.split(o2), n2.E2I = [e3];
    else {
      let i2 = new cE([t49]), r2 = t49.sortPoints(o2);
      i2.split(r2);
      let s2 = i2.toShapes();
      n2.I2I = [s2[1]], n2.I2B = r2, n2.I2E = [s2[0], s2[2]], n2.E2I = new PR.Polygon([e3.toArc()]).cutWithLine(t49);
    }
    return n2;
  })(t48, e2) : t48 instanceof PR.Line && e2 instanceof PR.Box ? (function(t49, e3) {
    let n2 = new ZE(), o2 = AR(t49, e3);
    if (0 === o2.length) n2.I2I = [], n2.I2B = [], n2.I2E = [t49], n2.E2I = [e3];
    else if (1 === o2.length) n2.I2I = [], n2.I2B = o2, n2.I2E = t49.split(o2), n2.E2I = [e3];
    else {
      let i2 = new cE([t49]), r2 = t49.sortPoints(o2);
      i2.split(r2);
      let s2 = i2.toShapes();
      e3.toSegments().some((t50) => t50.contains(o2[0]) && t50.contains(o2[1])) ? (n2.I2I = [], n2.I2B = [s2[1]], n2.I2E = [s2[0], s2[2]], n2.E2I = [e3]) : (n2.I2I = [s2[1]], n2.I2B = r2, n2.I2E = [s2[0], s2[2]], n2.E2I = new PR.Polygon(e3.toSegments()).cutWithLine(t49));
    }
    return n2;
  })(t48, e2) : t48 instanceof PR.Line && e2 instanceof PR.Polygon ? (function(t49, e3) {
    let n2 = new ZE(), o2 = ZR(t49, e3), i2 = new cE([t49]), r2 = o2.length > 0 ? o2.slice() : t49.sortPoints(o2);
    return i2.split(r2), [...i2].forEach((t50) => t50.setInclusion(e3)), n2.I2I = [...i2].filter((t50) => t50.bv === PR.INSIDE).map((t50) => t50.shape), n2.I2B = [...i2].slice(1).map((t50) => t50.bv === PR.BOUNDARY ? t50.shape : t50.shape.start), n2.I2E = [...i2].filter((t50) => t50.bv === PR.OUTSIDE).map((t50) => t50.shape), n2.E2I = e3.cutWithLine(t49), n2;
  })(t48, e2) : (t48 instanceof PR.Segment || t48 instanceof PR.Arc) && e2 instanceof PR.Polygon ? nA(t48, e2) : (t48 instanceof PR.Segment || t48 instanceof PR.Arc) && (e2 instanceof PR.Circle || e2 instanceof PR.Box) ? nA(t48, new PR.Polygon(e2)) : t48 instanceof PR.Polygon && e2 instanceof PR.Polygon ? oA(t48, e2) : (t48 instanceof PR.Circle || t48 instanceof PR.Box) && (e2 instanceof PR.Circle || e2 instanceof PR.Box) ? oA(new PR.Polygon(t48), new PR.Polygon(e2)) : (t48 instanceof PR.Circle || t48 instanceof PR.Box) && e2 instanceof PR.Polygon ? oA(new PR.Polygon(t48), e2) : t48 instanceof PR.Polygon && (e2 instanceof PR.Circle || e2 instanceof PR.Box) ? oA(t48, new PR.Polygon(e2)) : void 0;
}
function nA(t48, e2) {
  let n2 = new ZE(), o2 = (function(t49, e3) {
    return t49 instanceof PR.Line ? ZR(t49, e3) : t49 instanceof PR.Segment ? UR(t49, e3) : t49 instanceof PR.Arc ? GR(t49, e3) : [];
  })(t48, e2), i2 = o2.length > 0 ? o2.slice() : t48.sortPoints(o2), r2 = new cE([t48]);
  r2.split(i2), [...r2].forEach((t49) => t49.setInclusion(e2)), n2.I2I = [...r2].filter((t49) => t49.bv === PR.INSIDE).map((t49) => t49.shape), n2.I2B = [...r2].slice(1).map((t49) => t49.bv === PR.BOUNDARY ? t49.shape : t49.shape.start), n2.I2E = [...r2].filter((t49) => t49.bv === PR.OUTSIDE).map((t49) => t49.shape), n2.B2I = [], n2.B2B = [], n2.B2E = [];
  for (let o3 of [t48.start, t48.end]) switch (qE(e2, o3)) {
    case PR.INSIDE:
      n2.B2I.push(o3);
      break;
    case PR.BOUNDARY:
      n2.B2B.push(o3);
      break;
    case PR.OUTSIDE:
      n2.B2E.push(o3);
  }
  return n2;
}
function oA(t48, e2) {
  let n2 = new ZE(), [o2, i2] = EE(t48, e2), r2 = wE(t48, e2), s2 = NE(t48, e2), a2 = NE(e2, t48), [c2, l2] = TE(t48, e2), h2 = RE(t48, e2), d2 = RE(e2, t48);
  return n2.I2I = r2.isEmpty() ? [] : [r2], n2.I2B = l2, n2.I2E = s2.isEmpty() ? [] : [s2], n2.B2I = c2, n2.B2B = o2, n2.B2E = h2, n2.E2I = a2.isEmpty() ? [] : [a2], n2.E2B = d2, n2;
}
var iA = Object.freeze({ __proto__: null, contain: function(t48, e2) {
  return KE(e2, t48);
}, cover: tA, covered: QE, disjoint: function(t48, e2) {
  return !JE(t48, e2);
}, equal: function(t48, e2) {
  return eA(t48, e2).equal();
}, inside: KE, intersect: JE, relate: eA, touch: function(t48, e2) {
  return eA(t48, e2).touch();
} });
var rA = class t33 {
  constructor(t48 = 1, e2 = 0, n2 = 0, o2 = 1, i2 = 0, r2 = 0) {
    this.a = t48, this.b = e2, this.c = n2, this.d = o2, this.tx = i2, this.ty = r2;
  }
  fromMatrix3x3(e2) {
    const [n2, o2, i2] = e2[0], [r2, s2, a2] = e2[1];
    return new t33(n2, r2, o2, s2, i2, a2);
  }
  toMatrix3x3() {
    return [[this.a, this.c, this.tx], [this.b, this.d, this.ty], [0, 0, 1]];
  }
  clone() {
    return new t33(this.a, this.b, this.c, this.d, this.tx, this.ty);
  }
  transform(t48) {
    return [t48[0] * this.a + t48[1] * this.c + this.tx, t48[0] * this.b + t48[1] * this.d + this.ty];
  }
  multiply(e2) {
    return new t33(this.a * e2.a + this.c * e2.b, this.b * e2.a + this.d * e2.b, this.a * e2.c + this.c * e2.d, this.b * e2.c + this.d * e2.d, this.a * e2.tx + this.c * e2.ty + this.tx, this.b * e2.tx + this.d * e2.ty + this.ty);
  }
  translate(...e2) {
    let n2, o2;
    if (1 != e2.length || isNaN(e2[0].x) || isNaN(e2[0].y)) {
      if (2 !== e2.length || "number" != typeof e2[0] || "number" != typeof e2[1]) throw MR.ILLEGAL_PARAMETERS;
      n2 = e2[0], o2 = e2[1];
    } else n2 = e2[0].x, o2 = e2[0].y;
    return this.multiply(new t33(1, 0, 0, 1, n2, o2));
  }
  rotate(e2, n2 = 0, o2 = 0) {
    let i2 = Math.cos(e2), r2 = Math.sin(e2);
    return this.translate(n2, o2).multiply(new t33(i2, r2, -r2, i2, 0, 0)).translate(-n2, -o2);
  }
  scale(e2, n2) {
    return this.multiply(new t33(e2, 0, 0, n2, 0, 0));
  }
  equalTo(t48) {
    return !!PR.Utils.EQ(this.tx, t48.tx) && (!!PR.Utils.EQ(this.ty, t48.ty) && (!!PR.Utils.EQ(this.a, t48.a) && (!!PR.Utils.EQ(this.b, t48.b) && (!!PR.Utils.EQ(this.c, t48.c) && !!PR.Utils.EQ(this.d, t48.d)))));
  }
};
PR.Matrix = rA;
PR.matrix = (...t48) => new PR.Matrix(...t48);
var sA = class {
  constructor(t48, e2) {
    this.low = t48, this.high = e2;
  }
  get max() {
    return this.clone();
  }
  less_than(t48) {
    return this.low < t48.low || this.low === t48.low && this.high < t48.high;
  }
  equal_to(t48) {
    return this.low === t48.low && this.high === t48.high;
  }
  intersect(t48) {
    return !this.not_intersect(t48);
  }
  not_intersect(t48) {
    return this.high < t48.low || t48.high < this.low;
  }
  merge(t48) {
    const e2 = void 0 === this.low ? t48.low : this.low < t48.low ? this.low : t48.low, n2 = void 0 === this.high ? t48.high : this.high > t48.high ? this.high : t48.high, o2 = this.clone();
    return o2.low = e2, o2.high = n2, o2;
  }
  output() {
    return [this.low, this.high];
  }
  comparable_less_than(t48, e2) {
    return t48 < e2;
  }
};
var aA = class t34 extends sA {
  clone() {
    return new t34(this.low, this.high);
  }
};
var cA = class {
  constructor(t48, e2, n2 = null, o2 = null, i2 = null, r2 = 0) {
    if (this.left = n2, this.right = o2, this.parent = i2, this.color = r2, this.item = { key: void 0, values: [] }, void 0 !== e2 && this.item.values.push(e2), void 0 !== t48) if (Array.isArray(t48)) {
      const [e3, n3] = t48;
      if (!Number.isNaN(e3) && !Number.isNaN(n3)) {
        let t49 = e3, o3 = n3;
        t49 > o3 && ([t49, o3] = [o3, t49]), this.item.key = new aA(t49, o3);
      }
    } else this.item.key = t48;
    this.max = this.item.key ? this.item.key.max : void 0;
  }
  isNil() {
    return void 0 === this.item.key && 0 === this.item.values.length && null === this.left && null === this.right && 0 === this.color;
  }
  requireKey() {
    if (!this.item.key) throw new Error("Node key is undefined (nil/sentinel). Operation is not applicable.");
    return this.item.key;
  }
  less_than(t48) {
    const e2 = this.requireKey(), n2 = t48.requireKey();
    return e2.less_than(n2);
  }
  _value_equal(t48) {
    const e2 = this.item.values[0], n2 = t48.item.values[0];
    return e2 && n2 && e2.equal_to ? e2.equal_to(n2) : e2 === n2;
  }
  equal_to(t48) {
    const e2 = this.requireKey(), n2 = t48.requireKey();
    return e2.equal_to(n2);
  }
  intersect(t48) {
    const e2 = this.requireKey(), n2 = t48.requireKey();
    return e2.intersect(n2);
  }
  copy_data(t48) {
    this.item.key = t48.item.key, this.item.values = t48.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(t48) {
    if (!this.left) return true;
    const e2 = this.left.max ? this.left.max.high : this.left.item.key.high, n2 = this.requireKey(), o2 = t48.requireKey();
    return n2.comparable_less_than(e2, o2.low);
  }
  not_intersect_right_subtree(t48) {
    if (!this.right) return true;
    const e2 = this.right.max ? this.right.max.low : this.right.item.key.low, n2 = this.requireKey(), o2 = t48.requireKey();
    return n2.comparable_less_than(o2.high, e2);
  }
};
var lA = class t35 {
  constructor() {
    this.root = null, this.nil_node = new cA();
  }
  get size() {
    let t48 = 0;
    return this.tree_walk(this.root, (e2) => t48 += e2.item.values.length), t48;
  }
  get keys() {
    const t48 = [];
    return this.tree_walk(this.root, (e2) => t48.push(e2.item.key.output())), t48;
  }
  get values() {
    const t48 = [];
    return this.tree_walk(this.root, (e2) => {
      for (const n2 of e2.item.values) t48.push(n2);
    }), t48;
  }
  get items() {
    const t48 = [];
    return this.tree_walk(this.root, (e2) => {
      const n2 = e2.item.key.output();
      for (const o2 of e2.item.values) t48.push({ key: n2, value: o2 });
    }), t48;
  }
  isEmpty() {
    return null == this.root || this.root === this.nil_node;
  }
  clear() {
    this.root = null;
  }
  insert(t48, e2 = t48) {
    if (void 0 === t48) return;
    const n2 = this.tree_search(this.root, new cA(t48));
    if (n2) return n2.item.values.push(e2), n2;
    const o2 = new cA(t48, e2, this.nil_node, this.nil_node, null, 1);
    return this.tree_insert(o2), this.recalc_max(o2), o2;
  }
  exist(t48, e2 = t48) {
    const n2 = this.tree_search(this.root, new cA(t48));
    return !!n2 && (arguments.length < 2 || e2 === t48 || n2.item.values.some((t49) => t49 && t49.equal_to ? t49.equal_to(e2) : t49 === e2));
  }
  remove(t48, e2 = t48) {
    const n2 = this.tree_search(this.root, new cA(t48));
    if (!n2) return;
    if (arguments.length < 2) return this.tree_delete(n2), n2;
    const o2 = n2.item.values.findIndex((t49) => t49 && t49.equal_to ? t49.equal_to(e2) : t49 === e2);
    return o2 >= 0 ? (n2.item.values.splice(o2, 1), 0 === n2.item.values.length && this.tree_delete(n2), n2) : void 0;
  }
  search(t48, e2 = (t49, e3) => t49 === e3 ? e3.output() : t49) {
    const n2 = new cA(t48), o2 = [];
    this.tree_search_interval(this.root, n2, o2);
    const i2 = [];
    for (const t49 of o2) for (const n3 of t49.item.values) i2.push(e2(n3, t49.item.key));
    return i2;
  }
  intersect_any(t48) {
    const e2 = new cA(t48);
    return this.tree_find_any_interval(this.root, e2);
  }
  forEach(t48) {
    this.tree_walk(this.root, (e2) => {
      for (const n2 of e2.item.values) t48(e2.item.key, n2);
    });
  }
  map(e2) {
    const n2 = new t35();
    return this.tree_walk(this.root, (t48) => {
      for (const o2 of t48.item.values) n2.insert(t48.item.key, e2(o2, t48.item.key));
    }), n2;
  }
  *iterate(t48, e2 = (t49, e3) => t49 === e3 ? e3.output() : t49) {
    let n2 = null;
    for (t48 ? n2 = this.tree_search_nearest_forward(this.root, new cA(t48)) : this.root && (n2 = this.local_minimum(this.root)); n2; ) {
      for (const t49 of n2.item.values) yield e2(t49, n2.item.key);
      n2 = this.tree_successor(n2);
    }
  }
  recalc_max(t48) {
    let e2 = t48;
    for (; null != e2.parent; ) e2.parent.update_max(), e2 = e2.parent;
  }
  tree_insert(t48) {
    let e2 = this.root, n2 = null;
    if (null == this.root || this.root === this.nil_node) this.root = t48;
    else {
      for (; e2 !== this.nil_node; ) n2 = e2, e2 = t48.less_than(e2) ? e2.left : e2.right;
      t48.parent = n2, t48.less_than(n2) ? n2.left = t48 : n2.right = t48;
    }
    this.insert_fixup(t48);
  }
  insert_fixup(t48) {
    let e2, n2;
    for (e2 = t48; e2 !== this.root && 1 === e2.parent.color; ) e2.parent === e2.parent.parent.left ? (n2 = e2.parent.parent.right, 1 === n2.color ? (e2.parent.color = 0, n2.color = 0, e2.parent.parent.color = 1, e2 = e2.parent.parent) : (e2 === e2.parent.right && (e2 = e2.parent, this.rotate_left(e2)), e2.parent.color = 0, e2.parent.parent.color = 1, this.rotate_right(e2.parent.parent))) : (n2 = e2.parent.parent.left, 1 === n2.color ? (e2.parent.color = 0, n2.color = 0, e2.parent.parent.color = 1, e2 = e2.parent.parent) : (e2 === e2.parent.left && (e2 = e2.parent, this.rotate_right(e2)), e2.parent.color = 0, e2.parent.parent.color = 1, this.rotate_left(e2.parent.parent)));
    this.root.color = 0;
  }
  tree_delete(t48) {
    let e2, n2;
    e2 = t48.left === this.nil_node || t48.right === this.nil_node ? t48 : this.tree_successor(t48), n2 = e2.left !== this.nil_node ? e2.left : e2.right, n2.parent = e2.parent, e2 === this.root ? this.root = n2 : (e2 === e2.parent.left ? e2.parent.left = n2 : e2.parent.right = n2, e2.parent.update_max()), this.recalc_max(n2), e2 !== t48 && (t48.copy_data(e2), t48.update_max(), this.recalc_max(t48)), 0 === e2.color && this.delete_fixup(n2);
  }
  delete_fixup(t48) {
    let e2, n2 = t48;
    for (; n2 !== this.root && null != n2.parent && 0 === n2.color; ) n2 === n2.parent.left ? (e2 = n2.parent.right, 1 === e2.color && (e2.color = 0, n2.parent.color = 1, this.rotate_left(n2.parent), e2 = n2.parent.right), 0 === e2.left.color && 0 === e2.right.color ? (e2.color = 1, n2 = n2.parent) : (0 === e2.right.color && (e2.color = 1, e2.left.color = 0, this.rotate_right(e2), e2 = n2.parent.right), e2.color = n2.parent.color, n2.parent.color = 0, e2.right.color = 0, this.rotate_left(n2.parent), n2 = this.root)) : (e2 = n2.parent.left, 1 === e2.color && (e2.color = 0, n2.parent.color = 1, this.rotate_right(n2.parent), e2 = n2.parent.left), 0 === e2.left.color && 0 === e2.right.color ? (e2.color = 1, n2 = n2.parent) : (0 === e2.left.color && (e2.color = 1, e2.right.color = 0, this.rotate_left(e2), e2 = n2.parent.left), e2.color = n2.parent.color, n2.parent.color = 0, e2.left.color = 0, this.rotate_right(n2.parent), n2 = this.root));
    n2.color = 0;
  }
  tree_search(t48, e2) {
    if (null != t48 && t48 !== this.nil_node) return e2.equal_to(t48) ? t48 : e2.less_than(t48) ? this.tree_search(t48.left, e2) : this.tree_search(t48.right, e2);
  }
  tree_search_nearest_forward(t48, e2) {
    let n2 = null, o2 = t48;
    for (; o2 && o2 !== this.nil_node; ) o2.less_than(e2) ? o2.intersect(e2) ? (n2 = o2, o2 = o2.left) : o2 = o2.right : (n2 && !o2.less_than(n2) || (n2 = o2), o2 = o2.left);
    return n2 || null;
  }
  tree_search_interval(t48, e2, n2) {
    null != t48 && t48 !== this.nil_node && (t48.left === this.nil_node || t48.not_intersect_left_subtree(e2) || this.tree_search_interval(t48.left, e2, n2), t48.intersect(e2) && n2.push(t48), t48.right === this.nil_node || t48.not_intersect_right_subtree(e2) || this.tree_search_interval(t48.right, e2, n2));
  }
  tree_find_any_interval(t48, e2) {
    let n2 = false;
    return null != t48 && t48 !== this.nil_node && (t48.left === this.nil_node || t48.not_intersect_left_subtree(e2) || (n2 = this.tree_find_any_interval(t48.left, e2)), n2 || (n2 = t48.intersect(e2)), n2 || t48.right === this.nil_node || t48.not_intersect_right_subtree(e2) || (n2 = this.tree_find_any_interval(t48.right, e2))), n2;
  }
  local_minimum(t48) {
    let e2 = t48;
    for (; null != e2.left && e2.left !== this.nil_node; ) e2 = e2.left;
    return e2;
  }
  local_maximum(t48) {
    let e2 = t48;
    for (; null != e2.right && e2.right !== this.nil_node; ) e2 = e2.right;
    return e2;
  }
  tree_successor(t48) {
    let e2, n2, o2;
    if (t48.right !== this.nil_node) e2 = this.local_minimum(t48.right);
    else {
      for (n2 = t48, o2 = t48.parent; null != o2 && o2.right === n2; ) n2 = o2, o2 = o2.parent;
      e2 = o2;
    }
    return e2;
  }
  rotate_left(t48) {
    const e2 = t48.right;
    t48.right = e2.left, e2.left !== this.nil_node && (e2.left.parent = t48), e2.parent = t48.parent, t48 === this.root ? this.root = e2 : t48 === t48.parent.left ? t48.parent.left = e2 : t48.parent.right = e2, e2.left = t48, t48.parent = e2, null !== t48 && t48 !== this.nil_node && t48.update_max(), null != e2 && e2 !== this.nil_node && e2.update_max();
  }
  rotate_right(t48) {
    const e2 = t48.left;
    t48.left = e2.right, e2.right !== this.nil_node && (e2.right.parent = t48), e2.parent = t48.parent, t48 === this.root ? this.root = e2 : t48 === t48.parent.left ? t48.parent.left = e2 : t48.parent.right = e2, e2.right = t48, t48.parent = e2, null !== t48 && t48 !== this.nil_node && t48.update_max(), null != e2 && e2 !== this.nil_node && e2.update_max();
  }
  tree_walk(t48, e2) {
    null != t48 && t48 !== this.nil_node && (this.tree_walk(t48.left, e2), e2(t48), this.tree_walk(t48.right, e2));
  }
  testRedBlackProperty() {
    let t48 = true;
    return this.tree_walk(this.root, function(e2) {
      1 === e2.color && (0 === e2.left.color && 0 === e2.right.color || (t48 = false));
    }), t48;
  }
  testBlackHeightProperty(t48) {
    let e2 = 0, n2 = 0, o2 = 0;
    if (0 === t48.color && e2++, n2 = t48.left !== this.nil_node ? this.testBlackHeightProperty(t48.left) : 1, o2 = t48.right !== this.nil_node ? this.testBlackHeightProperty(t48.right) : 1, n2 !== o2) throw new Error("Red-black height property violated");
    return e2 += n2, e2;
  }
};
var hA = class extends Set {
  constructor(t48) {
    super(t48), this.index = new lA(), this.forEach((t49) => this.index.insert(t49));
  }
  add(t48) {
    let e2 = this.size;
    const { key: n2, value: o2 } = t48, i2 = n2 || t48.box, r2 = o2 || t48;
    return super.add(r2), this.size > e2 && this.index.insert(i2, r2), this;
  }
  delete(t48) {
    const { key: e2, value: n2 } = t48, o2 = e2 || t48.box, i2 = n2 || t48;
    let r2 = super.delete(i2);
    return r2 && this.index.remove(o2, i2), r2;
  }
  clear() {
    super.clear(), this.index = new lA();
  }
  search(t48) {
    return this.index.search(t48);
  }
  hit(t48) {
    let e2 = new PR.Box(t48.x - 1, t48.y - 1, t48.x + 1, t48.y + 1);
    return this.index.search(e2).filter((e3) => t48.on(e3));
  }
  svg() {
    return [...this].reduce((t48, e2) => t48 + e2.svg(), "");
  }
};
PR.PlanarSet = hA;
var dA = class {
  get name() {
    throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  get box() {
    throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  clone() {
    throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  translate(...t48) {
    return this.transform(new rA().translate(...t48));
  }
  rotate(t48, e2 = new PR.Point()) {
    return this.transform(new rA().rotate(t48, e2.x, e2.y));
  }
  scale(t48, e2) {
    return this.transform(new rA().scale(t48, e2));
  }
  transform(...t48) {
    throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
  toJSON() {
    return Object.assign({}, this, { name: this.name });
  }
  svg(t48 = {}) {
    throw MR.CANNOT_INVOKE_ABSTRACT_METHOD;
  }
};
PR.Point = class t36 extends dA {
  constructor(...t48) {
    if (super(), this.x = 0, this.y = 0, 0 !== t48.length) {
      if (1 === t48.length && t48[0] instanceof Array && 2 === t48[0].length) {
        let e2 = t48[0];
        if ("number" == typeof e2[0] && "number" == typeof e2[1]) return this.x = e2[0], void (this.y = e2[1]);
      }
      if (1 === t48.length && t48[0] instanceof Object && "point" === t48[0].name) {
        let { x: e2, y: n2 } = t48[0];
        return this.x = e2, void (this.y = n2);
      }
      if (2 === t48.length && "number" == typeof t48[0] && "number" == typeof t48[1]) return this.x = t48[0], void (this.y = t48[1]);
      throw MR.ILLEGAL_PARAMETERS;
    }
  }
  get box() {
    return new PR.Box(this.x, this.y, this.x, this.y);
  }
  clone() {
    return new PR.Point(this.x, this.y);
  }
  get vertices() {
    return [this.clone()];
  }
  equalTo(t48) {
    return PR.Utils.EQ(this.x, t48.x) && PR.Utils.EQ(this.y, t48.y);
  }
  lessThan(t48) {
    return !!PR.Utils.LT(this.y, t48.y) || !(!PR.Utils.EQ(this.y, t48.y) || !PR.Utils.LT(this.x, t48.x));
  }
  transform(t48) {
    return new PR.Point(t48.transform([this.x, this.y]));
  }
  projectionOn(t48) {
    if (this.equalTo(t48.pt)) return this.clone();
    let e2 = new PR.Vector(this, t48.pt);
    if (PR.Utils.EQ_0(e2.cross(t48.norm))) return t48.pt.clone();
    let n2 = e2.dot(t48.norm), o2 = t48.norm.multiply(n2);
    return this.translate(o2);
  }
  leftTo(t48) {
    let e2 = new PR.Vector(t48.pt, this);
    return PR.Utils.GT(e2.dot(t48.norm), 0);
  }
  distanceTo(e2) {
    if (e2 instanceof t36) {
      let t48 = e2.x - this.x, n2 = e2.y - this.y;
      return [Math.sqrt(t48 * t48 + n2 * n2), new PR.Segment(this, e2)];
    }
    return e2 instanceof PR.Line ? PR.Distance.point2line(this, e2) : e2 instanceof PR.Circle ? PR.Distance.point2circle(this, e2) : e2 instanceof PR.Segment ? PR.Distance.point2segment(this, e2) : e2 instanceof PR.Arc ? PR.Distance.point2arc(this, e2) : e2 instanceof PR.Polygon ? PR.Distance.point2polygon(this, e2) : e2 instanceof PR.PlanarSet ? PR.Distance.shape2planarSet(this, e2) : e2 instanceof PR.Multiline ? PR.Distance.shape2multiline(this, e2) : void 0;
  }
  on(t48) {
    if (t48 instanceof PR.Point) return this.equalTo(t48);
    if (t48.contains && t48.contains instanceof Function) return t48.contains(this);
    throw PR.Errors.UNSUPPORTED_SHAPE_TYPE;
  }
  get name() {
    return "point";
  }
  svg(t48 = {}) {
    const e2 = t48.r ?? 3;
    return `
<circle cx="${this.x}" cy="${this.y}" r="${e2}"
            ${TR({ fill: "red", ...t48 })} />`;
  }
};
var uA = (...t48) => new PR.Point(...t48);
PR.point = uA;
PR.Vector = class extends dA {
  constructor(...t48) {
    if (super(), this.x = 0, this.y = 0, 0 !== t48.length) {
      if (1 === t48.length && t48[0] instanceof Array && 2 === t48[0].length) {
        let e2 = t48[0];
        if ("number" == typeof e2[0] && "number" == typeof e2[1]) return this.x = e2[0], void (this.y = e2[1]);
      }
      if (1 === t48.length && t48[0] instanceof Object && "vector" === t48[0].name) {
        let { x: e2, y: n2 } = t48[0];
        return this.x = e2, void (this.y = n2);
      }
      if (1 === t48.length && t48[0] instanceof Object && "segment" === t48[0].name) {
        let { start: e2, end: n2 } = t48[0];
        return this.x = n2.x - e2.x, void (this.y = n2.y - e2.y);
      }
      if (2 === t48.length) {
        let e2 = t48[0], n2 = t48[1];
        if ("number" == typeof e2 && "number" == typeof n2) return this.x = e2, void (this.y = n2);
        if (e2 instanceof PR.Point && n2 instanceof PR.Point) return this.x = n2.x - e2.x, void (this.y = n2.y - e2.y);
      }
      throw MR.ILLEGAL_PARAMETERS;
    }
  }
  clone() {
    return new PR.Vector(this.x, this.y);
  }
  get slope() {
    let t48 = Math.atan2(this.y, this.x);
    return t48 < 0 && (t48 = 2 * Math.PI + t48), t48;
  }
  get length() {
    return Math.sqrt(this.dot(this));
  }
  isZeroLength() {
    return PR.Utils.EQ_0(this.length);
  }
  equalTo(t48) {
    return PR.Utils.EQ(this.x, t48.x) && PR.Utils.EQ(this.y, t48.y);
  }
  multiply(t48) {
    return new PR.Vector(t48 * this.x, t48 * this.y);
  }
  dot(t48) {
    return this.x * t48.x + this.y * t48.y;
  }
  cross(t48) {
    return this.x * t48.y - this.y * t48.x;
  }
  normalize() {
    if (this.isZeroLength()) throw MR.ZERO_DIVISION;
    return new PR.Vector(this.x / this.length, this.y / this.length);
  }
  rotate(t48, e2 = new PR.Point()) {
    if (0 === e2.x && 0 === e2.y) return this.transform(new rA().rotate(t48));
    throw MR.OPERATION_IS_NOT_SUPPORTED;
  }
  transform(t48) {
    return new PR.Vector(t48.transform([this.x, this.y]));
  }
  rotate90CCW() {
    return new PR.Vector(-this.y, this.x);
  }
  rotate90CW() {
    return new PR.Vector(this.y, -this.x);
  }
  invert() {
    return new PR.Vector(-this.x, -this.y);
  }
  add(t48) {
    return new PR.Vector(this.x + t48.x, this.y + t48.y);
  }
  subtract(t48) {
    return new PR.Vector(this.x - t48.x, this.y - t48.y);
  }
  angleTo(t48) {
    let e2 = this.normalize(), n2 = t48.normalize(), o2 = Math.atan2(e2.cross(n2), e2.dot(n2));
    return o2 < 0 && (o2 += 2 * Math.PI), o2;
  }
  projectionOn(t48) {
    let e2 = t48.normalize(), n2 = this.dot(e2);
    return e2.multiply(n2);
  }
  get name() {
    return "vector";
  }
};
var pA = (...t48) => new PR.Vector(...t48);
PR.vector = pA;
PR.Segment = class t37 extends dA {
  constructor(...t48) {
    if (super(), this.ps = new PR.Point(), this.pe = new PR.Point(), 0 !== t48.length) {
      if (1 === t48.length && t48[0] instanceof Array && 4 === t48[0].length) {
        let e2 = t48[0];
        return this.ps = new PR.Point(e2[0], e2[1]), void (this.pe = new PR.Point(e2[2], e2[3]));
      }
      if (1 === t48.length && t48[0] instanceof Object && "segment" === t48[0].name) {
        let { ps: e2, pe: n2 } = t48[0];
        return this.ps = new PR.Point(e2.x, e2.y), void (this.pe = new PR.Point(n2.x, n2.y));
      }
      if (!(1 === t48.length && t48[0] instanceof PR.Point)) {
        if (2 === t48.length && t48[0] instanceof PR.Point && t48[1] instanceof PR.Point) return this.ps = t48[0].clone(), void (this.pe = t48[1].clone());
        if (4 === t48.length) return this.ps = new PR.Point(t48[0], t48[1]), void (this.pe = new PR.Point(t48[2], t48[3]));
        throw MR.ILLEGAL_PARAMETERS;
      }
      this.ps = t48[0].clone();
    }
  }
  clone() {
    return new PR.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 PR.Vector(this.start, this.end).slope;
  }
  get box() {
    return new PR.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(t48) {
    return this.ps.equalTo(t48.ps) && this.pe.equalTo(t48.pe);
  }
  contains(t48) {
    return PR.Utils.EQ_0(this.distanceToPoint(t48));
  }
  intersect(t48) {
    return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? LR(this, t48) : t48 instanceof PR.Ray ? eE(t48, this) : t48 instanceof PR.Segment ? DR(this, t48) : t48 instanceof PR.Circle ? FR(this, t48) : t48 instanceof PR.Box ? (function(t49, e2) {
      let n2 = [];
      for (let o2 of e2.toSegments()) {
        let e3 = DR(o2, t49);
        for (let t50 of e3) n2.push(t50);
      }
      return n2;
    })(this, t48) : t48 instanceof PR.Arc ? jR(this, t48) : t48 instanceof PR.Polygon ? UR(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;
  }
  distanceTo(t48) {
    if (t48 instanceof PR.Point) {
      let [e2, n2] = PR.Distance.point2segment(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Circle) {
      let [e2, n2] = PR.Distance.segment2circle(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Line) {
      let [e2, n2] = PR.Distance.segment2line(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Segment) {
      let [e2, n2] = PR.Distance.segment2segment(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Arc) {
      let [e2, n2] = PR.Distance.segment2arc(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Polygon) {
      let [e2, n2] = PR.Distance.shape2polygon(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.PlanarSet) {
      let [e2, n2] = PR.Distance.shape2planarSet(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Multiline) return PR.Distance.shape2multiline(this, t48);
  }
  tangentInStart() {
    return new PR.Vector(this.start, this.end).normalize();
  }
  tangentInEnd() {
    return new PR.Vector(this.end, this.start).normalize();
  }
  reverse() {
    return new t37(this.end, this.start);
  }
  split(t48) {
    return this.start.equalTo(t48) ? [null, this.clone()] : this.end.equalTo(t48) ? [this.clone(), null] : [new PR.Segment(this.start, t48), new PR.Segment(t48, this.end)];
  }
  middle() {
    return new PR.Point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2);
  }
  pointAtLength(t48) {
    if (t48 > this.length || t48 < 0) return null;
    if (0 == t48) return this.start;
    if (t48 == this.length) return this.end;
    let e2 = t48 / this.length;
    return new PR.Point((this.end.x - this.start.x) * e2 + this.start.x, (this.end.y - this.start.y) * e2 + this.start.y);
  }
  distanceToPoint(t48) {
    let [e2, ...n2] = PR.Distance.point2segment(t48, this);
    return e2;
  }
  definiteIntegral(t48 = 0) {
    return (this.end.x - this.start.x) * (this.start.y - t48 + (this.end.y - t48)) / 2;
  }
  transform(e2 = new PR.Matrix()) {
    return new t37(this.ps.transform(e2), this.pe.transform(e2));
  }
  isZeroLength() {
    return this.ps.equalTo(this.pe);
  }
  sortPoints(t48) {
    return new PR.Line(this.start, this.end).sortPoints(t48);
  }
  get name() {
    return "segment";
  }
  svg(t48 = {}) {
    return `
<line x1="${this.start.x}" y1="${this.start.y}" x2="${this.end.x}" y2="${this.end.y}" ${TR(t48)} />`;
  }
};
var mA = (...t48) => new PR.Segment(...t48);
PR.segment = mA;
var { vector: gA } = PR;
PR.Line = class t38 extends dA {
  constructor(...e2) {
    if (super(), this.pt = new PR.Point(), this.norm = new PR.Vector(0, 1), 0 !== e2.length) {
      if (1 === e2.length && e2[0] instanceof Object && "line" === e2[0].name) {
        let { pt: t48, norm: n2 } = e2[0];
        return this.pt = new PR.Point(t48), void (this.norm = new PR.Vector(n2));
      }
      if (2 === e2.length) {
        let n2 = e2[0], o2 = e2[1];
        if (n2 instanceof PR.Point && o2 instanceof PR.Point) return this.pt = n2, this.norm = t38.points2norm(n2, o2), void (this.norm.dot(gA(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        if (n2 instanceof PR.Point && o2 instanceof PR.Vector) {
          if (PR.Utils.EQ_0(o2.x) && PR.Utils.EQ_0(o2.y)) throw MR.ILLEGAL_PARAMETERS;
          return this.pt = n2.clone(), this.norm = o2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(gA(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        }
        if (n2 instanceof PR.Vector && o2 instanceof PR.Point) {
          if (PR.Utils.EQ_0(n2.x) && PR.Utils.EQ_0(n2.y)) throw MR.ILLEGAL_PARAMETERS;
          return this.pt = o2.clone(), this.norm = n2.clone(), this.norm = this.norm.normalize(), void (this.norm.dot(gA(this.pt.x, this.pt.y)) >= 0 && this.norm.invert());
        }
      }
      throw MR.ILLEGAL_PARAMETERS;
    }
  }
  clone() {
    return new PR.Line(this.pt, this.norm);
  }
  get start() {
  }
  get end() {
  }
  get length() {
    return Number.POSITIVE_INFINITY;
  }
  get box() {
    return new PR.Box(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
  }
  get middle() {
  }
  get slope() {
    return new PR.Vector(this.norm.y, -this.norm.x).slope;
  }
  get standard() {
    return [this.norm.x, this.norm.y, this.norm.dot(gA(this.pt.x, this.pt.y))];
  }
  parallelTo(t48) {
    return PR.Utils.EQ_0(this.norm.cross(t48.norm));
  }
  incidentTo(t48) {
    return this.parallelTo(t48) && this.pt.on(t48);
  }
  contains(t48) {
    if (this.pt.equalTo(t48)) return true;
    let e2 = new PR.Vector(this.pt, t48);
    return PR.Utils.EQ_0(this.norm.dot(e2));
  }
  coord(t48) {
    return gA(t48.x, t48.y).cross(this.norm);
  }
  intersect(t48) {
    return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? RR(this, t48) : t48 instanceof PR.Ray ? iE(t48, this) : t48 instanceof PR.Circle ? ER(this, t48) : t48 instanceof PR.Box ? AR(this, t48) : t48 instanceof PR.Segment ? LR(t48, this) : t48 instanceof PR.Arc ? OR(this, t48) : t48 instanceof PR.Polygon ? ZR(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;
  }
  distanceTo(t48) {
    if (t48 instanceof PR.Point) {
      let [e2, n2] = PR.Distance.point2line(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Circle) {
      let [e2, n2] = PR.Distance.circle2line(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Segment) {
      let [e2, n2] = PR.Distance.segment2line(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof PR.Arc) {
      let [e2, n2] = PR.Distance.arc2line(t48, this);
      return [e2, n2.reverse()];
    }
    if (t48 instanceof PR.Polygon) {
      let [e2, n2] = PR.Distance.shape2polygon(this, t48);
      return [e2, n2];
    }
  }
  split(t48) {
    if (t48 instanceof PR.Point) return [new PR.Ray(t48, this.norm), new PR.Ray(t48, this.norm)];
    {
      let e2 = new PR.Multiline([this]), n2 = this.sortPoints(t48);
      return e2.split(n2), e2.toShapes();
    }
  }
  rotate(t48, e2 = new PR.Point()) {
    return new PR.Line(this.pt.rotate(t48, e2), this.norm.rotate(t48));
  }
  transform(t48) {
    return new PR.Line(this.pt.transform(t48), this.norm.clone());
  }
  sortPoints(t48) {
    return t48.slice().sort((t49, e2) => this.coord(t49) < this.coord(e2) ? -1 : this.coord(t49) > this.coord(e2) ? 1 : 0);
  }
  get name() {
    return "line";
  }
  svg(t48, e2 = {}) {
    let n2 = AR(this, t48);
    if (0 === n2.length) return "";
    let o2 = n2[0], i2 = 2 === n2.length ? n2[1] : n2.find((t49) => !t49.equalTo(o2));
    return void 0 === i2 && (i2 = o2), new PR.Segment(o2, i2).svg(e2);
  }
  static points2norm(t48, e2) {
    if (t48.equalTo(e2)) throw MR.ILLEGAL_PARAMETERS;
    return new PR.Vector(t48, e2).normalize().rotate90CCW();
  }
};
var fA = (...t48) => new PR.Line(...t48);
PR.line = fA;
PR.Circle = class extends dA {
  constructor(...t48) {
    if (super(), this.pc = new PR.Point(), this.r = 1, 1 === t48.length && t48[0] instanceof Object && "circle" === t48[0].name) {
      let { pc: e2, r: n2 } = t48[0];
      this.pc = new PR.Point(e2), this.r = n2;
    } else {
      let [e2, n2] = [...t48];
      e2 && e2 instanceof PR.Point && (this.pc = e2.clone()), void 0 !== n2 && (this.r = n2);
    }
  }
  clone() {
    return new PR.Circle(this.pc.clone(), this.r);
  }
  get center() {
    return this.pc;
  }
  get box() {
    return new PR.Box(this.pc.x - this.r, this.pc.y - this.r, this.pc.x + this.r, this.pc.y + this.r);
  }
  contains(t48) {
    return t48 instanceof PR.Point ? PR.Utils.LE(t48.distanceTo(this.center)[0], this.r) : t48 instanceof PR.Segment ? PR.Utils.LE(t48.start.distanceTo(this.center)[0], this.r) && PR.Utils.LE(t48.end.distanceTo(this.center)[0], this.r) : t48 instanceof PR.Arc ? 0 === this.intersect(t48).length && PR.Utils.LE(t48.start.distanceTo(this.center)[0], this.r) && PR.Utils.LE(t48.end.distanceTo(this.center)[0], this.r) : t48 instanceof PR.Circle ? 0 === this.intersect(t48).length && PR.Utils.LE(t48.r, this.r) && PR.Utils.LE(t48.center.distanceTo(this.center)[0], this.r) : void 0;
  }
  toArc(t48 = true) {
    return new PR.Arc(this.center, this.r, Math.PI, -Math.PI, t48);
  }
  scale(t48, e2) {
    if (t48 !== e2) throw MR.OPERATION_IS_NOT_SUPPORTED;
    if (0 !== this.pc.x || 0 !== this.pc.y) throw MR.OPERATION_IS_NOT_SUPPORTED;
    return new PR.Circle(this.pc, this.r * t48);
  }
  transform(t48 = new PR.Matrix()) {
    return new PR.Circle(this.pc.transform(t48), this.r);
  }
  intersect(t48) {
    return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? ER(t48, this) : t48 instanceof PR.Ray ? oE(t48, this) : t48 instanceof PR.Segment ? FR(t48, this) : t48 instanceof PR.Circle ? YR(t48, this) : t48 instanceof PR.Box ? (function(t49, e2) {
      let n2 = [];
      for (let o2 of e2.toSegments()) {
        let e3 = FR(o2, t49);
        for (let t50 of e3) n2.push(t50);
      }
      return n2;
    })(this, t48) : t48 instanceof PR.Arc ? XR(t48, this) : t48 instanceof PR.Polygon ? qR(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;
  }
  distanceTo(t48) {
    if (t48 instanceof PR.Point) {
      let [e2, n2] = PR.Distance.point2circle(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Circle) {
      let [e2, n2] = PR.Distance.circle2circle(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Line) {
      let [e2, n2] = PR.Distance.circle2line(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Segment) {
      let [e2, n2] = PR.Distance.segment2circle(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Arc) {
      let [e2, n2] = PR.Distance.arc2circle(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Polygon) {
      let [e2, n2] = PR.Distance.shape2polygon(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.PlanarSet) {
      let [e2, n2] = PR.Distance.shape2planarSet(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Multiline) {
      let [e2, n2] = PR.Distance.shape2multiline(this, t48);
      return [e2, n2];
    }
  }
  get name() {
    return "circle";
  }
  svg(t48 = {}) {
    return `
<circle cx="${this.pc.x}" cy="${this.pc.y}" r="${this.r}"
                ${TR({ fill: "none", ...t48 })} />`;
  }
};
PR.circle = (...t48) => new PR.Circle(...t48);
PR.Arc = class extends dA {
  constructor(...t48) {
    if (super(), this.pc = new PR.Point(), this.r = 1, this.startAngle = 0, this.endAngle = 2 * Math.PI, this.counterClockwise = true, 0 !== t48.length) if (1 === t48.length && t48[0] instanceof Object && "arc" === t48[0].name) {
      let { pc: e2, r: n2, startAngle: o2, endAngle: i2, counterClockwise: r2 } = t48[0];
      this.pc = new PR.Point(e2.x, e2.y), this.r = n2, this.startAngle = o2, this.endAngle = i2, this.counterClockwise = r2;
    } else {
      let [e2, n2, o2, i2, r2] = [...t48];
      e2 && e2 instanceof PR.Point && (this.pc = e2.clone()), void 0 !== n2 && (this.r = n2), void 0 !== o2 && (this.startAngle = o2), void 0 !== i2 && (this.endAngle = i2), void 0 !== r2 && (this.counterClockwise = r2);
    }
  }
  clone() {
    return new PR.Arc(this.pc.clone(), this.r, this.startAngle, this.endAngle, this.counterClockwise);
  }
  get sweep() {
    let t48 = this.startAngle, e2 = this.endAngle;
    if (PR.Utils.EQ(Math.abs(t48 - e2), PR.PIx2)) return PR.PIx2;
    Math.abs(t48) > PR.PIx2 && (t48 -= Math.trunc(t48 / PR.PIx2) * PR.PIx2), t48 < 0 && (t48 += PR.PIx2), Math.abs(e2) > PR.PIx2 && (e2 -= Math.trunc(e2 / PR.PIx2) * PR.PIx2), e2 < 0 && (e2 += PR.PIx2);
    let n2 = this.counterClockwise ? e2 - t48 : t48 - e2;
    return n2 < 0 && (n2 += PR.PIx2), n2;
  }
  get start() {
    return new PR.Point(this.pc.x + this.r, this.pc.y).rotate(this.startAngle, this.pc);
  }
  get end() {
    return new PR.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 t48 = this.breakToFunctional().reduce((t49, e2) => t49.merge(e2.start.box), new PR.Box());
    return t48 = t48.merge(this.end.box), t48;
  }
  contains(t48) {
    if (!PR.Utils.EQ(this.pc.distanceTo(t48)[0], this.r)) return false;
    if (t48.equalTo(this.start)) return true;
    let e2 = new PR.Vector(this.pc, t48).slope, n2 = new PR.Arc(this.pc, this.r, this.startAngle, e2, this.counterClockwise);
    return PR.Utils.LE(n2.length, this.length);
  }
  split(t48) {
    if (this.start.equalTo(t48)) return [null, this.clone()];
    if (this.end.equalTo(t48)) return [this.clone(), null];
    let e2 = new PR.Vector(this.pc, t48).slope;
    return [new PR.Arc(this.pc, this.r, this.startAngle, e2, this.counterClockwise), new PR.Arc(this.pc, this.r, e2, this.endAngle, this.counterClockwise)];
  }
  middle() {
    let t48 = this.counterClockwise ? this.startAngle + this.sweep / 2 : this.startAngle - this.sweep / 2;
    return new PR.Arc(this.pc, this.r, this.startAngle, t48, this.counterClockwise).end;
  }
  pointAtLength(t48) {
    if (t48 > this.length || t48 < 0) return null;
    if (0 === t48) return this.start;
    if (t48 === this.length) return this.end;
    let e2 = t48 / this.length, n2 = this.counterClockwise ? this.startAngle + this.sweep * e2 : this.startAngle - this.sweep * e2;
    return new PR.Arc(this.pc, this.r, this.startAngle, n2, this.counterClockwise).end;
  }
  chordHeight() {
    return (1 - Math.cos(Math.abs(this.sweep / 2))) * this.r;
  }
  intersect(t48) {
    return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? OR(t48, this) : t48 instanceof PR.Ray ? nE(t48, this) : t48 instanceof PR.Circle ? XR(this, t48) : t48 instanceof PR.Segment ? jR(t48, this) : t48 instanceof PR.Box ? (function(t49, e2) {
      let n2 = [];
      for (let o2 of e2.toSegments()) {
        let e3 = jR(o2, t49);
        for (let t50 of e3) n2.push(t50);
      }
      return n2;
    })(this, t48) : t48 instanceof PR.Arc ? $R(this, t48) : t48 instanceof PR.Polygon ? GR(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;
  }
  distanceTo(t48) {
    if (t48 instanceof PR.Point) {
      let [e2, n2] = PR.Distance.point2arc(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Circle) {
      let [e2, n2] = PR.Distance.arc2circle(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Line) {
      let [e2, n2] = PR.Distance.arc2line(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Segment) {
      let [e2, n2] = PR.Distance.segment2arc(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Arc) {
      let [e2, n2] = PR.Distance.arc2arc(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Polygon) {
      let [e2, n2] = PR.Distance.shape2polygon(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.PlanarSet) {
      let [e2, n2] = PR.Distance.shape2planarSet(this, t48);
      return [e2, n2];
    }
    if (t48 instanceof PR.Multiline) return PR.Distance.shape2multiline(this, t48);
  }
  breakToFunctional() {
    let t48 = [], e2 = [0, Math.PI / 2, Math.PI, 3 * Math.PI / 2], n2 = this.startAngle, o2 = this.endAngle;
    PR.Utils.EQ(Math.abs(n2 - o2), PR.PIx2) && (o2 = n2), Math.abs(n2) > PR.PIx2 && (n2 -= Math.trunc(n2 / PR.PIx2) * PR.PIx2), n2 < 0 && (n2 += PR.PIx2), Math.abs(o2) > PR.PIx2 && (o2 -= Math.trunc(o2 / PR.PIx2) * PR.PIx2), o2 < 0 && (o2 += PR.PIx2);
    let i2, r2, s2, a2 = n2;
    this.counterClockwise ? (r2 = Math.ceil(n2 / (Math.PI / 2)) % 4, s2 = 1) : (r2 = Math.floor(n2 / (Math.PI / 2)) % 4, s2 = -1);
    for (let o3 = 0, c2 = r2; o3 < 4; o3++, c2 = (c2 + s2 + 4) % 4) {
      if (i2 = e2[c2], i2 === a2) continue;
      let o4 = this.counterClockwise ? i2 - n2 : n2 - i2;
      if (o4 < 0 && (o4 += PR.PIx2), o4 > this.sweep) break;
      t48.push(new PR.Arc(this.pc, this.r, a2, i2, this.counterClockwise)), a2 = i2;
    }
    return 0 === t48.length ? (t48.push(this), t48) : (i2 = o2, a2 !== i2 && t48.push(new PR.Arc(this.pc, this.r, a2, i2, this.counterClockwise)), t48);
  }
  tangentInStart() {
    let t48 = new PR.Vector(this.pc, this.start), e2 = this.counterClockwise ? Math.PI / 2 : -Math.PI / 2;
    return t48.rotate(e2).normalize();
  }
  tangentInEnd() {
    let t48 = new PR.Vector(this.pc, this.end), e2 = this.counterClockwise ? -Math.PI / 2 : Math.PI / 2;
    return t48.rotate(e2).normalize();
  }
  reverse() {
    return new PR.Arc(this.pc, this.r, this.endAngle, this.startAngle, !this.counterClockwise);
  }
  transform(t48 = new PR.Matrix()) {
    let e2 = this.start.transform(t48), n2 = this.end.transform(t48), o2 = this.pc.transform(t48), i2 = this.counterClockwise;
    return t48.a * t48.d < 0 && (i2 = !i2), PR.Arc.arcSE(o2, e2, n2, i2);
  }
  static arcSE(t48, e2, n2, o2) {
    let { vector: i2 } = PR, r2 = i2(t48, e2).slope, s2 = i2(t48, n2).slope;
    PR.Utils.EQ(r2, s2) && (s2 += 2 * Math.PI, o2 = true);
    let a2 = i2(t48, e2).length;
    return new PR.Arc(t48, a2, r2, s2, o2);
  }
  definiteIntegral(t48 = 0) {
    return this.breakToFunctional().reduce((e2, n2) => e2 + n2.circularSegmentDefiniteIntegral(t48), 0);
  }
  circularSegmentDefiniteIntegral(t48) {
    let e2 = new PR.Segment(this.start, this.end).definiteIntegral(t48), n2 = PR.Utils.EQ(this.sweep, PR.PIx2) ? 0 : this.circularSegmentArea();
    return this.counterClockwise ? e2 - n2 : e2 + n2;
  }
  circularSegmentArea() {
    return 0.5 * this.r * this.r * (this.sweep - Math.sin(this.sweep));
  }
  sortPoints(t48) {
    let { vector: e2 } = PR;
    return t48.slice().sort((t49, n2) => {
      let o2 = e2(this.pc, t49).slope, i2 = e2(this.pc, n2).slope;
      return o2 < i2 ? -1 : o2 > i2 ? 1 : 0;
    });
  }
  get name() {
    return "arc";
  }
  svg(t48 = {}) {
    let e2 = this.sweep <= Math.PI ? "0" : "1", n2 = this.counterClockwise ? "1" : "0";
    if (PR.Utils.EQ(this.sweep, 2 * Math.PI)) {
      return new PR.Circle(this.pc, this.r).svg(t48);
    }
    return `
<path d="M${this.start.x},${this.start.y}
                             A${this.r},${this.r} 0 ${e2},${n2} ${this.end.x},${this.end.y}"
                    ${TR({ fill: "none", ...t48 })} />`;
  }
};
PR.arc = (...t48) => new PR.Arc(...t48);
PR.Box = class t39 extends dA {
  constructor(t48 = void 0, e2 = void 0, n2 = void 0, o2 = void 0) {
    super(), this.xmin = t48, this.ymin = e2, this.xmax = n2, this.ymax = o2;
  }
  clone() {
    return new t39(this.xmin, this.ymin, this.xmax, this.ymax);
  }
  get low() {
    return new PR.Point(this.xmin, this.ymin);
  }
  get high() {
    return new PR.Point(this.xmax, this.ymax);
  }
  get max() {
    return this.clone();
  }
  get center() {
    return new PR.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(t48) {
    return this.xmax < t48.xmin || this.xmin > t48.xmax || this.ymax < t48.ymin || this.ymin > t48.ymax;
  }
  intersect(t48) {
    return !this.not_intersect(t48);
  }
  merge(e2) {
    return new t39(void 0 === this.xmin ? e2.xmin : Math.min(this.xmin, e2.xmin), void 0 === this.ymin ? e2.ymin : Math.min(this.ymin, e2.ymin), void 0 === this.xmax ? e2.xmax : Math.max(this.xmax, e2.xmax), void 0 === this.ymax ? e2.ymax : Math.max(this.ymax, e2.ymax));
  }
  less_than(t48) {
    return !!this.low.lessThan(t48.low) || !(!this.low.equalTo(t48.low) || !this.high.lessThan(t48.high));
  }
  equal_to(t48) {
    return this.low.equalTo(t48.low) && this.high.equalTo(t48.high);
  }
  output() {
    return this.clone();
  }
  comparable_less_than(t48, e2) {
    return t48.lessThan(e2);
  }
  set(t48, e2, n2, o2) {
    this.xmin = t48, this.ymin = e2, this.xmax = n2, this.ymax = o2;
  }
  extend(e2) {
    return e2 <= 0 ? this.clone() : new t39(this.xmin - e2, this.ymin - e2, this.xmax + e2, this.ymax + e2);
  }
  toPoints() {
    return [new PR.Point(this.xmin, this.ymin), new PR.Point(this.xmax, this.ymin), new PR.Point(this.xmax, this.ymax), new PR.Point(this.xmin, this.ymax)];
  }
  toSegments() {
    let t48 = this.toPoints();
    return [new PR.Segment(t48[0], t48[1]), new PR.Segment(t48[1], t48[2]), new PR.Segment(t48[2], t48[3]), new PR.Segment(t48[3], t48[0])];
  }
  rotate(t48, e2 = new PR.Point()) {
    throw MR.OPERATION_IS_NOT_SUPPORTED;
  }
  transform(e2 = new PR.Matrix()) {
    return this.toPoints().map((t48) => t48.transform(e2)).reduce((t48, e3) => t48.merge(e3.box), new t39());
  }
  contains(t48) {
    return t48 instanceof PR.Point ? t48.x >= this.xmin && t48.x <= this.xmax && t48.y >= this.ymin && t48.y <= this.ymax : t48 instanceof PR.Segment ? t48.vertices.every((t49) => this.contains(t49)) : t48 instanceof PR.Box ? t48.toSegments().every((t49) => this.contains(t49)) : t48 instanceof PR.Circle ? this.contains(t48.box) : t48 instanceof PR.Arc ? t48.vertices.every((t49) => this.contains(t49)) && this.toSegments().every((e2) => 0 === jR(e2, t48).length) : !(t48 instanceof PR.Line || t48 instanceof PR.Ray) && (t48 instanceof PR.Multiline ? t48.toShapes().every((t49) => this.contains(t49)) : t48 instanceof PR.Polygon ? this.contains(t48.box) : void 0);
  }
  distanceTo(t48) {
    const e2 = this.toSegments().map((e3) => e3.distanceTo(t48));
    let n2 = [Number.MAX_SAFE_INTEGER, null];
    return e2.forEach((t49) => {
      t49[0] < n2[0] && (n2 = t49);
    }), n2;
  }
  get name() {
    return "box";
  }
  svg(t48 = {}) {
    const e2 = this.xmax - this.xmin, n2 = this.ymax - this.ymin;
    return `
<rect x="${this.xmin}" y="${this.ymin}" width="${e2}" height="${n2}"
                ${TR({ fill: "none", ...t48 })} />`;
  }
};
PR.box = (...t48) => new PR.Box(...t48);
PR.Edge = class {
  constructor(t48) {
    this.shape = t48, 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 PR.Segment;
  }
  get isArc() {
    return this.shape instanceof PR.Arc;
  }
  get isLine() {
    return this.shape instanceof PR.Line;
  }
  get isRay() {
    return this.shape instanceof PR.Ray;
  }
  middle() {
    return this.shape.middle();
  }
  pointAtLength(t48) {
    return this.shape.pointAtLength(t48);
  }
  contains(t48) {
    return this.shape.contains(t48);
  }
  setInclusion(t48) {
    if (void 0 !== this.bv) return this.bv;
    if (this.shape instanceof PR.Line || this.shape instanceof PR.Ray) return this.bv = PR.OUTSIDE, this.bv;
    if (void 0 === this.bvStart && (this.bvStart = qE(t48, this.start)), void 0 === this.bvEnd && (this.bvEnd = qE(t48, this.end)), this.bvStart === PR.OUTSIDE || this.bvEnd == PR.OUTSIDE) this.bv = PR.OUTSIDE;
    else if (this.bvStart === PR.INSIDE || this.bvEnd == PR.INSIDE) this.bv = PR.INSIDE;
    else {
      let e2 = qE(t48, this.middle());
      this.bv = e2;
    }
    return this.bv;
  }
  setOverlap(t48) {
    let e2, n2 = this.shape, o2 = t48.shape;
    n2 instanceof PR.Segment && o2 instanceof PR.Segment ? n2.start.equalTo(o2.start) && n2.end.equalTo(o2.end) ? e2 = PR.OVERLAP_SAME : n2.start.equalTo(o2.end) && n2.end.equalTo(o2.start) && (e2 = PR.OVERLAP_OPPOSITE) : (n2 instanceof PR.Arc && o2 instanceof PR.Arc || n2 instanceof PR.Segment && o2 instanceof PR.Arc || n2 instanceof PR.Arc && o2 instanceof PR.Segment) && (n2.start.equalTo(o2.start) && n2.end.equalTo(o2.end) && n2.middle().equalTo(o2.middle()) ? e2 = PR.OVERLAP_SAME : n2.start.equalTo(o2.end) && n2.end.equalTo(o2.start) && n2.middle().equalTo(o2.middle()) && (e2 = PR.OVERLAP_OPPOSITE)), void 0 === this.overlap && (this.overlap = e2), void 0 === t48.overlap && (t48.overlap = e2);
  }
  svg() {
    if (this.shape instanceof PR.Segment) return ` L${this.shape.end.x},${this.shape.end.y}`;
    if (this.shape instanceof PR.Arc) {
      let t48, e2 = this.shape, n2 = e2.counterClockwise ? "1" : "0";
      if (PR.Utils.EQ(e2.sweep, 2 * Math.PI)) {
        let o2 = e2.counterClockwise ? 1 : -1, i2 = new PR.Arc(e2.pc, e2.r, e2.startAngle, e2.startAngle + o2 * Math.PI, e2.counterClockwise), r2 = new PR.Arc(e2.pc, e2.r, e2.startAngle + o2 * Math.PI, e2.endAngle, e2.counterClockwise);
        return t48 = "0", ` A${i2.r},${i2.r} 0 ${t48},${n2} ${i2.end.x},${i2.end.y}
                    A${r2.r},${r2.r} 0 ${t48},${n2} ${r2.end.x},${r2.end.y}`;
      }
      return t48 = e2.sweep <= Math.PI ? "0" : "1", ` A${e2.r},${e2.r} 0 ${t48},${n2} ${e2.end.x},${e2.end.y}`;
    }
  }
  toJSON() {
    return this.shape.toJSON();
  }
};
var _A = class extends CR {
  constructor(t48, e2) {
    super(t48, e2), this.setCircularLinks();
  }
  setCircularLinks() {
    this.isEmpty() || (this.last.next = this.first, this.first.prev = this.last);
  }
  [Symbol.iterator]() {
    let t48;
    return { next: () => {
      let e2 = t48 || this.first, n2 = !this.first || !!t48 && t48 === this.first;
      return t48 = e2 ? e2.next : void 0, { value: e2, done: n2 };
    } };
  }
  append(t48) {
    return super.append(t48), this.setCircularLinks(), this;
  }
  insert(t48, e2) {
    return super.insert(t48, e2), this.setCircularLinks(), this;
  }
  remove(t48) {
    return super.remove(t48), this;
  }
};
PR.Face = class t40 extends _A {
  constructor(e2, ...n2) {
    if (super(), this._box = void 0, this._orientation = void 0, 0 !== n2.length) {
      if (1 === n2.length) {
        if (n2[0] instanceof Array) {
          let o2 = n2[0];
          if (0 === o2.length) return;
          if (o2.every((t48) => t48 instanceof PR.Point)) {
            let n3 = t40.points2segments(o2);
            this.shapes2face(e2.edges, n3);
          } else if (o2.every((t48) => t48 instanceof Array && 2 === t48.length)) {
            let n3 = o2.map((t48) => new PR.Point(t48[0], t48[1])), i2 = t40.points2segments(n3);
            this.shapes2face(e2.edges, i2);
          } else if (o2.every((t48) => t48 instanceof PR.Segment || t48 instanceof PR.Arc)) this.shapes2face(e2.edges, o2);
          else if (o2.every((t48) => "segment" === t48.name || "arc" === t48.name)) {
            let t48 = [];
            for (let e3 of o2) {
              let n3;
              n3 = "segment" === e3.name ? new PR.Segment(e3) : new PR.Arc(e3), t48.push(n3);
            }
            this.shapes2face(e2.edges, t48);
          }
        } else if (n2[0] instanceof t40) {
          let t48 = n2[0];
          this.first = t48.first, this.last = t48.last;
          for (let n3 of t48) e2.edges.add(n3);
        } else if (n2[0] instanceof PR.Circle) this.shapes2face(e2.edges, [n2[0].toArc(pR)]);
        else if (n2[0] instanceof PR.Box) {
          let t48 = n2[0];
          this.shapes2face(e2.edges, [new PR.Segment(new PR.Point(t48.xmin, t48.ymin), new PR.Point(t48.xmax, t48.ymin)), new PR.Segment(new PR.Point(t48.xmax, t48.ymin), new PR.Point(t48.xmax, t48.ymax)), new PR.Segment(new PR.Point(t48.xmax, t48.ymax), new PR.Point(t48.xmin, t48.ymax)), new PR.Segment(new PR.Point(t48.xmin, t48.ymax), new PR.Point(t48.xmin, t48.ymin))]);
        }
      }
      2 === n2.length && n2[0] instanceof PR.Edge && n2[1] instanceof PR.Edge && (this.first = n2[0], this.last = n2[1], this.last.next = this.first, this.first.prev = this.last, this.setArcLength());
    }
  }
  get edges() {
    return this.toArray();
  }
  get vertices() {
    return this.edges.map((t48) => t48.shape.start.clone());
  }
  get shapes() {
    return this.edges.map((t48) => t48.shape.clone());
  }
  get box() {
    if (void 0 === this._box) {
      let t48 = new PR.Box();
      for (let e2 of this) t48 = t48.merge(e2.box);
      this._box = t48;
    }
    return this._box;
  }
  get perimeter() {
    return this.last.arc_length + this.last.length;
  }
  pointAtLength(t48) {
    if (t48 > this.perimeter || t48 < 0) return null;
    let e2 = null;
    for (let n2 of this) if (t48 >= n2.arc_length && (n2 === this.last || t48 < n2.next.arc_length)) {
      e2 = n2.pointAtLength(t48 - n2.arc_length);
      break;
    }
    return e2;
  }
  static points2segments(t48) {
    let e2 = [];
    for (let n2 = 0; n2 < t48.length; n2++) t48[n2].equalTo(t48[(n2 + 1) % t48.length]) || e2.push(new PR.Segment(t48[n2], t48[(n2 + 1) % t48.length]));
    return e2;
  }
  shapes2face(t48, e2) {
    for (let n2 of e2) {
      let e3 = new PR.Edge(n2);
      this.append(e3), t48.add(e3);
    }
  }
  append(t48) {
    return super.append(t48), this.setOneEdgeArcLength(t48), t48.face = this, this;
  }
  insert(t48, e2) {
    return super.insert(t48, e2), this.setOneEdgeArcLength(t48), t48.face = this, this;
  }
  remove(t48) {
    return super.remove(t48), this.setArcLength(), this;
  }
  merge_with_next_edge(t48) {
    return t48.shape.end.x = t48.next.shape.end.x, t48.shape.end.y = t48.next.shape.end.y, this.remove(t48.next), this;
  }
  reverse() {
    let t48 = [], e2 = this.last;
    do {
      e2.shape = e2.shape.reverse(), t48.push(e2), e2 = e2.prev;
    } while (e2 !== this.last);
    this.first = void 0, this.last = void 0;
    for (let e3 of t48) void 0 === this.first ? (e3.prev = e3, e3.next = e3, this.first = e3, this.last = e3) : (e3.prev = this.last, this.last.next = e3, this.last = e3, this.last.next = this.first, this.first.prev = this.last), this.setOneEdgeArcLength(e3);
    void 0 !== this._orientation && (this._orientation = void 0, this._orientation = this.orientation());
  }
  setArcLength() {
    for (let t48 of this) this.setOneEdgeArcLength(t48), t48.face = this;
  }
  setOneEdgeArcLength(t48) {
    t48 === this.first ? t48.arc_length = 0 : t48.arc_length = t48.prev.arc_length + t48.prev.length;
  }
  area() {
    return Math.abs(this.signedArea());
  }
  signedArea() {
    let t48 = 0, e2 = this.box.ymin;
    for (let n2 of this) t48 += n2.shape.definiteIntegral(e2);
    return t48;
  }
  orientation() {
    if (void 0 === this._orientation) {
      let t48 = this.signedArea();
      PR.Utils.EQ_0(t48) ? this._orientation = mR.NOT_ORIENTABLE : PR.Utils.LT(t48, 0) ? this._orientation = mR.CCW : this._orientation = mR.CW;
    }
    return this._orientation;
  }
  isSimple(e2) {
    return 0 === t40.getSelfIntersections(this, e2, true).length;
  }
  static getSelfIntersections(t48, e2, n2 = false) {
    let o2 = [];
    for (let i2 of t48) {
      let r2 = e2.search(i2.box);
      for (let e3 of r2) {
        if (i2 === e3) continue;
        if (e3.face !== t48) continue;
        if (i2.shape instanceof PR.Segment && e3.shape instanceof PR.Segment && (i2.next === e3 || i2.prev === e3)) continue;
        let r3 = i2.shape.intersect(e3.shape);
        for (let t49 of r3) if ((!t49.equalTo(i2.start) || !t49.equalTo(e3.end) || e3 !== i2.prev) && (!t49.equalTo(i2.end) || !t49.equalTo(e3.start) || e3 !== i2.next) && (o2.push(t49), n2)) break;
        if (o2.length > 0 && n2) break;
      }
      if (o2.length > 0 && n2) break;
    }
    return o2;
  }
  findEdgeByPoint(t48) {
    let e2;
    for (let n2 of this) if (!t48.equalTo(n2.shape.start) && (t48.equalTo(n2.shape.end) || n2.shape.contains(t48))) {
      e2 = n2;
      break;
    }
    return e2;
  }
  toPolygon() {
    return new PR.Polygon(this.shapes);
  }
  toJSON() {
    return this.edges.map((t48) => t48.toJSON());
  }
  svg() {
    let t48 = `M${this.first.start.x},${this.first.start.y}`;
    for (let e2 of this) t48 += e2.svg();
    return t48 += " z", t48;
  }
};
PR.Ray = class t41 extends dA {
  constructor(...t48) {
    if (super(), this.pt = new PR.Point(), this.norm = new PR.Vector(0, 1), 0 !== t48.length && (t48.length >= 1 && t48[0] instanceof PR.Point && (this.pt = t48[0].clone()), 1 !== t48.length)) {
      if (!(2 === t48.length && t48[1] instanceof PR.Vector)) throw MR.ILLEGAL_PARAMETERS;
      this.norm = t48[1].clone();
    }
  }
  clone() {
    return new t41(this.pt, this.norm);
  }
  get slope() {
    return new PR.Vector(this.norm.y, -this.norm.x).slope;
  }
  get box() {
    let t48 = this.slope;
    return new PR.Box(t48 > Math.PI / 2 && t48 < 3 * Math.PI / 2 ? Number.NEGATIVE_INFINITY : this.pt.x, t48 >= 0 && t48 <= Math.PI ? this.pt.y : Number.NEGATIVE_INFINITY, t48 >= Math.PI / 2 && t48 <= 3 * Math.PI / 2 ? this.pt.x : Number.POSITIVE_INFINITY, t48 >= Math.PI && t48 <= 2 * Math.PI || 0 === t48 ? this.pt.y : Number.POSITIVE_INFINITY);
  }
  get start() {
    return this.pt;
  }
  get end() {
  }
  get length() {
    return Number.POSITIVE_INFINITY;
  }
  contains(t48) {
    if (this.pt.equalTo(t48)) return true;
    let e2 = new PR.Vector(this.pt, t48);
    return PR.Utils.EQ_0(this.norm.dot(e2)) && PR.Utils.GE(e2.cross(this.norm), 0);
  }
  coord(t48) {
    return pA(t48.x, t48.y).cross(this.norm);
  }
  split(t48) {
    return this.contains(t48) ? this.pt.equalTo(t48) ? [this] : [new PR.Segment(this.pt, t48), new PR.Ray(t48, this.norm)] : [];
  }
  intersect(t48) {
    return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Segment ? eE(this, t48) : t48 instanceof PR.Arc ? nE(this, t48) : t48 instanceof PR.Line ? iE(this, t48) : t48 instanceof PR.Ray ? (n2 = t48, RR(tE(e2 = this), tE(n2)).filter((t49) => e2.contains(t49)).filter((t49) => n2.contains(t49))) : t48 instanceof PR.Circle ? oE(this, t48) : t48 instanceof PR.Box ? (i2 = t48, AR(tE(o2 = this), i2).filter((t49) => o2.contains(t49))) : t48 instanceof PR.Polygon ? rE(this, t48) : t48 instanceof PR.Multiline ? aE(this, t48) : void 0;
    var e2, n2, o2, i2;
  }
  rotate(t48, e2 = new PR.Point()) {
    return new PR.Ray(this.pt.rotate(t48, e2), this.norm.rotate(t48));
  }
  transform(t48) {
    return new PR.Ray(this.pt.transform(t48), this.norm.clone());
  }
  get name() {
    return "ray";
  }
  svg(t48, e2 = {}) {
    let n2 = AR(new PR.Line(this.pt, this.norm), t48);
    return n2 = n2.filter((t49) => this.contains(t49)), 0 === n2.length || 2 === n2.length ? "" : new PR.Segment(this.pt, n2[0]).svg(e2);
  }
};
PR.ray = (...t48) => new PR.Ray(...t48);
var yA = class t42 {
  constructor() {
    this.faces = new PR.PlanarSet(), this.edges = new PR.PlanarSet();
    let t48 = [...arguments];
    if (1 === t48.length && (t48[0] instanceof Array && t48[0].length > 0 || t48[0] instanceof PR.Circle || t48[0] instanceof PR.Box)) {
      let e2 = t48[0];
      if (t48[0] instanceof Array && t48[0].every((t49) => t49 instanceof Array)) if (e2.every((t49) => t49 instanceof Array && 2 === t49.length && "number" == typeof t49[0] && "number" == typeof t49[1])) this.faces.add(new PR.Face(this, e2));
      else for (let t49 of e2) if (t49 instanceof Array && t49[0] instanceof Array && t49[0].every((t50) => t50 instanceof Array && 2 === t50.length && "number" == typeof t50[0] && "number" == typeof t50[1])) for (let e3 of t49) this.faces.add(new PR.Face(this, e3));
      else this.faces.add(new PR.Face(this, t49));
      else this.faces.add(new PR.Face(this, e2));
    }
  }
  get box() {
    return [...this.faces].reduce((t48, e2) => t48.merge(e2.box), new PR.Box());
  }
  get vertices() {
    return [...this.faces].flatMap((t48) => t48.vertices);
  }
  clone() {
    let e2 = new t42();
    for (let t48 of this.faces) e2.addFace(t48.shapes);
    return e2;
  }
  createFromArray(e2) {
    const n2 = new t42();
    return e2.forEach((t48) => [...t48.faces].forEach((t49) => n2.addFace(t49.shapes))), n2;
  }
  isEmpty() {
    return 0 === this.edges.size || 0 === this.faces.size;
  }
  isValid() {
    let t48 = true;
    for (let e2 of this.faces) if (!e2.isSimple(this.edges)) {
      t48 = false;
      break;
    }
    return t48;
  }
  area() {
    let t48 = [...this.faces].reduce((t49, e2) => t49 + e2.signedArea(), 0);
    return Math.abs(t48);
  }
  addFace(...t48) {
    let e2 = new PR.Face(this, ...t48);
    return this.faces.add(e2), e2;
  }
  deleteFace(t48) {
    for (let e2 of t48) this.edges.delete(e2);
    return this.faces.delete(t48);
  }
  recreateFaces() {
    this.faces.clear();
    for (let t49 of this.edges) t49.face = null;
    let t48, e2 = true;
    for (; e2; ) {
      e2 = false;
      for (let n2 of this.edges) if (null === n2.face) {
        t48 = n2, e2 = true;
        break;
      }
      if (e2) {
        let e3 = t48;
        do {
          e3 = e3.next;
        } while (e3.next !== t48);
        this.addFace(t48, e3);
      }
    }
  }
  removeChain(t48, e2, n2) {
    if (n2.next !== e2) {
      for (let o2 = e2; o2 !== n2.next; o2 = o2.next) if (t48.remove(o2), this.edges.delete(o2), t48.isEmpty()) {
        this.deleteFace(t48);
        break;
      }
    } else this.deleteFace(t48);
  }
  addVertex(t48, e2) {
    let n2 = e2.shape.split(t48);
    if (null === n2[0]) return e2.prev;
    if (null === n2[1]) return e2;
    let o2 = new PR.Edge(n2[0]), i2 = e2.prev;
    return e2.face.insert(o2, i2), this.edges.delete(e2), this.edges.add(o2), e2.shape = n2[1], this.edges.add(e2), o2;
  }
  removeEndVertex(t48) {
    const e2 = t48.next;
    e2 !== t48 && (t48.face.merge_with_next_edge(t48), this.edges.delete(e2));
  }
  cut(t48) {
    const e2 = this.splitToIslands().flatMap((e3) => e3._cutSingleIsland(t48)).filter((t49) => t49.isValid() && false === t49.isEmpty());
    return this.createFromArray(e2);
  }
  _cutSingleIsland(t48) {
    let e2 = this.clone();
    const n2 = t48.clone();
    let o2, i2, r2 = { int_points1: [], int_points2: [], int_points1_sorted: [], int_points2_sorted: [] };
    for (let t49 of n2.edges) for (let n3 of e2.edges) {
      let e3 = JR(t49, n3);
      for (let o3 of e3) lE(t49, o3, r2.int_points1), lE(n3, o3, r2.int_points2);
    }
    if (0 === r2.int_points1.length) return e2;
    r2.int_points1_sorted = dE(r2.int_points1), r2.int_points2_sorted = dE(r2.int_points2), _E(n2, r2.int_points1_sorted), _E(e2, r2.int_points2_sorted), pE(r2), r2.int_points1_sorted = dE(r2.int_points1), r2.int_points2_sorted = dE(r2.int_points2), mE(r2.int_points1), gE(r2.int_points1, e2);
    for (let t49 of r2.int_points1_sorted) t49.edge_before && t49.edge_after && t49.edge_before.bv === t49.edge_after.bv && (r2.int_points2[t49.id] = -1, t49.id = -1);
    if (r2.int_points1 = r2.int_points1.filter((t49) => t49.id >= 0), r2.int_points2 = r2.int_points2.filter((t49) => t49.id >= 0), r2.int_points1.forEach((t49, e3) => {
      t49.id = e3;
    }), r2.int_points2.forEach((t49, e3) => {
      t49.id = e3;
    }), 0 === r2.int_points1.length) return e2;
    r2.int_points1_sorted = dE(r2.int_points1), r2.int_points2_sorted = dE(r2.int_points2);
    for (let t49 = 1; t49 < r2.int_points1_sorted.length; t49++) if (i2 = r2.int_points1_sorted[t49], o2 = r2.int_points1_sorted[t49 - 1], i2.edge_before && 1 === i2.edge_before.bv) {
      let t50 = o2.edge_after, s2 = i2.edge_before, a2 = n2.getChain(t50, s2);
      yE(r2.int_points2[o2.id], r2.int_points2[i2.id], a2), a2.forEach((t51) => e2.edges.add(t51)), a2 = a2.reverse().map((t51) => new PR.Edge(t51.shape.reverse()));
      for (let t51 = 0; t51 < a2.length - 1; t51++) a2[t51].next = a2[t51 + 1], a2[t51 + 1].prev = a2[t51];
      yE(r2.int_points2[i2.id], r2.int_points2[o2.id], a2), a2.forEach((t51) => e2.edges.add(t51));
    }
    return e2.recreateFaces(), e2;
  }
  cutWithLine(t48) {
    let e2 = new cE([t48]);
    return this.cut(e2);
  }
  findEdgeByPoint(t48) {
    let e2;
    for (let n2 of this.faces) if (e2 = n2.findEdgeByPoint(t48), void 0 !== e2) break;
    return e2;
  }
  splitToIslands() {
    if (this.isEmpty()) return [];
    let t48 = this.toArray();
    t48.sort((t49, e3) => e3.area() - t49.area());
    let e2 = [...t48[0].faces][0].orientation(), n2 = t48.filter((t49) => [...t49.faces][0].orientation() === e2);
    for (let o2 of t48) {
      let t49 = [...o2.faces][0];
      if (t49.orientation() !== e2) {
        for (let e3 of n2) if (t49.shapes.every((t50) => e3.contains(t50))) {
          e3.addFace(t49.shapes);
          break;
        }
      }
    }
    return n2;
  }
  rearrange() {
    if (this.faces.size <= 1) return this.clone();
    const e2 = this.splitToIslands(), n2 = new t42();
    return e2.forEach((t48) => {
      t48.faces.forEach((t49) => n2.addFace(t49.shapes));
    }), n2;
  }
  orientation() {
    return this.isEmpty() ? mR.NOT_ORIENTABLE : [...this.faces][0].orientation();
  }
  isOuter(t48) {
    return t48.orientation() === this.orientation();
  }
  isMultiPolygon() {
    let t48 = 0;
    return this.faces.forEach((e2) => {
      this.isOuter(e2) && t48++;
    }), t48 > 1;
  }
  reverse() {
    for (let t48 of this.faces) t48.reverse();
    return this;
  }
  contains(t48) {
    if (t48 instanceof PR.Point) {
      let e2 = qE(this, t48);
      return 1 === e2 || 2 === e2;
    }
    return tA(this, t48);
  }
  distanceTo(t48) {
    if (t48 instanceof PR.Point) {
      let [e2, n2] = PR.Distance.point2polygon(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Circle || t48 instanceof PR.Line || t48 instanceof PR.Segment || t48 instanceof PR.Arc) {
      let [e2, n2] = PR.Distance.shape2polygon(t48, this);
      return n2 = n2.reverse(), [e2, n2];
    }
    if (t48 instanceof PR.Polygon) {
      let e2, n2, o2 = [Number.POSITIVE_INFINITY, new PR.Segment()];
      for (let i2 of this.edges) {
        let r2 = o2[0];
        [e2, n2] = PR.Distance.shape2planarSet(i2.shape, t48.edges, r2), PR.Utils.LT(e2, r2) && (o2 = [e2, n2]);
      }
      return o2;
    }
  }
  intersect(t48) {
    return t48 instanceof PR.Point ? this.contains(t48) ? [t48] : [] : t48 instanceof PR.Line ? ZR(t48, this) : t48 instanceof PR.Ray ? rE(t48, this) : t48 instanceof PR.Circle ? qR(t48, this) : t48 instanceof PR.Segment ? UR(t48, this) : t48 instanceof PR.Arc ? GR(t48, this) : t48 instanceof PR.Polygon ? (function(t49, e2) {
      let n2 = [];
      if (t49.isEmpty() || e2.isEmpty()) return n2;
      if (t49.box.not_intersect(e2.box)) return n2;
      for (let o2 of t49.edges) n2 = [...n2, ...KR(o2, e2)];
      return n2;
    })(t48, this) : t48 instanceof PR.Multiline ? (function(t49, e2) {
      let n2 = [];
      if (e2.isEmpty() || 0 === t49.size) return n2;
      for (let o2 of t49) n2 = [...n2, ...KR(o2, e2)];
      return n2;
    })(t48, this) : void 0;
  }
  translate(e2) {
    let n2 = new t42();
    for (let t48 of this.faces) n2.addFace(t48.shapes.map((t49) => t49.translate(e2)));
    return n2;
  }
  rotate(e2 = 0, n2 = new PR.Point()) {
    let o2 = new t42();
    for (let t48 of this.faces) o2.addFace(t48.shapes.map((t49) => t49.rotate(e2, n2)));
    return o2;
  }
  scale(e2, n2) {
    let o2 = new t42();
    for (let t48 of this.faces) o2.addFace(t48.shapes.map((t49) => t49.scale(e2, n2)));
    return o2;
  }
  transform(e2 = new PR.Matrix()) {
    let n2 = new t42();
    for (let t48 of this.faces) n2.addFace(t48.shapes.map((t49) => t49.transform(e2)));
    return n2;
  }
  toJSON() {
    return [...this.faces].map((t48) => t48.toJSON());
  }
  toArray() {
    return [...this.faces].map((t48) => t48.toPolygon());
  }
  dpath() {
    return [...this.faces].reduce((t48, e2) => t48 + e2.svg(), "");
  }
  svg(t48 = {}) {
    let e2 = `
<path ${TR({ fillRule: "evenodd", fill: "lightcyan", ...t48 })} d="`;
    for (let t49 of this.faces) e2 += `
${t49.svg()}`;
    return e2 += '" >\n</path>', e2;
  }
};
PR.Polygon = yA;
PR.polygon = (...t48) => new PR.Polygon(...t48);
var { Circle: bA, Line: xA, Point: vA, Vector: SA, Utils: IA } = PR;
PR.Inversion = class t43 {
  constructor(t48) {
    this.circle = t48;
  }
  get inversion_circle() {
    return this.circle;
  }
  static inversePoint(t48, e2) {
    const n2 = new SA(t48.pc, e2), o2 = t48.r * t48.r, i2 = n2.dot(n2);
    return IA.EQ_0(i2) ? new vA(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY) : t48.pc.translate(n2.multiply(o2 / i2));
  }
  static inverseCircle(t48, e2) {
    const n2 = t48.pc.distanceTo(e2.pc)[0];
    if (IA.EQ(n2, e2.r)) {
      let n3 = t48.r * t48.r / (2 * e2.r), o2 = new SA(t48.pc, e2.pc);
      o2 = o2.normalize();
      let i2 = t48.pc.translate(o2.multiply(n3));
      return new xA(i2, o2);
    }
    {
      let n3 = new SA(t48.pc, e2.pc), o2 = t48.r * t48.r / (n3.dot(n3) - e2.r * e2.r), i2 = t48.pc.translate(n3.multiply(o2)), r2 = Math.abs(o2) * e2.r;
      return new bA(i2, r2);
    }
  }
  static inverseLine(t48, e2) {
    const [n2, o2] = t48.pc.distanceTo(e2);
    if (IA.EQ_0(n2)) return e2.clone();
    {
      let e3 = t48.r * t48.r / (2 * n2), i2 = new SA(t48.pc, o2.end);
      return i2 = i2.multiply(e3 / n2), new bA(t48.pc.translate(i2), e3);
    }
  }
  inverse(e2) {
    return e2 instanceof vA ? t43.inversePoint(this.circle, e2) : e2 instanceof bA ? t43.inverseCircle(this.circle, e2) : e2 instanceof xA ? t43.inverseLine(this.circle, e2) : void 0;
  }
};
PR.inversion = (t48) => new PR.Inversion(t48);
PR.Distance = class t44 {
  static point2point(t48, e2) {
    return t48.distanceTo(e2);
  }
  static point2line(t48, e2) {
    let n2 = t48.projectionOn(e2);
    return [new PR.Vector(t48, n2).length, new PR.Segment(t48, n2)];
  }
  static point2circle(t48, e2) {
    let [n2, o2] = t48.distanceTo(e2.center);
    if (PR.Utils.EQ_0(n2)) return [e2.r, new PR.Segment(t48, e2.toArc().start)];
    {
      let o3 = Math.abs(n2 - e2.r), i2 = new PR.Vector(e2.pc, t48).normalize().multiply(e2.r), r2 = e2.pc.translate(i2);
      return [o3, new PR.Segment(t48, r2)];
    }
  }
  static point2segment(e2, n2) {
    if (n2.start.equalTo(n2.end)) return t44.point2point(e2, n2.start);
    let o2, i2, r2 = new PR.Vector(n2.start, n2.end), s2 = new PR.Vector(n2.start, e2), a2 = new PR.Vector(n2.end, e2), c2 = r2.dot(s2), l2 = -r2.dot(a2);
    if (PR.Utils.GE(c2, 0) && PR.Utils.GE(l2, 0)) {
      let t48 = n2.tangentInStart();
      return o2 = Math.abs(t48.cross(s2)), i2 = n2.start.translate(t48.multiply(t48.dot(s2))), [o2, new PR.Segment(e2, i2)];
    }
    return c2 < 0 ? e2.distanceTo(n2.start) : e2.distanceTo(n2.end);
  }
  static point2arc(e2, n2) {
    let o2, i2, r2 = new PR.Circle(n2.pc, n2.r), s2 = [];
    return [o2, i2] = t44.point2circle(e2, r2), i2.end.on(n2) && s2.push(t44.point2circle(e2, r2)), s2.push(t44.point2point(e2, n2.start)), s2.push(t44.point2point(e2, n2.end)), t44.sort(s2), s2[0];
  }
  static point2edge(e2, n2) {
    return n2.shape instanceof PR.Segment ? t44.point2segment(e2, n2.shape) : t44.point2arc(e2, n2.shape);
  }
  static segment2line(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    let i2 = [];
    return i2.push(t44.point2line(e2.start, n2)), i2.push(t44.point2line(e2.end, n2)), t44.sort(i2), i2[0];
  }
  static segment2segment(e2, n2) {
    let o2 = DR(e2, n2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    let i2, r2, s2 = [];
    return [i2, r2] = t44.point2segment(n2.start, e2), s2.push([i2, r2.reverse()]), [i2, r2] = t44.point2segment(n2.end, e2), s2.push([i2, r2.reverse()]), s2.push(t44.point2segment(e2.start, n2)), s2.push(t44.point2segment(e2.end, n2)), t44.sort(s2), s2[0];
  }
  static segment2circle(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    let i2 = new PR.Line(e2.ps, e2.pe), [r2, s2] = t44.point2line(n2.center, i2);
    if (PR.Utils.GE(r2, n2.r) && s2.end.on(e2)) return t44.point2circle(s2.end, n2);
    {
      let [o3, i3] = t44.point2circle(e2.start, n2), [r3, s3] = t44.point2circle(e2.end, n2);
      return PR.Utils.LT(o3, r3) ? [o3, i3] : [r3, s3];
    }
  }
  static segment2arc(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    let i2 = new PR.Line(e2.ps, e2.pe), r2 = new PR.Circle(n2.pc, n2.r), [s2, a2] = t44.point2line(r2.center, i2);
    if (PR.Utils.GE(s2, r2.r) && a2.end.on(e2)) {
      let [e3, o3] = t44.point2circle(a2.end, r2);
      if (o3.end.on(n2)) return [e3, o3];
    }
    let c2, l2, h2 = [];
    return h2.push(t44.point2arc(e2.start, n2)), h2.push(t44.point2arc(e2.end, n2)), [c2, l2] = t44.point2segment(n2.start, e2), h2.push([c2, l2.reverse()]), [c2, l2] = t44.point2segment(n2.end, e2), h2.push([c2, l2.reverse()]), t44.sort(h2), h2[0];
  }
  static circle2circle(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    if (e2.center.equalTo(n2.center)) {
      let o3 = e2.toArc(), i2 = n2.toArc();
      return t44.point2point(o3.start, i2.start);
    }
    {
      let o3 = new PR.Line(e2.center, n2.center), i2 = o3.intersect(e2), r2 = o3.intersect(n2), s2 = [];
      return s2.push(t44.point2point(i2[0], r2[0])), s2.push(t44.point2point(i2[0], r2[1])), s2.push(t44.point2point(i2[1], r2[0])), s2.push(t44.point2point(i2[1], r2[1])), t44.sort(s2), s2[0];
    }
  }
  static circle2line(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    let [i2, r2] = t44.point2line(e2.center, n2), [s2, a2] = t44.point2circle(r2.end, e2);
    return a2 = a2.reverse(), [s2, a2];
  }
  static arc2line(e2, n2) {
    let o2 = n2.intersect(e2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    let i2 = new PR.Circle(e2.center, e2.r), [r2, s2] = t44.point2line(i2.center, n2);
    if (!PR.Utils.GE(r2, i2.r)) {
      let o3 = [];
      return o3.push(t44.point2line(e2.start, n2)), o3.push(t44.point2line(e2.end, n2)), t44.sort(o3), o3[0];
    }
    {
      let [n3, o3] = t44.point2circle(s2.end, i2);
      if (o3.end.on(e2)) return [n3, o3];
    }
  }
  static arc2circle(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    let i2 = new PR.Circle(e2.center, e2.r), [r2, s2] = t44.circle2circle(i2, n2);
    if (s2.start.on(e2)) return [r2, s2];
    {
      let o3 = [];
      return o3.push(t44.point2circle(e2.start, n2)), o3.push(t44.point2circle(e2.end, n2)), t44.sort(o3), o3[0];
    }
  }
  static arc2arc(e2, n2) {
    let o2 = e2.intersect(n2);
    if (o2.length > 0) return [0, new PR.Segment(o2[0], o2[0])];
    let i2 = new PR.Circle(e2.center, e2.r), r2 = new PR.Circle(n2.center, n2.r), [s2, a2] = t44.circle2circle(i2, r2);
    if (a2.start.on(e2) && a2.end.on(n2)) return [s2, a2];
    {
      let o3, i3, r3 = [];
      return [o3, i3] = t44.point2arc(e2.start, n2), i3.end.on(n2) && r3.push([o3, i3]), [o3, i3] = t44.point2arc(e2.end, n2), i3.end.on(n2) && r3.push([o3, i3]), [o3, i3] = t44.point2arc(n2.start, e2), i3.end.on(e2) && r3.push([o3, i3.reverse()]), [o3, i3] = t44.point2arc(n2.end, e2), i3.end.on(e2) && r3.push([o3, i3.reverse()]), [o3, i3] = t44.point2point(e2.start, n2.start), r3.push([o3, i3]), [o3, i3] = t44.point2point(e2.start, n2.end), r3.push([o3, i3]), [o3, i3] = t44.point2point(e2.end, n2.start), r3.push([o3, i3]), [o3, i3] = t44.point2point(e2.end, n2.end), r3.push([o3, i3]), t44.sort(r3), r3[0];
    }
  }
  static point2polygon(e2, n2) {
    let o2 = [Number.POSITIVE_INFINITY, new PR.Segment()];
    for (let i2 of n2.edges) {
      let [n3, r2] = t44.point2edge(e2, i2);
      PR.Utils.LT(n3, o2[0]) && (o2 = [n3, r2]);
    }
    return o2;
  }
  static shape2polygon(t48, e2) {
    let n2 = [Number.POSITIVE_INFINITY, new PR.Segment()];
    for (let o2 of e2.edges) {
      let [e3, i2] = t48.distanceTo(o2.shape);
      PR.Utils.LT(e3, n2[0]) && (n2 = [e3, i2]);
    }
    return n2;
  }
  static polygon2polygon(t48, e2) {
    let n2 = [Number.POSITIVE_INFINITY, new PR.Segment()];
    for (let o2 of t48.edges) for (let t49 of e2.edges) {
      let [e3, i2] = o2.shape.distanceTo(t49.shape);
      PR.Utils.LT(e3, n2[0]) && (n2 = [e3, i2]);
    }
    return n2;
  }
  static box2box_minmax(t48, e2) {
    let n2 = Math.max(Math.max(t48.xmin - e2.xmax, 0), Math.max(e2.xmin - t48.xmax, 0)), o2 = Math.max(Math.max(t48.ymin - e2.ymax, 0), Math.max(e2.ymin - t48.ymax, 0)), i2 = n2 * n2 + o2 * o2, r2 = t48.merge(e2), s2 = r2.xmax - r2.xmin, a2 = r2.ymax - r2.ymin;
    return [i2, s2 * s2 + a2 * a2];
  }
  static minmax_tree_process_level(e2, n2, o2, i2) {
    let r2, s2;
    for (let a3 of n2) {
      [r2, s2] = t44.box2box_minmax(e2.box, a3.item.key);
      for (let t48 of a3.item.values) t48 instanceof PR.Edge ? i2.insert([r2, s2], t48.shape) : i2.insert([r2, s2], t48);
      PR.Utils.LT(s2, o2) && (o2 = s2);
    }
    if (0 === n2.length) return o2;
    let a2 = [...n2.map((t48) => t48.left.isNil() ? void 0 : t48.left).filter((t48) => void 0 !== t48), ...n2.map((t48) => t48.right.isNil() ? void 0 : t48.right).filter((t48) => void 0 !== t48)].filter((n3) => {
      let [i3, r3] = t44.box2box_minmax(e2.box, n3.max);
      return PR.Utils.LE(i3, o2);
    });
    return o2 = t44.minmax_tree_process_level(e2, a2, o2, i2);
  }
  static minmax_tree(e2, n2, o2) {
    let i2 = new lA(), r2 = [n2.index.root], s2 = o2 < Number.POSITIVE_INFINITY ? o2 * o2 : Number.POSITIVE_INFINITY;
    return s2 = t44.minmax_tree_process_level(e2, r2, s2, i2), i2;
  }
  static minmax_tree_calc_distance(e2, n2, o2) {
    let i2, r2;
    if (null != n2 && !n2.isNil()) {
      if ([i2, r2] = t44.minmax_tree_calc_distance(e2, n2.left, o2), r2) return [i2, r2];
      if (PR.Utils.LT(i2[0], Math.sqrt(n2.item.key.low))) return [i2, true];
      let [s2, a2] = t44.distanceToArray(e2, n2.item.values);
      return PR.Utils.LT(s2, i2[0]) && (i2 = [s2, a2]), [i2, r2] = t44.minmax_tree_calc_distance(e2, n2.right, i2), [i2, r2];
    }
    return [o2, false];
  }
  static shape2planarSet(e2, n2, o2 = Number.POSITIVE_INFINITY) {
    let i2 = [o2, new PR.Segment()], r2 = false;
    if (n2 instanceof PR.PlanarSet) {
      let s2 = t44.minmax_tree(e2, n2, o2);
      [i2, r2] = t44.minmax_tree_calc_distance(e2, s2.root, i2);
    }
    return i2;
  }
  static sort(t48) {
    t48.sort((t49, e2) => PR.Utils.LT(t49[0], e2[0]) ? -1 : PR.Utils.GT(t49[0], e2[0]) ? 1 : 0);
  }
  static distance(t48, e2) {
    return t48.distanceTo(e2);
  }
  static distanceToArray(t48, e2) {
    let n2 = [Number.POSITIVE_INFINITY, new PR.Segment()];
    for (let o2 of e2) {
      let [e3, i2] = t48.distanceTo(o2);
      PR.Utils.LT(e3, n2[0]) && (n2 = [e3, i2]);
    }
    return n2;
  }
  static shape2multiline(e2, n2) {
    let o2 = [Number.POSITIVE_INFINITY, new PR.Segment()];
    for (let i2 of n2) {
      let [n3, r2] = t44.distance(e2, i2.shape);
      PR.Utils.LT(n3, o2[0]) && (o2 = [n3, r2]);
    }
    return o2;
  }
  static multiline2multiline(e2, n2) {
    let o2 = [Number.POSITIVE_INFINITY, new PR.Segment()];
    for (let i2 of e2) for (let e3 of n2) {
      let [n3, r2] = t44.distance(i2.shape, e3.shape);
      PR.Utils.LT(n3, o2[0]) && (o2 = [n3, r2]);
    }
    return o2;
  }
};
var { Multiline: PA, Point: MA, Segment: CA, Polygon: NA } = PR;
function wA(t48) {
  return new MA(t48.split(" ").map(Number));
}
function TA(t48) {
  return t48.split(", ").map(wA);
}
function RA(t48) {
  const e2 = TA(t48);
  let n2 = [];
  for (let t49 = 0; t49 < e2.length - 1; t49++) n2.push(new CA(e2[t49], e2[t49 + 1]));
  return new PA(n2);
}
function EA(t48) {
  const e2 = t48.replace(/\(\(/, "").replace(/\)\)$/, "").split("), ("), n2 = new NA();
  let o2;
  return e2.forEach((t49, e3) => {
    let i2 = t49.split(", ").map((t50) => new MA(t50.split(" ").map(Number)));
    const r2 = n2.addFace(i2);
    0 === e3 ? o2 = r2.orientation() : r2.orientation() === o2 && r2.reverse();
  }), n2;
}
function AA(t48) {
  if (t48.startsWith("POLYGON")) {
    return EA(t48.replace(/^POLYGON /, ""));
  }
  return (function(t49) {
    const e2 = t49.split(/\)\), \(\(/).map((t50) => "((" + t50 + "))").map(EA), n2 = new NA();
    return e2.reduce((t50, e3) => [...t50, ...e3?.faces], []).forEach((t50) => n2.addFace([...t50?.shapes])), n2;
  })(t48.replace(/^MULTIPOLYGON \(\(\((.*)\)\)\)$/, "$1"));
}
function OA(t48) {
  return t48.split("\n")?.every((t49) => t49.includes("POINT"));
}
function LA(t48) {
  return t48.split("\n")?.every((t49) => t49.includes("LINESTRING"));
}
PR.isWktString = function(t48) {
  return t48.startsWith("POINT") || OA(t48) || t48.startsWith("LINESTRING") || LA(t48) || t48.startsWith("MULTILINESTRING") || t48.startsWith("POLYGON") || t48.startsWith("MULTIPOINT") || t48.startsWith("MULTIPOLYGON") || t48.startsWith("GEOMETRYCOLLECTION");
}, PR.parseWKT = function t45(e2) {
  if (e2.startsWith("POINT")) {
    return wA(e2.replace(/^POINT \(/, "").replace(/\)$/, ""));
  }
  if (e2.startsWith("MULTIPOINT")) {
    return TA(e2.replace(/^MULTIPOINT \(/, "").replace(/\)$/, ""));
  }
  if (e2.startsWith("LINESTRING")) {
    return RA(e2.replace(/^LINESTRING \(/, "").replace(/\)$/, ""));
  }
  if (e2.startsWith("MULTILINESTRING")) {
    return (function(t48) {
      return t48.replace(/\(\(/, "").replace(/\)\)$/, "").split("), (").map(RA);
    })(e2.replace(/^MULTILINESTRING /, ""));
  }
  if (e2.startsWith("POLYGON") || e2.startsWith("MULTIPOLYGON")) return AA(e2);
  if (e2.startsWith("GEOMETRYCOLLECTION")) {
    const n2 = /(?<type>POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON) \((?:[^\(\)]|\([^\)]*\))*\)/g, o2 = e2.match(n2);
    o2[0].startsWith("GEOMETRYCOLLECTION") && (o2[0] = o2[0].replace("GEOMETRYCOLLECTION (", ""));
    return o2.map(t45).map((t48) => t48 instanceof Array ? t48 : [t48]).reduce((t48, e3) => [...t48, ...e3], []);
  }
  return OA(e2) ? (function(t48) {
    return t48.split("\n").map((t49) => t49.match(/\(([^)]+)\)/)[1]).map(wA);
  })(e2) : LA(e2) ? (function(t48) {
    return t48.split("\n").map((t49) => t49.match(/\(([^)]+)\)/)[1]).map(RA).reduce((t49, e3) => [...t49, ...e3], []);
  })(e2) : [];
}, PR.BooleanOperations = BE, PR.Relations = iA;
var Jk = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_RAMP_ATTEMPTS: 16, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, MAX_ITERATIONS: 5e4, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY };
new Int32Array(0);
var lF = { DISTANCE_TO_COST: 0.05, RIP_THRESHOLD_START: 0.05, RIP_THRESHOLD_END: 0.8, RIP_CONGESTION_REGION_COST_FACTOR: 0.1, ACCEPT_BEST_SOLUTION_ON_TIMEOUT: true, GREEDY_FINAL_ROUTE_ITERS: 4, MAX_RIPS_WITHOUT_MAX_REGION_COST_IMPROVEMENT: 6, EXTRA_RIPS_AFTER_BEATING_BASELINE_MAX_REGION_COST: Number.POSITIVE_INFINITY };
var d$ = Math.PI / 2;
var j$ = 0.1;
var Y$ = 0.15;
var $$ = j$ + Y$;
var X$ = 3 * $$ / 4;
var vX = c(T(), 1);
var ZB = (Number.POSITIVE_INFINITY, 1e-9);
var xH = (new Int32Array(0), (t48) => (t48.ccwRotationDegrees ?? 0) * Math.PI / 180);
var xW = class t46 {
  static generators = /* @__PURE__ */ new Map();
  static register(e2) {
    t46.generators.set(e2.componentKind, e2);
  }
  static create(e2) {
    const n2 = e2.detectedComponent.componentKind, o2 = t46.generators.get(n2);
    if (!o2) throw new Error(`No topology generator registered for component kind "${n2}"`);
    return new o2(e2);
  }
};
var vW = (t48) => [t48.obstacle.obstacleId ?? t48.obstacle.componentId ?? "obstacle", t48.start.x.toFixed(4), t48.start.y.toFixed(4), t48.end.x.toFixed(4), t48.end.y.toFixed(4), t48.expansionDirection.x, t48.expansionDirection.y].join(":");
var SW = (t48) => {
  let e2 = 0;
  for (const n2 of t48) e2 = 31 * e2 + n2.charCodeAt(0) >>> 0;
  return e2;
};
var IW = (t48, e2) => `hsla(${SW(vW(t48)) % 360},72%,36%,${e2})`;
var PW = (t48) => {
  const e2 = t48.expansionDirection;
  return e2.x < 0 ? "left" : e2.x > 0 ? "right" : e2.y < 0 ? "bottom" : "top";
};
var MW = (t48) => ({ x: (t48.start.x + t48.end.x) / 2, y: (t48.start.y + t48.end.y) / 2 });
var CW = (t48) => {
  const e2 = /^bga-gapfill-(\d+)-/.exec(t48.capacityMeshNodeId);
  return e2 ? Number.parseInt(e2[1], 10) : null;
};
var NW = (t48, e2) => {
  const n2 = MW(t48), o2 = MW(e2), i2 = n2.y - o2.y;
  if (Math.abs(i2) > 1e-6) return i2;
  const r2 = n2.x - o2.x;
  return Math.abs(r2) > 1e-6 ? r2 : vW(t48).localeCompare(vW(e2));
};
var wW = (t48) => {
  const e2 = [...t48].sort(NW), n2 = [];
  let o2 = e2.shift();
  for (; o2 && (n2.push(o2), 0 !== e2.length); ) {
    const t49 = MW(o2);
    let n3 = 0, i2 = Number.POSITIVE_INFINITY;
    for (let o3 = 0; o3 < e2.length; o3++) {
      const r2 = e2[o3], s2 = MW(r2), a2 = (s2.x - t49.x) ** 2 + (s2.y - t49.y) ** 2;
      a2 < i2 - 1e-9 ? (i2 = a2, n3 = o3) : Math.abs(a2 - i2) <= 1e-9 && NW(r2, e2[n3]) < 0 && (n3 = o3);
    }
    o2 = e2.splice(n3, 1)[0];
  }
  return n2;
};
var TW = (t48, e2) => {
  const n2 = vW(t48), o2 = e2.findIndex((t49) => vW(t49) === n2);
  return o2 >= 0 ? `E${o2 + 1}` : `E${SW(n2).toString(36).slice(0, 4)}`;
};
var RW = (t48) => t48.flatMap((t49) => {
  const e2 = ke(t49);
  return [{ obstacle: t49, start: { x: e2.minX, y: e2.minY }, end: { x: e2.minX, y: e2.maxY }, expansionDirection: { x: -1, y: 0 } }, { obstacle: t49, start: { x: e2.maxX, y: e2.minY }, end: { x: e2.maxX, y: e2.maxY }, expansionDirection: { x: 1, y: 0 } }, { obstacle: t49, start: { x: e2.minX, y: e2.minY }, end: { x: e2.maxX, y: e2.minY }, expansionDirection: { x: 0, y: -1 } }, { obstacle: t49, start: { x: e2.minX, y: e2.maxY }, end: { x: e2.maxX, y: e2.maxY }, expansionDirection: { x: 0, y: 1 } }];
});
var EW = 1e-3;
var AW = 1e-3;
var OW = class extends wt {
  constructor(t48) {
    super(), this.inputProblem = t48;
  }
  inputProblem;
  meshIndex;
  allEdges = [];
  queueEdges = [];
  disconnectedEdges = [];
  currentEdge = null;
  lastSearchBounds = null;
  lastCandidateMeshNodes = [];
  lastMatchedMeshNode = null;
  _setup() {
    const t48 = Math.max(this.inputProblem.meshNodes.length, 1);
    this.meshIndex = new Ot(t48);
    for (const t49 of this.inputProblem.meshNodes) {
      const e3 = ke(t49);
      this.meshIndex.add(e3.minX, e3.minY, e3.maxX, e3.maxY);
    }
    this.meshIndex.finish();
    const e2 = RW(this.inputProblem.unmarkedComponentObstacles);
    this.queueEdges = e2, this.allEdges = wW(e2), this.currentEdge = null, this.lastSearchBounds = null, this.lastCandidateMeshNodes = [], this.lastMatchedMeshNode = null;
  }
  _step() {
    const t48 = this.queueEdges.shift();
    if (!t48) return this.currentEdge = null, this.lastSearchBounds = null, this.lastCandidateMeshNodes = [], this.lastMatchedMeshNode = null, void (this.solved = true);
    this.currentEdge = t48, this.lastMatchedMeshNode = null;
    const e2 = Math.abs(t48.start.x - t48.end.x) <= EW, n2 = e2 ? { minX: t48.start.x - AW, maxX: t48.start.x + AW, minY: Math.min(t48.start.y, t48.end.y), maxY: Math.max(t48.start.y, t48.end.y) } : { minX: Math.min(t48.start.x, t48.end.x), maxX: Math.max(t48.start.x, t48.end.x), minY: t48.start.y - AW, maxY: t48.start.y + AW };
    this.lastSearchBounds = n2;
    const o2 = this.meshIndex.search(n2.minX, n2.minY, n2.maxX, n2.maxY);
    this.lastCandidateMeshNodes = o2.map((t49) => this.inputProblem.meshNodes[t49]);
    let i2 = false;
    for (const n3 of o2) {
      const o3 = this.inputProblem.meshNodes[n3], r2 = ke(o3);
      if (e2) {
        if (!(Math.min(r2.maxY, Math.max(t48.start.y, t48.end.y)) - Math.max(r2.minY, Math.min(t48.start.y, t48.end.y)) > EW)) continue;
        if (-1 === t48.expansionDirection.x && Math.abs(r2.maxX - t48.start.x) <= EW) {
          i2 = true, this.lastMatchedMeshNode = o3;
          break;
        }
        if (1 === t48.expansionDirection.x && Math.abs(r2.minX - t48.start.x) <= EW) {
          i2 = true, this.lastMatchedMeshNode = o3;
          break;
        }
        continue;
      }
      if (Math.min(r2.maxX, Math.max(t48.start.x, t48.end.x)) - Math.max(r2.minX, Math.min(t48.start.x, t48.end.x)) > EW) {
        if (-1 === t48.expansionDirection.y && Math.abs(r2.maxY - t48.start.y) <= EW) {
          i2 = true, this.lastMatchedMeshNode = o3;
          break;
        }
        if (1 === t48.expansionDirection.y && Math.abs(r2.minY - t48.start.y) <= EW) {
          i2 = true, this.lastMatchedMeshNode = o3;
          break;
        }
      }
    }
    i2 || this.disconnectedEdges.push(t48);
  }
  getOutput() {
    return this.disconnectedEdges;
  }
  visualize() {
    const t48 = this.disconnectedEdges, e2 = this.allEdges.length > 0 ? this.allEdges : [...t48, ...this.currentEdge ? [this.currentEdge] : []], n2 = this.currentEdge ? IW(this.currentEdge, 0.88) : "rgba(40,40,40,0.4)", o2 = this.inputProblem.meshNodes.map((t49) => ({ ...ac(t49, { rectMargin: 0.01 }), fill: t49._containsObstacle ? "rgba(120,120,120,0.18)" : "rgba(120,120,120,0.08)", stroke: t49._containsObstacle ? "rgba(120,120,120,0.42)" : "rgba(120,120,120,0.24)" })), i2 = this.lastSearchBounds && this.currentEdge ? [{ center: (r2 = this.lastSearchBounds, { x: (r2.minX + r2.maxX) / 2, y: (r2.minY + r2.maxY) / 2 }), width: this.lastSearchBounds.maxX - this.lastSearchBounds.minX, height: this.lastSearchBounds.maxY - this.lastSearchBounds.minY, fill: IW(this.currentEdge, 0.1), stroke: IW(this.currentEdge, 0.36), label: [TW(this.currentEdge, e2), "search band"].join(" ") }] : [];
    var r2;
    const s2 = this.lastCandidateMeshNodes.map((t49) => ({ ...ac(t49, { rectMargin: 0.018 }), fill: t49 === this.lastMatchedMeshNode ? "rgba(0,180,90,0.24)" : this.currentEdge ? IW(this.currentEdge, 0.16) : "rgba(80,120,160,0.16)", stroke: t49 === this.lastMatchedMeshNode ? "rgba(0,150,80,0.88)" : n2, label: [t49 === this.lastMatchedMeshNode ? "matched" : "candidate", t49.capacityMeshNodeId, `z:${t49.availableZ.join(",")}`].join("\n") })), a2 = this.inputProblem.unmarkedComponentObstacles.map((t49) => ({ center: t49.center, width: t49.width, height: t49.height, fill: "rgba(160,160,160,0.10)", stroke: "rgba(160,160,160,0.40)", label: t49.obstacleId ?? t49.componentId ?? "obstacle" })), c2 = t48.map((t49) => ({ points: [t49.start, t49.end], strokeColor: IW(t49, 0.14), strokeWidth: 0.01, strokeDash: "5 4", label: [TW(t49, e2), PW(t49), "disconnected"].join(" ") })), l2 = [], h2 = [];
    if (this.currentEdge) {
      const t49 = MW(this.currentEdge);
      l2.push({ points: [this.currentEdge.start, this.currentEdge.end], strokeColor: IW(this.currentEdge, 1), strokeWidth: 0.06, label: [TW(this.currentEdge, e2), PW(this.currentEdge), "checking"].join(" ") }, { points: [t49, { x: t49.x + 0.16 * this.currentEdge.expansionDirection.x, y: t49.y + 0.16 * this.currentEdge.expansionDirection.y }], strokeColor: IW(this.currentEdge, 0.82), strokeWidth: 0.02, strokeDash: "3 3" }), h2.push({ ...t49, color: IW(this.currentEdge, 1), label: TW(this.currentEdge, e2) });
    }
    return { rects: [...o2, ...i2, ...s2, ...a2], lines: [...c2, ...l2], points: h2 };
  }
};
var LW = 1e-3;
var DW = 1e-3;
var zW = 1e-6;
var kW = class extends wt {
  constructor(t48) {
    super(), this.inputProblem = t48;
  }
  inputProblem;
  meshIndex;
  meshBounds;
  expandedNodes = [];
  _setup() {
    const t48 = Math.max(this.inputProblem.meshNodes.length, 1);
    this.meshIndex = new Ot(t48);
    let e2 = Number.POSITIVE_INFINITY, n2 = Number.NEGATIVE_INFINITY, o2 = Number.POSITIVE_INFINITY, i2 = Number.NEGATIVE_INFINITY;
    for (const t49 of this.inputProblem.meshNodes) {
      const r2 = ke(t49);
      this.meshIndex.add(r2.minX, r2.minY, r2.maxX, r2.maxY), e2 = Math.min(e2, r2.minX), n2 = Math.max(n2, r2.maxX), o2 = Math.min(o2, r2.minY), i2 = Math.max(i2, r2.maxY);
    }
    this.meshIndex.finish(), this.meshBounds = this.inputProblem.meshNodes.length ? { minX: e2, maxX: n2, minY: o2, maxY: i2 } : { minX: 0, maxX: 0, minY: 0, maxY: 0 };
  }
  getObstacleAvailableZ(t48) {
    return t48.__zLayers ?? t48.layers.map((t49) => No(t49, this.inputProblem.layerCount));
  }
  getSharedOverlapArea(t48, e2) {
    if (!t48.availableZ.some((t49) => e2.availableZ.includes(t49))) return 0;
    const n2 = ke(t48), o2 = ke(e2), i2 = Math.min(n2.maxX, o2.maxX) - Math.max(n2.minX, o2.minX), r2 = Math.min(n2.maxY, o2.maxY) - Math.max(n2.minY, o2.minY);
    return i2 <= zW || r2 <= zW ? 0 : i2 * r2;
  }
  getNodeObstacleOverlapArea(t48, e2) {
    const n2 = this.getObstacleAvailableZ(e2);
    if (!t48.availableZ.some((t49) => n2.includes(t49))) return 0;
    const o2 = ke(t48), i2 = ke(e2), r2 = Math.min(o2.maxX, i2.maxX) - Math.max(o2.minX, i2.minX), s2 = Math.min(o2.maxY, i2.maxY) - Math.max(o2.minY, i2.minY);
    return r2 <= zW || s2 <= zW ? 0 : r2 * s2;
  }
  getClosestMeshNode(t48, e2) {
    const n2 = Math.abs(t48.start.x - t48.end.x) <= LW, o2 = this.getObstacleAvailableZ(t48.obstacle), i2 = n2 ? t48.expansionDirection.x < 0 ? { minX: this.meshBounds.minX, maxX: t48.start.x, minY: Math.min(t48.start.y, t48.end.y) - DW, maxY: Math.max(t48.start.y, t48.end.y) + DW } : { minX: t48.start.x, maxX: this.meshBounds.maxX, minY: Math.min(t48.start.y, t48.end.y) - DW, maxY: Math.max(t48.start.y, t48.end.y) + DW } : t48.expansionDirection.y < 0 ? { minX: Math.min(t48.start.x, t48.end.x) - DW, maxX: Math.max(t48.start.x, t48.end.x) + DW, minY: this.meshBounds.minY, maxY: t48.start.y } : { minX: Math.min(t48.start.x, t48.end.x) - DW, maxX: Math.max(t48.start.x, t48.end.x) + DW, minY: t48.start.y, maxY: this.meshBounds.maxY }, r2 = this.meshIndex.search(i2.minX, i2.minY, i2.maxX, i2.maxY);
    let s2 = null, a2 = Number.POSITIVE_INFINITY;
    const c2 = [...r2.map((t49) => this.inputProblem.meshNodes[t49]), ...e2];
    for (const e3 of c2) {
      if (e3._containsObstacle) continue;
      if (!e3.availableZ.some((t49) => o2.includes(t49))) continue;
      const i3 = ke(e3);
      if ((n2 ? Math.min(Math.max(t48.start.y, t48.end.y), i3.maxY) - Math.max(Math.min(t48.start.y, t48.end.y), i3.minY) : Math.min(Math.max(t48.start.x, t48.end.x), i3.maxX) - Math.max(Math.min(t48.start.x, t48.end.x), i3.minX)) <= LW) continue;
      const r3 = n2 ? t48.expansionDirection.x < 0 ? t48.start.x - i3.maxX : i3.minX - t48.start.x : t48.expansionDirection.y < 0 ? t48.start.y - i3.maxY : i3.minY - t48.start.y;
      r3 < LW || (r3 >= a2 || (a2 = r3, s2 = e3));
    }
    return s2;
  }
  createExpandedNode(t48, e2, n2) {
    const o2 = ke(e2), i2 = this.getObstacleAvailableZ(t48.obstacle);
    if (Math.abs(t48.start.x - t48.end.x) <= LW) {
      const r3 = Math.max(Math.min(t48.start.y, t48.end.y), o2.minY), s3 = Math.min(Math.max(t48.start.y, t48.end.y), o2.maxY), a3 = t48.expansionDirection.x < 0 ? o2.maxX : t48.start.x, c3 = t48.expansionDirection.x < 0 ? t48.start.x : o2.minX;
      return c3 - a3 <= LW || s3 - r3 <= LW ? null : { capacityMeshNodeId: `bga-gapfill-${n2}-${t48.obstacle.obstacleId ?? "no-obstacle"}-${e2.capacityMeshNodeId}`, center: { x: (a3 + c3) / 2, y: (r3 + s3) / 2 }, width: c3 - a3, height: s3 - r3, layer: `z${i2.join(",")}`, availableZ: i2 };
    }
    const r2 = Math.max(Math.min(t48.start.x, t48.end.x), o2.minX), s2 = Math.min(Math.max(t48.start.x, t48.end.x), o2.maxX), a2 = t48.expansionDirection.y < 0 ? o2.maxY : t48.start.y, c2 = t48.expansionDirection.y < 0 ? t48.start.y : o2.minY;
    return s2 - r2 <= LW || c2 - a2 <= LW ? null : { capacityMeshNodeId: `bga-gapfill-${n2}-${t48.obstacle.obstacleId ?? "no-obstacle"}-${e2.capacityMeshNodeId}`, center: { x: (r2 + s2) / 2, y: (a2 + c2) / 2 }, width: s2 - r2, height: c2 - a2, layer: `z${i2.join(",")}`, availableZ: i2 };
  }
  overlapsExistingGeometry(t48, e2) {
    for (const e3 of this.inputProblem.meshNodes) if (this.getSharedOverlapArea(t48, e3) > 0) return true;
    for (const n2 of e2) if (this.getSharedOverlapArea(t48, n2) > 0) return true;
    for (const e3 of this.inputProblem.edgesWithObstacle) if (this.getNodeObstacleOverlapArea(t48, e3.obstacle) > 0) return true;
    return false;
  }
  _step() {
    const t48 = [];
    for (const [e2, n2] of this.inputProblem.edgesWithObstacle.entries()) {
      const o2 = this.getClosestMeshNode(n2, t48);
      if (!o2) continue;
      const i2 = this.createExpandedNode(n2, o2, e2);
      i2 && (this.overlapsExistingGeometry(i2, t48) || t48.push(i2));
    }
    this.expandedNodes = t48, this.solved = true;
  }
  getOutput() {
    return this.expandedNodes;
  }
  visualize() {
    const t48 = this.inputProblem.edgesWithObstacle, e2 = wW(t48);
    return { rects: [...this.inputProblem.meshNodes.map((t49) => ({ ...ac(t49, { rectMargin: 0.01 }), fill: t49._containsObstacle ? "rgba(255,0,0,0.16)" : "rgba(0,120,255,0.08)", stroke: t49._containsObstacle ? "rgba(255,0,0,0.35)" : "rgba(0,120,255,0.28)" })), ...this.expandedNodes.map((n2) => {
      const o2 = CW(n2), i2 = null === o2 ? null : t48[o2] ?? null;
      return { ...ac(n2, { rectMargin: 0.012, zOffset: 0.01 }), fill: i2 ? IW(i2, 0.24) : "rgba(0,160,100,0.24)", stroke: i2 ? IW(i2, 0.72) : "rgba(0,160,100,0.68)", label: [i2 ? TW(i2, e2) : "E?", "expanded", n2.capacityMeshNodeId, `z:${n2.availableZ.join(",")}`].join("\n") };
    })], lines: [...this.inputProblem.edgesWithObstacle.map((t49) => ({ points: [t49.start, t49.end], strokeColor: IW(t49, 0.9), strokeWidth: 0.034, label: [TW(t49, e2), PW(t49)].join(" ") })), ...this.inputProblem.edgesWithObstacle.map((t49) => {
      const e3 = MW(t49);
      return { points: [e3, { x: e3.x + 0.16 * t49.expansionDirection.x, y: e3.y + 0.16 * t49.expansionDirection.y }], strokeColor: IW(t49, 0.7), strokeWidth: 0.016, strokeDash: "3 3" };
    })], points: this.inputProblem.edgesWithObstacle.map((t49) => ({ ...MW(t49), color: IW(t49, 0.95), label: TW(t49, e2) })) };
  }
};
var FW = 1e-3;
var jW = class extends Rt {
  constructor(t48) {
    super(t48), this.inputProblem = t48;
  }
  inputProblem;
  detectEdgesNotConnectedToMesh;
  expandUnconnectedEdgesToMesh;
  pipelineDef = [Tt("detectEdgesNotConnectedToMesh", OW, (t48) => [t48.inputProblem]), Tt("expandUnconnectedEdgesToMesh", kW, (t48) => [{ meshNodes: t48.inputProblem.meshNodes, edgesWithObstacle: t48.detectEdgesNotConnectedToMesh.getOutput(), layerCount: t48.inputProblem.layerCount }])];
  getOutput() {
    return [...this.inputProblem.meshNodes, ...this.expandUnconnectedEdgesToMesh.getOutput()];
  }
  getExpandedNodes() {
    return this.expandUnconnectedEdgesToMesh.getOutput();
  }
  getObstacleLayer(t48) {
    return `z${(t48.obstacle.__zLayers ?? t48.obstacle.layers.map((t49) => No(t49, this.inputProblem.layerCount))).join(",")}`;
  }
  getObstacleRects() {
    return this.inputProblem.unmarkedComponentObstacles.map((t48) => {
      const e2 = t48.__zLayers ?? t48.layers.map((t49) => No(t49, this.inputProblem.layerCount));
      return { center: t48.center, width: t48.width, height: t48.height, fill: "rgba(150,150,150,0.08)", stroke: "rgba(90,90,90,0.42)", label: t48.obstacleId ?? t48.componentId ?? "bga obstacle", layer: `z${e2.join(",")}` };
    });
  }
  getBaseMeshRects() {
    return this.inputProblem.meshNodes.map((t48) => ({ ...ac(t48, { rectMargin: 0.025, zOffset: 0.01 }), fill: t48._containsObstacle ? "rgba(210,60,60,0.14)" : "rgba(80,120,160,0.08)", stroke: t48._containsObstacle ? "rgba(190,40,40,0.42)" : "rgba(80,120,160,0.28)", label: `mesh ${t48.capacityMeshNodeId}
z:${t48.availableZ.join(",")}` }));
  }
  initialVisualize() {
    const t48 = RW(this.inputProblem.unmarkedComponentObstacles), e2 = wW(t48), n2 = [...t48.map((t49) => ({ points: [t49.start, t49.end], strokeColor: IW(t49, 0.72), strokeWidth: 0.018, strokeDash: "0.05 0.035", layer: this.getObstacleLayer(t49), label: [TW(t49, e2), PW(t49)].join(" ") })), ...t48.map((t49) => {
      const e3 = MW(t49);
      return { points: [e3, { x: e3.x + 0.18 * t49.expansionDirection.x, y: e3.y + 0.18 * t49.expansionDirection.y }], strokeColor: IW(t49, 0.64), strokeWidth: 0.012, strokeDash: "0.035 0.025", layer: this.getObstacleLayer(t49) };
    })];
    return { title: "BGA GapFill: candidate obstacle edges", rects: [...this.getBaseMeshRects(), ...this.getObstacleRects()], lines: n2 };
  }
  finalVisualize() {
    const t48 = this.getStageOutput("detectEdgesNotConnectedToMesh") ?? [], e2 = this.getStageOutput("expandUnconnectedEdgesToMesh") ?? [], n2 = wW(RW(this.inputProblem.unmarkedComponentObstacles)), o2 = /* @__PURE__ */ new Map();
    for (const t49 of e2) {
      const e3 = CW(t49);
      null !== e3 && o2.set(e3, t49);
    }
    const i2 = e2.map((e3) => {
      const o3 = CW(e3), i3 = null === o3 ? null : t48[o3] ?? null, r3 = i3 ? (({ expandedNode: t49, edge: e4, meshNodes: n3 }) => {
        const o4 = ke(t49), i4 = Math.abs(e4.start.x - e4.end.x) <= FW;
        return n3.filter((n4) => {
          if (n4._containsObstacle) return false;
          if (!t49.availableZ.some((t50) => n4.availableZ.includes(t50))) return false;
          const r4 = ke(n4);
          return i4 ? !(Math.min(o4.maxY, r4.maxY) - Math.max(o4.minY, r4.minY) <= FW) && (e4.expansionDirection.x < 0 ? Math.abs(r4.maxX - o4.minX) <= FW : Math.abs(r4.minX - o4.maxX) <= FW) : !(Math.min(o4.maxX, r4.maxX) - Math.max(o4.minX, r4.minX) <= FW) && (e4.expansionDirection.y < 0 ? Math.abs(r4.maxY - o4.minY) <= FW : Math.abs(r4.minY - o4.maxY) <= FW);
        }).map((t50) => t50.capacityMeshNodeId);
      })({ expandedNode: e3, edge: i3, meshNodes: this.inputProblem.meshNodes }) : [], s3 = i3 ? TW(i3, n2) : "E?", a3 = null === i3 ? "rgba(0,160,100,0.72)" : IW(i3, 0.72);
      return { ...ac(e3, { rectMargin: 0.012, zOffset: 0.01 }), fill: null === i3 ? "rgba(0,160,100,0.24)" : IW(i3, 0.16), stroke: a3, label: [`${s3} gap fill`, r3.length > 0 ? `to ${r3.join(",")}` : "target mesh not adjacent", `z:${e3.availableZ.join(",")}`].join("\n") };
    }), r2 = t48.map((t49, e3) => {
      const i3 = o2.get(e3);
      return { points: [t49.start, t49.end], strokeColor: i3 ? IW(t49, 0.68) : "rgba(80,80,80,0.14)", strokeWidth: i3 ? 0.026 : 8e-3, ...i3 ? {} : { strokeDash: "5 4" }, layer: this.getObstacleLayer(t49), label: [[TW(t49, n2), PW(t49)].join(" "), i3 ? "filled" : "no fill created"].join("\n") };
    }), s2 = t48.flatMap((t49, e3) => {
      const n3 = MW(t49), i3 = o2.get(e3);
      return i3 ? [{ points: [n3, i3.center], strokeColor: IW(t49, 0.42), strokeWidth: 0.012, strokeDash: "0.035 0.025", layer: this.getObstacleLayer(t49) }] : [];
    }), a2 = t48.flatMap((t49, e3) => o2.has(e3) ? [{ ...MW(t49), color: IW(t49, 0.82), label: TW(t49, n2), layer: this.getObstacleLayer(t49) }] : []);
    return { title: "BGA GapFill: disconnected edges and created mesh", rects: [...this.getBaseMeshRects(), ...this.getObstacleRects(), ...i2], lines: [...r2, ...s2], points: a2 };
  }
};
function YW(t48, e2) {
  const n2 = [];
  for (let o2 = 0; o2 < t48.length; o2++) {
    const i2 = t48[o2];
    n2.push(i2);
    const r2 = t48[o2 + 1];
    if (void 0 === r2) continue;
    const s2 = Math.round((r2 - i2) / e2);
    if (!(s2 <= 1)) for (let t49 = 1; t49 < s2; t49++) {
      const e3 = t49 / s2;
      n2.push(Number((i2 + (r2 - i2) * e3).toFixed(6)));
    }
  }
  return n2;
}
var $W = 1e-3;
function XW(t48) {
  const e2 = [];
  for (let n3 = 1; n3 < t48.length; n3++) {
    const o3 = t48[n3] - t48[n3 - 1];
    o3 > $W && e2.push(o3);
  }
  if (0 === e2.length) return null;
  const n2 = Math.min(...e2), o2 = e2.filter((t49) => t49 <= 1.5 * n2).sort((t49, e3) => t49 - e3), i2 = Math.floor(o2.length / 2);
  return o2.length % 2 == 0 ? (o2[i2 - 1] + o2[i2]) / 2 : o2[i2];
}
function BW(t48) {
  return [...new Set(t48)].sort((t49, e2) => t49 - e2);
}
function HW(t48) {
  return Number(t48.toFixed(6));
}
var WW = class t47 {
  static fromObstacles(e2) {
    if (0 === e2.length) return null;
    const n2 = BW(e2.map((t48) => t48.center.x)), o2 = BW(e2.map((t48) => t48.center.y)), i2 = XW(n2), r2 = XW(o2);
    return null === i2 || null === r2 ? null : new t47({ obstacles: e2, xCoordinates: YW(n2, i2), yCoordinates: YW(o2, r2), pitchX: i2, pitchY: r2 });
  }
  xCoordinates;
  yCoordinates;
  pitchX;
  pitchY;
  originX;
  originY;
  rowCount;
  colCount;
  padWidth;
  padHeight;
  slots = /* @__PURE__ */ new Map();
  constructor(t48) {
    this.xCoordinates = t48.xCoordinates, this.yCoordinates = t48.yCoordinates, this.pitchX = t48.pitchX, this.pitchY = t48.pitchY, this.originX = this.xCoordinates[0], this.originY = this.yCoordinates[0], this.colCount = this.xCoordinates.length, this.rowCount = this.yCoordinates.length, this.padWidth = t48.obstacles[0].width, this.padHeight = t48.obstacles[0].height;
    for (const e2 of t48.obstacles) {
      const t49 = this.getSlotForObstacle(e2);
      t49 && this.slots.set(this.getSlotKey(t49.row, t49.col), { ...t49, obstacle: e2 });
    }
  }
  getSlotKey(t48, e2) {
    return `${t48}:${e2}`;
  }
  getAxisIndex(t48, e2) {
    let n2 = -1, o2 = Number.POSITIVE_INFINITY;
    for (let i2 = 0; i2 < t48.length; i2++) {
      const r2 = Math.abs(t48[i2] - e2);
      r2 < o2 && (o2 = r2, n2 = i2);
    }
    return o2 <= $W ? n2 : null;
  }
  getAxisCoordinate(t48, e2) {
    return t48[e2];
  }
  hasPadAt(t48, e2) {
    return this.slots.has(this.getSlotKey(t48, e2));
  }
  getSlotForObstacle(t48) {
    const e2 = this.getAxisIndex(this.yCoordinates, t48.center.y), n2 = this.getAxisIndex(this.xCoordinates, t48.center.x);
    return null === e2 || null === n2 || e2 < 0 || e2 >= this.rowCount || n2 < 0 || n2 >= this.colCount ? null : { row: e2, col: n2 };
  }
  getSlotCenter(t48, e2) {
    return { x: this.getAxisCoordinate(this.xCoordinates, e2), y: this.getAxisCoordinate(this.yCoordinates, t48) };
  }
  getHorizontalGap(t48, e2) {
    const n2 = this.getSlotCenter(t48, e2), o2 = this.getSlotCenter(t48, e2 + 1), i2 = Math.abs(o2.x - n2.x);
    return { orientation: "horizontal", row: t48, col: e2, center: { x: HW((n2.x + o2.x) / 2), y: n2.y }, width: i2 - this.padWidth, height: this.padHeight, isBetweenTwoPads: this.hasPadAt(t48, e2) && this.hasPadAt(t48, e2 + 1) };
  }
  getVerticalGap(t48, e2) {
    const n2 = this.getSlotCenter(t48, e2), o2 = this.getSlotCenter(t48 + 1, e2), i2 = Math.abs(o2.y - n2.y);
    return { orientation: "vertical", row: t48, col: e2, center: { x: n2.x, y: HW((n2.y + o2.y) / 2) }, width: this.padWidth, height: i2 - this.padHeight, isBetweenTwoPads: this.hasPadAt(t48, e2) && this.hasPadAt(t48 + 1, e2) };
  }
  getDiagonalGap(t48, e2) {
    const n2 = this.getSlotCenter(t48, e2), o2 = this.getSlotCenter(t48 + 1, e2 + 1), i2 = Math.abs(o2.x - n2.x), r2 = Math.abs(o2.y - n2.y);
    return { orientation: "diagonal", row: t48, col: e2, center: { x: HW((n2.x + o2.x) / 2), y: HW((n2.y + o2.y) / 2) }, width: i2 - this.padWidth, height: r2 - this.padHeight, isBetweenTwoPads: this.hasPadAt(t48, e2) && this.hasPadAt(t48 + 1, e2 + 1) };
  }
  getDiagonalGaps() {
    const t48 = [];
    for (let e2 = 0; e2 < this.rowCount - 1; e2++) for (let n2 = 0; n2 < this.colCount - 1; n2++) t48.push(this.getDiagonalGap(e2, n2));
    return t48.filter((t49) => t49.width > $W && t49.height > $W);
  }
  getAxisGaps() {
    const t48 = [];
    for (let e2 = 0; e2 < this.rowCount; e2++) for (let n2 = 0; n2 < this.colCount - 1; n2++) t48.push(this.getHorizontalGap(e2, n2));
    for (let e2 = 0; e2 < this.rowCount - 1; e2++) for (let n2 = 0; n2 < this.colCount; n2++) t48.push(this.getVerticalGap(e2, n2));
    return t48.filter((t49) => t49.width > $W && t49.height > $W);
  }
  getMissingSlots() {
    const t48 = [];
    for (let e2 = 0; e2 < this.rowCount; e2++) for (let n2 = 0; n2 < this.colCount; n2++) this.hasPadAt(e2, n2) || t48.push({ row: e2, col: n2, center: this.getSlotCenter(e2, n2), width: this.padWidth, height: this.padHeight });
    return t48;
  }
};
function VW(t48) {
  if ([t48.point.pointId, t48.point.pcb_port_id].filter((t49) => "string" == typeof t49).some((e3) => t48.obstacle.connectedTo.includes(e3))) return true;
  if (0 === t48.obstacle.connectedTo.length) return false;
  if (Oe(t48.point, t48.obstacle) > 1e-3) return false;
  const e2 = uo(t48.point).map((e3) => No(e3, t48.layerCount)), n2 = t48.obstacle.layers.map((e3) => No(e3, t48.layerCount));
  return e2.some((t49) => n2.includes(t49));
}
function UW(t48) {
  return t48.obstacleId ?? [t48.componentId ?? "no-component", t48.center.x, t48.center.y, t48.width, t48.height, t48.layers.join(",")].join(":");
}
function GW({ componentId: t48, orientationKey: e2, row: n2, col: o2, center: i2, width: r2, height: s2 }) {
  return ["cmn", e2, t48, n2, o2, i2.x, i2.y, r2, s2].join("_");
}
function ZW(t48) {
  const { componentId: e2, bgaGap: n2, freeLayers: o2, multiLayerThreshold: i2 } = t48, r2 = n2.width > i2 && n2.height > i2;
  let s2 = "d";
  "horizontal" === n2.orientation && (s2 = "h"), "vertical" === n2.orientation && (s2 = "v");
  const a2 = GW({ componentId: e2, orientationKey: s2, row: n2.row, col: n2.col, center: n2.center, width: n2.width, height: n2.height });
  return "diagonal" === n2.orientation && r2 || !n2.isBetweenTwoPads && r2 ? [{ center: n2.center, width: n2.width, height: n2.height, availableZ: [...o2], capacityMeshNodeId: `${a2}_all`, layer: "" }] : o2.map((t49) => ({ center: n2.center, width: n2.width, height: n2.height, availableZ: [t49], capacityMeshNodeId: `${a2}_${t49}`, layer: "" }));
}
function qW(t48) {
  const { componentId: e2, obstacle: n2, freeLayers: o2, layerCount: i2 } = t48, r2 = n2.layers.map((t49) => No(t49, i2)), s2 = o2.filter((t49) => !r2.includes(t49)), a2 = UW(n2);
  return s2.map((t49) => ({ capacityMeshNodeId: `free-${e2}-${a2}-${t49}`, center: n2.center, width: n2.width, height: n2.height, layer: `z${t49}`, availableZ: [t49] }));
}
function JW(t48, e2, n2) {
  const o2 = e2.layers.map((t49) => No(t49, n2.layerCount)), i2 = UW(e2), r2 = (function(t49) {
    for (const e3 of t49.srj.connections) for (const n3 of e3.pointsToConnect) if (VW({ point: n3, obstacle: t49.obstacle, layerCount: t49.srj.layerCount })) return e3.__rootConnectionNames?.[0] ?? e3.name;
  })({ obstacle: e2, srj: n2 });
  return { capacityMeshNodeId: `obstacle-${t48}-${i2}-${o2.join(",")}-${e2.center.x}-${e2.center.y}`, _containsObstacle: true, ...r2 ? { _containsTarget: true, _targetConnectionName: r2 } : {}, center: e2.center, width: e2.width, height: e2.height, layer: `z${o2.join(",")}`, availableZ: o2 };
}
var KW = class extends wt {
  constructor(t48) {
    super(), this.inputProblem = t48;
  }
  inputProblem;
  componentObstacles = [];
  meshNodes = [];
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    const { srj: t48, componentBounds: e2, componentId: n2, markedComponentObstacles: o2, unmarkedComponentObstacles: i2 } = this.inputProblem, r2 = t48.obstacles.filter((t49) => true === t49.isCopperPour).filter((t49) => ze(ke(t49), e2)).flatMap((e3) => e3.layers.map((e4) => No(e4, t48.layerCount))), s2 = Array.from({ length: t48.layerCount }, (t49, e3) => e3).filter((t49) => !r2.includes(t49));
    if (this.componentObstacles = o2, 0 === o2.length || 0 === s2.length) return void (this.solved = true);
    const a2 = WW.fromObstacles(o2);
    if (!a2) return void (this.solved = true);
    const c2 = a2.getAxisGaps(), l2 = a2.getDiagonalGaps(), h2 = a2.getMissingSlots(), d2 = 1.2 * (this.inputProblem.viaDiameter ?? Do(t48).padDiameter);
    this.meshNodes = [...c2.flatMap((t49) => ZW({ componentId: n2, bgaGap: t49, freeLayers: s2, multiLayerThreshold: d2 })), ...l2.flatMap((t49) => ZW({ componentId: n2, bgaGap: t49, freeLayers: s2, multiLayerThreshold: d2 })), ...h2.flatMap((t49) => (function(t50) {
      const { componentId: e3, missingBgaSlot: n3, freeLayers: o3, multiLayerThreshold: i3 } = t50, r3 = GW({ componentId: e3, orientationKey: "missing", row: n3.row, col: n3.col, center: n3.center, width: n3.width, height: n3.height });
      return n3.width > i3 && n3.height > i3 ? [{ center: n3.center, width: n3.width, height: n3.height, availableZ: [...o3], capacityMeshNodeId: `${r3}_all`, layer: "" }] : o3.map((t51) => ({ center: n3.center, width: n3.width, height: n3.height, availableZ: [t51], capacityMeshNodeId: `${r3}_${t51}`, layer: "" }));
    })({ componentId: n2, missingBgaSlot: t49, freeLayers: s2, multiLayerThreshold: d2 })), ...o2.flatMap((e3) => [...qW({ componentId: n2, obstacle: e3, freeLayers: s2, layerCount: t48.layerCount }), JW(n2, e3, t48)]), ...i2.flatMap((e3) => [JW(n2, e3, t48)])], this.meshNodes = (function(t49) {
      const e3 = /* @__PURE__ */ new Map();
      return t49.map((t50) => {
        const n3 = e3.get(t50.capacityMeshNodeId) ?? 0;
        return e3.set(t50.capacityMeshNodeId, n3 + 1), 0 === n3 ? t50 : { ...t50, capacityMeshNodeId: `${t50.capacityMeshNodeId}__dup${n3}` };
      });
    })(this.meshNodes), this.solved = true;
  }
  getOutput() {
    return this.meshNodes;
  }
  visualize() {
    return { rects: [{ center: { x: (this.inputProblem.componentBounds.minX + this.inputProblem.componentBounds.maxX) / 2, y: (this.inputProblem.componentBounds.minY + this.inputProblem.componentBounds.maxY) / 2 }, width: this.inputProblem.componentBounds.maxX - this.inputProblem.componentBounds.minX, height: this.inputProblem.componentBounds.maxY - this.inputProblem.componentBounds.minY, fill: "rgba(0,0,0,0)", stroke: "rgba(30,30,30,0.65)", label: `component ${this.inputProblem.componentId}` }, ...this.inputProblem.markedComponentObstacles.map((t48) => ({ center: t48.center, width: t48.width, height: t48.height, fill: "rgba(255,0,0,0.18)", stroke: "rgba(255,0,0,0.52)", label: `pad ${t48.obstacleId ?? "obstacle"}` })), ...this.inputProblem.unmarkedComponentObstacles.map((t48) => ({ center: t48.center, width: t48.width, height: t48.height, fill: "rgba(255,140,0,0.14)", stroke: "rgba(255,140,0,0.42)", label: `foreign ${t48.obstacleId ?? "obstacle"}` })), ...this.meshNodes.map((t48) => ({ ...ac(t48, { rectMargin: 0.01 }), fill: t48._containsObstacle ? "rgba(255,0,0,0.14)" : t48.capacityMeshNodeId.includes("missing") ? "rgba(0,200,120,0.18)" : "rgba(0,120,255,0.12)", stroke: t48._containsObstacle ? "rgba(255,0,0,0.36)" : t48.capacityMeshNodeId.includes("missing") ? "rgba(0,200,120,0.52)" : "rgba(0,120,255,0.38)" }))] };
  }
};
function QW(t48) {
  return t48.capacityMeshNodeId.startsWith("bga-gapfill-");
}
function tV(t48) {
  return JSON.stringify({ availableZ: [...t48.availableZ].sort((t49, e2) => t49 - e2), _containsTarget: t48._containsTarget ?? false, _targetConnectionName: t48._targetConnectionName ?? null, _depth: t48._depth ?? null, _strawNode: t48._strawNode ?? false, _strawParentCapacityMeshNodeId: t48._strawParentCapacityMeshNodeId ?? null, _qfpRegionType: t48._qfpRegionType ?? null, _isNarrowQfpPadGap: t48._isNarrowQfpPadGap ?? false, _soicRegionType: t48._soicRegionType ?? null, _offBoardConnectionId: t48._offBoardConnectionId ?? null, _offboardNetName: t48._offboardNetName ?? null, _isVirtualOffboard: t48._isVirtualOffboard ?? false, _containsObstacle: t48._containsObstacle ?? false });
}
function eV(t48, e2) {
  const n2 = ke(t48);
  for (const o2 of e2) {
    if (!t48.availableZ.some((t49) => o2.availableZ.includes(t49))) continue;
    const e3 = ke(o2);
    if (ze(n2, e3)) return true;
  }
  return false;
}
function nV(t48) {
  const e2 = t48[0];
  if (!e2) throw new Error("createMergedNode requires at least one source node");
  let n2 = Number.POSITIVE_INFINITY, o2 = Number.NEGATIVE_INFINITY, i2 = Number.POSITIVE_INFINITY, r2 = Number.NEGATIVE_INFINITY;
  for (const e3 of t48) {
    const t49 = ke(e3);
    n2 = Math.min(n2, t49.minX), o2 = Math.max(o2, t49.maxX), i2 = Math.min(i2, t49.minY), r2 = Math.max(r2, t49.maxY);
  }
  return { ...e2, capacityMeshNodeId: `merge:${t48.map((t49) => t49.capacityMeshNodeId).join(":")}`, center: { x: (n2 + o2) / 2, y: (i2 + r2) / 2 }, width: o2 - n2, height: r2 - i2 };
}
function oV(t48, e2, n2) {
  return { center: t48.center, width: t48.width, height: t48.height, fill: e2, stroke: e2, label: n2 };
}
var iV = class extends wt {
  constructor(t48) {
    super(), this.inputProblem = t48;
  }
  inputProblem;
  obstacleNodes = [];
  passthroughNodes = [];
  mergedNodes = [];
  pendingGroups = [];
  totalGroupCount = 0;
  processedGroupCount = 0;
  debugFilteredNodes = [];
  debugMergeEvents = [];
  currentGroupKey = null;
  currentRootNodeId = null;
  lastMergedNodeId = null;
  _setup() {
    this.obstacleNodes = this.inputProblem.meshNodes.filter((t49) => true === t49._containsObstacle), this.passthroughNodes = [], this.mergedNodes = [], this.pendingGroups = [], this.totalGroupCount = 0, this.processedGroupCount = 0, this.debugFilteredNodes = [], this.debugMergeEvents = [], this.currentGroupKey = null, this.currentRootNodeId = null, this.lastMergedNodeId = null;
    const t48 = /* @__PURE__ */ new Map();
    for (const e2 of this.inputProblem.meshNodes) {
      if (true === e2._containsObstacle) {
        this.passthroughNodes.push(e2), this.debugFilteredNodes.push({ type: "preserved-obstacle", node: e2, reason: "contains-obstacle" });
        continue;
      }
      if (QW(e2)) {
        this.passthroughNodes.push(e2);
        continue;
      }
      if (e2.availableZ.length !== this.inputProblem.layerCount) {
        this.passthroughNodes.push(e2);
        continue;
      }
      let n2 = false;
      for (let t49 = 0; t49 < this.inputProblem.layerCount; t49 += 1) if (!e2.availableZ.includes(t49)) {
        n2 = true;
        break;
      }
      if (n2) {
        this.passthroughNodes.push(e2);
        continue;
      }
      if (eV(e2, this.obstacleNodes)) {
        this.passthroughNodes.push(e2), this.debugFilteredNodes.push({ type: "preserved-overlap", node: e2, reason: "overlaps-obstacle" });
        continue;
      }
      const o2 = tV(e2), i2 = t48.get(o2);
      i2 ? i2.push(e2) : t48.set(o2, [e2]);
    }
    for (const [e2, n2] of t48.entries()) n2.length <= 1 ? this.passthroughNodes.push(...n2) : this.pendingGroups.push({ groupKey: e2, nodes: n2 });
    this.pendingGroups.sort((t49, e2) => e2.nodes.length - t49.nodes.length), this.totalGroupCount = this.pendingGroups.length, this.updateStats("setup");
  }
  _step() {
    const t48 = this.pendingGroups.shift();
    if (!t48) return this.currentGroupKey = null, this.currentRootNodeId = null, this.solved = true, void this.updateStats("done");
    const e2 = t48.nodes[0];
    this.currentGroupKey = t48.groupKey, this.currentRootNodeId = e2 ? e2.capacityMeshNodeId : null;
    const n2 = (function(t49) {
      if (!t49.nodes[0]) return { outputNodes: [], mergeEvents: [] };
      let e3 = Number.POSITIVE_INFINITY, n3 = Number.POSITIVE_INFINITY, o3 = Number.POSITIVE_INFINITY, i2 = Number.POSITIVE_INFINITY;
      for (const r3 of t49.nodes) {
        e3 = Math.min(e3, r3.width), n3 = Math.min(n3, r3.height);
        const t50 = ke(r3);
        o3 = Math.min(o3, t50.minX), i2 = Math.min(i2, t50.minY);
      }
      const r2 = /* @__PURE__ */ new Map(), s2 = [];
      for (const a3 of t49.nodes) {
        const t50 = ke(a3), c3 = Math.round((t50.minX - o3) / e3), l3 = Math.round((t50.minY - i2) / n3), h2 = Math.max(1, Math.round(a3.width / e3)), d2 = Math.max(1, Math.round(a3.height / n3));
        for (let t51 = 0; t51 < d2; t51 += 1) for (let e4 = 0; e4 < h2; e4 += 1) r2.set(`${c3 + e4},${l3 + t51}`, a3);
        s2.push({ col: c3, row: l3 });
      }
      s2.sort((t50, e4) => t50.row - e4.row || t50.col - e4.col);
      const a2 = /* @__PURE__ */ new Set(), c2 = [], l2 = [];
      for (const o4 of s2) {
        const i3 = `${o4.col},${o4.row}`;
        if (a2.has(i3)) continue;
        let s3 = 0;
        for (; ; ) {
          const t50 = `${o4.col + s3},${o4.row}`;
          if (!r2.has(t50)) break;
          if (a2.has(t50)) break;
          s3 += 1;
        }
        let h2 = s3, d2 = 1, u2 = 1, p2 = 1;
        for (let t50 = 1; ; t50 += 1) {
          const i4 = o4.row + t50 - 1;
          let s4 = 0;
          for (; s4 < h2; ) {
            const t51 = `${o4.col + s4},${i4}`;
            if (!r2.has(t51)) break;
            if (a2.has(t51)) break;
            s4 += 1;
          }
          if (0 === s4) break;
          h2 = Math.min(h2, s4);
          for (let o5 = h2; o5 >= 1; o5 -= 1) {
            const i5 = o5 * e3, r3 = t50 * n3, s5 = Math.min(i5, r3);
            if ((s5 <= 1e-6 ? Number.POSITIVE_INFINITY : Math.max(i5, r3) / s5) > 4) continue;
            const a3 = o5 * t50;
            a3 > p2 && (p2 = a3, d2 = o5, u2 = t50);
            break;
          }
        }
        const m2 = /* @__PURE__ */ new Map();
        for (let t50 = 0; t50 < u2; t50 += 1) for (let e4 = 0; e4 < d2; e4 += 1) {
          const n4 = `${o4.col + e4},${o4.row + t50}`, i4 = r2.get(n4);
          i4 && (a2.add(n4), m2.set(i4.capacityMeshNodeId, i4));
        }
        const g2 = [...m2.values()];
        if (g2.length <= 1) {
          const t50 = g2[0];
          t50 && c2.push(t50);
          continue;
        }
        const f2 = nV(g2);
        c2.push(f2), l2.push({ type: "merge", groupKey: t49.groupKey, sourceNodes: g2, mergedNode: f2 });
      }
      return { outputNodes: c2, mergeEvents: l2 };
    })(t48);
    this.mergedNodes.push(...n2.outputNodes), this.processedGroupCount += 1, this.debugMergeEvents.push(...n2.mergeEvents);
    const o2 = n2.mergeEvents[n2.mergeEvents.length - 1];
    o2 && (this.lastMergedNodeId = o2.mergedNode.capacityMeshNodeId), this.updateStats(n2.mergeEvents.length > 0 ? "merged-group" : "passthrough-group");
  }
  computeProgress() {
    return 0 === this.totalGroupCount ? 1 : this.processedGroupCount / this.totalGroupCount;
  }
  updateStats(t48) {
    const e2 = new Set(this.debugMergeEvents.map((t49) => t49.groupKey)), n2 = { lastAction: t48, totalGroupCount: this.totalGroupCount, processedGroupCount: this.processedGroupCount, pendingGroupCount: this.pendingGroups.length, mergedNodeCount: this.mergedNodes.length, passthroughNodeCount: this.passthroughNodes.length, gapFillNodeCount: this.passthroughNodes.filter(QW).length, preservedObstacleNodeCount: this.debugFilteredNodes.filter((t49) => "preserved-obstacle" === t49.type).length, preservedOverlapNodeCount: this.debugFilteredNodes.filter((t49) => "preserved-overlap" === t49.type).length, mergeCount: this.debugMergeEvents.length, mergedGroupCount: e2.size, currentGroupKey: this.currentGroupKey, currentRootNodeId: this.currentRootNodeId, lastMergedNodeId: this.lastMergedNodeId };
    this.stats = n2;
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return [...this.mergedNodes, ...this.passthroughNodes];
  }
  visualize() {
    const t48 = this.getOutput(), e2 = this.currentRootNodeId ? t48.find((t49) => t49.capacityMeshNodeId === this.currentRootNodeId) ?? null : null, n2 = this.lastMergedNodeId ? t48.find((t49) => t49.capacityMeshNodeId === this.lastMergedNodeId) ?? null : null;
    return { rects: [...this.debugFilteredNodes.map((t49) => oV(t49.node, "preserved-obstacle" === t49.type ? "rgba(255,64,64,0.35)" : "rgba(255,160,64,0.35)", t49.reason)), ...this.passthroughNodes.map((t49) => oV(t49, t49._containsObstacle ? "rgba(255,0,0,0.35)" : QW(t49) ? "rgba(0,120,255,0.18)" : "rgba(160,160,160,0.12)")), ...this.mergedNodes.map((t49) => oV(t49, "rgba(120,120,120,0.14)")), ...e2 ? [oV(e2, "rgba(255,215,0,0.35)", "active-group")] : [], ...n2 ? [oV(n2, "rgba(0,200,120,0.28)", "merged")] : []] };
  }
};
var rV = class extends wt {
  constructor(t48) {
    super(), this.inputProblem = t48;
  }
  inputProblem;
  obstacleQueue = [];
  obstacleQueueIndex = 0;
  meshNodes = [];
  _setup() {
    this.obstacleQueue = this.inputProblem.obstacles, this.obstacleQueueIndex = 0, this.meshNodes = [...this.inputProblem.meshNodes];
  }
  _step() {
    if (this.obstacleQueueIndex >= this.obstacleQueue.length) return void (this.solved = true);
    const t48 = this.obstacleQueue[this.obstacleQueueIndex], e2 = t48.layers.map((t49) => No(t49, this.inputProblem.layerCount)), n2 = [];
    for (const o2 of this.meshNodes) {
      if (o2._containsObstacle) {
        n2.push(o2);
        continue;
      }
      if (!e2.some((t49) => o2.availableZ.includes(t49))) {
        n2.push(o2);
        continue;
      }
      if (!ze(ke(o2), ke(t48))) {
        n2.push(o2);
        continue;
      }
      if (1 === o2.availableZ.length) continue;
      const i2 = o2.availableZ.filter((t49) => !e2.includes(t49));
      for (const t49 of i2) {
        const e3 = { ...o2, capacityMeshNodeId: `${o2.capacityMeshNodeId}:z${t49}`, availableZ: [t49], layer: `z${t49}` };
        n2.push(e3);
      }
    }
    this.meshNodes = n2, this.obstacleQueueIndex += 1, this.stats = { obstaclesProcessed: this.obstacleQueueIndex, obstacleCount: this.obstacleQueue.length, meshNodeCount: this.meshNodes.length };
  }
  computeProgress() {
    return 0 === this.obstacleQueue.length ? 1 : this.obstacleQueueIndex / this.obstacleQueue.length;
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return this.meshNodes;
  }
  visualize() {
    const t48 = this.obstacleQueueIndex < this.obstacleQueue.length ? this.obstacleQueue[this.obstacleQueueIndex] ?? null : null, e2 = this.obstacleQueue.slice(0, this.obstacleQueueIndex), n2 = t48 ? this.obstacleQueue.slice(this.obstacleQueueIndex + 1) : [];
    return { rects: [...e2.map((t49) => ({ center: t49.center, width: t49.width, height: t49.height, fill: "rgba(160,160,160,0.10)", stroke: "rgba(160,160,160,0.35)", label: `processed ${t49.obstacleId ?? "obstacle"}` })), ...t48 ? [{ center: t48.center, width: t48.width, height: t48.height, fill: "rgba(255,140,0,0.22)", stroke: "rgba(255,140,0,0.75)", label: `active ${t48.obstacleId ?? "obstacle"}` }] : [], ...n2.map((t49) => ({ center: t49.center, width: t49.width, height: t49.height, fill: "rgba(255,0,0,0.05)", stroke: "rgba(255,0,0,0.22)", label: `pending ${t49.obstacleId ?? "obstacle"}` })), ...this.meshNodes.map((t49) => ({ ...ac(t49, { rectMargin: 0.01 }), fill: t49._containsObstacle ? "rgba(255,0,0,0.18)" : "rgba(0,120,255,0.12)", stroke: t49._containsObstacle ? "rgba(255,0,0,0.45)" : "rgba(0,120,255,0.45)" }))] };
  }
};
xW.register(class extends Rt {
  constructor(t48) {
    super(t48), this.inputProblem = t48;
  }
  inputProblem;
  static componentKind = "bga";
  initialTopologySolver;
  removeMeshNodeOverlappingWithUnmarkedObstacle;
  gapfillDueToNodeRemoval;
  mergeMeshNodes;
  markedComponentObstacles = [];
  unmarkedComponentObstacles = [];
  pipelineDef = [Tt("initialTopologySolver", KW, (t48) => [{ srj: t48.inputProblem.inputSrj, componentBounds: t48.inputProblem.detectedComponent.bounds, componentId: t48.inputProblem.detectedComponent.componentId, markedComponentObstacles: t48.markedComponentObstacles, unmarkedComponentObstacles: t48.unmarkedComponentObstacles, viaDiameter: t48.inputProblem.viaDiameter }]), Tt("removeMeshNodeOverlappingWithUnmarkedObstacle", rV, (t48) => [{ meshNodes: t48.initialTopologySolver.getOutput(), obstacles: t48.unmarkedComponentObstacles, layerCount: t48.inputProblem.inputSrj.layerCount }]), Tt("gapfillDueToNodeRemoval", jW, (t48) => [{ meshNodes: t48.removeMeshNodeOverlappingWithUnmarkedObstacle.getOutput(), unmarkedComponentObstacles: t48.unmarkedComponentObstacles, layerCount: t48.inputProblem.inputSrj.layerCount }]), Tt("mergeMeshNodes", iV, (t48) => [{ meshNodes: t48.gapfillDueToNodeRemoval.getOutput(), layerCount: t48.inputProblem.inputSrj.layerCount }])];
  _setup() {
    const t48 = this.inputProblem.detectedComponent.bounds, e2 = this.inputProblem.detectedComponent.componentId, n2 = [], o2 = [];
    for (const i2 of this.inputProblem.inputSrj.obstacles) {
      const r2 = ke(i2);
      ze(t48, r2) && (i2.componentId !== e2 ? o2.push(i2) : n2.push(i2));
    }
    this.markedComponentObstacles = n2, this.unmarkedComponentObstacles = o2;
  }
  getConstructorParams() {
    return [this.inputProblem];
  }
  getOutput() {
    return { routingRegions: this.mergeMeshNodes?.getOutput() ?? this.gapfillDueToNodeRemoval?.getOutput() ?? this.removeMeshNodeOverlappingWithUnmarkedObstacle?.getOutput() ?? [] };
  }
  initialVisualize() {
    return { rects: [{ center: { x: (this.inputProblem.detectedComponent.bounds.minX + this.inputProblem.detectedComponent.bounds.maxX) / 2, y: (this.inputProblem.detectedComponent.bounds.minY + this.inputProblem.detectedComponent.bounds.maxY) / 2 }, width: this.inputProblem.detectedComponent.bounds.maxX - this.inputProblem.detectedComponent.bounds.minX, height: this.inputProblem.detectedComponent.bounds.maxY - this.inputProblem.detectedComponent.bounds.minY, fill: "rgba(0,0,0,0)", stroke: "rgba(30,30,30,0.65)", label: `bga ${this.inputProblem.detectedComponent.componentId}` }, ...this.markedComponentObstacles.map((t48) => ({ center: t48.center, width: t48.width, height: t48.height, fill: "rgba(255,0,0,0.18)", stroke: "rgba(255,0,0,0.52)", label: `pad ${t48.obstacleId ?? "obstacle"}` })), ...this.unmarkedComponentObstacles.map((t48) => ({ center: t48.center, width: t48.width, height: t48.height, fill: "rgba(255,140,0,0.14)", stroke: "rgba(255,140,0,0.42)", label: `foreign ${t48.obstacleId ?? "obstacle"}` }))] };
  }
  finalVisualize() {
    return { rects: this.getOutput().routingRegions.map((t48) => ({ ...ac(t48, { rectMargin: 0.01 }), fill: t48._containsObstacle ? "rgba(255,0,0,0.16)" : "rgba(0,120,255,0.12)", stroke: t48._containsObstacle ? "rgba(255,0,0,0.36)" : "rgba(0,120,255,0.42)" })) };
  }
});
var sV = 1e-6;
function aV(t48, e2) {
  return t48.__zLayers && t48.__zLayers.length > 0 ? wo(t48.__zLayers, e2) : To(t48.layers, e2);
}
function cV(t48) {
  const e2 = [...t48].sort((t49, e3) => t49 - e3), n2 = [];
  for (let t49 = 1; t49 < e2.length; t49++) {
    const o3 = e2[t49] - e2[t49 - 1];
    o3 > sV && n2.push(o3);
  }
  const o2 = n2.length > 0 ? Math.max(sV, Math.min(...n2) / 4) : 1e-3, i2 = [];
  for (const t49 of e2) {
    const e3 = i2[i2.length - 1];
    (void 0 === e3 || Math.abs(t49 - e3) > o2) && i2.push(t49);
  }
  return i2;
}
function lV(t48) {
  return Array.from({ length: Math.max(0, t48) }, (t49, e2) => e2);
}
var hV = 1e-6;
function dV(t48) {
  return t48.maxX - t48.minX > hV && t48.maxY - t48.minY > hV;
}
function uV(t48) {
  return (function(t49) {
    const e2 = Math.min(t49.width, t49.height), n2 = Math.max(t49.width, t49.height);
    return e2 <= 0 ? 0 : n2 / e2;
  })(t48) >= 1.5;
}
function pV(t48, e2) {
  const n2 = [{ side: "top", distance: Math.abs(t48.center.y - e2.minY) }, { side: "right", distance: Math.abs(e2.maxX - t48.center.x) }, { side: "bottom", distance: Math.abs(e2.maxY - t48.center.y) }, { side: "left", distance: Math.abs(t48.center.x - e2.minX) }];
  return n2.sort((t49, e3) => t49.distance - e3.distance), n2[0].side;
}
function mV(t48, e2) {
  return t48.map((t49, n2) => ({ key: `pad:${t49.obstacleId ?? n2}`, bounds: Me(t49), regionType: "pad", obstacleZ: aV(t49, e2) }));
}
function gV(t48, e2) {
  return t48.map((t49, n2) => ({ key: `thermal-pad:${t49.obstacleId ?? n2}`, bounds: Me(t49), regionType: "pad", obstacleZ: aV(t49, e2) }));
}
function fV(t48, e2) {
  return !!dV(t48) && Math.min(t48.maxX - t48.minX, t48.maxY - t48.minY) <= e2;
}
function _V({ side: t48, sideObstacles: e2, bounds: n2, innerBounds: o2, narrowThreshold: i2 }) {
  const r2 = [];
  for (let s2 = 0; s2 < e2.length - 1; s2++) {
    const a2 = Me(e2[s2]), c2 = Me(e2[s2 + 1]);
    let l2;
    l2 = "top" === t48 ? { minX: a2.maxX, maxX: c2.minX, minY: n2.minY, maxY: o2.minY } : "right" === t48 ? { minX: o2.maxX, maxX: n2.maxX, minY: a2.maxY, maxY: c2.minY } : "bottom" === t48 ? { minX: a2.maxX, maxX: c2.minX, minY: o2.maxY, maxY: n2.maxY } : { minX: n2.minX, maxX: o2.minX, minY: a2.maxY, maxY: c2.minY }, r2.push({ key: `${t48}-gap-${s2}`, bounds: l2, regionType: "pad-gap", isNarrowPadGap: fV(l2, i2) });
  }
  return r2;
}
function yV({ side: t48, sideObstacles: e2, thermalPadBounds: n2, narrowThreshold: o2 }) {
  const i2 = [];
  for (let r2 = 0; r2 < e2.length; r2++) {
    const s2 = Me(e2[r2]), a2 = e2[r2 - 1] ? Me(e2[r2 - 1]) : null, c2 = e2[r2 + 1] ? Me(e2[r2 + 1]) : null;
    let l2;
    l2 = "top" === t48 ? { minX: a2 ? (a2.maxX + s2.minX) / 2 : s2.minX, maxX: c2 ? (s2.maxX + c2.minX) / 2 : s2.maxX, minY: s2.maxY, maxY: n2.minY } : "right" === t48 ? { minX: n2.maxX, maxX: s2.minX, minY: a2 ? (a2.maxY + s2.minY) / 2 : s2.minY, maxY: c2 ? (s2.maxY + c2.minY) / 2 : s2.maxY } : "bottom" === t48 ? { minX: a2 ? (a2.maxX + s2.minX) / 2 : s2.minX, maxX: c2 ? (s2.maxX + c2.minX) / 2 : s2.maxX, minY: n2.maxY, maxY: s2.minY } : { minX: s2.maxX, maxX: n2.minX, minY: a2 ? (a2.maxY + s2.minY) / 2 : s2.minY, maxY: c2 ? (s2.maxY + c2.minY) / 2 : s2.maxY }, i2.push({ key: `inner-${t48}-pad-${r2}`, bounds: l2, regionType: "pad-gap", isNarrowPadGap: fV(l2, o2) });
  }
  return i2;
}
function bV({ bounds: t48, innerBounds: e2, sideGroups: n2 }) {
  const o2 = n2.top[0] ? Me(n2.top[0]) : null, i2 = n2.top.at(-1) ? Me(n2.top.at(-1)) : null, r2 = n2.right[0] ? Me(n2.right[0]) : null, s2 = n2.right.at(-1) ? Me(n2.right.at(-1)) : null, a2 = n2.bottom[0] ? Me(n2.bottom[0]) : null, c2 = n2.bottom.at(-1) ? Me(n2.bottom.at(-1)) : null, l2 = n2.left[0] ? Me(n2.left[0]) : null, h2 = n2.left.at(-1) ? Me(n2.left.at(-1)) : null;
  return [{ key: "corner-nw-outer", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: "corner-nw-top", regionType: "corner", bounds: { minX: e2.minX, maxX: o2?.minX ?? e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: "corner-nw-left", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.minY, maxY: l2?.minY ?? e2.minY } }, { key: "corner-ne-outer", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: t48.minY, maxY: e2.minY } }, { key: "corner-ne-top", regionType: "corner", bounds: { minX: i2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: t48.minY, maxY: e2.minY } }, { key: "corner-ne-right", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.minY, maxY: r2?.minY ?? e2.minY } }, { key: "corner-se-outer", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: "corner-se-right", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: s2?.maxY ?? e2.maxY, maxY: e2.maxY } }, { key: "corner-se-bottom", regionType: "corner", bounds: { minX: c2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: "corner-sw-outer", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: "corner-sw-bottom", regionType: "corner", bounds: { minX: e2.minX, maxX: a2?.minX ?? e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: "corner-sw-left", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: h2?.maxY ?? e2.maxY, maxY: e2.maxY } }];
}
function xV({ innerBounds: t48, thermalPadBounds: e2, sideGroups: n2 }) {
  const o2 = n2.top[0] ? Me(n2.top[0]) : null, i2 = n2.top.at(-1) ? Me(n2.top.at(-1)) : null, r2 = n2.right[0] ? Me(n2.right[0]) : null, s2 = n2.right.at(-1) ? Me(n2.right.at(-1)) : null, a2 = n2.bottom[0] ? Me(n2.bottom[0]) : null, c2 = n2.bottom.at(-1) ? Me(n2.bottom.at(-1)) : null, l2 = n2.left[0] ? Me(n2.left[0]) : null, h2 = n2.left.at(-1) ? Me(n2.left.at(-1)) : null;
  return [{ key: "inner-corner-nw-core", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: "inner-corner-nw-top", regionType: "corner", bounds: { minX: e2.minX, maxX: o2?.minX ?? e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: "inner-corner-nw-left", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.minY, maxY: l2?.minY ?? e2.minY } }, { key: "inner-corner-ne-core", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: t48.minY, maxY: e2.minY } }, { key: "inner-corner-ne-top", regionType: "corner", bounds: { minX: i2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: t48.minY, maxY: e2.minY } }, { key: "inner-corner-ne-right", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.minY, maxY: r2?.minY ?? e2.minY } }, { key: "inner-corner-se-core", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: "inner-corner-se-right", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: s2?.maxY ?? e2.maxY, maxY: e2.maxY } }, { key: "inner-corner-se-bottom", regionType: "corner", bounds: { minX: c2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: "inner-corner-sw-core", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: "inner-corner-sw-bottom", regionType: "corner", bounds: { minX: e2.minX, maxX: a2?.minX ?? e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: "inner-corner-sw-left", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: h2?.maxY ?? e2.maxY, maxY: e2.maxY } }];
}
xW.register(class extends wt {
  constructor(t48) {
    super(), this.inputProblem = t48;
  }
  inputProblem;
  static componentKind = "qfp_thermalpad";
  output = null;
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    if (this.output) return void (this.solved = true);
    const { layerCount: t48, obstacles: e2 } = this.inputProblem.inputSrj, { bounds: n2, componentId: o2 } = this.inputProblem.detectedComponent, i2 = lV(t48), r2 = e2.filter((t49) => t49.componentId === o2), s2 = r2.length > 0 ? r2 : e2, { padRingObstacles: a2, thermalPadObstacles: c2 } = (function(t49) {
      return { padRingObstacles: t49.filter(uV), thermalPadObstacles: t49.filter((t50) => !uV(t50)) };
    })(s2), l2 = (function(t49, e3) {
      const n3 = { top: [], right: [], bottom: [], left: [] };
      for (const o3 of t49) n3[pV(o3, e3)].push(o3);
      return n3.top.sort((t50, e4) => t50.center.x - e4.center.x), n3.bottom.sort((t50, e4) => t50.center.x - e4.center.x), n3.left.sort((t50, e4) => t50.center.y - e4.center.y), n3.right.sort((t50, e4) => t50.center.y - e4.center.y), n3;
    })(a2, n2), h2 = (function({ bounds: t49, sideGroups: e3 }) {
      return { minX: e3.left.length > 0 ? Math.max(...e3.left.map((t50) => Me(t50).maxX)) : t49.minX, maxX: e3.right.length > 0 ? Math.min(...e3.right.map((t50) => Me(t50).minX)) : t49.maxX, minY: e3.top.length > 0 ? Math.max(...e3.top.map((t50) => Me(t50).maxY)) : t49.minY, maxY: e3.bottom.length > 0 ? Math.min(...e3.bottom.map((t50) => Me(t50).minY)) : t49.maxY };
    })({ bounds: n2, sideGroups: l2 }), d2 = (function(t49) {
      return 0 === t49.length ? null : t49.reduce((t50, e3) => {
        const n3 = Me(e3);
        return { minX: Math.min(t50.minX, n3.minX), maxX: Math.max(t50.maxX, n3.maxX), minY: Math.min(t50.minY, n3.minY), maxY: Math.max(t50.maxY, n3.maxY) };
      }, Me(t49[0]));
    })(c2);
    if (!d2) return this.failed = true, void (this.error = "QfpThermalPadTopologyGeneratorSolver requires a thermal pad");
    const u2 = o2, p2 = this.inputProblem.viaDiameter ?? Do(this.inputProblem.inputSrj).padDiameter, m2 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, g2 = p2 + 2 * m2, f2 = this.inputProblem.inputSrj.minTraceWidth + 2 * m2, _2 = [...mV(a2, t48), ...gV(c2, t48), ..._V({ side: "top", sideObstacles: l2.top, bounds: n2, innerBounds: h2, narrowThreshold: f2 }), ..._V({ side: "right", sideObstacles: l2.right, bounds: n2, innerBounds: h2, narrowThreshold: f2 }), ..._V({ side: "bottom", sideObstacles: l2.bottom, bounds: n2, innerBounds: h2, narrowThreshold: f2 }), ..._V({ side: "left", sideObstacles: l2.left, bounds: n2, innerBounds: h2, narrowThreshold: f2 }), ...yV({ side: "top", sideObstacles: l2.top, thermalPadBounds: d2, narrowThreshold: f2 }), ...yV({ side: "right", sideObstacles: l2.right, thermalPadBounds: d2, narrowThreshold: f2 }), ...yV({ side: "bottom", sideObstacles: l2.bottom, thermalPadBounds: d2, narrowThreshold: f2 }), ...yV({ side: "left", sideObstacles: l2.left, thermalPadBounds: d2, narrowThreshold: f2 }), ...xV({ innerBounds: h2, thermalPadBounds: d2, sideGroups: l2 }), ...bV({ bounds: n2, innerBounds: h2, sideGroups: l2 })].flatMap((t49) => (function({ nodeId: t50, bounds: e3, availableZ: n3, multiLayerThreshold: o3, regionType: i3, isNarrowPadGap: r3 = false, obstacleZ: s3 = [] }) {
      if (!dV(e3)) return [];
      const a3 = (function(t51) {
        return { center: { x: (t51.minX + t51.maxX) / 2, y: (t51.minY + t51.maxY) / 2 }, width: t51.maxX - t51.minX, height: t51.maxY - t51.minY };
      })(e3), c3 = Math.min(a3.width, a3.height) > o3, l3 = c3 ? [{ availableZ: n3.filter((t51) => !s3.includes(t51)), containsObstacle: false }, { availableZ: n3.filter((t51) => s3.includes(t51)), containsObstacle: true }].filter((t51) => t51.availableZ.length > 0) : n3.map((t51) => ({ availableZ: [t51], containsObstacle: s3.includes(t51) }));
      return l3.map((e4) => ({ capacityMeshNodeId: 1 === l3.length ? t50 : c3 ? `${t50}:${e4.containsObstacle ? "obstacle" : "free"}` : `${t50}:z${e4.availableZ[0]}`, center: a3.center, width: a3.width, height: a3.height, layer: `z${e4.availableZ.join(",")}`, availableZ: e4.availableZ, _qfpRegionType: i3, _isNarrowQfpPadGap: r3, _containsObstacle: e4.containsObstacle }));
    })({ nodeId: `qfp_thermalpad:${u2}:${t49.key}`, bounds: t49.bounds, availableZ: i2, multiLayerThreshold: g2, regionType: t49.regionType, isNarrowPadGap: t49.isNarrowPadGap, obstacleZ: t49.obstacleZ }));
    this.output = { routingRegions: _2 }, this.stats = { componentId: o2, layerCount: t48, viaDiameter: p2, obstacleMargin: m2, multiLayerThreshold: g2, narrowPadGapThreshold: f2, thermalPadCount: c2.length, perimeterPadCount: a2.length, innerCornerRectCount: _2.filter((t49) => t49.capacityMeshNodeId.includes(":inner-corner-")).length, narrowPadGapNodeCount: _2.filter((t49) => t49._isNarrowQfpPadGap).length, topPadCount: l2.top.length, rightPadCount: l2.right.length, bottomPadCount: l2.bottom.length, leftPadCount: l2.left.length, multiLayerNodeCount: _2.filter((t49) => t49.availableZ.length > 1).length, totalMeshNodeCount: _2.length }, this.solved = true;
  }
  getOutput() {
    if (!this.output) throw new Error("QfpThermalPadTopologyGeneratorSolver has not solved yet");
    return this.output;
  }
});
var vV = 1e-6;
function SV(t48) {
  return t48.maxX - t48.minX > vV && t48.maxY - t48.minY > vV;
}
function IV(t48, e2) {
  const n2 = [{ side: "top", distance: Math.abs(t48.center.y - e2.minY) }, { side: "right", distance: Math.abs(e2.maxX - t48.center.x) }, { side: "bottom", distance: Math.abs(e2.maxY - t48.center.y) }, { side: "left", distance: Math.abs(t48.center.x - e2.minX) }];
  return n2.sort((t49, e3) => t49.distance - e3.distance), n2[0].side;
}
function PV(t48, e2) {
  return t48.map((t49, n2) => ({ key: `pad:${t49.obstacleId ?? n2}`, bounds: Me(t49), regionType: "pad", obstacleZ: aV(t49, e2), connectedTo: [...t49.connectedTo] }));
}
function MV(t48, e2) {
  return !!SV(t48) && Math.min(t48.maxX - t48.minX, t48.maxY - t48.minY) <= e2;
}
function CV({ side: t48, sideObstacles: e2, bounds: n2, centralBounds: o2, narrowThreshold: i2 }) {
  const r2 = [];
  for (let s2 = 0; s2 < e2.length - 1; s2++) {
    const a2 = Me(e2[s2]), c2 = Me(e2[s2 + 1]);
    let l2;
    l2 = "top" === t48 ? { minX: a2.maxX, maxX: c2.minX, minY: n2.minY, maxY: o2.minY } : "right" === t48 ? { minX: o2.maxX, maxX: n2.maxX, minY: a2.maxY, maxY: c2.minY } : "bottom" === t48 ? { minX: a2.maxX, maxX: c2.minX, minY: o2.maxY, maxY: n2.maxY } : { minX: n2.minX, maxX: o2.minX, minY: a2.maxY, maxY: c2.minY }, r2.push({ key: `${t48}-gap-${s2}`, bounds: l2, regionType: "pad-gap", isNarrowPadGap: MV(l2, i2) });
  }
  return r2;
}
function NV({ bounds: t48, centralBounds: e2, sideGroups: n2 }) {
  const o2 = n2.top[0] ? Me(n2.top[0]) : null, i2 = n2.top.at(-1) ? Me(n2.top.at(-1)) : null, r2 = n2.right[0] ? Me(n2.right[0]) : null, s2 = n2.right.at(-1) ? Me(n2.right.at(-1)) : null, a2 = n2.bottom[0] ? Me(n2.bottom[0]) : null, c2 = n2.bottom.at(-1) ? Me(n2.bottom.at(-1)) : null, l2 = n2.left[0] ? Me(n2.left[0]) : null, h2 = n2.left.at(-1) ? Me(n2.left.at(-1)) : null;
  return [{ key: "corner-nw-outer", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: "corner-nw-top", regionType: "corner", bounds: { minX: e2.minX, maxX: o2?.minX ?? e2.minX, minY: t48.minY, maxY: e2.minY } }, { key: "corner-nw-left", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.minY, maxY: l2?.minY ?? e2.minY } }, { key: "corner-ne-outer", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: t48.minY, maxY: e2.minY } }, { key: "corner-ne-top", regionType: "corner", bounds: { minX: i2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: t48.minY, maxY: e2.minY } }, { key: "corner-ne-right", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.minY, maxY: r2?.minY ?? e2.minY } }, { key: "corner-se-outer", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: "corner-se-right", regionType: "corner", bounds: { minX: e2.maxX, maxX: t48.maxX, minY: s2?.maxY ?? e2.maxY, maxY: e2.maxY } }, { key: "corner-se-bottom", regionType: "corner", bounds: { minX: c2?.maxX ?? e2.maxX, maxX: e2.maxX, minY: e2.maxY, maxY: t48.maxY } }, { key: "corner-sw-outer", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: "corner-sw-bottom", regionType: "corner", bounds: { minX: e2.minX, maxX: a2?.minX ?? e2.minX, minY: e2.maxY, maxY: t48.maxY } }, { key: "corner-sw-left", regionType: "corner", bounds: { minX: t48.minX, maxX: e2.minX, minY: h2?.maxY ?? e2.maxY, maxY: e2.maxY } }];
}
xW.register(class extends wt {
  constructor(t48) {
    super(), this.inputProblem = t48;
  }
  inputProblem;
  static componentKind = "qfp";
  output = null;
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    if (this.output) return void (this.solved = true);
    const { layerCount: t48, obstacles: e2 } = this.inputProblem.inputSrj, { bounds: n2, componentId: o2 } = this.inputProblem.detectedComponent, i2 = lV(t48), r2 = e2.filter((t49) => t49.componentId === o2), s2 = r2.length > 0 ? r2 : e2, a2 = (function(t49, e3) {
      const n3 = { top: [], right: [], bottom: [], left: [] };
      for (const o3 of t49) n3[IV(o3, e3)].push(o3);
      return n3.top.sort((t50, e4) => t50.center.x - e4.center.x), n3.bottom.sort((t50, e4) => t50.center.x - e4.center.x), n3.left.sort((t50, e4) => t50.center.y - e4.center.y), n3.right.sort((t50, e4) => t50.center.y - e4.center.y), n3;
    })(s2, n2), c2 = (function({ bounds: t49, sideGroups: e3 }) {
      return { minX: e3.left.length > 0 ? Math.max(...e3.left.map((t50) => Me(t50).maxX)) : t49.minX, maxX: e3.right.length > 0 ? Math.min(...e3.right.map((t50) => Me(t50).minX)) : t49.maxX, minY: e3.top.length > 0 ? Math.max(...e3.top.map((t50) => Me(t50).maxY)) : t49.minY, maxY: e3.bottom.length > 0 ? Math.min(...e3.bottom.map((t50) => Me(t50).minY)) : t49.maxY };
    })({ bounds: n2, sideGroups: a2 }), l2 = o2, h2 = this.inputProblem.viaDiameter ?? Do(this.inputProblem.inputSrj).padDiameter, d2 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, u2 = h2 + 2 * d2, p2 = this.inputProblem.inputSrj.minTraceWidth + 2 * d2, m2 = [{ key: "center", bounds: c2, regionType: "center" }, ...PV(s2, t48), ...CV({ side: "top", sideObstacles: a2.top, bounds: n2, centralBounds: c2, narrowThreshold: p2 }), ...CV({ side: "right", sideObstacles: a2.right, bounds: n2, centralBounds: c2, narrowThreshold: p2 }), ...CV({ side: "bottom", sideObstacles: a2.bottom, bounds: n2, centralBounds: c2, narrowThreshold: p2 }), ...CV({ side: "left", sideObstacles: a2.left, bounds: n2, centralBounds: c2, narrowThreshold: p2 }), ...NV({ bounds: n2, centralBounds: c2, sideGroups: a2 })].flatMap((t49) => (function({ nodeId: t50, bounds: e3, availableZ: n3, multiLayerThreshold: o3, regionType: i3, isNarrowPadGap: r3 = false, obstacleZ: s3 = [], connectedTo: a3 }) {
      if (!SV(e3)) return [];
      const c3 = (function(t51) {
        return { center: { x: (t51.minX + t51.maxX) / 2, y: (t51.minY + t51.maxY) / 2 }, width: t51.maxX - t51.minX, height: t51.maxY - t51.minY };
      })(e3), l3 = Math.min(c3.width, c3.height) > o3, h3 = l3 ? [{ availableZ: n3.filter((t51) => !s3.includes(t51)), containsObstacle: false }, { availableZ: n3.filter((t51) => s3.includes(t51)), containsObstacle: true }].filter((t51) => t51.availableZ.length > 0) : n3.map((t51) => ({ availableZ: [t51], containsObstacle: s3.includes(t51) }));
      return h3.map((e4) => ({ capacityMeshNodeId: 1 === h3.length ? t50 : l3 ? `${t50}:${e4.containsObstacle ? "obstacle" : "free"}` : `${t50}:z${e4.availableZ[0]}`, center: c3.center, width: c3.width, height: c3.height, layer: `z${e4.availableZ.join(",")}`, availableZ: e4.availableZ, _qfpRegionType: i3, _isNarrowQfpPadGap: r3, _containsObstacle: e4.containsObstacle, _connectedTo: e4.containsObstacle ? a3 : void 0 }));
    })({ nodeId: `qfp:${l2}:${t49.key}`, bounds: t49.bounds, availableZ: i2, multiLayerThreshold: u2, regionType: t49.regionType, isNarrowPadGap: t49.isNarrowPadGap, obstacleZ: t49.obstacleZ, connectedTo: t49.connectedTo }));
    this.output = { routingRegions: m2 }, this.stats = { componentId: o2, layerCount: t48, viaDiameter: h2, obstacleMargin: d2, multiLayerThreshold: u2, narrowPadGapThreshold: p2, narrowPadGapNodeCount: m2.filter((t49) => t49._isNarrowQfpPadGap).length, topPadCount: a2.top.length, rightPadCount: a2.right.length, bottomPadCount: a2.bottom.length, leftPadCount: a2.left.length, multiLayerNodeCount: m2.filter((t49) => t49.availableZ.length > 1).length, totalMeshNodeCount: m2.length }, this.solved = true;
  }
  getOutput() {
    if (!this.output) throw new Error("QfpTopologyGeneratorSolver has not solved yet");
    return this.output;
  }
});
var wV = 1e-6;
function TV({ nodeId: t48, bounds: e2, availableZ: n2, multiLayerThreshold: o2, regionType: i2, obstacleZ: r2 = [], connectedTo: s2 }) {
  if (!(function(t49) {
    return t49.maxX - t49.minX > wV && t49.maxY - t49.minY > wV;
  })(e2)) return [];
  const a2 = (function(t49) {
    return { center: { x: (t49.minX + t49.maxX) / 2, y: (t49.minY + t49.maxY) / 2 }, width: t49.maxX - t49.minX, height: t49.maxY - t49.minY };
  })(e2), c2 = Math.min(a2.width, a2.height) > o2, l2 = c2 ? [{ availableZ: n2.filter((t49) => !r2.includes(t49)), containsObstacle: false }, { availableZ: n2.filter((t49) => r2.includes(t49)), containsObstacle: true }].filter((t49) => t49.availableZ.length > 0) : n2.map((t49) => ({ availableZ: [t49], containsObstacle: r2.includes(t49) }));
  return l2.map((e3) => ({ capacityMeshNodeId: 1 === l2.length ? t48 : c2 ? `${t48}:${e3.containsObstacle ? "obstacle" : "free"}` : `${t48}:z${e3.availableZ[0]}`, center: a2.center, width: a2.width, height: a2.height, layer: `z${e3.availableZ.join(",")}`, availableZ: e3.availableZ, _soicRegionType: i2, _containsObstacle: e3.containsObstacle, _connectedTo: e3.containsObstacle ? s2 : void 0 }));
}
function RV(t48, e2) {
  let n2 = 0, o2 = Number.POSITIVE_INFINITY;
  for (let i2 = 0; i2 < e2.length; i2++) {
    const r2 = Math.abs(t48 - e2[i2]);
    r2 < o2 && (n2 = i2, o2 = r2);
  }
  return n2;
}
function EV(t48, e2) {
  return t48.map((t49, n2) => ({ key: `pad:${t49.obstacleId ?? n2}`, bounds: Me(t49), regionType: "pad", obstacleZ: aV(t49, e2), connectedTo: [...t49.connectedTo] }));
}
xW.register(class extends wt {
  constructor(t48) {
    super(), this.inputProblem = t48;
  }
  inputProblem;
  static componentKind = "soic";
  output = null;
  getConstructorParams() {
    return [this.inputProblem];
  }
  _step() {
    if (this.output) return void (this.solved = true);
    const { layerCount: t48, obstacles: e2 } = this.inputProblem.inputSrj, { bounds: n2, componentId: o2 } = this.inputProblem.detectedComponent, i2 = lV(t48), r2 = e2.filter((t49) => t49.componentId === o2), s2 = r2.length > 0 ? r2 : e2, a2 = (function(t49) {
      const e3 = cV(t49.map((t50) => t50.center.y)).length;
      return 2 === cV(t49.map((t50) => t50.center.x)).length && 2 !== e3 ? "vertical-columns" : "horizontal-rows";
    })(s2), c2 = (function({ obstacles: t49, orientation: e3 }) {
      const n3 = { left: [], right: [], top: [], bottom: [] };
      if ("vertical-columns" === e3) {
        const e4 = cV(t49.map((t50) => t50.center.x));
        for (const o4 of t49) n3[0 === RV(o4.center.x, e4) ? "left" : "right"].push(o4);
        return n3.left.sort((t50, e5) => t50.center.y - e5.center.y), n3.right.sort((t50, e5) => t50.center.y - e5.center.y), n3;
      }
      const o3 = cV(t49.map((t50) => t50.center.y));
      for (const e4 of t49) n3[0 === RV(e4.center.y, o3) ? "top" : "bottom"].push(e4);
      return n3.top.sort((t50, e4) => t50.center.x - e4.center.x), n3.bottom.sort((t50, e4) => t50.center.x - e4.center.x), n3;
    })({ obstacles: s2, orientation: a2 }), l2 = (function({ bounds: t49, orientation: e3, sideGroups: n3 }) {
      return "vertical-columns" === e3 ? { minX: Math.max(...n3.left.map((t50) => Me(t50).maxX)), maxX: Math.min(...n3.right.map((t50) => Me(t50).minX)), minY: t49.minY, maxY: t49.maxY } : { minX: t49.minX, maxX: t49.maxX, minY: Math.max(...n3.top.map((t50) => Me(t50).maxY)), maxY: Math.min(...n3.bottom.map((t50) => Me(t50).minY)) };
    })({ bounds: n2, orientation: a2, sideGroups: c2 }), h2 = o2, d2 = this.inputProblem.viaDiameter ?? Do(this.inputProblem.inputSrj).padDiameter, u2 = this.inputProblem.obstacleMargin ?? this.inputProblem.inputSrj.defaultObstacleMargin ?? 0.15, p2 = 2 * (d2 + u2), m2 = "vertical-columns" === a2 ? ["left", "right"] : ["top", "bottom"], g2 = [{ key: "center", bounds: l2, regionType: "center" }, ...EV(s2, t48), ...m2.flatMap((t49) => (function({ side: t50, sideObstacles: e3, bounds: n3, centralBounds: o3 }) {
      const i3 = [];
      for (let r3 = 0; r3 < e3.length - 1; r3++) {
        const s3 = Me(e3[r3]), a3 = Me(e3[r3 + 1]);
        let c3;
        c3 = "left" === t50 ? { minX: n3.minX, maxX: o3.minX, minY: s3.maxY, maxY: a3.minY } : "right" === t50 ? { minX: o3.maxX, maxX: n3.maxX, minY: s3.maxY, maxY: a3.minY } : "top" === t50 ? { minX: s3.maxX, maxX: a3.minX, minY: n3.minY, maxY: o3.minY } : { minX: s3.maxX, maxX: a3.minX, minY: o3.maxY, maxY: n3.maxY }, i3.push({ key: `${t50}-gap-${r3}`, bounds: c3, regionType: "pad-gap" });
      }
      return i3;
    })({ side: t49, sideObstacles: c2[t49], bounds: n2, centralBounds: l2 }))], f2 = g2.flatMap((t49) => TV({ nodeId: `soic:${h2}:${t49.key}`, bounds: t49.bounds, availableZ: i2, multiLayerThreshold: p2, regionType: t49.regionType, obstacleZ: t49.obstacleZ, connectedTo: t49.connectedTo }));
    this.output = { routingRegions: f2 }, this.stats = { componentId: o2, layerCount: t48, orientation: a2, viaDiameter: d2, obstacleMargin: u2, multiLayerThreshold: p2, firstSidePadCount: c2[m2[0]].length, secondSidePadCount: c2[m2[1]].length, multiLayerNodeCount: f2.filter((t49) => t49.availableZ.length > 1).length, totalMeshNodeCount: f2.length }, this.solved = true;
  }
  getOutput() {
    if (!this.output) throw new Error("SoicTopologyGeneratorSolver has not solved yet");
    return this.output;
  }
});

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/node_modules/graphics-debug/dist/chunk-ZJJUR6DP.js
var import_svgson2 = __toESM(require_svgson_umd(), 1);

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/prepare-buses.ts
var FANOUT_BORDER_TARGETS = /* @__PURE__ */ new Set([
  "left",
  "right",
  "top",
  "bottom",
  "top-left",
  "top-right",
  "bottom-left",
  "bottom-right"
]);
var FANOUT_EDGES = /* @__PURE__ */ new Set(["left", "right", "top", "bottom"]);
var AVAILABLE_BOUNDARY_REGIONS = {
  top_left: {
    direction: "up",
    preferredExit: "top-left",
    exitEdge: "top"
  },
  top_middle: {
    direction: "up",
    preferredExit: "top",
    exitEdge: "top"
  },
  top_right: {
    direction: "up",
    preferredExit: "top-right",
    exitEdge: "top"
  },
  right_top: {
    direction: "right",
    preferredExit: "top-right",
    exitEdge: "right"
  },
  right_middle: {
    direction: "right",
    preferredExit: "right",
    exitEdge: "right"
  },
  right_bottom: {
    direction: "right",
    preferredExit: "bottom-right",
    exitEdge: "right"
  },
  bottom_right: {
    direction: "down",
    preferredExit: "bottom-right",
    exitEdge: "bottom"
  },
  bottom_middle: {
    direction: "down",
    preferredExit: "bottom",
    exitEdge: "bottom"
  },
  bottom_left: {
    direction: "down",
    preferredExit: "bottom-left",
    exitEdge: "bottom"
  },
  left_bottom: {
    direction: "left",
    preferredExit: "bottom-left",
    exitEdge: "left"
  },
  left_middle: {
    direction: "left",
    preferredExit: "left",
    exitEdge: "left"
  },
  left_top: {
    direction: "left",
    preferredExit: "top-left",
    exitEdge: "left"
  },
  top: {
    direction: "up",
    preferredExit: "top",
    exitEdge: "top"
  },
  right: {
    direction: "right",
    preferredExit: "right",
    exitEdge: "right"
  },
  bottom: {
    direction: "down",
    preferredExit: "bottom",
    exitEdge: "bottom"
  },
  left: {
    direction: "left",
    preferredExit: "left",
    exitEdge: "left"
  }
};
function uniqueSorted(values) {
  const sortedValues = [...values].sort((a2, b2) => a2 - b2);
  const result = [];
  for (const value of sortedValues) {
    if (result.length === 0 || Math.abs(result[result.length - 1] - value) > 1e-6) {
      result.push(value);
    }
  }
  return result;
}
function getPitch(coordinates) {
  let pitch = Number.POSITIVE_INFINITY;
  for (let index2 = 1; index2 < coordinates.length; index2++) {
    const difference = coordinates[index2] - coordinates[index2 - 1];
    if (difference > 1e-6) pitch = Math.min(pitch, difference);
  }
  return pitch;
}
function getAlignedPitch(obstacles, axis) {
  const perpendicularAxis = axis === "x" ? "y" : "x";
  let pitch = Number.POSITIVE_INFINITY;
  for (let firstIndex = 0; firstIndex < obstacles.length; firstIndex++) {
    const first = obstacles[firstIndex];
    for (let secondIndex = firstIndex + 1; secondIndex < obstacles.length; secondIndex++) {
      const second = obstacles[secondIndex];
      if (Math.abs(
        first.center[perpendicularAxis] - second.center[perpendicularAxis]
      ) > 1e-6) {
        continue;
      }
      const separation = Math.abs(first.center[axis] - second.center[axis]);
      if (separation > 1e-6) pitch = Math.min(pitch, separation);
    }
  }
  return pitch;
}
function getComponentBounds(obstacles) {
  return {
    minX: Math.min(
      ...obstacles.map((obstacle) => obstacle.center.x - obstacle.width / 2)
    ),
    maxX: Math.max(
      ...obstacles.map((obstacle) => obstacle.center.x + obstacle.width / 2)
    ),
    minY: Math.min(
      ...obstacles.map((obstacle) => obstacle.center.y - obstacle.height / 2)
    ),
    maxY: Math.max(
      ...obstacles.map((obstacle) => obstacle.center.y + obstacle.height / 2)
    )
  };
}
function resolveComponentBounds(grid, options) {
  const requestedBounds = options.componentBounds?.[grid.componentId];
  if (!requestedBounds) {
    const inferredMarginX = grid.pitchX * 2.25;
    const inferredMarginY = grid.pitchY * 2.25;
    return {
      minX: grid.bounds.minX - inferredMarginX,
      maxX: grid.bounds.maxX + inferredMarginX,
      minY: grid.bounds.minY - inferredMarginY,
      maxY: grid.bounds.maxY + inferredMarginY
    };
  }
  const values = [
    requestedBounds.minX,
    requestedBounds.maxX,
    requestedBounds.minY,
    requestedBounds.maxY
  ];
  if (values.some((value) => !Number.isFinite(value)) || requestedBounds.minX >= requestedBounds.maxX || requestedBounds.minY >= requestedBounds.maxY) {
    throw new Error(
      `FanoutSolver: componentBounds for "${grid.componentId}" must contain finite, increasing bounds`
    );
  }
  if (requestedBounds.minX > grid.bounds.minX + 1e-6 || requestedBounds.maxX < grid.bounds.maxX - 1e-6 || requestedBounds.minY > grid.bounds.minY + 1e-6 || requestedBounds.maxY < grid.bounds.maxY - 1e-6) {
    throw new Error(
      `FanoutSolver: componentBounds for "${grid.componentId}" must contain every component pad`
    );
  }
  return { ...requestedBounds };
}
function validateSharedBoundary(boundary, componentGrids) {
  const values = [boundary.minX, boundary.maxX, boundary.minY, boundary.maxY];
  if (values.some((value) => !Number.isFinite(value)) || boundary.minX >= boundary.maxX || boundary.minY >= boundary.maxY) {
    throw new Error(
      "FanoutSolver: sharedBoundary must contain finite, increasing bounds"
    );
  }
  for (const grid of componentGrids) {
    if (boundary.minX > grid.bounds.minX + 1e-6 || boundary.maxX < grid.bounds.maxX - 1e-6 || boundary.minY > grid.bounds.minY + 1e-6 || boundary.maxY < grid.bounds.maxY - 1e-6) {
      throw new Error(
        `FanoutSolver: sharedBoundary must contain every pad of component "${grid.componentId}"`
      );
    }
  }
  return { ...boundary };
}
function resolveSharedBoundary(componentGrids, options) {
  if (options.sharedBoundary) {
    return validateSharedBoundary(options.sharedBoundary, componentGrids);
  }
  const componentBounds = componentGrids.map(
    (grid) => resolveComponentBounds(grid, options)
  );
  const maximumPitch = Math.max(
    ...componentGrids.flatMap((grid) => [grid.pitchX, grid.pitchY])
  );
  const inferredMargin = maximumPitch * 2.25;
  return validateSharedBoundary(
    {
      minX: Math.min(...componentBounds.map((bounds) => bounds.minX)) - inferredMargin,
      maxX: Math.max(...componentBounds.map((bounds) => bounds.maxX)) + inferredMargin,
      minY: Math.min(...componentBounds.map((bounds) => bounds.minY)) - inferredMargin,
      maxY: Math.max(...componentBounds.map((bounds) => bounds.maxY)) + inferredMargin
    },
    componentGrids
  );
}
function findComponentGrids(obstacles) {
  const obstaclesByComponent = /* @__PURE__ */ new Map();
  for (const obstacle of obstacles) {
    if (!obstacle.componentId || obstacle.isCopperPour) continue;
    const componentObstacles = obstaclesByComponent.get(obstacle.componentId) ?? [];
    componentObstacles.push(obstacle);
    obstaclesByComponent.set(obstacle.componentId, componentObstacles);
  }
  const grids = [];
  for (const [componentId, componentObstacles] of obstaclesByComponent) {
    const xCoordinates = uniqueSorted(
      componentObstacles.map((obstacle) => obstacle.center.x)
    );
    const yCoordinates = uniqueSorted(
      componentObstacles.map((obstacle) => obstacle.center.y)
    );
    const alignedPitchX = getAlignedPitch(componentObstacles, "x");
    const alignedPitchY = getAlignedPitch(componentObstacles, "y");
    const coordinatePitchX = getPitch(xCoordinates);
    const coordinatePitchY = getPitch(yCoordinates);
    const fallbackPitch = Math.min(
      ...[
        alignedPitchX,
        alignedPitchY,
        coordinatePitchX,
        coordinatePitchY
      ].filter(Number.isFinite)
    );
    const padSizeFallback = Math.max(
      ...componentObstacles.flatMap((obstacle) => [
        obstacle.width,
        obstacle.height
      ])
    );
    const resolvedFallback = Number.isFinite(fallbackPitch) ? fallbackPitch : padSizeFallback;
    const pitchX = Number.isFinite(alignedPitchX) ? alignedPitchX : Number.isFinite(coordinatePitchX) ? coordinatePitchX : resolvedFallback;
    const pitchY = Number.isFinite(alignedPitchY) ? alignedPitchY : Number.isFinite(coordinatePitchY) ? coordinatePitchY : resolvedFallback;
    grids.push({
      componentId,
      obstacles: componentObstacles,
      xCoordinates,
      yCoordinates,
      pitchX,
      pitchY,
      bounds: getComponentBounds(componentObstacles)
    });
  }
  return grids;
}
function getPointLayers(point) {
  return "layer" in point ? [point.layer] : point.layers;
}
function findPointObstacleMatches(params) {
  const { point, connection, componentGrids } = params;
  const pointLayers = getPointLayers(point);
  const matches = [];
  for (const grid of componentGrids) {
    const candidateObstacles = grid.obstacles.filter(
      (obstacle) => obstacle.layers.some((layer) => pointLayers.includes(layer))
    ).filter((obstacle) => pointIsInsideObstacle(point, obstacle, 1e-5)).sort((a2, b2) => {
      const aDirect = a2.connectedTo.includes(connection.name) || a2.connectedTo.includes(point.pointId ?? "") || a2.connectedTo.includes(point.pcb_port_id ?? "");
      const bDirect = b2.connectedTo.includes(connection.name) || b2.connectedTo.includes(point.pointId ?? "") || b2.connectedTo.includes(point.pcb_port_id ?? "");
      if (aDirect !== bDirect) return aDirect ? -1 : 1;
      return a2.width * a2.height - b2.width * b2.height;
    });
    if (candidateObstacles[0]) {
      matches.push({ grid, obstacle: candidateObstacles[0] });
    }
  }
  return matches;
}
function inferBusId(connection) {
  for (const point of connection.pointsToConnect) {
    if ("layers" in point && point.busId) return point.busId;
  }
  const nameMatch = /^BUS[_:-]([^_:-]+)(?:[_:-]\d+)?$/i.exec(connection.name);
  return nameMatch?.[1] ?? null;
}
function resolvePreferredExit(busId, value) {
  if (value === void 0) return void 0;
  if (!FANOUT_BORDER_TARGETS.has(value)) {
    throw new Error(
      `FanoutSolver: bus "${busId}" has invalid preferredExit "${value}"`
    );
  }
  return value;
}
function resolveExitEdge(busId, value) {
  if (value === void 0) return void 0;
  if (!FANOUT_EDGES.has(value)) {
    throw new Error(
      `FanoutSolver: bus "${busId}" has invalid exitEdge "${value}"`
    );
  }
  return value;
}
function resolveExitPosition(busId, value) {
  if (value === void 0) return void 0;
  try {
    return getFanoutExitPositionConfig(value);
  } catch {
    throw new Error(
      `FanoutSolver: bus "${busId}" has invalid exitPosition "${value}"`
    );
  }
}
function assertExitPositionFieldMatches(params) {
  const { busId, exitPosition, fieldName, expected, actual, sourceName } = params;
  if (actual === void 0 || actual === expected) return;
  throw new Error(
    `FanoutSolver: bus "${busId}" exitPosition "${exitPosition}" conflicts with ${sourceName} ${fieldName} "${actual}"`
  );
}
function resolveBusExitFields(params) {
  const { busId, requestedBus, options } = params;
  const exitPosition = requestedBus.exitPosition;
  const exitPositionConfig = resolveExitPosition(busId, exitPosition);
  const busPreferredExit = resolvePreferredExit(
    busId,
    requestedBus.preferredExit
  );
  const optionPreferredExit = resolvePreferredExit(
    busId,
    options.busExitPreferences?.[busId]
  );
  const busExitEdge = resolveExitEdge(busId, requestedBus.exitEdge);
  if (exitPositionConfig && exitPosition) {
    for (const [actual, sourceName] of [
      [requestedBus.direction, "bus"],
      [options.busDirections?.[busId], "busDirections"]
    ]) {
      assertExitPositionFieldMatches({
        busId,
        exitPosition,
        fieldName: "direction",
        expected: exitPositionConfig.direction,
        actual,
        sourceName
      });
    }
    for (const [actual, sourceName] of [
      [busPreferredExit, "bus"],
      [optionPreferredExit, "busExitPreferences"]
    ]) {
      assertExitPositionFieldMatches({
        busId,
        exitPosition,
        fieldName: "preferredExit",
        expected: exitPositionConfig.preferredExit,
        actual,
        sourceName
      });
    }
    assertExitPositionFieldMatches({
      busId,
      exitPosition,
      fieldName: "exitEdge",
      expected: exitPositionConfig.exitEdge,
      actual: busExitEdge,
      sourceName: "bus"
    });
    return {
      exitPosition,
      ...exitPositionConfig.direction ? { direction: exitPositionConfig.direction } : {},
      ...exitPositionConfig.preferredExit ? { preferredExit: exitPositionConfig.preferredExit } : {},
      ...exitPositionConfig.exitEdge ? { exitEdge: exitPositionConfig.exitEdge } : {}
    };
  }
  const direction = options.busDirections?.[busId] ?? requestedBus.direction ?? options.defaultDirection;
  const preferredExit = resolvePreferredExit(
    busId,
    optionPreferredExit ?? busPreferredExit ?? options.defaultPreferredExit
  );
  return {
    ...direction ? { direction } : {},
    ...preferredExit ? { preferredExit } : {},
    ...busExitEdge ? { exitEdge: busExitEdge } : {}
  };
}
function resolveAllowedLayers(busId, allowedLayers) {
  if (allowedLayers === void 0) return void 0;
  if (allowedLayers.length === 0) {
    throw new Error(
      `FanoutSolver: bus "${busId}" must allow at least one layer`
    );
  }
  for (const layer of allowedLayers) {
    if (typeof layer !== "string" || layer.length === 0) {
      throw new Error(
        `FanoutSolver: bus "${busId}" has an invalid allowed layer`
      );
    }
  }
  return [...new Set(allowedLayers)];
}
function resolveMaxLengthSkew(busId, value) {
  if (value === void 0) return void 0;
  if (!Number.isFinite(value) || value < 0) {
    throw new Error(
      `FanoutSolver: bus "${busId}" maxLengthSkew must be a finite non-negative number`
    );
  }
  return value;
}
function resolveAvailableBoundaryRegions(value) {
  if (value === void 0) return void 0;
  if (value.length === 0) {
    throw new Error(
      "FanoutSolver: availableCornersAndSides must contain at least one boundary region"
    );
  }
  const regions = [];
  const seen = /* @__PURE__ */ new Set();
  for (const input of value) {
    const region = AVAILABLE_BOUNDARY_REGIONS[input];
    if (!region) {
      throw new Error(
        `FanoutSolver: invalid availableCornersAndSides value "${input}"`
      );
    }
    const key = `${region.exitEdge}:${region.direction}:${region.preferredExit}`;
    if (seen.has(key)) continue;
    seen.add(key);
    regions.push(region);
  }
  return regions;
}
function resolveTermination(busId, value) {
  if (value === void 0 || value.type === "boundary") {
    return { type: "boundary" };
  }
  if (value.type !== "plane" || typeof value.layer !== "string" || value.layer.length === 0) {
    throw new Error(
      `FanoutSolver: bus "${busId}" has an invalid termination target`
    );
  }
  return { type: "plane", layer: value.layer };
}
function resolveBusSpecs(srj, options) {
  const requestedBuses = options.buses ?? srj.buses;
  const specsById = /* @__PURE__ */ new Map();
  const claimedConnectionNames = /* @__PURE__ */ new Set();
  const knownConnectionNames = new Set(
    srj.connections.map((connection) => connection.name)
  );
  for (const requestedBus of requestedBuses ?? []) {
    if (specsById.has(requestedBus.busId)) {
      throw new Error(`FanoutSolver: duplicate bus id "${requestedBus.busId}"`);
    }
    for (const connectionName of requestedBus.connectionNames) {
      if (!knownConnectionNames.has(connectionName)) {
        throw new Error(
          `FanoutSolver: bus "${requestedBus.busId}" references unknown connection "${connectionName}"`
        );
      }
      if (claimedConnectionNames.has(connectionName)) {
        throw new Error(
          `FanoutSolver: connection "${connectionName}" belongs to more than one bus`
        );
      }
      claimedConnectionNames.add(connectionName);
    }
    const termination = resolveTermination(
      requestedBus.busId,
      requestedBus.termination
    );
    const resolvedExitFields = resolveBusExitFields({
      busId: requestedBus.busId,
      requestedBus,
      options
    });
    const allowedLayers = resolveAllowedLayers(
      requestedBus.busId,
      requestedBus.allowedLayers
    );
    const maxLengthSkew = resolveMaxLengthSkew(
      requestedBus.busId,
      requestedBus.maxLengthSkew
    );
    if (termination.type === "plane" && maxLengthSkew !== void 0) {
      throw new Error(
        `FanoutSolver: plane-terminated bus "${requestedBus.busId}" cannot specify maxLengthSkew`
      );
    }
    if (termination.type === "plane" && resolvedExitFields.preferredExit !== void 0) {
      throw new Error(
        `FanoutSolver: plane-terminated bus "${requestedBus.busId}" cannot also specify preferredExit`
      );
    }
    specsById.set(requestedBus.busId, {
      ...requestedBus,
      sourceComponentId: requestedBus.sourceComponentId ?? options.sourceComponentId,
      ...resolvedExitFields,
      ...allowedLayers === void 0 ? {} : { allowedLayers },
      ...maxLengthSkew === void 0 ? {} : { maxLengthSkew },
      termination
    });
  }
  for (const connection of srj.connections) {
    if (claimedConnectionNames.has(connection.name)) continue;
    const inferredBusId = inferBusId(connection);
    if (inferredBusId) {
      const existing = specsById.get(inferredBusId);
      if (existing) {
        specsById.set(inferredBusId, {
          ...existing,
          connectionNames: [...existing.connectionNames, connection.name]
        });
      } else {
        specsById.set(inferredBusId, {
          busId: inferredBusId,
          connectionNames: [connection.name],
          direction: options.busDirections?.[inferredBusId] ?? options.defaultDirection,
          sourceComponentId: options.sourceComponentId,
          preferredExit: resolvePreferredExit(
            inferredBusId,
            options.busExitPreferences?.[inferredBusId] ?? options.defaultPreferredExit
          ),
          termination: { type: "boundary" }
        });
      }
    } else {
      const singletonBusId = `connection:${connection.name}`;
      specsById.set(singletonBusId, {
        busId: singletonBusId,
        connectionNames: [connection.name],
        sourceComponentId: options.sourceComponentId,
        direction: options.busDirections?.[singletonBusId] ?? options.defaultDirection,
        preferredExit: resolvePreferredExit(
          singletonBusId,
          options.busExitPreferences?.[singletonBusId] ?? options.defaultPreferredExit
        ),
        termination: { type: "boundary" }
      });
    }
  }
  return [...specsById.values()];
}
function chooseSourceGrid(params) {
  const { busSpec, connections, componentGrids } = params;
  const matchCountByComponent = /* @__PURE__ */ new Map();
  for (const connection of connections) {
    const matchedComponents = /* @__PURE__ */ new Set();
    for (const point of connection.pointsToConnect) {
      for (const match of findPointObstacleMatches({
        point,
        connection,
        componentGrids
      })) {
        matchedComponents.add(match.grid.componentId);
      }
    }
    for (const componentId of matchedComponents) {
      matchCountByComponent.set(
        componentId,
        (matchCountByComponent.get(componentId) ?? 0) + 1
      );
    }
  }
  const selectedGrid = [...componentGrids].sort((a2, b2) => {
    const countDifference = (matchCountByComponent.get(b2.componentId) ?? 0) - (matchCountByComponent.get(a2.componentId) ?? 0);
    if (countDifference !== 0) return countDifference;
    return b2.obstacles.length - a2.obstacles.length;
  })[0];
  const requestedGrid = busSpec.sourceComponentId ? componentGrids.find(
    (grid) => grid.componentId === busSpec.sourceComponentId
  ) : void 0;
  if (busSpec.sourceComponentId && !requestedGrid) {
    throw new Error(
      `FanoutSolver: source component "${busSpec.sourceComponentId}" for bus "${busSpec.busId}" was not found`
    );
  }
  const sourceGrid = requestedGrid ?? selectedGrid;
  const sourceMatchCount = sourceGrid ? matchCountByComponent.get(sourceGrid.componentId) ?? 0 : 0;
  if (!sourceGrid || sourceMatchCount !== connections.length) {
    throw new Error(
      busSpec.sourceComponentId ? `FanoutSolver: source component "${busSpec.sourceComponentId}" is not an endpoint on every connection in bus "${busSpec.busId}"` : `FanoutSolver: bus "${busSpec.busId}" does not have one component endpoint on every connection`
    );
  }
  return sourceGrid;
}
function chooseTargetPoint(sourcePoint, connection, sourcePointIndex, termination) {
  const targetCandidates = connection.pointsToConnect.filter(
    (_2, pointIndex) => pointIndex !== sourcePointIndex
  );
  const targetPoint = targetCandidates.sort(
    (a2, b2) => distance3(sourcePoint, b2) - distance3(sourcePoint, a2)
  )[0];
  if (!targetPoint && termination.type === "plane") {
    return sourcePoint;
  }
  if (!targetPoint) {
    throw new Error(
      `FanoutSolver: connection "${connection.name}" has no target beyond its BGA pad`
    );
  }
  return targetPoint;
}
function prepareConnection(params) {
  const {
    connection,
    connectionIndex,
    sourceGrid,
    componentGrids,
    termination,
    exitTargetPoint
  } = params;
  for (let sourcePointIndex = 0; sourcePointIndex < connection.pointsToConnect.length; sourcePointIndex++) {
    const sourcePoint = connection.pointsToConnect[sourcePointIndex];
    const sourceMatch = findPointObstacleMatches({
      point: sourcePoint,
      connection,
      componentGrids
    }).find((match) => match.grid.componentId === sourceGrid.componentId);
    if (!sourceMatch) continue;
    const sourceLayer = getPointLayers(sourcePoint).find(
      (layer) => sourceMatch.obstacle.layers.includes(layer)
    );
    if (!sourceLayer) {
      throw new Error(
        `FanoutSolver: connection "${connection.name}" has no source layer shared with its BGA pad`
      );
    }
    const targetPoint = chooseTargetPoint(
      sourcePoint,
      connection,
      sourcePointIndex,
      termination
    );
    return {
      connection,
      connectionIndex,
      sourcePoint,
      sourcePointIndex,
      sourceLayer,
      sourceObstacle: sourceMatch.obstacle,
      targetPoint,
      exitTargetPoint: exitTargetPoint ?? {
        x: targetPoint.x,
        y: targetPoint.y
      },
      hasExplicitLayeredExitTarget: exitTargetPoint?.layer !== void 0
    };
  }
  throw new Error(
    `FanoutSolver: connection "${connection.name}" does not touch component "${sourceGrid.componentId}"`
  );
}
function inferDirection(busId, connections) {
  let dx2 = 0;
  let dy2 = 0;
  for (const preparedConnection of connections) {
    const exitTargetPoint = preparedConnection.exitTargetPoint ?? preparedConnection.targetPoint;
    dx2 += exitTargetPoint.x - preparedConnection.sourcePoint.x;
    dy2 += exitTargetPoint.y - preparedConnection.sourcePoint.y;
  }
  if (Math.abs(dx2) < 1e-9 && Math.abs(dy2) < 1e-9) {
    throw new Error(
      `FanoutSolver: cannot infer an escape direction for bus "${busId}"`
    );
  }
  if (Math.abs(dx2) >= Math.abs(dy2)) return dx2 >= 0 ? "right" : "left";
  return dy2 >= 0 ? "up" : "down";
}
function getDirectionsForBorderTarget(target) {
  switch (target) {
    case "left":
      return ["left"];
    case "right":
      return ["right"];
    case "top":
      return ["up"];
    case "bottom":
      return ["down"];
    case "top-left":
      return ["up", "left"];
    case "top-right":
      return ["up", "right"];
    case "bottom-left":
      return ["down", "left"];
    case "bottom-right":
      return ["down", "right"];
  }
}
function getAverageSourcePoint(connections) {
  return {
    x: connections.reduce(
      (sum, connection) => sum + connection.sourcePoint.x,
      0
    ) / connections.length,
    y: connections.reduce(
      (sum, connection) => sum + connection.sourcePoint.y,
      0
    ) / connections.length
  };
}
function getDistanceToBoundary(source, direction, boundary) {
  switch (direction) {
    case "left":
      return source.x - boundary.minX;
    case "right":
      return boundary.maxX - source.x;
    case "up":
      return boundary.maxY - source.y;
    case "down":
      return source.y - boundary.minY;
  }
}
function getRegionAnchor(region, boundary) {
  if (region.direction === "up" || region.direction === "down") {
    if (region.preferredExit.endsWith("left")) return boundary.minX;
    if (region.preferredExit.endsWith("right")) return boundary.maxX;
    return (boundary.minX + boundary.maxX) / 2;
  }
  if (region.preferredExit.startsWith("top")) return boundary.maxY;
  if (region.preferredExit.startsWith("bottom")) return boundary.minY;
  return (boundary.minY + boundary.maxY) / 2;
}
function getRegionSourceCoordinate(source, direction) {
  return direction === "up" || direction === "down" ? source.x : source.y;
}
function tryInferDirection(busId, connections) {
  try {
    return inferDirection(busId, connections);
  } catch {
    return void 0;
  }
}
function resolveAvailableBusExit(params) {
  const {
    busId,
    explicitDirection,
    preferredExit,
    connections,
    sharedBoundary,
    availableRegions
  } = params;
  const compatibleRegions = availableRegions.filter(
    (region) => (explicitDirection === void 0 || region.direction === explicitDirection) && (preferredExit === void 0 || region.preferredExit === preferredExit)
  );
  if (compatibleRegions.length === 0) {
    throw new Error(
      `FanoutSolver: bus "${busId}" cannot use its requested exit with availableCornersAndSides`
    );
  }
  const inferredDirection = explicitDirection ? void 0 : tryInferDirection(busId, connections);
  const preferredDirectionRegions = inferredDirection ? compatibleRegions.filter(
    (region) => region.direction === inferredDirection
  ) : [];
  const candidates = preferredDirectionRegions.length > 0 ? preferredDirectionRegions : compatibleRegions;
  const averageSource = getAverageSourcePoint(connections);
  return [...candidates].toSorted(
    (first, second) => getDistanceToBoundary(averageSource, first.direction, sharedBoundary) - getDistanceToBoundary(
      averageSource,
      second.direction,
      sharedBoundary
    ) || Math.abs(
      getRegionSourceCoordinate(averageSource, first.direction) - getRegionAnchor(first, sharedBoundary)
    ) - Math.abs(
      getRegionSourceCoordinate(averageSource, second.direction) - getRegionAnchor(second, sharedBoundary)
    ) || first.preferredExit.localeCompare(second.preferredExit)
  )[0];
}
function validateExplicitExitAvailability(params) {
  const { busId, exitEdge, preferredExit, availableRegions } = params;
  const requestedBandSide = getCornerBandSide(exitEdge, preferredExit);
  const hasCompatibleRegion = availableRegions.some(
    (region) => region.exitEdge === exitEdge && getCornerBandSide(region.exitEdge, region.preferredExit) === requestedBandSide
  );
  if (!hasCompatibleRegion) {
    throw new Error(
      `FanoutSolver: bus "${busId}" cannot use its requested exit with availableCornersAndSides`
    );
  }
}
function resolveBusDirection(params) {
  const {
    busId,
    explicitDirection,
    preferredExit,
    connections,
    sharedBoundary,
    availableRegions
  } = params;
  if (availableRegions) {
    return resolveAvailableBusExit({
      busId,
      explicitDirection,
      preferredExit,
      connections,
      sharedBoundary,
      availableRegions
    });
  }
  if (!preferredExit) {
    return {
      direction: explicitDirection ?? inferDirection(busId, connections)
    };
  }
  const compatibleDirections = getDirectionsForBorderTarget(preferredExit);
  if (explicitDirection) {
    if (!compatibleDirections.includes(explicitDirection)) {
      throw new Error(
        `FanoutSolver: bus "${busId}" direction "${explicitDirection}" is incompatible with preferredExit "${preferredExit}"`
      );
    }
    return { direction: explicitDirection, preferredExit };
  }
  if (compatibleDirections.length === 1) {
    return { direction: compatibleDirections[0], preferredExit };
  }
  let inferredDirection;
  try {
    inferredDirection = inferDirection(busId, connections);
  } catch {
    inferredDirection = void 0;
  }
  if (inferredDirection && compatibleDirections.includes(inferredDirection)) {
    return { direction: inferredDirection, preferredExit };
  }
  const averageSource = getAverageSourcePoint(connections);
  return {
    direction: compatibleDirections.toSorted(
      (first, second) => getDistanceToBoundary(averageSource, first, sharedBoundary) - getDistanceToBoundary(averageSource, second, sharedBoundary) || first.localeCompare(second)
    )[0],
    preferredExit
  };
}
function prepareFanoutBuses(srj, options) {
  const componentGrids = findComponentGrids(srj.obstacles);
  if (componentGrids.length === 0 && srj.connections.length > 0) {
    throw new Error(
      "FanoutSolver: no componentId-tagged pad footprint was found"
    );
  }
  const connectionIndexByName = new Map(
    srj.connections.map((connection, index2) => [connection.name, index2])
  );
  const resolvedBusInputs = resolveBusSpecs(srj, options).map((busSpec) => {
    for (const [connectionName, point] of Object.entries(
      busSpec.connectionExitTargets ?? {}
    )) {
      if (!busSpec.connectionNames.includes(connectionName)) {
        throw new Error(
          `FanoutSolver: connectionExitTargets contains connection "${connectionName}" outside bus "${busSpec.busId}"`
        );
      }
      if (!Number.isFinite(point.x) || !Number.isFinite(point.y)) {
        throw new Error(
          `FanoutSolver: connectionExitTargets for connection "${connectionName}" must contain finite x and y coordinates`
        );
      }
    }
    const connections = busSpec.connectionNames.map((connectionName) => {
      const connectionIndex = connectionIndexByName.get(connectionName);
      if (connectionIndex === void 0) {
        throw new Error(
          `FanoutSolver: connection "${connectionName}" is missing from the input`
        );
      }
      return srj.connections[connectionIndex];
    });
    const sourceGrid = chooseSourceGrid({
      busSpec,
      connections,
      componentGrids
    });
    const preparedConnections = connections.map(
      (connection) => prepareConnection({
        connection,
        connectionIndex: connectionIndexByName.get(connection.name),
        sourceGrid,
        componentGrids,
        termination: busSpec.termination ?? { type: "boundary" },
        exitTargetPoint: busSpec.connectionExitTargets?.[connection.name]
      })
    );
    return { busSpec, sourceGrid, preparedConnections };
  });
  const sourceGrids = [
    ...new Map(
      resolvedBusInputs.map(({ sourceGrid }) => [
        sourceGrid.componentId,
        sourceGrid
      ])
    ).values()
  ];
  const sharedBoundary = resolveSharedBoundary(sourceGrids, options);
  const availableRegions = resolveAvailableBoundaryRegions(
    options.availableCornersAndSides
  );
  const buses = [];
  for (const {
    busSpec,
    sourceGrid,
    preparedConnections
  } of resolvedBusInputs) {
    if (busSpec.exitEdge && !busSpec.preferredExit) {
      throw new Error(
        `FanoutSolver: bus "${busSpec.busId}" exitEdge requires preferredExit`
      );
    }
    if (busSpec.exitEdge && busSpec.preferredExit && !borderTargetIncludesEdge(busSpec.preferredExit, busSpec.exitEdge)) {
      throw new Error(
        `FanoutSolver: bus "${busSpec.busId}" exitEdge "${busSpec.exitEdge}" is incompatible with preferredExit "${busSpec.preferredExit}"`
      );
    }
    const resolvedExit = resolveBusDirection({
      busId: busSpec.busId,
      explicitDirection: busSpec.direction ?? options.busDirections?.[busSpec.busId],
      preferredExit: busSpec.preferredExit,
      connections: preparedConnections,
      sharedBoundary,
      availableRegions: busSpec.termination?.type === "plane" || busSpec.exitEdge ? void 0 : availableRegions
    });
    if (busSpec.termination?.type !== "plane" && busSpec.exitEdge && resolvedExit.preferredExit && availableRegions) {
      validateExplicitExitAvailability({
        busId: busSpec.busId,
        exitEdge: busSpec.exitEdge,
        preferredExit: resolvedExit.preferredExit,
        availableRegions
      });
    }
    buses.push({
      busId: busSpec.busId,
      ...busSpec.maxLengthSkew === void 0 ? {} : { maxLengthSkew: busSpec.maxLengthSkew },
      direction: resolvedExit.direction,
      preferredExit: resolvedExit.preferredExit,
      ...busSpec.exitEdge ? { exitEdge: busSpec.exitEdge } : {},
      cornerBandConnectionCount: 0,
      allowedLayers: busSpec.allowedLayers,
      termination: busSpec.termination ?? { type: "boundary" },
      connections: preparedConnections,
      componentId: sourceGrid.componentId,
      componentObstacles: sourceGrid.obstacles,
      componentBounds: resolveComponentBounds(sourceGrid, options),
      sharedBoundary,
      xCoordinates: [...sourceGrid.xCoordinates],
      yCoordinates: [...sourceGrid.yCoordinates],
      pitchX: sourceGrid.pitchX,
      pitchY: sourceGrid.pitchY
    });
  }
  const cornerBandConnectionCounts = /* @__PURE__ */ new Map();
  for (const bus of buses) {
    const side = getCornerBandSide(bus.exitEdge, bus.preferredExit);
    if (!bus.exitEdge || !side) continue;
    const key = `${bus.exitEdge}:${side}`;
    cornerBandConnectionCounts.set(
      key,
      (cornerBandConnectionCounts.get(key) ?? 0) + bus.connections.length
    );
  }
  for (const bus of buses) {
    const side = getCornerBandSide(bus.exitEdge, bus.preferredExit);
    if (!bus.exitEdge || !side) continue;
    bus.cornerBandConnectionCount = cornerBandConnectionCounts.get(`${bus.exitEdge}:${side}`) ?? bus.connections.length;
  }
  return buses;
}

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/match-angularly-ordered-local-vias.ts
var TAU = Math.PI * 2;

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/route-single-layer-adaptive-exits.ts
var FANOUT_FLOW_DEBUG_ENABLED = globalThis.process?.env?.FANOUT_FLOW_DEBUG === "1";

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/runtime-process.ts
var getRuntimeProcess = (runtime) => runtime.process ?? { env: {} };

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/fanout-solver.ts
var process2 = getRuntimeProcess(globalThis);

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/fit-local-via-grid.ts
function fitLocalViaGrid(coordinates, tolerance) {
  if (coordinates.length < 2) return null;
  const measured = (coordinates.at(-1) - coordinates[0]) / (coordinates.length - 1);
  const pitch = Number(measured.toPrecision(3));
  if (!(pitch > 0) || Math.abs(pitch - measured) > tolerance) return null;
  const measuredOrigin = coordinates.reduce((sum, value, i2) => sum + value - i2 * pitch, 0) / coordinates.length;
  const quantum = 10 ** (Math.floor(Math.log10(pitch)) - 2);
  const origin = Math.round(measuredOrigin / quantum) * quantum;
  const fitted = coordinates.map((_2, i2) => origin + i2 * pitch);
  if (fitted.some((value, i2) => Math.abs(value - coordinates[i2]) > tolerance))
    return null;
  return { coordinates: fitted, pitch };
}

// ../bus-lanes-solver/node_modules/@tscircuit/fanout-solver/lib/route-local-signal-dogbones.ts
function routeLocalSignalDogbones(input, options) {
  const connections = structuredClone(input.connections);
  const endpoints = [];
  const virtualConnections = [];
  const buses = [];
  const layers = getCopperLayerNames(input.layerCount);
  for (const [connectionIndex, connection] of connections.entries()) {
    const target = options.targetLayers.get(connection.name);
    if (!target || !layers.includes(target))
      throw Error(`Missing or invalid target layer for ${connection.name}`);
    if (connection.pointsToConnect.length !== 2)
      throw Error(`${connection.name}: two terminals required`);
    for (const [pointIndex, point] of connection.pointsToConnect.entries()) {
      const available = "layer" in point ? [point.layer] : point.layers;
      if (available.includes(target)) {
        const { layers: _layers, ...metadata } = point;
        connection.pointsToConnect[pointIndex] = { ...metadata, layer: target };
        continue;
      }
      const sourceObstacle = input.obstacles.find(
        (o2) => o2.componentId && distancePointToObstacle(point, o2) < 1e-8 && o2.connectedTo.some(
          (id) => id === point.pcb_port_id || id === point.pointId || id === connection.name
        )
      );
      if (!sourceObstacle?.componentId)
        throw Error(
          `${connection.name}: local dogbone requires a component pad terminal`
        );
      const name = `dogbone_endpoint_${endpoints.length}`;
      endpoints.push({ connectionIndex, pointIndex });
      virtualConnections.push({
        ...connection,
        name,
        pointsToConnect: [point, connection.pointsToConnect[1 - pointIndex]]
      });
      buses.push({
        busId: name,
        connectionNames: [name],
        sourceComponentId: sourceObstacle.componentId
      });
    }
  }
  if (!endpoints.length)
    return { connections, traces: [] };
  const prepared = prepareFanoutBuses(
    { ...input, connections: virtualConnections, buses: [] },
    { buses }
  );
  for (const bus of prepared) {
    const tolerance = Math.min(...bus.componentObstacles.flatMap((o2) => [o2.width, o2.height])) / 100;
    const cluster = (values) => {
      const groups = [];
      for (const value of [...values].sort((a2, b2) => a2 - b2)) {
        if (groups.length && value - groups.at(-1)[0] < tolerance)
          groups.at(-1).push(value);
        else groups.push([value]);
      }
      return groups.map((g2) => g2.reduce((s2, v2) => s2 + v2, 0) / g2.length);
    };
    bus.xCoordinates = cluster(bus.xCoordinates);
    bus.yCoordinates = cluster(bus.yCoordinates);
    const pitch = (coordinates, fallback) => coordinates.length > 1 ? Math.min(...coordinates.slice(1).map((v2, i2) => v2 - coordinates[i2])) : fallback;
    bus.pitchX = pitch(bus.xCoordinates, bus.pitchX);
    bus.pitchY = pitch(bus.yCoordinates, bus.pitchY);
    const fillMissingRows = (coordinates, step) => coordinates.flatMap((value, i2) => {
      if (i2 === coordinates.length - 1) return [value];
      const gap = coordinates[i2 + 1] - value, count = Math.max(1, Math.round(gap / step));
      if (Math.abs(gap / count - step) > tolerance) return [value];
      return Array.from(
        { length: count },
        (_2, j2) => value + gap * j2 / count
      );
    });
    bus.xCoordinates = fillMissingRows(bus.xCoordinates, bus.pitchX);
    bus.yCoordinates = fillMissingRows(bus.yCoordinates, bus.pitchY);
    const xGrid = fitLocalViaGrid(bus.xCoordinates, tolerance);
    const yGrid = fitLocalViaGrid(bus.yCoordinates, tolerance);
    if (xGrid) {
      bus.xCoordinates = xGrid.coordinates;
      bus.pitchX = xGrid.pitch;
    }
    if (yGrid) {
      bus.yCoordinates = yGrid.coordinates;
      bus.pitchY = yGrid.pitch;
    }
  }
  const blockingSegments = [];
  const blockingVias = [];
  for (const trace of input.traces ?? []) {
    for (const [i2, point] of trace.route.entries()) {
      if (point.route_type === "via") {
        blockingVias.push({
          connectionIndex: -1,
          center: point,
          diameter: point.via_diameter ?? options.viaDiameter,
          spanLayers: layers
        });
        const next = trace.route[i2 + 1];
        if (next?.route_type === "wire")
          blockingSegments.push({
            connectionIndex: -1,
            segment: {
              start: point,
              end: next,
              layer: next.layer,
              width: next.width
            }
          });
      } else if (point.route_type === "wire") {
        const next = trace.route[i2 + 1];
        if (next?.route_type === "wire")
          blockingSegments.push({
            connectionIndex: -1,
            segment: {
              start: point,
              end: next,
              layer: point.layer,
              width: point.width
            }
          });
        else if (next?.route_type === "via")
          blockingSegments.push({
            connectionIndex: -1,
            segment: {
              start: point,
              end: next,
              layer: point.layer,
              width: point.width
            }
          });
      } else
        throw Error("Unsupported fixed copper primitive for local dogbones");
    }
  }
  const geometryRules = {
    viaDiameter: options.viaDiameter,
    viaHoleDiameter: options.viaHoleDiameter,
    traceWidth: options.traceWidth,
    clearance: options.clearance,
    holeToHoleClearance: options.holeToHoleClearance,
    additionalObstacles: input.obstacles,
    blockingSegments,
    blockingVias
  };
  const candidates = getComponentDogboneViaSiteCandidates(
    prepared,
    geometryRules
  );
  const preferredViaPointsByConnectionIndex = /* @__PURE__ */ new Map();
  for (const connection of prepared.flatMap((b2) => b2.connections)) {
    const choices = candidates.filter(
      (c2) => c2.connectionIndex === connection.connectionIndex
    );
    const origin = connection.sourcePoint;
    const rank = (p2) => Number(p2.x < origin.x) * 2 + Number(p2.y > origin.y) * 2 + Math.hypot(p2.x - origin.x, p2.y - origin.y);
    choices.sort((a2, b2) => rank(a2.point) - rank(b2.point));
    if (choices[0])
      preferredViaPointsByConnectionIndex.set(
        connection.connectionIndex,
        choices[0].point
      );
  }
  const sites = matchComponentDogboneViaSites(prepared, {
    ...geometryRules,
    preferredViaPointsByConnectionIndex
  });
  if (!sites) throw Error("No collision-free local dogbone assignment");
  const allPrepared = prepared.flatMap((b2) => b2.connections);
  for (let i2 = 0; i2 < allPrepared.length; i2++)
    for (let j2 = 0; j2 < i2; j2++) {
      const a2 = allPrepared[i2], b2 = allPrepared[j2], p2 = sites.get(a2.connectionIndex), q2 = sites.get(b2.connectionIndex);
      const stubA = {
        start: a2.sourcePoint,
        end: p2,
        layer: a2.sourceLayer,
        width: options.traceWidth
      };
      const stubB = {
        start: b2.sourcePoint,
        end: q2,
        layer: b2.sourceLayer,
        width: options.traceWidth
      };
      const viaSeparation = Math.max(
        options.viaDiameter + options.clearance,
        options.viaHoleDiameter + (options.holeToHoleClearance ?? options.clearance)
      );
      const viaTrace = options.viaDiameter / 2 + options.traceWidth / 2 + options.clearance;
      if (distance3(p2, q2) < viaSeparation - 1e-9 || distancePointToSegment(p2, stubB.start, stubB.end) < viaTrace - 1e-9 || distancePointToSegment(q2, stubA.start, stubA.end) < viaTrace - 1e-9 || a2.sourceLayer === b2.sourceLayer && !segmentsAreClear(stubA, stubB, options.clearance))
        throw Error("Local dogbones collide between components");
    }
  const traces = [];
  for (const [endpointIndex, endpoint] of endpoints.entries()) {
    const connection = connections[endpoint.connectionIndex];
    const source = connection.pointsToConnect[endpoint.pointIndex];
    const preparedConnection = prepared.flatMap((b2) => b2.connections).find((c2) => c2.connectionIndex === endpointIndex);
    const fromLayer = preparedConnection.sourceLayer;
    const toLayer = options.targetLayers.get(connection.name);
    const site = sites.get(endpointIndex);
    const margin = options.viaDiameter / 2 + (options.boardEdgeClearance ?? 0);
    if (site.x < input.bounds.minX + margin || site.x > input.bounds.maxX - margin || site.y < input.bounds.minY + margin || site.y > input.bounds.maxY - margin)
      throw Error(`${connection.name}: dogbone outside board bounds`);
    const span = getViaSpanLayers({
      fromLayer,
      toLayer,
      layerNames: layers,
      allowBlindAndBuriedVias: options.allowBlindAndBuriedVias ?? false
    });
    traces.push({
      type: "pcb_trace",
      pcb_trace_id: `local_dogbone_${connection.name}_${endpoint.pointIndex}`,
      connection_name: connection.name,
      route: [
        {
          route_type: "wire",
          x: source.x,
          y: source.y,
          layer: fromLayer,
          width: options.traceWidth
        },
        {
          route_type: "wire",
          ...site,
          layer: fromLayer,
          width: options.traceWidth
        },
        {
          route_type: "via",
          ...site,
          from_layer: fromLayer,
          to_layer: toLayer,
          layers: span,
          via_diameter: options.viaDiameter,
          via_hole_diameter: options.viaHoleDiameter
        },
        {
          route_type: "wire",
          ...site,
          layer: toLayer,
          width: options.traceWidth
        }
      ]
    });
    connection.pointsToConnect[endpoint.pointIndex] = {
      ...site,
      layer: toLayer
    };
  }
  return { connections, traces };
}

// lib/alternate-signal-dogbones.ts
function routeAlternateSignalDogbones(input, options, attempt) {
  const delta = input.connections.reduce(
    (s2, c2) => ({
      x: s2.x + c2.pointsToConnect[1].x - c2.pointsToConnect[0].x,
      y: s2.y + c2.pointsToConnect[1].y - c2.pointsToConnect[0].y
    }),
    { x: 0, y: 0 }
  );
  const base = Math.abs(delta.x) > Math.abs(delta.y) ? delta.x > 0 ? 3 : 1 : 0;
  const busNames = new Set(
    (input.buses ?? []).flatMap((b2) => b2.connectionNames)
  );
  const backward = backwardFacingPackageTerminals({
    ...input,
    connections: input.connections.filter((c2) => busNames.has(c2.name))
  });
  const order = input.traces?.length ? [0, ...[0, 1, 2, 3].map((i2) => (base + i2) % 4).filter((i2) => i2 !== 0)] : [3, 0, 1, 2].map((i2) => (base + i2) % 4);
  const turns = backward ? (base + attempt) % 4 : order[attempt % 4];
  const rotate2 = (p2, k2) => {
    let { x: x2, y: y2 } = p2;
    for (let i2 = 0; i2 < k2; i2++) [x2, y2] = [-y2, x2];
    return { ...p2, x: x2, y: y2 };
  };
  const corners = [
    { x: input.bounds.minX, y: input.bounds.minY },
    { x: input.bounds.maxX, y: input.bounds.maxY }
  ].map((p2) => rotate2(p2, turns));
  const rotated = {
    ...input,
    bounds: {
      minX: Math.min(...corners.map((p2) => p2.x)),
      maxX: Math.max(...corners.map((p2) => p2.x)),
      minY: Math.min(...corners.map((p2) => p2.y)),
      maxY: Math.max(...corners.map((p2) => p2.y))
    },
    connections: input.connections.map((c2) => ({
      ...c2,
      pointsToConnect: c2.pointsToConnect.map((p2) => rotate2(p2, turns))
    })),
    obstacles: input.obstacles.map((o2) => ({
      ...o2,
      center: rotate2(o2.center, turns),
      ccwRotationDegrees: (o2.ccwRotationDegrees ?? 0) + 90 * turns
    })),
    traces: input.traces?.map((t48) => ({
      ...t48,
      route: t48.route.map((p2) => rotate2(p2, turns))
    }))
  };
  const result = routeLocalSignalDogbones(
    rotated,
    options
  );
  return {
    connections: result.connections.map((c2) => ({
      ...c2,
      pointsToConnect: c2.pointsToConnect.map((p2) => rotate2(p2, (4 - turns) % 4))
    })),
    traces: result.traces.map((t48) => ({
      ...t48,
      route: t48.route.map((p2) => {
        if (!("x" in p2)) throw Error("Unexpected dogbone primitive");
        return rotate2(p2, (4 - turns) % 4);
      })
    }))
  };
}

// lib/run-bounded-routing.ts
function* runBoundedRouting(generator, limit) {
  let state = generator.next();
  let steps = 0;
  try {
    while (!state.done && steps++ < limit) {
      yield;
      state = generator.next();
    }
    return state.done ? state.value : null;
  } finally {
    if (!state.done) generator.return(null);
  }
}

// lib/repair-bus-dogbones.ts
function signalWidth(input, connection) {
  return input.buses?.find((bus) => bus.connectionNames.includes(connection.name))?.traceWidth ?? connection.nominalTraceWidth ?? connection.width ?? input.minTraceWidth;
}
function signalDogboneOptions(input, targetLayers) {
  return {
    targetLayers,
    viaDiameter: input.minViaPadDiameter ?? 0.6,
    viaHoleDiameter: input.minViaHoleDiameter ?? 0.3,
    traceWidth: Math.max(
      input.minTraceWidth,
      ...input.connections.map((c2) => signalWidth(input, c2))
    ),
    clearance: input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075,
    boardEdgeClearance: input.minBoardEdgeClearance,
    holeToHoleClearance: input.minViaHoleEdgeToViaHoleEdgeClearance,
    allowBlindAndBuriedVias: input.allowBlindAndBuriedVias ?? false
  };
}
function ownedSignalEscapes(native, traces) {
  return traces.map((trace) => ({
    ...trace,
    source_trace_id: native.connections.find((c2) => c2.name === trace.connection_name)?.source_trace_id ?? trace.connection_name
  }));
}
function* repairBusDogbones(native, laneInput, current, generatedEscapes) {
  let input = structuredClone(laneInput);
  let traces = current;
  let escapes = generatedEscapes;
  const widths = new Map(
    native.connections.map((c2) => [c2.name, signalWidth(native, c2)])
  );
  const missing = input.connections.filter(
    (c2) => !traces.some((t48) => t48.connection_name === c2.name)
  );
  if (!missing.length) return { input, traces, escapes };
  if (missing.length > 3 || missing.some(
    (c2) => !input.buses?.some((b2) => b2.connectionNames.includes(c2.name))
  ))
    return null;
  const missingCount = (names) => missing.filter((c2) => names.includes(c2.name)).length;
  const buses = (input.buses ?? []).filter((bus) => missingCount(bus.connectionNames)).sort(
    (a2, b2) => missingCount(b2.connectionNames) - missingCount(a2.connectionNames)
  );
  for (const bus of buses) {
    const names = new Set(bus.connectionNames);
    const group = native.connections.filter((c2) => names.has(c2.name));
    const outside = traces.filter((t48) => !names.has(t48.connection_name));
    const pair = input.differentialPairs?.find(
      (p2) => p2.connectionNames.every((name) => names.has(name))
    );
    if (!pair || group.length !== names.size) return null;
    const layer = input.connections.find((c2) => names.has(c2.name)).pointsToConnect[0].layer;
    const congested = missingCount(bus.connectionNames) > 1;
    const variants = congested ? [1, 0, 3, 5, 2, 4] : [2, 1, 0, 3, 5, 4];
    let solved = false;
    for (let choice = 0; choice < 4 && !solved; choice++) {
      const attempt = ((congested ? 1 : 0) + choice) % 4;
      const base = {
        ...native,
        connections: group,
        traces: [
          ...native.traces ?? [],
          ...escapes.filter((t48) => !names.has(t48.connection_name)),
          ...outside
        ]
      };
      let replacement;
      try {
        replacement = routeAlternateSignalDogbones(
          base,
          signalDogboneOptions(
            base,
            new Map(group.map((c2) => [c2.name, layer]))
          ),
          attempt
        );
      } catch {
        yield;
        continue;
      }
      const newEscapes = ownedSignalEscapes(native, replacement.traces);
      const local = {
        ...input,
        connections: replacement.connections,
        buses: [bus],
        differentialPairs: [pair],
        traces: [...base.traces, ...newEscapes]
      };
      const fixed = fixedCopper(local);
      const ordinary = local.connections.filter(
        (c2) => !pair.connectionNames.includes(c2.name)
      );
      for (const variant of variants) {
        const paired = yield* runBoundedRouting(
          routeCoupledPair(local, pair, fixed, {
            copper: [],
            penalty: 0,
            variant
          }),
          6e3
        );
        if (!paired) continue;
        const generator = negotiateLanes(
          local,
          ordinary,
          fixed,
          paired,
          widths,
          void 0,
          /* @__PURE__ */ new Map(),
          () => false,
          true
        );
        let state = generator.next();
        let steps = 0;
        let best = 0;
        let completed = null;
        try {
          while (!state.done && steps++ < 1e4) {
            if (state.value.length > best) {
              best = state.value.length;
              if (best >= local.connections.length - 1) {
                const closed = yield* runBoundedRouting(
                  ejectBlockingLanes(
                    { ...local, connections: ordinary },
                    state.value.filter(
                      (t48) => !pair.connectionNames.includes(t48.connection_name)
                    ),
                    [...fixed, ...paired.flatMap(routeCopper)],
                    widths,
                    /* @__PURE__ */ new Map(),
                    { maxSearches: 200 }
                  ),
                  2e4
                );
                if (closed) {
                  completed = [...paired, ...closed];
                  break;
                }
              }
            }
            yield;
            state = generator.next();
          }
          if (state.done) completed = state.value;
        } finally {
          if (!state.done) generator.return(null);
        }
        if (!completed) continue;
        traces = [...outside, ...completed];
        escapes = [
          ...escapes.filter((t48) => !names.has(t48.connection_name)),
          ...newEscapes
        ];
        input = {
          ...input,
          connections: input.connections.map(
            (c2) => local.connections.find((next) => next.name === c2.name) ?? c2
          ),
          traces: [...native.traces ?? [], ...escapes]
        };
        solved = true;
        break;
      }
    }
    if (!solved) return null;
  }
  return traces.length === input.connections.length ? { input, traces, escapes } : null;
}

// lib/repair-shared-layer-conflicts.ts
function* repairSharedLayerConflicts(input, initial, layers, options = {}) {
  const connections = input.connections, fixed = fixedCopper(input), index2 = new RouteConflictIndex();
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const clashes = (routes2) => {
    const collisions = [];
    for (let a2 = 0; a2 < routes2.length; a2++)
      for (let b2 = 0; b2 < a2; b2++)
        if (routes2[a2].route[0].layer === routes2[b2].route[0].layer && index2.firstConflict(
          routes2[a2].route,
          routes2[b2].route,
          (routes2[a2].route[0].width + routes2[b2].route[0].width) / 2 + clearance - 1e-8
        ))
          collisions.push([a2, b2]);
    return collisions;
  };
  function* route(c2, blocked, others) {
    const choices = [];
    for (const layer of layers.get(c2.name) ?? [c2.pointsToConnect[0].layer]) {
      const connection = {
        ...c2,
        pointsToConnect: c2.pointsToConnect.map((p2) => ({ ...p2, layer }))
      };
      const scene = new VectorScene(input, connection, signalWidth(input, c2), [
        ...fixed,
        ...blocked.flatMap(routeCopper)
      ]);
      const search = new GridVisibilitySearch(
        scene,
        ...connection.pointsToConnect,
        others.flatMap(routeCopper),
        10,
        void 0,
        {
          maxLength: Math.min(
            maximumCarrierLength(input, c2.name),
            (options.lengthTargets?.get(c2.name) ?? Infinity) - fixedRouteLength(input, c2.name)
          ),
          paretoLength: true,
          checkReachability: true
        }
      );
      let steps = 0;
      try {
        while (!search.solved && !search.failed && steps++ < 4e3) {
          search.step();
          yield;
        }
        if (search.solved) {
          const trace = {
            type: "pcb_trace",
            pcb_trace_id: `bus_lane_${c2.name}`,
            connection_name: c2.name,
            source_trace_id: c2.source_trace_id ?? c2.name,
            route: search.result.map((p2) => ({
              ...p2,
              route_type: "wire",
              layer,
              width: signalWidth(input, c2)
            }))
          };
          const target = options.lengthTargets?.get(c2.name);
          if (target === void 0) choices.push(trace);
          else
            try {
              choices.push(
                tuneSmoothLengths(
                  {
                    ...input,
                    connections: [connection],
                    traces: [...input.traces ?? [], ...blocked],
                    buses: [],
                    differentialPairs: []
                  },
                  chamferOrdinaryCorners(
                    { ...input, connections: [connection] },
                    [trace],
                    [...fixed, ...blocked.flatMap(routeCopper)],
                    1.5
                  ),
                  /* @__PURE__ */ new Map([[c2.name, target]]),
                  { maxCandidates: 65536, packMeanders: true }
                )[0]
              );
            } catch {
            }
        }
      } finally {
        search.cancel();
      }
    }
    return choices;
  }
  const routes = initial.filter((t48) => {
    const c2 = connections.find((c3) => c3.name === t48.connection_name);
    if (!c2 || length(t48.route) > maximumCarrierLength(input, c2.name) + 1e-7)
      return false;
    const target = options.lengthTargets?.get(c2.name);
    if (target !== void 0 && Math.abs(length(t48.route) + fixedRouteLength(input, c2.name) - target) > 1e-7)
      return false;
    if (c2.pointsToConnect.some(
      (p2) => ![t48.route[0], t48.route.at(-1)].some(
        (q2) => Math.hypot(p2.x - q2.x, p2.y - q2.y) < 1e-7
      )
    ))
      return false;
    const layer = t48.route[0].layer;
    const projected = {
      ...c2,
      pointsToConnect: c2.pointsToConnect.map((p2) => ({ ...p2, layer }))
    };
    return new VectorScene(
      input,
      projected,
      signalWidth(input, c2),
      fixed
    ).pathVisible(t48.route);
  });
  for (const c2 of connections.filter(
    (c3) => !routes.some((t48) => t48.connection_name === c3.name)
  )) {
    const choices = yield* route(c2, [], routes);
    if (!choices.length) {
      options.onBlockedConnection?.(c2.name);
      return null;
    }
    choices.sort(
      (a2, b2) => clashes([...routes, a2]).length - clashes([...routes, b2]).length || length(a2.route) - length(b2.route)
    );
    routes.push(choices[0]);
  }
  const create = (routes2, constraints, depth) => ({
    routes: routes2,
    constraints,
    depth,
    collisions: clashes(routes2),
    cost: routes2.reduce((sum, t48) => sum + length(t48.route), 0)
  });
  const queue = [create(routes, /* @__PURE__ */ new Map(), 0)], seen = /* @__PURE__ */ new Set();
  let best = Infinity;
  const ids = /* @__PURE__ */ new WeakMap();
  let nextId = 0;
  const id = (t48) => {
    if (!ids.has(t48)) ids.set(t48, nextId++);
    return ids.get(t48);
  };
  for (let nodes = 0; queue.length && nodes < (options.maxNodes ?? 2e3); nodes++) {
    queue.sort(
      (a2, b2) => a2.collisions.length - b2.collisions.length || a2.depth - b2.depth || a2.cost - b2.cost
    );
    const node = queue.shift();
    if (!node.collisions.length) return node.routes;
    if (node.collisions.length < best || nodes % 20 === 0) {
      if (node.collisions.length < best)
        options.onBestCandidate?.(
          node.routes,
          node.collisions.map(([a2, b2]) => [
            node.routes[a2].connection_name,
            node.routes[b2].connection_name
          ])
        );
      best = Math.min(best, node.collisions.length);
      options.onProgress?.({
        nodes,
        collisions: node.collisions.length,
        queue: queue.length
      });
    }
    const degree = /* @__PURE__ */ new Map();
    for (const pair2 of node.collisions)
      for (const i2 of pair2) degree.set(i2, (degree.get(i2) ?? 0) + 1);
    node.collisions.sort(
      (a2, b2) => degree.get(a2[0]) + degree.get(a2[1]) - (degree.get(b2[0]) + degree.get(b2[1]))
    );
    const pair = node.collisions[0];
    for (const [change, block] of [pair, [pair[1], pair[0]]]) {
      const name = node.routes[change].connection_name, connection = connections.find((c2) => c2.name === name);
      const constraints = new Map(node.constraints);
      constraints.set(name, [
        ...constraints.get(name) ?? [],
        node.routes[block]
      ]);
      const signature = connections.map(
        (c2) => `${c2.name}:${(constraints.get(c2.name) ?? []).map(id).sort((a2, b2) => a2 - b2).join(",")}`
      ).join(";");
      if (seen.has(signature)) continue;
      seen.add(signature);
      const others = node.routes.filter((_2, i2) => i2 !== change);
      for (const choice of yield* route(
        connection,
        constraints.get(name),
        others
      )) {
        const result = node.routes.map((t48, i2) => i2 === change ? choice : t48);
        queue.push(create(result, constraints, node.depth + 1));
      }
    }
    if (queue.length > 256) {
      queue.sort(
        (a2, b2) => a2.collisions.length - b2.collisions.length || a2.depth - b2.depth || a2.cost - b2.cost
      );
      queue.length = 256;
    }
    yield;
  }
  return null;
}

// lib/reserve-bus-package-exits.ts
function reserveBusPackageExits(input, pair) {
  const pairLayer = input.connections.find(
    (c2) => c2.name === pair.connectionNames[0]
  ).pointsToConnect[0].layer;
  const ownBus = input.buses?.find(
    (bus2) => pair.connectionNames.some((name) => bus2.connectionNames.includes(name))
  );
  const related = ownBus ? [ownBus] : (input.buses ?? []).filter(
    (bus2) => input.connections.some(
      (c2) => bus2.connectionNames.includes(c2.name) && c2.pointsToConnect[0].layer === pairLayer
    )
  );
  if (!related.length) return [];
  const bus = related[0], names = new Set(related.flatMap((bus2) => bus2.connectionNames)), members = input.connections.filter((c2) => names.has(c2.name));
  const regions = packageApproachRegions(input, 0), layer = members[0].pointsToConnect[0].layer, width = bus.traceWidth ?? input.minTraceWidth;
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const reserve = Math.max(0, members.length - 2) * (width + clearance);
  const faces = /* @__PURE__ */ new Map();
  for (const connection of members)
    for (const point of connection.pointsToConnect) {
      const region = regions.map((region2, index2) => ({
        box: region2.pads,
        index: index2,
        distance: Math.hypot(
          point.x - (region2.pads.minX + region2.pads.maxX) / 2,
          point.y - (region2.pads.minY + region2.pads.maxY) / 2
        )
      })).sort((a2, b2) => a2.distance - b2.distance)[0];
      if (!region) continue;
      const { box } = region;
      const edge = [
        { side: "left", d: point.x - box.minX, x: -1, y: 0 },
        { side: "right", d: box.maxX - point.x, x: 1, y: 0 },
        { side: "bottom", d: point.y - box.minY, x: 0, y: -1 },
        { side: "top", d: box.maxY - point.y, x: 0, y: 1 }
      ].sort((a2, b2) => a2.d - b2.d)[0];
      const key = `${region.index}:${edge.side}`;
      let face = faces.get(key);
      if (!face) faces.set(key, face = []);
      face.push({ point, edge, name: connection.name });
    }
  const reservations = [];
  for (const face of faces.values()) {
    const nearest = Math.min(...face.map((member) => member.edge.d));
    for (const { point, edge, name } of face) {
      if (pair.connectionNames.includes(name) || edge.d > nearest + width / 2)
        continue;
      reservations.push({
        a: point,
        b: { x: point.x + edge.x * reserve, y: point.y + edge.y * reserve },
        radius: width / 2,
        layer,
        owners: [name]
      });
    }
  }
  return reservations;
}

// lib/plan-shared-pair-corridors.ts
function* planSharedPairCorridors(input, terminalLayers, freshDogbones = false) {
  const pairs = input.differentialPairs ?? [];
  const bounded = input.buses?.some((bus) => bus.maxLength !== void 0);
  const domains = pairs.map(() => []);
  const geometry = pairs.map(() => /* @__PURE__ */ new Set());
  const tried = /* @__PURE__ */ new Set();
  const fixed = fixedCopper(input);
  const conflicts = new RouteConflictIndex();
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const scenes = /* @__PURE__ */ new Map();
  let serial = 0;
  const collides = (a2, b2) => a2.layer === b2.layer && a2.traces.some(
    (t48) => b2.traces.some(
      (r2) => conflicts.firstConflict(
        t48.route,
        r2.route,
        (t48.route[0].width + r2.route[0].width) / 2 + clearance - 1e-8
      )
    )
  );
  const alternatives = freshDogbones ? [100, 2, 3, 0, 1, 101, 102, 103, 4, 104, 5, 105, 6, 106, 7, 107] : [1, 2, [0, 1], [1, 0], 0, [0, 2], [2, 0], 3, [1, 2], [2, 1], 4, 5, 6, 7];
  for (const variant of alternatives) {
    for (const [index2, pair] of pairs.entries()) {
      const members = pair.connectionNames.map(
        (name) => input.connections.find((c2) => c2.name === name)
      );
      const layers = terminalLayers.get(members[0].name)?.filter(
        (layer) => members.every((c2) => terminalLayers.get(c2.name)?.includes(layer))
      ) ?? [members[0].pointsToConnect[0].layer];
      for (const layer of layers.filter(
        (layer2) => !input.allowedLayers || input.allowedLayers.includes(layer2)
      )) {
        const reserved = typeof variant === "number" && variant >= 100;
        const sceneKey = JSON.stringify([index2, layer, reserved]);
        const local = scenes.get(sceneKey) ?? {
          ...input,
          connections: input.connections.map(
            (c2) => pair.connectionNames.includes(c2.name) ? {
              ...c2,
              pointsToConnect: c2.pointsToConnect.map((p2) => ({
                ...p2,
                layer
              }))
            } : c2
          )
        };
        scenes.set(sceneKey, local);
        const search = runBoundedRouting(
          routeCoupledPair(
            local,
            pair,
            reserved ? [...fixed, ...reserveBusPackageExits(local, pair)] : fixed,
            {
              copper: [],
              penalty: 0,
              ...typeof variant === "number" ? { variant: reserved ? variant - 100 : variant } : { handoffOffsets: variant }
            }
          ),
          6e3
        );
        let state = search.next();
        try {
          while (!state.done) {
            yield void 0;
            state = search.next();
          }
        } finally {
          if (!state.done) search.return(null);
        }
        if (!state.value) continue;
        if (bounded && state.value.some(
          (trace) => length(trace.route) > maximumCarrierLength(input, trace.connection_name) + 1e-7
        ))
          continue;
        const key = JSON.stringify(state.value.map((t48) => t48.route));
        if (geometry[index2].has(key)) continue;
        geometry[index2].add(key);
        domains[index2].push({
          id: serial++,
          layer,
          traces: state.value,
          length: state.value.reduce((sum, t48) => sum + length(t48.route), 0)
        });
      }
    }
    if (bounded)
      for (const choices of domains) choices.sort((a2, b2) => a2.length - b2.length);
    const plans = [];
    const visit = (selected, index2) => {
      if (plans.length >= 256) return;
      if (index2 === domains.length) {
        const key = selected.map((c2) => c2.id).join(",");
        if (!tried.has(key)) plans.push(selected);
        return;
      }
      for (const choice of domains[index2])
        if (!selected.some((other) => collides(choice, other)))
          visit([...selected, choice], index2 + 1);
    };
    visit([], 0);
    const busNames = new Set(input.buses?.flatMap((bus) => bus.connectionNames));
    const pairNames = new Set(pairs.flatMap((pair) => pair.connectionNames));
    const costs = new Map(
      plans.map((plan) => [
        plan,
        freshDogbones ? input.connections.filter((c2) => busNames.has(c2.name) && !pairNames.has(c2.name)).reduce(
          (sum, c2) => sum + plan.filter(
            (choice) => choice.layer === c2.pointsToConnect[0].layer
          ).flatMap((choice) => choice.traces).filter(
            (trace) => conflicts.firstConflict(
              c2.pointsToConnect,
              trace.route,
              (trace.route[0].width + input.minTraceWidth) / 2 + clearance - 1e-8
            )
          ).length,
          0
        ) : 0
      ])
    );
    plans.sort(
      (a2, b2) => costs.get(a2) - costs.get(b2) || a2.reduce((sum, c2) => sum + c2.length, 0) - b2.reduce((sum, c2) => sum + c2.length, 0)
    );
    for (const plan of plans) {
      tried.add(plan.map((c2) => c2.id).join(","));
      yield plan.flatMap((c2) => c2.traces);
    }
  }
}

// lib/reachable-signal-dogbones.ts
var near = (a2, b2) => distance(a2, b2) < 1e-8;
function localSignalSiteCandidates(input, connection, options) {
  const sites = [[], []];
  const single = { ...input, connections: [connection] };
  for (let end = 0; end < 2; end++) {
    const rejected = [];
    for (let attempt = 0; attempt < 8; attempt++) {
      try {
        const generated = routeLocalSignalDogbones(
          {
            ...single,
            obstacles: [...single.obstacles, ...rejected]
          },
          options
        );
        const point = generated.connections[0].pointsToConnect[end];
        if (sites[end].some((site) => near(site.point, point))) break;
        const escape = ownedSignalEscapes(input, generated.traces).find(
          (trace) => near(trace.route[0], connection.pointsToConnect[end])
        );
        if (!escape) break;
        sites[end].push({
          point,
          escape,
          copper: fixedCopper({ ...input, obstacles: [], traces: [escape] })
        });
        rejected.push({
          type: "rect",
          center: { x: point.x, y: point.y },
          width: 1e-6,
          height: 1e-6,
          layers: getCopperLayerNames(input.layerCount),
          connectedTo: []
        });
      } catch {
        break;
      }
    }
    sites[end].sort((a2, b2) => a2.point.x - b2.point.x || a2.point.y - b2.point.y);
  }
  return sites;
}
function* reachableSignalDogbones(input, options, allowedLayers, nearestTerminalAttachments = false) {
  const endpoints = [];
  const fixed = fixedCopper(input);
  for (const [connectionIndex, connection] of input.connections.entries()) {
    const sites = localSignalSiteCandidates(input, connection, options);
    if (sites.some((end) => !end.length)) return null;
    let best;
    for (const layer of allowedLayers.get(connection.name) ?? []) {
      const supportsLayer = (site) => site.escape.route.some(
        (point) => point.route_type === "via" && point.layers?.includes(layer)
      );
      const starts = sites[0].filter(supportsLayer).map((site) => ({ ...site.point, layer }));
      const ends = sites[1].filter(supportsLayer).map((site) => ({ ...site.point, layer }));
      if (!starts.length || !ends.length) continue;
      const local = { ...connection, pointsToConnect: [starts[0], ends[0]] };
      const search = new GridVisibilitySearch(
        new VectorScene(input, local, options.traceWidth, fixed),
        starts[0],
        ends[0],
        [],
        0,
        void 0,
        { starts, ends, nearestTerminalAttachments, checkReachability: true }
      );
      try {
        let steps = 0;
        while (!search.solved && !search.failed && steps++ < 4e3) {
          search.step();
          yield;
        }
        if (search.solved) {
          const cost = length(search.result);
          if (!best || cost < best.cost)
            best = { cost, start: search.result[0], end: search.result.at(-1) };
        }
      } finally {
        search.cancel();
      }
    }
    if (!best) return null;
    for (let pointIndex = 0; pointIndex < 2; pointIndex++) {
      const source = connection.pointsToConnect[pointIndex];
      const target = connection.pointsToConnect[1 - pointIndex];
      const preferred = pointIndex ? best.end : best.start;
      const dx2 = target.x - source.x, dy2 = target.y - source.y;
      const outwardRank = (point) => {
        const displacement = Math.abs(dx2) >= Math.abs(dy2) ? Math.sign(dx2) * (point.x - source.x) : Math.sign(dy2) * (point.y - source.y);
        return displacement > 1e-9 ? 0 : Math.abs(displacement) <= 1e-9 ? 1 : 2;
      };
      sites[pointIndex].sort((a2, b2) => {
        const difference = distance(source, a2.point) - distance(source, b2.point);
        return Number(!near(a2.point, preferred)) - Number(!near(b2.point, preferred)) || outwardRank(a2.point) - outwardRank(b2.point) || (Math.abs(difference) < 1e-8 ? 0 : difference) || a2.point.x - b2.point.x || a2.point.y - b2.point.y;
      });
      const owners = [connection.name, source.pcb_port_id, source.pointId];
      const pad = input.obstacles.filter(
        (o2) => o2.componentId && o2.connectedTo.some((owner) => owners.includes(owner))
      ).sort(
        (a2, b2) => distance(a2.center, source) - distance(b2.center, source)
      )[0];
      if (!pad?.componentId) return null;
      endpoints.push({
        connectionIndex,
        pointIndex,
        component: pad.componentId,
        sites: sites[pointIndex]
      });
    }
  }
  const assigned = /* @__PURE__ */ new Map();
  const compatible = (a2, b2) => {
    if (a2.copper.some(
      (c2) => b2.copper.some(
        (d2) => c2.layer === d2.layer && clearanceToCopper(c2.a, c2.b, d2) < c2.radius + options.clearance - 1e-8
      )
    ))
      return false;
    const first = a2.escape.route.find((p2) => p2.route_type === "via");
    const second = b2.escape.route.find((p2) => p2.route_type === "via");
    return distance(first, second) >= options.viaHoleDiameter + (options.holeToHoleClearance ?? options.clearance) - 1e-8;
  };
  let states = 0;
  for (const component of new Set(endpoints.map((end) => end.component))) {
    const search = (remaining) => {
      if (++states > 1e5) return false;
      if (!remaining.length) return true;
      const domains = remaining.map((endpoint2) => ({
        endpoint: endpoint2,
        sites: endpoint2.sites.filter(
          (site) => [...assigned.values()].every((other) => compatible(site, other))
        )
      })).sort(
        (a2, b2) => a2.sites.length - b2.sites.length || a2.endpoint.connectionIndex - b2.endpoint.connectionIndex || a2.endpoint.pointIndex - b2.endpoint.pointIndex
      );
      const { endpoint, sites } = domains[0];
      for (const site of sites) {
        assigned.set(endpoint, site);
        if (search(remaining.filter((end) => end !== endpoint))) return true;
        assigned.delete(endpoint);
      }
      return false;
    };
    if (!search(endpoints.filter((end) => end.component === component)))
      return null;
    yield;
  }
  const connections = structuredClone(input.connections);
  const traces = [];
  for (const endpoint of endpoints) {
    const site = assigned.get(endpoint);
    const connection = connections[endpoint.connectionIndex];
    connection.pointsToConnect[endpoint.pointIndex] = {
      ...site.point,
      layer: options.targetLayers.get(connection.name)
    };
    traces.push(site.escape);
  }
  return { connections, traces };
}

// lib/flexible-signal-state.ts
function signalLayers(input, connection) {
  return (input.allowedLayers ?? getCopperLayerNames(input.layerCount)).filter(
    (layer) => !connection.pointsToConnect.some((point) => point.layer === layer) && (input.buses ?? []).every(
      (bus) => !bus.connectionNames.includes(connection.name) || !bus.allowedLayers || bus.allowedLayers.includes(layer)
    )
  );
}
function signalTrace(input, connection, route, layer) {
  const width = signalWidth(input, connection);
  return {
    type: "pcb_trace",
    pcb_trace_id: `bus_lane_${connection.name}`,
    connection_name: connection.name,
    source_trace_id: connection.source_trace_id ?? connection.name,
    route: route.map((point) => ({
      ...point,
      route_type: "wire",
      layer,
      width
    }))
  };
}

// lib/copper-conflict-index.ts
var CopperConflictIndex = class {
  geometry = /* @__PURE__ */ new WeakMap();
  prepare(copper) {
    const cached = this.geometry.get(copper);
    if (cached) return cached;
    const bounds = new Float64Array(copper.length * 4);
    let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
    for (let i2 = 0; i2 < copper.length; i2++) {
      const c2 = copper[i2], k2 = i2 * 4;
      bounds[k2] = Math.min(c2.a.x, c2.b.x) - c2.radius;
      bounds[k2 + 1] = Math.max(c2.a.x, c2.b.x) + c2.radius;
      bounds[k2 + 2] = Math.min(c2.a.y, c2.b.y) - c2.radius;
      bounds[k2 + 3] = Math.max(c2.a.y, c2.b.y) + c2.radius;
      if (c2.rect) {
        bounds[k2] = Math.min(bounds[k2], c2.rect.minX);
        bounds[k2 + 1] = Math.max(bounds[k2 + 1], c2.rect.maxX);
        bounds[k2 + 2] = Math.min(bounds[k2 + 2], c2.rect.minY);
        bounds[k2 + 3] = Math.max(bounds[k2 + 3], c2.rect.maxY);
      }
      minX = Math.min(minX, bounds[k2]);
      maxX = Math.max(maxX, bounds[k2 + 1]);
      minY = Math.min(minY, bounds[k2 + 2]);
      maxY = Math.max(maxY, bounds[k2 + 3]);
    }
    const geometry = { copper, bounds, minX, maxX, minY, maxY };
    this.geometry.set(copper, geometry);
    return geometry;
  }
  firstConflict(first, second, clearance) {
    const a2 = this.prepare(first), b2 = this.prepare(second);
    if (a2.maxX + clearance < b2.minX || b2.maxX + clearance < a2.minX || a2.maxY + clearance < b2.minY || b2.maxY + clearance < a2.minY)
      return;
    for (let i2 = 0; i2 < first.length; i2++) {
      const c2 = first[i2], ai = i2 * 4;
      for (let j2 = 0; j2 < second.length; j2++) {
        const d2 = second[j2], bj = j2 * 4;
        if (c2.layer !== d2.layer || a2.bounds[ai + 1] + clearance < b2.bounds[bj] || b2.bounds[bj + 1] + clearance < a2.bounds[ai] || a2.bounds[ai + 3] + clearance < b2.bounds[bj + 2] || b2.bounds[bj + 3] + clearance < a2.bounds[ai + 2])
          continue;
        if (clearanceToCopper(c2.a, c2.b, d2) < c2.radius + clearance) return [c2, d2];
      }
    }
  }
};

// lib/find-signal-site-pocket.ts
function* expandSignalSitePocket(state) {
  const { native, pending, retained, traces } = state;
  const fixed = fixedCopper(pending), conflicts = new RouteConflictIndex(), remove = /* @__PURE__ */ new Set();
  const clearance = native.minTraceToPadEdgeClearance ?? native.defaultObstacleMargin ?? 0.075;
  const probe = function* (connection, hard, local = pending, lanes = traces) {
    const results = [];
    const source = native.connections.find((c2) => c2.name === connection.name);
    const width = signalWidth(native, source);
    for (const layer of signalLayers(native, source)) {
      const c2 = {
        ...connection,
        pointsToConnect: connection.pointsToConnect.map((p2) => ({
          ...p2,
          layer
        }))
      };
      const search = new GridVisibilitySearch(
        new VectorScene(local, c2, width, hard),
        c2.pointsToConnect[0],
        c2.pointsToConnect[1],
        lanes.flatMap(routeCopper),
        100,
        void 0,
        {
          checkReachability: true,
          maxLength: maximumCarrierLength(local, c2.name),
          paretoLength: Number.isFinite(maximumCarrierLength(local, c2.name))
        }
      );
      try {
        let steps = 0;
        while (!search.solved && !search.failed && steps++ < 3e3) {
          search.step();
          yield;
        }
        if (search.solved)
          results.push({
            layer,
            blockers: lanes.filter(
              (t48) => t48.route[0].layer === layer && conflicts.firstConflict(
                search.result,
                t48.route,
                (width + t48.route[0].width) / 2 + clearance - 1e-8
              )
            )
          });
      } finally {
        search.cancel();
      }
    }
    return results;
  };
  for (const connection of pending.connections.filter(
    (c2) => !traces.some((t48) => t48.connection_name === c2.name)
  )) {
    const best = (yield* probe(connection, fixed)).sort(
      (a2, b2) => a2.blockers.length - b2.blockers.length
    )[0];
    remove.add(connection.name);
    for (const trace of best?.blockers ?? []) remove.add(trace.connection_name);
  }
  const additions = /* @__PURE__ */ new Set(), remaining = traces.filter((t48) => !remove.has(t48.connection_name));
  for (const connection of pending.connections.filter(
    (c2) => remove.has(c2.name)
  )) {
    const reduced = {
      ...pending,
      traces: [
        ...native.traces ?? [],
        ...state.escapes.filter((t48) => !remove.has(t48.connection_name)),
        ...retained
      ]
    };
    const choices = yield* probe(
      connection,
      fixedCopper(reduced),
      reduced,
      remaining
    );
    for (const choice of choices)
      if (choice.blockers.length <= 3)
        for (const trace of choice.blockers)
          additions.add(trace.connection_name);
    const best = choices.sort(
      (a2, b2) => a2.blockers.length - b2.blockers.length
    )[0];
    for (const trace of best?.blockers ?? [])
      additions.add(trace.connection_name);
  }
  for (const name of additions) remove.add(name);
  return remove;
}
function* findViaAwareSignalPocket(state) {
  const { native } = state, carriers = [...state.retained, ...state.traces];
  const pairs = new Set(
    native.differentialPairs?.flatMap((p2) => p2.connectionNames)
  ), remove = /* @__PURE__ */ new Set();
  const clearance = native.minTraceToPadEdgeClearance ?? native.defaultObstacleMargin ?? 0.075;
  const existing = [...state.escapes, ...carriers].map((trace) => ({
    name: trace.connection_name,
    copper: fixedCopper({ ...native, obstacles: [], traces: [trace] })
  }));
  const conflicts = new CopperConflictIndex();
  const hits = (copper) => new Set(
    existing.filter(
      (other) => conflicts.firstConflict(copper, other.copper, clearance - 1e-8)
    ).map((other) => other.name)
  );
  for (const connection of native.connections.filter(
    (c2) => !carriers.some((t48) => t48.connection_name === c2.name)
  )) {
    const layers = signalLayers(native, connection);
    if (!layers.length) return /* @__PURE__ */ new Set();
    const single = { ...native, connections: [connection] };
    const ends = [[], []];
    for (let variant = 0; variant < 4; variant++) {
      try {
        const generated = routeAlternateSignalDogbones(
          single,
          signalDogboneOptions(single, /* @__PURE__ */ new Map([[connection.name, layers[0]]])),
          variant
        );
        for (let end = 0; end < 2; end++) {
          const point = generated.connections[0].pointsToConnect[end];
          if (ends[end].some(
            (site) => Math.hypot(site.point.x - point.x, site.point.y - point.y) < 1e-6
          ))
            continue;
          const escape = ownedSignalEscapes(native, generated.traces).find(
            (t48) => Math.hypot(
              t48.route[0].x - connection.pointsToConnect[end].x,
              t48.route[0].y - connection.pointsToConnect[end].y
            ) < 1e-6
          );
          if (escape) ends[end].push({ point, escape });
        }
      } catch {
      }
      yield;
    }
    let best;
    for (const a2 of ends[0])
      for (const b2 of ends[1]) {
        const escapeCopper = fixedCopper({
          ...native,
          obstacles: [],
          traces: [a2.escape, b2.escape]
        }), viaHits = hits(escapeCopper);
        if ([...viaHits].some((name) => pairs.has(name))) continue;
        const input = {
          ...native,
          connections: [connection],
          traces: [
            ...native.traces ?? [],
            ...state.escapes.filter((t48) => !viaHits.has(t48.connection_name)),
            ...carriers.filter((t48) => pairs.has(t48.connection_name))
          ]
        };
        const hard = fixedCopper(input);
        for (const layer of layers) {
          const local = {
            ...connection,
            pointsToConnect: [a2.point, b2.point].map((point) => ({
              ...point,
              layer
            }))
          };
          const search = new GridVisibilitySearch(
            new VectorScene(
              input,
              local,
              signalWidth(native, connection),
              hard
            ),
            local.pointsToConnect[0],
            local.pointsToConnect[1],
            carriers.filter((t48) => !pairs.has(t48.connection_name)).flatMap(routeCopper),
            100,
            void 0,
            {
              checkReachability: true,
              maxLength: maximumCarrierLength(native, connection.name) - length(a2.escape.route) - length(b2.escape.route)
            }
          );
          try {
            let steps = 0;
            while (!search.solved && !search.failed && steps++ < 4e3) {
              search.step();
              yield;
            }
            if (search.solved) {
              const trace = signalTrace(
                native,
                connection,
                search.result,
                layer
              ), names = hits([...escapeCopper, ...routeCopper(trace)]), cost = names.size * 1e3 + length(trace.route);
              if (![...names].some((name) => pairs.has(name)) && (!best || cost < best.cost))
                best = { cost, names };
            }
          } finally {
            search.cancel();
          }
        }
      }
    remove.add(connection.name);
    for (const name of best?.names ?? []) remove.add(name);
  }
  return remove;
}

// lib/negotiate-signal-sites.ts
function* negotiateSignalSites(state, remove, stopWithOneRemaining = false) {
  if (!remove.size) return null;
  const { native } = state;
  const all = [...state.retained, ...state.traces];
  const stable = all.filter((trace) => !remove.has(trace.connection_name));
  const fixedEscapes = state.escapes.filter(
    (trace) => !remove.has(trace.connection_name)
  );
  const targets = new Map([
    ...state.pending.connections.map((c2) => [
      c2.name,
      c2.pointsToConnect[0].layer
    ]),
    ...all.map((t48) => [
      t48.connection_name,
      t48.route[0].layer
    ])
  ]);
  const base = {
    ...native,
    connections: native.connections.filter((c2) => remove.has(c2.name)),
    traces: [...native.traces ?? [], ...fixedEscapes, ...stable]
  };
  if (!base.connections.length) return null;
  const hard = fixedCopper(base), variants = /* @__PURE__ */ new Map();
  const histories = /* @__PURE__ */ new Map(), projectors = /* @__PURE__ */ new Map();
  const clearance = native.minTraceToPadEdgeClearance ?? native.defaultObstacleMargin ?? 0.075;
  for (const connection of base.connections) {
    const single = { ...base, connections: [connection] }, ends = [[], []];
    for (let variant = 0; variant < 4; variant++) {
      try {
        const generated = routeAlternateSignalDogbones(
          single,
          signalDogboneOptions(single, targets),
          variant
        );
        for (let end = 0; end < 2; end++) {
          const point = generated.connections[0].pointsToConnect[end];
          if (ends[end].some(
            (site) => Math.hypot(site.point.x - point.x, site.point.y - point.y) < 1e-6
          ))
            continue;
          const escape = ownedSignalEscapes(native, generated.traces).find(
            (t48) => Math.hypot(
              t48.route[0].x - connection.pointsToConnect[end].x,
              t48.route[0].y - connection.pointsToConnect[end].y
            ) < 1e-6
          );
          if (escape) ends[end].push({ point, escape });
        }
      } catch {
      }
      yield;
    }
    const choices = [];
    for (const a2 of ends[0])
      for (const b2 of ends[1])
        for (const layer of signalLayers(native, connection)) {
          const local = {
            ...connection,
            pointsToConnect: [a2.point, b2.point].map((point) => ({
              ...point,
              layer
            }))
          };
          const escapes = [a2.escape, b2.escape];
          if (escapes.some(
            (t48) => !t48.route.some(
              (p2) => p2.route_type === "via" && p2.layers?.includes(layer)
            )
          ))
            continue;
          const maxLength = maximumCarrierLength(
            { ...native, traces: [...native.traces ?? [], ...escapes] },
            connection.name
          );
          const escapeCopper = fixedCopper({
            ...base,
            obstacles: [],
            traces: escapes
          });
          const scene = new VectorScene(
            base,
            local,
            signalWidth(native, connection),
            hard
          );
          const search = new GridVisibilitySearch(
            scene,
            local.pointsToConnect[0],
            local.pointsToConnect[1],
            [],
            0,
            void 0,
            { checkReachability: true, maxLength }
          );
          try {
            let steps = 0;
            while (!search.solved && !search.failed && steps++ < 3e3) {
              search.step();
              yield;
            }
            if (search.solved)
              choices.push({
                connection: local,
                escapes,
                escapeCopper,
                scene,
                layer,
                length: length(search.result),
                maxLength
              });
          } finally {
            search.cancel();
          }
        }
    choices.sort((a2, b2) => a2.length - b2.length);
    if (!choices.length) return null;
    variants.set(connection.name, choices);
  }
  const copperConflicts = new CopperConflictIndex();
  const overlap = (a2, b2) => copperConflicts.firstConflict(a2, b2, clearance - 1e-8);
  const conflicts = new RouteConflictIndex(), pools2 = /* @__PURE__ */ new Map(), signatures = /* @__PURE__ */ new Map(), compatibility = /* @__PURE__ */ new Map();
  let candidateId = 0;
  const compatible = (a2, b2) => {
    const key = a2.id < b2.id ? `${a2.id},${b2.id}` : `${b2.id},${a2.id}`;
    const cached = compatibility.get(key);
    if (cached !== void 0) return cached;
    const required = (a2.trace.route[0].width + b2.trace.route[0].width) / 2 + clearance;
    const clash = a2.layer === b2.layer && conflicts.firstConflict(
      a2.trace.route,
      b2.trace.route,
      required - 1e-8
    ) || overlap(a2.escapeCopper, b2.copper) || overlap(b2.escapeCopper, a2.copper);
    compatibility.set(key, !clash);
    return !clash;
  };
  const addCandidate = (candidate) => {
    const name = candidate.connection.name, key = JSON.stringify([
      candidate.escapes.map((t48) => t48.route),
      candidate.trace.route
    ]);
    let seen = signatures.get(name);
    if (!seen) signatures.set(name, seen = /* @__PURE__ */ new Set());
    if (seen.has(key)) return;
    seen.add(key);
    let pool = pools2.get(name);
    if (!pool) pools2.set(name, pool = []);
    pool.push(candidate);
    if (pool.length > 48) pool.splice(8, 1);
  };
  const select = () => {
    if (base.connections.some((c2) => !pools2.get(c2.name)?.length)) return;
    let nodes = 0, answer;
    const visit = (selected, domains) => {
      if (++nodes > 4e3) return;
      if (!domains.length) {
        answer = selected;
        return;
      }
      domains.sort((a2, b2) => a2.length - b2.length);
      for (const option of domains[0]) {
        const remaining = domains.slice(1).map((domain) => domain.filter((other) => compatible(option, other)));
        if (remaining.some((domain) => !domain.length)) continue;
        visit([...selected, option], remaining);
        if (answer) return;
      }
    };
    visit(
      [],
      base.connections.map((c2) => [...pools2.get(c2.name)].reverse())
    );
    return answer;
  };
  const routed = /* @__PURE__ */ new Map(), queue = [...base.connections].sort(
    (a2, b2) => variants.get(a2.name).length - variants.get(b2.name).length
  ), visits = /* @__PURE__ */ new Map();
  const finish = () => {
    const chosen = [...routed.values()], escapes = [...fixedEscapes, ...chosen.flatMap((option) => option.escapes)];
    const connections = base.connections.map(
      (c2) => routed.get(c2.name)?.connection ?? variants.get(c2.name)[0].connection
    );
    return {
      native,
      pending: {
        ...base,
        connections,
        traces: [...native.traces ?? [], ...escapes, ...stable]
      },
      escapes,
      retained: stable,
      traces: chosen.map((option) => option.trace)
    };
  };
  for (let iteration = 0; queue.length && iteration < 1200; iteration++) {
    const connection = queue.shift(), choices = variants.get(connection.name), visit = visits.get(connection.name) ?? 0;
    visits.set(connection.name, visit + 1);
    routed.delete(connection.name);
    const others = [...routed.values()], soft = others.flatMap((option) => option.copper);
    let best;
    for (let k2 = 0; k2 < Math.min(choices.length, 4); k2++) {
      const option = choices[(visit * 4 + k2) % choices.length], { scene, connection: local, layer } = option;
      if (stopWithOneRemaining && best) {
        const [a2, b2] = local.pointsToConnect;
        const forcedHits = others.filter(
          (other) => overlap(option.escapeCopper, other.copper)
        ).length;
        if (Math.hypot(a2.x - b2.x, a2.y - b2.y) + 100 * forcedHits > best.score + 1e-7)
          continue;
      }
      if (!projectors.has(layer)) {
        const projector = new GridHistoryProjector(scene);
        projectors.set(layer, projector);
        histories.set(layer, new Float32Array(projector.cellCount));
      }
      const search = new GridVisibilitySearch(
        scene,
        local.pointsToConnect[0],
        local.pointsToConnect[1],
        soft,
        10 + iteration,
        histories.get(layer),
        {
          checkReachability: true,
          maxLength: option.maxLength,
          paretoLength: Number.isFinite(option.maxLength)
        }
      );
      try {
        let steps = 0;
        while (!search.solved && !search.failed && steps++ < 3e3) {
          search.step();
          yield;
        }
        if (search.solved) {
          const trace = signalTrace(native, connection, search.result, layer), copper = [...option.escapeCopper, ...routeCopper(trace)];
          const hits = others.filter((other) => overlap(copper, other.copper)), score = length(trace.route) + hits.length * 100;
          const candidate = {
            ...option,
            id: candidateId++,
            trace,
            copper,
            hits,
            score
          };
          if (!stopWithOneRemaining) addCandidate(candidate);
          if (!best || score < best.score) best = candidate;
        }
      } finally {
        search.cancel();
      }
    }
    if (!best) {
      queue.push(connection);
      continue;
    }
    for (const other of best.hits) {
      const hit = overlap(best.copper, other.copper);
      if (hit) {
        const [a2, b2] = hit;
        projectors.get(a2.layer)?.penalizeIntersection(
          histories.get(a2.layer),
          a2.a,
          a2.b,
          b2.a,
          b2.b,
          a2.radius + b2.radius + clearance,
          true
        );
      }
      routed.delete(other.connection.name);
      if (!queue.some((c2) => c2.name === other.connection.name))
        queue.push(
          base.connections.find((c2) => c2.name === other.connection.name)
        );
    }
    routed.set(connection.name, best);
    if (stopWithOneRemaining && routed.size >= base.connections.length - 1)
      return finish();
    if (!stopWithOneRemaining && iteration % 8 === 0 && routed.size >= base.connections.length - 3) {
      const selected = select();
      if (selected) {
        for (const option of selected)
          routed.set(option.connection.name, option);
        queue.length = 0;
      }
    }
    yield;
  }
  return routed.size === base.connections.length ? finish() : null;
}

// lib/route-fresh-shared-buses.ts
function* routeFreshSharedBuses(native, allocation, originalEscapes, terminalLayers, options) {
  const pairNames = new Set(
    native.differentialPairs?.flatMap((pair) => pair.connectionNames)
  );
  const busNames = new Set(native.buses?.flatMap((bus) => bus.connectionNames));
  const busLayerLoads = /* @__PURE__ */ new Map();
  for (const bus of allocation.buses ?? []) {
    const occupied = new Set(
      allocation.connections.filter((c2) => bus.connectionNames.includes(c2.name)).map((c2) => c2.pointsToConnect[0].layer)
    );
    for (const layer of occupied)
      busLayerLoads.set(layer, (busLayerLoads.get(layer) ?? 0) + 1);
  }
  const sharedTimingLayers = [...busLayerLoads.values()].some(
    (count) => count > 1
  );
  const pairEscapes = originalEscapes.filter(
    (trace) => pairNames.has(trace.connection_name)
  );
  const targets = new Map(
    allocation.connections.map((connection) => [
      connection.name,
      connection.pointsToConnect[0].layer
    ])
  );
  const layers = new Map(
    native.connections.map((connection) => [
      connection.name,
      signalLayers(native, connection)
    ])
  );
  const direction = native.connections.reduce(
    (sum, c2) => ({
      x: sum.x + c2.pointsToConnect[1].x - c2.pointsToConnect[0].x,
      y: sum.y + c2.pointsToConnect[1].y - c2.pointsToConnect[0].y
    }),
    { x: 0, y: 0 }
  );
  const nearestAttachments = Math.abs(direction.x) > Math.abs(direction.y);
  for (const paired of planSharedPairCorridors(
    allocation,
    native.buses?.some((bus) => bus.maxLength !== void 0) ? layers : terminalLayers,
    true
  )) {
    if (!paired) {
      yield;
      continue;
    }
    if (exteriorPairSpacingReports(allocation, paired).some(
      (report) => busNames.has(report.connectionNames[0]) && (report.separatedExteriorLengthMm ?? 0) > 0.05 * length(
        paired.find(
          (trace) => trace.connection_name === report.connectionNames[0]
        ).route
      )
    ))
      continue;
    const ordinary = {
      ...native,
      connections: native.connections.filter(
        (connection) => !pairNames.has(connection.name)
      ),
      traces: [...native.traces ?? [], ...pairEscapes, ...paired]
    };
    const generated = yield* reachableSignalDogbones(
      ordinary,
      signalDogboneOptions(ordinary, targets),
      layers,
      nearestAttachments
    );
    if (!generated) continue;
    const escapes = [...pairEscapes, ...generated.traces];
    const pending = {
      ...native,
      connections: generated.connections,
      buses: native.buses?.some((bus) => bus.maxLength !== void 0) ? native.buses.map((bus) => ({
        ...bus,
        connectionNames: bus.connectionNames.filter(
          (name) => generated.connections.some((c2) => c2.name === name)
        )
      })).filter((bus) => bus.connectionNames.length) : [],
      differentialPairs: [],
      traces: [...native.traces ?? [], ...escapes, ...paired]
    };
    const widths = new Map(
      pending.connections.map((c2) => [c2.name, signalWidth(native, c2)])
    );
    const route = negotiateLanes(
      pending,
      pending.connections,
      fixedCopper(pending),
      [],
      widths,
      void 0,
      layers,
      () => false,
      true,
      true
    );
    let state;
    try {
      let step = route.next(), iterations = 0, lastImprovement = 0, bestCount = 0;
      while (!step.done && iterations++ < 3e5) {
        bestCount = Math.max(bestCount, step.value.length);
        if (native.buses?.some((b2) => b2.maxLength !== void 0) && iterations > 6e4 && bestCount < pending.connections.length - 3)
          break;
        if (step.value.length >= Math.max(
          1,
          pending.connections.length - (native.buses?.some((b2) => b2.maxLength !== void 0) ? 4 : 2)
        ) && (!state || step.value.length > state.traces.length)) {
          lastImprovement = iterations;
          state = {
            native,
            pending: structuredClone(pending),
            escapes,
            retained: paired,
            traces: step.value
          };
        }
        if (state && !sharedTimingLayers) break;
        if (step.value.length === pending.connections.length) break;
        if (state && iterations - lastImprovement >= (native.buses?.some((b2) => b2.maxLength !== void 0) ? 12e3 : 6e4))
          break;
        yield;
        step = route.next();
      }
      if (step.done && step.value)
        state = {
          native,
          pending,
          escapes,
          retained: paired,
          traces: step.value
        };
    } finally {
      route.return(null);
    }
    if (!state) continue;
    if (native.buses?.some((b2) => b2.maxLength !== void 0) && state.traces.length < state.pending.connections.length) {
      const repaired = yield* repairSharedLayerConflicts(
        state.pending,
        state.traces,
        layers,
        { maxNodes: 256 }
      );
      if (repaired) state = { ...state, traces: repaired };
    }
    if (state.retained.length + state.traces.length < native.connections.length) {
      const pocket = yield* expandSignalSitePocket(state);
      state = (yield* negotiateSignalSites(state, pocket, true)) ?? void 0;
      if (!state) continue;
    }
    if (state.retained.length + state.traces.length < native.connections.length) {
      const pocket = yield* findViaAwareSignalPocket(state);
      state = (yield* negotiateSignalSites(state, pocket)) ?? void 0;
      if (!state) continue;
    }
    let traces = [...state.retained, ...state.traces];
    if (traces.length !== native.connections.length) continue;
    const input = {
      ...native,
      connections: native.connections.map((connection) => {
        const trace = traces.find((t48) => t48.connection_name === connection.name);
        return {
          ...connection,
          pointsToConnect: [trace.route[0], trace.route.at(-1)]
        };
      }),
      traces: [...native.traces ?? [], ...state.escapes]
    };
    const fixed = fixedCopper(input);
    for (let pass = 0; pass < 3; pass++) {
      for (let index2 = 0; index2 < traces.length; index2++) {
        const trace = traces[index2];
        if (trace.coupledSection) continue;
        const width = trace.route[0].width, layer = trace.route[0].layer;
        const connection = input.connections.find(
          (c2) => c2.name === trace.connection_name
        );
        traces[index2] = {
          ...trace,
          route: reduceOrdinaryTurns(
            trace.route,
            new VectorScene(input, connection, width, [
              ...fixed,
              ...traces.flatMap(routeCopper)
            ])
          ).map((point) => ({ ...point, route_type: "wire", layer, width }))
        };
      }
      traces = chamferOrdinaryCorners(input, traces);
      yield;
    }
    const matcher = BusLanesSolver.forRefinement(input, traces, options);
    try {
      while (!matcher.solved && !matcher.failed) {
        matcher.step();
        yield;
      }
      if (matcher.solved)
        return { input, traces: matcher.traces, escapes: state.escapes };
    } finally {
      if (!matcher.solved && !matcher.failed) matcher.tryFinalAcceptance();
    }
  }
  return null;
}

// lib/is-unrouted-component-pad.ts
function isUnroutedComponentPad(input, connection, point) {
  const owners = new Set(
    [
      connection.name,
      connection.source_trace_id,
      point.pointId,
      point.pcb_port_id
    ].filter((s2) => !!s2)
  );
  const layers = point.layers ?? [point.layer];
  const pad = input.obstacles.find((o2) => {
    if (!o2.componentId || !o2.connectedTo.some((id) => owners.has(id)) || !o2.layers.some((l2) => layers.includes(l2)))
      return false;
    const angle = -(o2.ccwRotationDegrees ?? 0) * Math.PI / 180;
    const dx2 = point.x - o2.center.x, dy2 = point.y - o2.center.y;
    if (o2.shape === "circle") return Math.hypot(dx2, dy2) <= o2.width / 2 + 1e-8;
    const x2 = dx2 * Math.cos(angle) - dy2 * Math.sin(angle), y2 = dx2 * Math.sin(angle) + dy2 * Math.cos(angle);
    return Math.abs(x2) <= o2.width / 2 + 1e-8 && Math.abs(y2) <= o2.height / 2 + 1e-8;
  });
  if (!pad) return false;
  return !fixedCopper({ ...input, obstacles: [] }).some(
    (c2) => layers.includes(c2.layer) && c2.owners.some((id) => owners.has(id)) && clearanceToCopper(point, point, c2) <= 1e-8
  );
}

// lib/rematch-trapped-signal-dogbones.ts
function* reachable(input, connection, fixed, width, layer, end = connection.pointsToConnect[1], bounds) {
  const local = {
    ...connection,
    pointsToConnect: connection.pointsToConnect.map((point, index2) => ({
      ...index2 ? end : point,
      layer
    }))
  };
  const search = new GridVisibilitySearch(
    new VectorScene(input, local, width, fixed),
    local.pointsToConnect[0],
    local.pointsToConnect[1],
    [],
    0,
    void 0,
    bounds ? { bounds } : void 0
  );
  try {
    while (!search.solved && !search.failed) {
      search.step();
      yield;
    }
    return search.solved;
  } finally {
    if (!search.solved && !search.failed) search.cancel();
  }
}
function componentField(input, source, endpoint) {
  const point = source.pointsToConnect[endpoint];
  const owners = new Set(
    [
      source.name,
      source.source_trace_id,
      point.pcb_port_id,
      point.pointId
    ].filter(Boolean)
  );
  const pad = input.obstacles.filter(
    (obstacle) => obstacle.componentId && obstacle.connectedTo.some((owner) => owners.has(owner))
  ).sort((a2, b2) => distance(a2.center, point) - distance(b2.center, point))[0];
  if (!pad) return;
  const pads = input.obstacles.filter(
    (obstacle) => obstacle.componentId === pad.componentId
  );
  const rectangles = pads.map((obstacle) => {
    const angle = (obstacle.ccwRotationDegrees ?? 0) * Math.PI / 180;
    return {
      center: obstacle.center,
      width: Math.abs(Math.cos(angle)) * obstacle.width + Math.abs(Math.sin(angle)) * obstacle.height,
      height: Math.abs(Math.sin(angle)) * obstacle.width + Math.abs(Math.cos(angle)) * obstacle.height
    };
  });
  return {
    minX: Math.min(
      ...rectangles.map((obstacle) => obstacle.center.x - obstacle.width / 2)
    ),
    maxX: Math.max(
      ...rectangles.map((obstacle) => obstacle.center.x + obstacle.width / 2)
    ),
    minY: Math.min(
      ...rectangles.map((obstacle) => obstacle.center.y - obstacle.height / 2)
    ),
    maxY: Math.max(
      ...rectangles.map((obstacle) => obstacle.center.y + obstacle.height / 2)
    )
  };
}
function* trappedEndpoints(input, source, connection, fixed, width, layers) {
  const result = [];
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const margin = 3 * (width + clearance);
  for (const endpoint of [0, 1]) {
    const field = componentField(input, source, endpoint);
    if (!field) continue;
    const point = connection.pointsToConnect[endpoint];
    const edge = width / 2 + (input.minBoardEdgeClearance ?? 0);
    const bounds = {
      minX: Math.max(input.bounds.minX + edge, field.minX - 2 * margin),
      maxX: Math.min(input.bounds.maxX - edge, field.maxX + 2 * margin),
      minY: Math.max(input.bounds.minY + edge, field.minY - 2 * margin),
      maxY: Math.min(input.bounds.maxY - edge, field.maxY + 2 * margin)
    };
    const goals = [
      { ...point, x: Math.max(bounds.minX, field.minX - margin) },
      { ...point, x: Math.min(bounds.maxX, field.maxX + margin) },
      { ...point, y: Math.max(bounds.minY, field.minY - margin) },
      { ...point, y: Math.min(bounds.maxY, field.maxY + margin) }
    ].filter(
      (goal) => goal.x < field.minX || goal.x > field.maxX || goal.y < field.minY || goal.y > field.maxY
    ).sort((a2, b2) => distance(point, a2) - distance(point, b2));
    let escaped = false;
    for (const layer of layers) {
      const local = { ...connection, pointsToConnect: [point, point] };
      for (const goal of goals) {
        if (yield* reachable(input, local, fixed, width, layer, goal, bounds)) {
          escaped = true;
          break;
        }
      }
      if (escaped) break;
    }
    if (goals.length && !escaped) result.push(endpoint);
  }
  return result;
}
function* rematchTrappedSignalDogbones(native, pending, completed, escapes, terminalLayers, reachableLayersByConnection) {
  const result = {
    connections: structuredClone(pending.connections),
    escapes: [...escapes]
  };
  const physicalLayers = getCopperLayerNames(native.layerCount);
  for (const [index2, connection] of result.connections.entries()) {
    const source = native.connections.find(
      (original) => original.name === connection.name
    );
    const owned = result.escapes.filter(
      (trace) => trace.connection_name === connection.name
    );
    const vias = owned.map(
      (trace) => trace.route.find((point) => point.route_type === "via")
    );
    if (!source || owned.length !== 2 || vias.some((via) => !via) || source.pointsToConnect.some(
      (point) => !isUnroutedComponentPad(native, source, point)
    ))
      continue;
    const layers = (terminalLayers.get(connection.name) ?? [
      connection.pointsToConnect[0].layer
    ]).filter((layer) => layer !== "top" && physicalLayers.includes(layer));
    if (!layers.length) continue;
    const width = connection.nominalTraceWidth ?? connection.width ?? native.minTraceWidth;
    const sceneInput = {
      ...pending,
      connections: result.connections,
      traces: [...native.traces ?? [], ...result.escapes, ...completed]
    };
    const fixed = fixedCopper(sceneInput);
    const blockedLayers = [];
    let reachableLayers = 0;
    for (const layer of layers) {
      if (yield* reachable(sceneInput, connection, fixed, width, layer))
        reachableLayers++;
      else blockedLayers.push(layer);
    }
    reachableLayersByConnection?.set(
      connection.name,
      layers.filter((layer) => !blockedLayers.includes(layer))
    );
    if (reachableLayers >= Math.min(2, layers.length)) continue;
    let shared = false;
    const trapped = yield* trappedEndpoints(
      sceneInput,
      source,
      connection,
      fixed,
      width,
      blockedLayers
    );
    if (!trapped.length && reachableLayers === 0) trapped.push(0, 1);
    if (!trapped.length) continue;
    const base = {
      ...native,
      connections: [source],
      traces: [
        ...native.traces ?? [],
        ...result.escapes.filter(
          (trace) => trace.connection_name !== connection.name
        ),
        ...completed
      ]
    };
    const queue = trapped.map((endpoint) => [vias[endpoint]]);
    const seen = /* @__PURE__ */ new Set([
      JSON.stringify(connection.pointsToConnect.map(({ x: x2, y: y2 }) => [x2, y2]))
    ]);
    for (let trial = 0; trial < 16 && queue.length; trial++) {
      const excluded = queue.shift();
      const searchInput = {
        ...base,
        obstacles: [
          ...base.obstacles,
          ...excluded.map((point) => ({
            shape: "circle",
            center: { x: point.x, y: point.y },
            width: 1e-6,
            height: 1e-6,
            layers: physicalLayers,
            connectedTo: []
          }))
        ]
      };
      let candidate;
      try {
        candidate = routeLocalSignalDogbones(
          searchInput,
          {
            targetLayers: /* @__PURE__ */ new Map([
              [connection.name, connection.pointsToConnect[0].layer]
            ]),
            viaDiameter: Math.max(
              ...vias.map(
                (via) => via.via_diameter ?? native.minViaPadDiameter ?? 0.6
              )
            ),
            viaHoleDiameter: Math.max(
              ...vias.map(
                (via) => via.via_hole_diameter ?? native.minViaHoleDiameter ?? 0.3
              )
            ),
            traceWidth: Math.max(
              ...owned.flatMap(
                (trace) => trace.route.flatMap(
                  (point) => point.route_type === "wire" ? [point.width] : []
                )
              )
            ),
            clearance: native.minTraceToPadEdgeClearance ?? native.defaultObstacleMargin ?? 0.075,
            holeToHoleClearance: native.minViaHoleEdgeToViaHoleEdgeClearance,
            boardEdgeClearance: native.minBoardEdgeClearance,
            allowBlindAndBuriedVias: native.allowBlindAndBuriedVias ?? false
          }
        );
      } catch {
        yield;
        continue;
      }
      yield;
      const replacement = {
        ...connection,
        pointsToConnect: candidate.connections[0].pointsToConnect
      };
      const key = JSON.stringify(
        replacement.pointsToConnect.map(({ x: x2, y: y2 }) => [x2, y2])
      );
      if (seen.has(key)) continue;
      seen.add(key);
      const traces = candidate.traces.map((trace) => ({
        ...trace,
        source_trace_id: source.source_trace_id ?? connection.name
      }));
      const candidateInput = {
        ...sceneInput,
        traces: [...base.traces, ...traces]
      };
      const candidateFixed = fixedCopper(candidateInput);
      let candidateReachableLayers = 0;
      const candidateLayers = [];
      for (const layer of layers) {
        if (yield* reachable(
          candidateInput,
          replacement,
          candidateFixed,
          width,
          layer
        )) {
          candidateReachableLayers++;
          candidateLayers.push(layer);
        }
      }
      shared = candidateReachableLayers > reachableLayers;
      if (shared) {
        reachableLayersByConnection?.set(connection.name, candidateLayers);
        result.connections[index2] = replacement;
        result.escapes = [
          ...result.escapes.filter(
            (trace) => trace.connection_name !== connection.name
          ),
          ...traces
        ];
        break;
      }
      for (const endpoint of yield* trappedEndpoints(
        candidateInput,
        source,
        replacement,
        candidateFixed,
        width,
        blockedLayers
      )) {
        const point = replacement.pointsToConnect[endpoint];
        if (!excluded.some((old) => distance(old, point) < 1e-8))
          queue.push([...excluded, point]);
      }
    }
  }
  return result;
}

// lib/route-shared-layer-buses.ts
function* routeSharedLayerBuses(native, allocation, escapes, terminalLayers, options) {
  const busNames = new Set(allocation.buses?.flatMap((b2) => b2.connectionNames));
  const pairNames = new Set(
    allocation.differentialPairs?.flatMap((p2) => p2.connectionNames)
  );
  const constrained = /* @__PURE__ */ new Set([...busNames, ...pairNames]);
  const widths = new Map(
    allocation.connections.map((c2) => [c2.name, signalWidth(allocation, c2)])
  );
  const access = /* @__PURE__ */ new Map();
  const identities = /* @__PURE__ */ new WeakMap();
  let serial = 0;
  const fixed = fixedCopper(allocation);
  const bounded = allocation.buses?.some((bus) => bus.maxLength !== void 0);
  const availableLayers = bounded ? new Map(native.connections.map((c2) => [c2.name, signalLayers(native, c2)])) : terminalLayers;
  const plans = planSharedPairCorridors(allocation, availableLayers);
  for (const paired of plans) {
    if (!paired) {
      yield;
      continue;
    }
    const local = structuredClone(allocation);
    for (const c2 of local.connections) {
      const trace = paired.find((t48) => t48.connection_name === c2.name);
      if (trace)
        for (const p2 of c2.pointsToConnect)
          p2.layer = trace.route[0].layer;
    }
    const busInput = {
      ...local,
      connections: local.connections.filter((c2) => constrained.has(c2.name))
    };
    const ordinary = busInput.connections.filter((c2) => !pairNames.has(c2.name));
    let accessible = true;
    const pairedCopper = paired.flatMap(routeCopper);
    const reachableLayers = /* @__PURE__ */ new Map();
    for (const connection of ordinary) {
      const reachableForConnection = [];
      for (const layer of bounded ? availableLayers.get(connection.name) : [connection.pointsToConnect[0].layer]) {
        const key = JSON.stringify([
          connection.name,
          layer,
          paired.filter((t48) => t48.route[0].layer === layer).map((t48) => {
            if (!identities.has(t48)) identities.set(t48, serial++);
            return identities.get(t48);
          })
        ]);
        let reachable2 = access.get(key);
        if (reachable2 === void 0) {
          const candidate = {
            ...connection,
            pointsToConnect: connection.pointsToConnect.map((p2) => ({
              ...p2,
              layer
            }))
          };
          const search = new GridVisibilitySearch(
            new VectorScene(busInput, candidate, widths.get(connection.name), [
              ...fixed,
              ...pairedCopper
            ]),
            candidate.pointsToConnect[0],
            candidate.pointsToConnect[1],
            [],
            0,
            void 0,
            bounded ? {
              checkReachability: true,
              maxLength: maximumCarrierLength(busInput, connection.name)
            } : void 0
          );
          try {
            let steps2 = 0;
            while (!search.solved && !search.failed && steps2++ < 4e3) {
              search.step();
              yield;
            }
            if (search.solved || search.failed) {
              reachable2 = search.solved;
              access.set(key, reachable2);
            }
          } finally {
            search.cancel();
          }
        }
        if (reachable2 !== false) reachableForConnection.push(layer);
      }
      if (!reachableForConnection.length) {
        accessible = false;
        break;
      }
      reachableLayers.set(connection.name, reachableForConnection);
    }
    if (!accessible) continue;
    const route = negotiateLanes(
      busInput,
      ordinary,
      fixedCopper(local),
      paired,
      widths,
      void 0,
      bounded ? reachableLayers : /* @__PURE__ */ new Map(),
      () => !bounded,
      true
    );
    let state = route.next(), steps = 0;
    try {
      while (!state.done && steps++ < (bounded ? 3e5 : 16e3)) {
        yield;
        state = route.next();
      }
    } finally {
      if (!state.done) route.return(null);
    }
    if (!state.done || !state.value) continue;
    let matched = state.value;
    let valid = true;
    let jointMatched = false;
    if (bounded) {
      const matcher = BusLanesSolver.forRefinement(busInput, matched, options);
      try {
        while (!matcher.solved && !matcher.failed) {
          matcher.step();
          yield;
        }
        if (matcher.solved) {
          matched = matcher.traces;
          jointMatched = true;
        }
      } finally {
        if (!matcher.solved && !matcher.failed) matcher.tryFinalAcceptance();
      }
    }
    for (const bus of jointMatched ? [] : local.buses ?? []) {
      const names = new Set(bus.connectionNames);
      const group = {
        ...local,
        connections: local.connections.filter((c2) => names.has(c2.name)),
        buses: [bus],
        differentialPairs: local.differentialPairs?.filter(
          (p2) => p2.connectionNames.every((n2) => names.has(n2))
        ),
        traces: [
          ...local.traces ?? [],
          ...matched.filter((t48) => !names.has(t48.connection_name))
        ]
      };
      const matcher = BusLanesSolver.forRefinement(
        group,
        matched.filter((t48) => names.has(t48.connection_name)),
        options
      );
      try {
        while (!matcher.solved && !matcher.failed) {
          matcher.step();
          yield;
        }
        if (!matcher.solved) {
          valid = false;
          break;
        }
        matched = [
          ...matched.filter((t48) => !names.has(t48.connection_name)),
          ...matcher.traces
        ];
      } finally {
        if (!matcher.solved && !matcher.failed) matcher.tryFinalAcceptance();
      }
    }
    if (!valid) continue;
    const pending = {
      ...local,
      connections: local.connections.filter((c2) => !constrained.has(c2.name)),
      buses: [],
      differentialPairs: []
    };
    let rematched = { connections: pending.connections, escapes };
    for (let repair = 0; repair < 2; repair++) {
      if (repair) {
        const reachableLayers2 = new Map(terminalLayers);
        rematched = yield* rematchTrappedSignalDogbones(
          native,
          pending,
          matched,
          escapes,
          terminalLayers,
          reachableLayers2
        );
        if (pending.connections.some(
          (c2) => reachableLayers2.get(c2.name)?.length === 0
        ) || rematched.escapes.every((trace, i2) => trace === escapes[i2]))
          break;
      }
      const remainingInput = {
        ...pending,
        connections: rematched.connections,
        traces: [...native.traces ?? [], ...rematched.escapes, ...matched]
      };
      const remaining = new BusLanesSolver(
        remainingInput,
        {
          ...options,
          maxSearchIterations: Math.min(
            options.maxSearchIterations ?? 2e5,
            2e5
          )
        },
        terminalLayers
      );
      try {
        while (!remaining.solved && !remaining.failed) {
          remaining.step();
          yield;
        }
        if (!remaining.solved) continue;
        const traces = [...matched, ...remaining.traces];
        return {
          escapes: rematched.escapes,
          traces,
          input: {
            ...local,
            connections: local.connections.map((c2) => {
              const t48 = traces.find((t49) => t49.connection_name === c2.name);
              return {
                ...c2,
                pointsToConnect: [t48.route[0], t48.route.at(-1)]
              };
            }),
            traces: [...native.traces ?? [], ...rematched.escapes]
          }
        };
      } finally {
        if (!remaining.solved && !remaining.failed)
          remaining.tryFinalAcceptance();
      }
    }
  }
  return null;
}

// lib/extend-package-coupling.ts
var reverse3 = (t48) => ({
  ...t48,
  route: t48.route.toReversed(),
  coupledSection: t48.coupledSection ? [
    t48.route.length - 1 - t48.coupledSection[1],
    t48.route.length - 1 - t48.coupledSection[0]
  ] : void 0,
  curvedSegments: t48.curvedSegments?.map((i2) => t48.route.length - i2)
});
var indexOf = (path, point) => path.findIndex((p2) => distance(p2, point) < 1e-7);
var preservePoint = (path, point) => {
  if (indexOf(path, point) >= 0) return path;
  const i2 = path.findIndex(
    (p2, i3) => i3 > 0 && pointSegmentDistanceToPoints(point, path[i3 - 1], p2) < 1e-8
  );
  return i2 < 0 ? path : [...path.slice(0, i2), point, ...path.slice(i2)];
};
function* extendPackageCoupling(input, original, options = {}) {
  let result = original;
  const fixed = fixedCopper(input);
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  let budget = 2e3;
  for (const pair of input.differentialPairs ?? []) {
    for (const reversed of [false, true]) {
      for (const side of [0, 1]) {
        if (budget <= 0) return result;
        const nativeRails = pair.connectionNames.map(
          (name) => result.find((t48) => t48.connection_name === name)
        );
        if (nativeRails.some((t48) => !t48?.coupledSection)) continue;
        const rails = nativeRails.map(
          (t48) => reversed ? reverse3(t48) : t48
        );
        const ref = rails[side], other = rails[1 - side];
        const [rs, re] = ref.coupledSection, [os, oe] = other.coupledSection;
        const width = other.route[0].width, separation = width + (pair.traceGap ?? clearance);
        if (re < 1 || oe < 1 || distance(ref.route[re - 1], ref.route[re]) < 1e-7)
          continue;
        const regions = packageApproachRegions(input, width / 2 + clearance);
        const region = regions.find(
          (r2) => pointInBox(ref.route.at(-1), r2.copper) && pointInBox(other.route.at(-1), r2.copper)
        );
        if (!region || pointInBox(ref.route[re], region.copper)) continue;
        let stop = re + 1;
        while (stop < ref.route.length && !pointInBox(ref.route[stop], region.copper))
          stop++;
        if (stop === ref.route.length || ref.curvedSegments?.some((i2) => i2 >= re && i2 <= stop))
          continue;
        const a2 = ref.route[stop - 1], b2 = ref.route[stop];
        let lo = 0, hi = 1;
        for (let i2 = 0; i2 < 40; i2++) {
          const t48 = (lo + hi) / 2;
          if (pointInBox(
            { x: a2.x + (b2.x - a2.x) * t48, y: a2.y + (b2.y - a2.y) * t48 },
            region.copper
          ))
            hi = t48;
          else lo = t48;
        }
        const cut2 = { x: a2.x + (b2.x - a2.x) * hi, y: a2.y + (b2.y - a2.y) * hi };
        const anchor = {
          x: (ref.route[re - 1].x + ref.route[re].x) / 2,
          y: (ref.route[re - 1].y + ref.route[re].y) / 2
        };
        let section = simplify([anchor, ...ref.route.slice(re, stop), cut2]);
        let paths;
        try {
          paths = [separation, -separation].map((d2) => offsetPath(section, d2));
        } catch {
          continue;
        }
        let path = paths.find(
          (p2) => pointSegmentDistanceToPoints(
            p2[0],
            other.route[oe - 1],
            other.route[oe]
          ) < 1e-7
        );
        if (!path) continue;
        const localWire = (p2) => ({
          ...p2,
          route_type: "wire",
          width,
          layer: other.route[0].layer
        });
        const localRails = [
          {
            ...ref,
            route: section.map(localWire),
            curvedSegments: [],
            coupledSection: [0, section.length - 1]
          },
          {
            ...other,
            route: path.map(localWire),
            curvedSegments: [],
            coupledSection: [0, path.length - 1]
          }
        ];
        const bevel2 = bevelCoupledCorners(input, [
          ...result.filter(
            (t48) => !pair.connectionNames.includes(t48.connection_name)
          ),
          ...localRails
        ]);
        section = bevel2.find(
          (t48) => t48.connection_name === ref.connection_name
        ).route;
        path = bevel2.find(
          (t48) => t48.connection_name === other.connection_name
        ).route;
        const refRoute = [
          ...ref.route.slice(0, re),
          ...section,
          ...ref.route.slice(stop)
        ].map(localWire);
        const connection = input.connections.find(
          (c2) => c2.name === other.connection_name
        );
        const scene = new VectorScene(input, connection, width, [
          ...fixed,
          ...result.filter((t48) => t48.connection_name !== ref.connection_name).flatMap(routeCopper),
          ...routeCopper({ ...ref, route: refRoute })
        ]);
        if (!scene.pathVisible(path)) continue;
        let join = oe + 1;
        while (join < other.route.length && !pointInBox(other.route[join], region.copper))
          join++;
        if (join === other.route.length) continue;
        let accepted = false;
        for (; join < other.route.length; join++) {
          if (!pointInBox(other.route[join], region.copper)) continue;
          const search = new GridVisibilitySearch(
            scene,
            path.at(-1),
            other.route[join]
          );
          try {
            let steps = 0;
            while (!search.solved && !search.failed && steps++ < 256 && budget-- > 0) {
              search.step();
              yield;
            }
            if (!search.solved) continue;
          } finally {
            search.cancel();
          }
          const wire = (p2) => ({
            ...p2,
            route_type: "wire",
            layer: other.route[0].layer,
            width
          });
          const next = preservePoint(
            preservePoint(
              simplify([
                ...other.route.slice(0, oe),
                ...path,
                ...reduceOrdinaryTurns(search.result, scene).slice(1),
                ...other.route.slice(join + 1)
              ]).map(wire),
              wire(other.route[os])
            ),
            wire(path.at(-1))
          );
          if (!scene.pathVisible(next) || !tuningPathIsSelfClear(next, width + clearance))
            continue;
          const replacement = [
            {
              ...ref,
              route: refRoute,
              curvedSegments: remapCurvedSegments(ref, refRoute),
              coupledSection: [rs, re + section.length - 1]
            },
            {
              ...other,
              route: next,
              curvedSegments: remapCurvedSegments(other, next),
              coupledSection: [
                indexOf(next, other.route[os]),
                indexOf(next, path.at(-1))
              ]
            }
          ].map((t48) => reversed ? reverse3(t48) : t48);
          const unchanged = result.filter(
            (t48) => !pair.connectionNames.includes(t48.connection_name)
          );
          const surrounding = [...fixed, ...unchanged.flatMap(routeCopper)];
          for (const trim of [
            1.8,
            1.5,
            0.75,
            0.375,
            0.1875,
            0.09375,
            0.046875,
            0.0234375
          ]) {
            const refinedPair = chamferOrdinaryCorners(
              input,
              result.filter(
                (t48) => pair.connectionNames.includes(t48.connection_name)
              ).map(
                (t48) => replacement.find(
                  (r2) => r2.connection_name === t48.connection_name
                )
              ),
              surrounding,
              trim
            );
            const refined = result.map(
              (t48) => refinedPair.find(
                (r2) => r2.connection_name === t48.connection_name
              ) ?? t48
            );
            if (!routeAnglesAreConventional(refinedPair) || options.preserveMatching !== false && [
              ...busLengthReports(input, refined),
              ...pairLengthReports(input, refined)
            ].some(
              (r2) => !r2.withinLengthLimit || !r2.aboveMinimumLength || r2.toleranceMm !== null && !r2.matched
            ) || sharedPairSpacingReports(input, refined).some((r2) => !r2.matched))
              continue;
            const copper = [...surrounding, ...refinedPair.flatMap(routeCopper)];
            if (refinedPair.some((t48) => {
              const w2 = t48.route[0].width;
              return !tuningPathIsSelfClear(t48.route, w2 + clearance) || !new VectorScene(
                input,
                input.connections.find(
                  (c2) => c2.name === t48.connection_name
                ),
                w2,
                copper
              ).pathVisible(t48.route);
            }))
              continue;
            result = refined;
            accepted = true;
            break;
          }
          if (accepted) break;
        }
      }
    }
  }
  return result;
}

// lib/route-backward-package-buses.ts
function initialPairVariants(input) {
  const busNames = new Set(input.buses?.flatMap((b2) => b2.connectionNames));
  const groups = independentBusGroups({
    ...input,
    connections: input.connections.filter((c2) => busNames.has(c2.name))
  });
  return (groups ?? []).map((group) => {
    const pair = group.differentialPairs?.[0];
    if (!pair) return 0;
    const members = pair.connectionNames.map(
      (name) => group.connections.find((c2) => c2.name === name)
    );
    const centers = [0, 1].map((end) => ({
      x: (members[0].pointsToConnect[end].x + members[1].pointsToConnect[end].x) / 2,
      y: (members[0].pointsToConnect[end].y + members[1].pointsToConnect[end].y) / 2
    }));
    const dx2 = Math.abs(centers[1].x - centers[0].x);
    const dy2 = Math.abs(centers[1].y - centers[0].y);
    const pitch = signalWidth(input, members[0]) + (pair.traceGap ?? input.minTraceToPadEdgeClearance ?? 0.075);
    return Math.min(dx2, dy2) <= 4 * pitch ? 3 : 0;
  });
}
function* matchRoutes(input, traces, options) {
  const solver = BusLanesSolver.forRefinement(input, traces, options);
  try {
    while (!solver.solved && !solver.failed) {
      solver.step();
      yield;
    }
    return solver.solved ? solver.traces : null;
  } finally {
    if (!solver.solved && !solver.failed) solver.tryFinalAcceptance();
  }
}
function* routeBackwardPackageBuses(native, allocation, terminalLayers, options) {
  const targets = new Map(
    allocation.connections.map((c2) => [c2.name, c2.pointsToConnect[0].layer])
  );
  const alternatives = [0, 2].map(
    (attempt) => routeAlternateSignalDogbones(
      native,
      signalDogboneOptions(native, targets),
      attempt
    )
  );
  const connections = native.connections.map((c2, i2) => ({
    ...c2,
    pointsToConnect: [
      alternatives[0].connections[i2].pointsToConnect[0],
      alternatives[1].connections[i2].pointsToConnect[1]
    ]
  }));
  const escapes = ownedSignalEscapes(
    native,
    alternatives.flatMap(
      (alternative, end) => alternative.traces.filter((trace) => {
        const connection = native.connections.find(
          (c2) => c2.name === trace.connection_name
        );
        const point = connection.pointsToConnect[end];
        const start = trace.route[0];
        return start.route_type === "wire" && Math.hypot(start.x - point.x, start.y - point.y) < 1e-8;
      })
    )
  );
  const fullInput = {
    ...native,
    connections,
    traces: [...native.traces ?? [], ...escapes]
  };
  const standalone = (fullInput.differentialPairs ?? []).filter(
    (pair) => !fullInput.buses?.some(
      (bus) => pair.connectionNames.some((name) => bus.connectionNames.includes(name))
    )
  );
  const heldNames = new Set(standalone.flatMap((p2) => p2.connectionNames));
  const input = {
    ...fullInput,
    connections: fullInput.connections.filter((c2) => !heldNames.has(c2.name)),
    differentialPairs: fullInput.differentialPairs?.filter(
      (p2) => !p2.connectionNames.some((name) => heldNames.has(name))
    )
  };
  const network = yield* runBoundedRouting(
    preparePairedNetwork(input, terminalLayers, initialPairVariants(input)),
    6e4
  );
  if (!network) return null;
  const clearance = input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075;
  const regions = packageApproachRegions(
    input,
    Math.max(...network.transforms.map((t48) => t48.envelope / 2)) + clearance
  );
  const locked = network.transforms.filter(
    (t48) => regions.some((region) => pointInBox(t48.center[0], region.copper))
  );
  const dropped = new Set(
    locked.flatMap((t48) => [
      t48.connection.name,
      ...t48.approaches.map((c2) => c2.name)
    ])
  );
  const lockedRails = locked.flatMap((t48) => t48.rails);
  network.local = {
    ...network.local,
    connections: network.local.connections.filter((c2) => !dropped.has(c2.name)),
    traces: [
      ...(network.local.traces ?? []).filter(
        (t48) => !locked.some((l2) => t48.connection_name === l2.connection.name)
      ),
      ...lockedRails
    ],
    buses: network.local.buses?.map((bus) => ({
      ...bus,
      connectionNames: bus.connectionNames.filter((name) => !dropped.has(name))
    }))
  };
  network.transforms = network.transforms.filter((t48) => !locked.includes(t48));
  network.copper = fixedCopper(network.local);
  const generator = negotiateLanes(
    network.local,
    network.local.connections,
    network.copper,
    [],
    network.widths,
    void 0,
    terminalLayers,
    () => false,
    true
  );
  const originalNames = new Set(input.connections.map((c2) => c2.name));
  const busNames = new Set(input.buses?.flatMap((b2) => b2.connectionNames));
  const routeIds = /* @__PURE__ */ new WeakMap();
  const tried = /* @__PURE__ */ new Set();
  let serial = 0;
  let partial = null;
  let state = generator.next();
  let steps = 0;
  try {
    while (!state.done && steps++ < 2e5) {
      const current = state.value;
      const missing = network.local.connections.filter(
        (c2) => !current.some((t48) => t48.connection_name === c2.name)
      );
      if (missing.length <= 3 && missing.every((c2) => originalNames.has(c2.name) && busNames.has(c2.name))) {
        const key = state.value.map((trace) => {
          if (!routeIds.has(trace)) routeIds.set(trace, serial++);
          return routeIds.get(trace);
        }).join(",");
        if (!tried.has(key) && tried.size < 24) {
          tried.add(key);
          partial = yield* runBoundedRouting(
            rebuildPairedNetwork(network, [...state.value, ...lockedRails], {
              allowPartial: true
            }),
            12e3
          );
          if (partial) break;
        }
      }
      yield;
      state = generator.next();
    }
    if (state.done && state.value)
      partial = yield* runBoundedRouting(
        rebuildPairedNetwork(network, [...state.value, ...lockedRails]),
        12e3
      );
  } finally {
    if (!state.done) generator.return(null);
  }
  if (!partial) return null;
  const repaired = yield* repairBusDogbones(native, input, partial, escapes);
  if (!repaired) return null;
  const completeInput = {
    ...fullInput,
    connections: fullInput.connections.map(
      (c2) => repaired.input.connections.find((next) => next.name === c2.name) ?? c2
    ),
    traces: repaired.input.traces
  };
  let traces = repaired.traces;
  for (const trace of traces)
    for (const point of completeInput.connections.find(
      (c2) => c2.name === trace.connection_name
    ).pointsToConnect)
      point.layer = trace.route[0].route_type === "wire" ? trace.route[0].layer : point.layer;
  for (const pair of standalone) {
    const members = completeInput.connections.filter(
      (c2) => pair.connectionNames.includes(c2.name)
    );
    const layers = [
      .../* @__PURE__ */ new Set([
        members[0].pointsToConnect[0].layer,
        ...(terminalLayers.get(members[0].name) ?? []).filter(
          (layer) => members.every((c2) => terminalLayers.get(c2.name)?.includes(layer))
        )
      ])
    ].filter((layer) => layer !== "top");
    let paired = null;
    for (const layer of layers) {
      for (const c2 of members)
        for (const point of c2.pointsToConnect) point.layer = layer;
      for (let variant = 0; variant < 6 && !paired; variant++)
        paired = yield* runBoundedRouting(
          routeCoupledPair(
            completeInput,
            pair,
            [...fixedCopper(completeInput), ...traces.flatMap(routeCopper)],
            { copper: [], penalty: 0, variant }
          ),
          12e3
        );
      if (paired) break;
    }
    if (!paired) return null;
    traces = [...traces, ...paired];
  }
  const finished = yield* finishPairedNetwork(
    { ...network, input: completeInput, transforms: [] },
    traces
  );
  if (!finished) return null;
  const matched = yield* matchRoutes(completeInput, finished, options);
  if (!matched) return null;
  const extended = yield* extendPackageCoupling(completeInput, matched, {
    preserveMatching: false
  });
  if (exteriorPairSpacingReports(completeInput, extended).some((r2) => !r2.matched))
    return null;
  const final = yield* matchRoutes(completeInput, extended, options);
  if (!final || exteriorPairSpacingReports(completeInput, final).some((r2) => !r2.matched))
    return null;
  const ceilings = new Map(
    busLengthReports(completeInput, matched).map((bus) => [
      bus.busId,
      Math.max(
        ...bus.lengths.map((length2) => length2.totalLengthMm ?? Infinity)
      )
    ])
  );
  if (busLengthReports(completeInput, final).some(
    (bus) => Math.max(
      ...bus.lengths.map((length2) => length2.totalLengthMm ?? Infinity)
    ) > ceilings.get(bus.busId) + 1e-6
  ))
    return null;
  return { input: completeInput, traces: final, escapes: repaired.escapes };
}

// lib/shorten-pair-approaches.ts
function shortenPairApproaches(input, traces) {
  const result = [...traces], fixed = fixedCopper(input);
  for (let i2 = 0; i2 < result.length; i2++) {
    const t48 = result[i2];
    if (!t48.coupledSection) continue;
    const [s2, e2] = t48.coupledSection, first = t48.route[0];
    const scene = new VectorScene(
      input,
      input.connections.find((c2) => c2.name === t48.connection_name),
      first.width,
      [...fixed, ...result.flatMap(routeCopper)]
    );
    const regions = packageApproachRegions(
      input,
      first.width + (input.differentialPairs?.find(
        (p2) => p2.connectionNames.includes(t48.connection_name)
      )?.traceGap ?? 0.1) / 2 + (input.minTraceToPadEdgeClearance ?? input.defaultObstacleMargin ?? 0.075)
    );
    const shorten = (start, end) => {
      const local = regions.find(
        (r2) => pointInBox(t48.route[start === 0 ? 0 : t48.route.length - 1], r2.copper)
      );
      const externalCurve = (t48.curvedSegments ?? []).some(
        (i3) => i3 > start && i3 <= end && (!local || !pointInBox(t48.route[i3 - 1], local.copper) || !pointInBox(t48.route[i3], local.copper))
      );
      return externalCurve ? reduceOrdinaryTurns(t48.route.slice(start, end + 1), scene) : t48.route.slice(start, end + 1);
    };
    const prefix = shorten(0, s2), suffix = shorten(e2, t48.route.length - 1);
    const route = [
      ...prefix.slice(0, -1),
      ...t48.route.slice(s2, e2 + 1),
      ...suffix.slice(1)
    ].map((p2) => ({
      ...p2,
      route_type: "wire",
      layer: first.layer,
      width: first.width
    }));
    result[i2] = {
      ...t48,
      route,
      curvedSegments: remapCurvedSegments(t48, route),
      coupledSection: [prefix.length - 1, prefix.length + e2 - s2 - 1]
    };
  }
  return result;
}

// lib/bus-lanes-pipeline-solver.ts
var BusLanesPipelineSolver = class extends BaseSolver {
  input;
  options;
  phase = "resolve_layers";
  traces = [];
  failureCode = null;
  acceptedTraces;
  envelopeOptimization;
  /** Runs only after a complete accepted route exists. A budget interrupt or
   * exception restores that private snapshot, never mutable work-in-progress. */
  *optimizeEnvelope() {
    if (!this.options.smoothTuning) return;
    const before = signalEnvelope(this.acceptedTraces);
    const started = performance.now();
    this.stats = {
      ...this.stats,
      envelopeOptimization: {
        beforeAreaMm2: before.areaMm2,
        afterAreaMm2: before.areaMm2,
        milliseconds: 0
      }
    };
    try {
      for (let pass = 0; pass < 2; pass++) {
        const original = this.acceptedTraces;
        const previousBounds = signalEnvelope(original);
        const view = carrierCompactionView(this.input, original);
        if (!view) return;
        const viaClearance = view.carriers.map(
          (trace) => createTerminalViaClearanceChecker(view.input, trace)
        );
        const candidate = yield* compactEnvelopeCandidate(
          view.input,
          view.carriers
        );
        if (candidate === view.carriers) return;
        for (const fraction of [1, 0.999, 0.99, 0.95, 0.9, 0.75, 0.5]) {
          const carriers = candidate.map((trace, i2) => ({
            ...trace,
            route: trace.route.map((point, j2) => ({
              ...point,
              x: view.carriers[i2].route[j2].x + (point.x - view.carriers[i2].route[j2].x) * fraction,
              y: view.carriers[i2].route[j2].y + (point.y - view.carriers[i2].route[j2].y) * fraction
            }))
          }));
          if (carriers.some((trace, i2) => !viaClearance[i2](trace.route)))
            continue;
          const complete = view.join(carriers);
          const after = signalEnvelope(complete);
          if (!Number.isFinite(after.areaMm2) || after.areaMm2 >= previousBounds.areaMm2 - 1e-6 || after.minX < previousBounds.minX - 1e-8 || after.maxX > previousBounds.maxX + 1e-8 || after.minY < previousBounds.minY - 1e-8 || after.maxY > previousBounds.maxY + 1e-8)
            continue;
          const validator = BusLanesSolver.forValidation(
            view.input,
            carriers,
            this.options
          );
          try {
            while (!validator.solved && !validator.failed) {
              validator.step();
              yield;
            }
            if (!validator.solved || exteriorPairSpacingReports(view.input, carriers).some(
              (r2) => !r2.matched
            ))
              continue;
            this.acceptedTraces = structuredClone(complete);
            this.stats = {
              ...this.stats,
              envelopeOptimization: {
                beforeAreaMm2: before.areaMm2,
                afterAreaMm2: after.areaMm2,
                milliseconds: performance.now() - started
              }
            };
            break;
          } finally {
            if (!validator.solved && !validator.failed)
              validator.tryFinalAcceptance();
          }
        }
        if (this.acceptedTraces === original) break;
      }
    } finally {
      this.stats = {
        ...this.stats,
        envelopeOptimization: {
          ...this.stats.envelopeOptimization,
          milliseconds: performance.now() - started
        }
      };
    }
  }
  finishAccepted(early) {
    const optimization = this.envelopeOptimization;
    this.envelopeOptimization = void 0;
    try {
      optimization?.return();
    } catch (error) {
      this.stats = { ...this.stats, optimizationCleanupError: String(error) };
    }
    this.traces = structuredClone(this.acceptedTraces);
    this.solved = true;
    this.failed = false;
    this.error = null;
    this.failureCode = null;
    this.phase = "solved";
    this.progress = 1;
    this.stats = { ...this.stats, optimizationStoppedEarly: early };
  }
  sharedPackages;
  backwardPackages;
  child;
  escapes = [];
  attempt = 0;
  completedLanes = [];
  remainingInput;
  followingInput;
  siteRematch;
  packageCoupling;
  terminalLayers = /* @__PURE__ */ new Map();
  constructor(input, options = {}) {
    super();
    this.input = structuredClone(input);
    this.options = { smoothTuning: true, denseSearch: true, ...options };
    this.MAX_ITERATIONS = (options.maxSearchIterations ?? 2e5) * Math.max(1, input.layerCount);
  }
  getConstructorParams() {
    return [this.input, this.options];
  }
  getOutput() {
    if (!this.solved)
      throw Error(this.error ?? "Bus lane pipeline is not solved");
    return {
      ...this.input,
      traces: [...this.input.traces ?? [], ...this.traces]
    };
  }
  tryFinalAcceptance() {
    if (this.solved) return;
    if (this.acceptedTraces) {
      this.finishAccepted(true);
      return;
    }
    this.sharedPackages?.return(null);
    this.sharedPackages = void 0;
    this.backwardPackages?.return(null);
    this.backwardPackages = void 0;
    this.packageCoupling?.return([]);
    this.packageCoupling = void 0;
    this.siteRematch?.return({ connections: [], escapes: [] });
    this.siteRematch = void 0;
    this.child?.tryFinalAcceptance();
    this.failureCode = "search_budget_exhausted";
    this.traces = [];
  }
  childOptions(reserveForControls = false) {
    const remaining = Math.max(1, this.MAX_ITERATIONS - this.iterations);
    const reserve = reserveForControls ? Math.min(2e5, Math.floor(remaining / 4)) : 0;
    return {
      ...this.options,
      // Keep the aggregate pipeline budget. Restarting a dense bus at the
      // old per-layer cutoff discards compatible computed alternatives just
      // before they converge. Unconstrained controls retain a work reserve.
      maxSearchIterations: this.options.maxSearchIterations ?? Math.max(1, remaining - reserve)
    };
  }
  *finishPackageCoupling(input, lanes) {
    let refined = yield* extendPackageCoupling(input, lanes);
    if (exteriorPairSpacingReports(input, refined).every((r2) => r2.matched))
      return refined;
    refined = yield* extendPackageCoupling(
      input,
      shortenPairApproaches(input, refined),
      { preserveMatching: false }
    );
    if (exteriorPairSpacingReports(input, refined).some((r2) => !r2.matched))
      throw Error(
        "Pair approaches still separate outside native package fanouts"
      );
    if (input.buses?.some((b2) => b2.maxLength !== void 0)) {
      const repaired = yield* rebalancePairEscapes(
        input,
        refined,
        this.escapes,
        this.options
      );
      if (repaired) {
        this.escapes = repaired.escapes;
        return repaired.traces;
      }
    }
    const matcher = BusLanesSolver.forRefinement(input, refined, this.options);
    try {
      while (!matcher.solved && !matcher.failed) {
        matcher.step();
        yield;
      }
      if (!matcher.solved)
        throw Error(matcher.error ?? "Package approach length matching failed");
      const ceilings = new Map(
        busLengthReports(input, lanes).map((b2) => [
          b2.busId,
          Math.max(
            ...b2.lengths.map(
              (l2) => l2.totalLengthMm ?? Number.POSITIVE_INFINITY
            )
          )
        ])
      );
      if (busLengthReports(input, matcher.traces).some(
        (b2) => Math.max(
          ...b2.lengths.map(
            (l2) => l2.totalLengthMm ?? Number.POSITIVE_INFINITY
          )
        ) > ceilings.get(b2.busId) + 1e-6
      ))
        throw Error("Package refinement increased the bus length target");
      if (exteriorPairSpacingReports(input, matcher.traces).some(
        (r2) => !r2.matched
      ))
        throw Error("Package approach matching separated the pair");
      return matcher.traces;
    } finally {
      if (!matcher.solved && !matcher.failed) matcher.tryFinalAcceptance();
    }
  }
  prepare() {
    if (this.options.fanout === "none") {
      this.child = new BusLanesSolver(this.input, this.options);
      return;
    }
    const physicalLayers = getCopperLayerNames(this.input.layerCount);
    if (this.input.allowedLayers?.some((layer) => !physicalLayers.includes(layer)))
      throw Error("Allowed signal layer is not in the physical stack");
    const layers = physicalLayers.filter(
      (layer) => !this.input.allowedLayers || this.input.allowedLayers.includes(layer)
    );
    if (!layers.length) throw Error("No allowed signal layers");
    const names = new Set(this.input.connections.map((c2) => c2.name));
    for (const bus of this.input.buses ?? [])
      if (bus.connectionNames.some((name) => !names.has(name)))
        throw Error("Unknown bus member");
    const groups = this.input.connections.map((c2) => /* @__PURE__ */ new Set([c2.name]));
    for (const members of [
      ...(this.input.differentialPairs ?? []).map((p2) => p2.connectionNames)
    ]) {
      const related = groups.filter((g2) => members.some((n2) => g2.has(n2)));
      if (members.some((n2) => !related.some((g2) => g2.has(n2))))
        throw Error("Unknown bus or differential pair member");
      const merged = new Set(related.flatMap((g2) => [...g2]));
      for (const group of related) groups.splice(groups.indexOf(group), 1);
      groups.push(merged);
    }
    const layerShare = Math.ceil(this.input.connections.length / layers.length);
    const balancedCohorts = this.attempt === 0 && (this.input.buses ?? []).every(
      (bus) => bus.connectionNames.length <= layerShare
    );
    for (const bus of balancedCohorts ? this.input.buses ?? [] : []) {
      const related = groups.filter(
        (group) => bus.connectionNames.some((name) => group.has(name))
      );
      const merged = new Set(related.flatMap((group) => [...group]));
      if (merged.size > layerShare) continue;
      const relatedBuses = (this.input.buses ?? []).filter(
        (candidate) => candidate.connectionNames.some((name) => merged.has(name))
      );
      const members = this.input.connections.filter(
        (connection) => merged.has(connection.name)
      );
      if (!layers.some(
        (layer) => relatedBuses.every(
          (candidate) => !candidate.allowedLayers || candidate.allowedLayers.includes(layer)
        ) && members.every(
          (connection) => connection.pointsToConnect.every(
            (point) => (point.layers ?? [point.layer]).includes(layer) || isUnroutedComponentPad(this.input, connection, point)
          )
        )
      ))
        continue;
      for (const group of related) groups.splice(groups.indexOf(group), 1);
      groups.push(merged);
    }
    groups.sort((a2, b2) => b2.size - a2.size);
    const load = new Map(layers.map((l2) => [l2, 0]));
    const targets = /* @__PURE__ */ new Map();
    for (const group of groups) {
      const buses = (this.input.buses ?? []).filter(
        (b2) => b2.connectionNames.some((n2) => group.has(n2))
      );
      const members = this.input.connections.filter((c2) => group.has(c2.name));
      const allowed = layers.filter(
        (layer) => buses.every(
          (b2) => !b2.allowedLayers || b2.allowedLayers.includes(layer)
        ) && members.every(
          (connection) => connection.pointsToConnect.every(
            (point) => (point.layers ?? [point.layer]).includes(layer) || isUnroutedComponentPad(this.input, connection, point)
          )
        )
      );
      if (!allowed.length)
        throw Error(
          "Bus/pair has no common allowed signal layer; existing fanout handoffs cannot be dogboned again"
        );
      const preferred = buses.flatMap((b2) => [b2.preferredLayer, ...b2.preferredLayers ?? []]).filter((l2) => !!l2);
      const countVias = (l2) => members.flatMap((c2) => c2.pointsToConnect).filter((p2) => !(p2.layers ?? [p2.layer]).includes(l2)).length;
      const rank = (l2) => preferred.includes(l2) ? preferred.indexOf(l2) : preferred.length;
      const layerCost = new Map(
        allowed.map((layer) => [
          layer,
          countVias(layer) + this.input.obstacles.filter(
            (o2) => o2.componentId && o2.layers.includes(layer)
          ).length / 8
        ])
      );
      const retryOrder = new Map(
        allowed.map((layer) => {
          const peers = allowed.filter(
            (other) => rank(other) === rank(layer) && layerCost.get(other) === layerCost.get(layer)
          );
          return [
            layer,
            (peers.indexOf(layer) - this.attempt % peers.length + peers.length) % peers.length
          ];
        })
      );
      allowed.sort((a2, b2) => {
        const via = layerCost.get(a2) - layerCost.get(b2);
        const crossingCost = (layer) => {
          const cross4 = (p2, q2, r2) => (q2.x - p2.x) * (r2.y - p2.y) - (q2.y - p2.y) * (r2.x - p2.x);
          let crossings = 0;
          for (const member of members)
            for (const other of this.input.connections) {
              if (targets.get(other.name) !== layer) continue;
              const [p2, q2] = member.pointsToConnect, [r2, s2] = other.pointsToConnect;
              if (cross4(p2, q2, r2) * cross4(p2, q2, s2) < 0 && cross4(r2, s2, p2) * cross4(r2, s2, q2) < 0)
                crossings++;
            }
          return crossings * (this.attempt === 1 ? 0 : 4) + load.get(layer);
        };
        return (group.size > 2 ? rank(a2) - rank(b2) || via || crossingCost(a2) - crossingCost(b2) : via || 4 * (rank(a2) - rank(b2)) + crossingCost(a2) - crossingCost(b2)) || retryOrder.get(a2) - retryOrder.get(b2);
      });
      const target = allowed[0];
      for (const name of group) targets.set(name, target);
      load.set(target, load.get(target) + group.size);
    }
    const widths = this.input.connections.map(
      (c2) => (this.input.buses ?? []).find((b2) => b2.connectionNames.includes(c2.name))?.traceWidth ?? c2.nominalTraceWidth ?? c2.width ?? this.input.minTraceWidth
    );
    const result = routeAlternateSignalDogbones(
      this.input,
      {
        targetLayers: targets,
        viaDiameter: this.input.minViaPadDiameter ?? 0.6,
        viaHoleDiameter: this.input.minViaHoleDiameter ?? 0.3,
        traceWidth: Math.max(this.input.minTraceWidth, ...widths),
        clearance: this.input.minTraceToPadEdgeClearance ?? this.input.defaultObstacleMargin ?? 0.075,
        boardEdgeClearance: this.input.minBoardEdgeClearance,
        holeToHoleClearance: this.input.minViaHoleEdgeToViaHoleEdgeClearance,
        allowBlindAndBuriedVias: this.input.allowBlindAndBuriedVias ?? false
      },
      this.attempt
    );
    this.escapes = result.traces.map((t48) => ({
      ...t48,
      source_trace_id: this.input.connections.find((c2) => c2.name === t48.connection_name)?.source_trace_id ?? t48.connection_name
    }));
    const terminalLayers = /* @__PURE__ */ new Map();
    for (const connection of this.input.connections) {
      if (groups.some((group) => group.size > 2 && group.has(connection.name)))
        continue;
      const vias = this.escapes.filter((t48) => t48.connection_name === connection.name).flatMap((t48) => t48.route.filter((p2) => p2.route_type === "via"));
      if (vias.length !== 2) continue;
      const available = layers.filter(
        (layer) => (this.input.buses ?? []).every(
          (bus) => !bus.connectionNames.includes(connection.name) || !bus.allowedLayers || bus.allowedLayers.includes(layer)
        ) && vias.every(
          (via) => layer !== via.from_layer && (via.layers ?? physicalLayers.slice(
            Math.min(
              physicalLayers.indexOf(via.from_layer),
              physicalLayers.indexOf(via.to_layer)
            ),
            Math.max(
              physicalLayers.indexOf(via.from_layer),
              physicalLayers.indexOf(via.to_layer)
            ) + 1
          )).includes(layer)
        )
      );
      if (available.length > 1) terminalLayers.set(connection.name, available);
    }
    this.terminalLayers = terminalLayers;
    const laneInput = {
      ...this.input,
      connections: result.connections,
      traces: [...this.input.traces ?? [], ...this.escapes]
    };
    const busNames = new Set(laneInput.buses?.flatMap((b2) => b2.connectionNames));
    const multilayerBus = (laneInput.buses ?? []).some(
      (bus) => new Set(
        laneInput.connections.filter(
          (connection) => bus.connectionNames.includes(connection.name)
        ).map((connection) => connection.pointsToConnect[0].layer)
      ).size > 1
    );
    const pairsPerLayer = /* @__PURE__ */ new Map();
    for (const pair of laneInput.differentialPairs ?? []) {
      const layer = laneInput.connections.find(
        (c2) => c2.name === pair.connectionNames[0]
      ).pointsToConnect[0].layer;
      pairsPerLayer.set(layer, (pairsPerLayer.get(layer) ?? 0) + 1);
    }
    const deferStandalonePairs = [...pairsPerLayer.values()].some(
      (count) => count > 1
    );
    const constrained = /* @__PURE__ */ new Set([
      ...busNames,
      ...(laneInput.differentialPairs ?? []).filter(
        (p2) => !deferStandalonePairs || p2.connectionNames.some((name) => busNames.has(name))
      ).flatMap((p2) => p2.connectionNames)
    ]);
    const matching = laneInput.connections.filter(
      (c2) => constrained.has(c2.name)
    );
    const remaining = laneInput.connections.filter(
      (c2) => !constrained.has(c2.name)
    );
    const direction = laneInput.connections.filter((c2) => busNames.has(c2.name)).reduce(
      (sum, c2) => ({
        x: sum.x + c2.pointsToConnect[1].x - c2.pointsToConnect[0].x,
        y: sum.y + c2.pointsToConnect[1].y - c2.pointsToConnect[0].y
      }),
      { x: 0, y: 0 }
    );
    if (!multilayerBus && this.attempt === 0 && deferStandalonePairs && (laneInput.buses?.length ?? 0) > 1 && this.options.smoothTuning && this.options.denseSearch && (this.input.buses?.some((bus) => bus.maxLength !== void 0) || Math.abs(direction.x) > Math.abs(direction.y) || backwardFacingPackageTerminals({
      ...this.input,
      connections: this.input.connections.filter(
        (c2) => busNames.has(c2.name)
      )
    }))) {
      const freshSites = layers.length === 2 && !this.input.allowBlindAndBuriedVias && this.escapes.length === 2 * this.input.connections.length && backwardFacingPackageTerminals({
        ...this.input,
        connections: this.input.connections.filter(
          (c2) => busNames.has(c2.name)
        )
      }) && this.input.connections.every(
        (c2) => c2.pointsToConnect.length === 2 && c2.pointsToConnect.every(
          (p2) => isUnroutedComponentPad(this.input, c2, p2)
        )
      );
      this.sharedPackages = (freshSites ? routeFreshSharedBuses : routeSharedLayerBuses)(
        this.input,
        laneInput,
        this.escapes,
        terminalLayers,
        this.childOptions()
      );
      return;
    }
    if (!multilayerBus && this.attempt === 0 && this.options.smoothTuning && this.options.denseSearch && Math.abs(direction.y) >= Math.abs(direction.x) && backwardFacingPackageTerminals({
      ...this.input,
      connections: this.input.connections.filter((c2) => busNames.has(c2.name))
    }) && this.input.connections.every(
      (c2) => c2.pointsToConnect.length === 2 && c2.pointsToConnect.every(
        (p2) => isUnroutedComponentPad(this.input, c2, p2)
      )
    )) {
      this.backwardPackages = routeBackwardPackageBuses(
        this.input,
        laneInput,
        terminalLayers,
        this.childOptions()
      );
      return;
    }
    const joint = !multilayerBus && (this.attempt > 0 || Math.abs(direction.x) > Math.abs(direction.y)) && backwardFacingPackageTerminals({
      ...this.input,
      connections: this.input.connections.filter((c2) => busNames.has(c2.name))
    });
    if (matching.length && remaining.length && !joint) {
      this.remainingInput = {
        ...laneInput,
        connections: remaining,
        buses: [],
        differentialPairs: (laneInput.differentialPairs ?? []).filter(
          (p2) => p2.connectionNames.every((n2) => !constrained.has(n2))
        )
      };
      if (deferStandalonePairs) {
        const standaloneNames = new Set(
          this.remainingInput.differentialPairs?.flatMap(
            (p2) => p2.connectionNames
          )
        );
        const standalone = remaining.filter((c2) => standaloneNames.has(c2.name));
        const controls = remaining.filter((c2) => !standaloneNames.has(c2.name));
        if (standalone.length && controls.length) {
          this.followingInput = {
            ...this.remainingInput,
            connections: controls,
            differentialPairs: []
          };
          this.remainingInput = {
            ...this.remainingInput,
            connections: standalone
          };
        }
      }
      this.child = new BusLanesSolver(
        {
          ...laneInput,
          connections: matching,
          differentialPairs: (laneInput.differentialPairs ?? []).filter(
            (p2) => p2.connectionNames.every((n2) => constrained.has(n2))
          )
        },
        this.childOptions(true),
        terminalLayers
      );
    } else
      this.child = new BusLanesSolver(
        laneInput,
        this.childOptions(),
        terminalLayers
      );
  }
  _step() {
    try {
      if (this.envelopeOptimization) {
        const step = this.envelopeOptimization.next();
        if (step.done) this.finishAccepted(false);
        return;
      }
      if (this.siteRematch) {
        const step = this.siteRematch.next();
        this.phase = "resolve_control_sites";
        this.stats = { ...this.stats, routingStage: "control_sites" };
        if (!step.done) return;
        this.escapes = step.value.escapes;
        this.child = new BusLanesSolver(
          {
            ...this.remainingInput,
            connections: step.value.connections,
            traces: [
              ...this.input.traces ?? [],
              ...this.escapes,
              ...this.completedLanes
            ]
          },
          this.childOptions(),
          this.terminalLayers
        );
        this.remainingInput = void 0;
        this.siteRematch = void 0;
        return;
      }
      if (!this.child && !this.backwardPackages && !this.sharedPackages)
        this.prepare();
      if (this.sharedPackages) {
        this.phase = "route_shared_layers";
        const state = this.sharedPackages.next();
        if (!state.done) return;
        this.sharedPackages = void 0;
        if (!state.value) throw Error("Shared-layer bus routing exhausted");
        this.escapes = state.value.escapes;
        this.child = BusLanesSolver.forValidation(
          state.value.input,
          state.value.traces,
          this.childOptions()
        );
      }
      if (this.backwardPackages) {
        this.phase = "route_backward_packages";
        const step = this.backwardPackages.next();
        if (!step.done) return;
        this.backwardPackages = void 0;
        if (!step.value) throw Error("Backward package bus routing failed");
        this.escapes = step.value.escapes;
        this.child = BusLanesSolver.forRefinement(
          step.value.input,
          step.value.traces,
          this.childOptions()
        );
      }
      this.child.step();
      this.phase = `lanes_${this.child.phase}`;
      this.stats = {
        ...this.child.stats,
        layerAttempt: this.attempt,
        dogbones: this.escapes.length,
        routingStage: this.completedLanes.length ? "remaining_signals" : this.remainingInput ? "matched_buses" : "all_signals"
      };
      this.progress = this.child.progress;
      if (this.child.failed)
        throw Error(this.child.error ?? "Bus lanes failed");
      if (this.child.solved && !this.remainingInput && this.followingInput) {
        this.remainingInput = this.followingInput;
        this.followingInput = void 0;
      }
      if (this.child.solved && this.remainingInput) {
        this.completedLanes.push(...this.child.traces);
        this.siteRematch = rematchTrappedSignalDogbones(
          this.input,
          this.remainingInput,
          this.completedLanes,
          this.escapes,
          this.terminalLayers
        );
        return;
      }
      if (this.child.solved) {
        const lanes = [...this.completedLanes, ...this.child.traces];
        let refined = lanes;
        if (this.options.smoothTuning && this.input.differentialPairs?.length) {
          this.packageCoupling ??= this.finishPackageCoupling(
            {
              ...this.input,
              traces: [...this.input.traces ?? [], ...this.escapes],
              connections: this.input.connections.map((c2) => {
                const lane = lanes.find((t48) => t48.connection_name === c2.name);
                return {
                  ...c2,
                  pointsToConnect: [
                    lane.route[0],
                    lane.route.at(-1)
                  ]
                };
              })
            },
            lanes
          );
          const step = this.packageCoupling.next();
          if (!step.done) {
            this.phase = "extend_package_coupling";
            return;
          }
          refined = step.value;
          this.packageCoupling = void 0;
        }
        if (this.options.smoothTuning)
          refined = simplifyMatchedTraces(
            {
              ...this.input,
              traces: [...this.input.traces ?? [], ...this.escapes],
              connections: this.input.connections.map((c2) => {
                const t48 = refined.find((t49) => t49.connection_name === c2.name);
                return {
                  ...c2,
                  pointsToConnect: [
                    t48.route[0],
                    t48.route.at(-1)
                  ]
                };
              })
            },
            refined
          );
        if (this.options.smoothTuning && (this.input.allowedLayers?.length ?? this.input.layerCount) === 2)
          refined = compactUnconstrainedLanes(
            {
              ...this.input,
              traces: [...this.input.traces ?? [], ...this.escapes],
              connections: this.input.connections.map((c2) => {
                const t48 = refined.find((t49) => t49.connection_name === c2.name);
                return {
                  ...c2,
                  pointsToConnect: [
                    t48.route[0],
                    t48.route.at(-1)
                  ]
                };
              })
            },
            refined
          );
        this.traces = refined.map((lane) => {
          const signalLayer = lane.route.find(
            (p2) => p2.route_type === "wire"
          ).layer;
          const escapes = this.escapes.filter((t48) => t48.connection_name === lane.connection_name).map((t48) => {
            const via = t48.route.find((p2) => p2.route_type === "via");
            return {
              ...t48,
              route: t48.route.map(
                (p2) => p2.route_type === "via" ? { ...p2, to_layer: signalLayer } : p2.layer === via.to_layer ? { ...p2, layer: signalLayer } : p2
              )
            };
          });
          const near2 = (a2, b2) => Math.hypot(a2.x - b2.x, a2.y - b2.y) < 1e-8;
          const prefix = escapes.find(
            (t48) => near2(t48.route.at(-1), lane.route[0])
          );
          const suffix = escapes.find(
            (t48) => t48 !== prefix && near2(t48.route.at(-1), lane.route.at(-1))
          );
          const prefixRoute = prefix?.route, suffixRoute = suffix?.route;
          const reversed = suffixRoute?.toReversed().map(
            (p2) => p2.route_type === "via" ? { ...p2, from_layer: p2.to_layer, to_layer: p2.from_layer } : p2
          ) ?? [];
          const offset = (prefix?.route.length ?? 1) - 1;
          return {
            ...lane,
            coupledSection: lane.coupledSection?.map((i2) => i2 + offset),
            curvedSegments: lane.curvedSegments?.map((i2) => i2 + offset),
            route: [
              ...prefixRoute?.slice(0, -1) ?? [],
              ...lane.route,
              ...reversed.slice(1)
            ]
          };
        });
        if (busLengthReports(this.input, this.traces).some(
          (b2) => !b2.withinLengthLimit || !b2.aboveMinimumLength
        ))
          throw Error("Final absolute bus length violation");
        this.acceptedTraces = structuredClone(this.traces);
        this.phase = "optimize_envelope";
        this.envelopeOptimization = this.optimizeEnvelope();
      }
    } catch (error) {
      if (this.acceptedTraces) {
        this.stats = { ...this.stats, optimizationError: String(error) };
        this.finishAccepted(true);
        return;
      }
      this.sharedPackages?.return(null);
      this.sharedPackages = void 0;
      this.backwardPackages?.return(null);
      this.backwardPackages = void 0;
      this.packageCoupling?.return([]);
      this.packageCoupling = void 0;
      this.siteRematch?.return({ connections: [], escapes: [] });
      this.siteRematch = void 0;
      this.attempt++;
      if (this.options.fanout !== "none" && this.attempt < this.input.layerCount) {
        this.child = void 0;
        this.escapes = [];
        this.completedLanes = [];
        this.remainingInput = void 0;
        this.followingInput = void 0;
        this.phase = "retry_layers";
        return;
      }
      this.failureCode = this.child?.failureCode ?? "local_dogbone_failed";
      this.error = error instanceof Error ? error.message : String(error);
      this.failed = true;
      this.phase = "failed";
      this.traces = [];
    }
  }
  visualize() {
    return this.child?.visualize() ?? { points: [], lines: [] };
  }
};
export {
  BusLanesPipelineSolver,
  BusLanesSolver,
  busLengthReports,
  exteriorPairSpacingReports,
  pairLengthReports
};
/*! Bundled license information:

svgson/dist/svgson.umd.js:
  (*!
   * Determine if an object is a Buffer
   *
   * @author   Feross Aboukhadijeh <https://feross.org>
   * @license  MIT
   *)

@tscircuit/capacity-autorouter/dist/index.js:
  (*! Bundled license information:
  
  is-buffer/index.js:
    (*!
     * Determine if an object is a Buffer
     *
     * @author   Feross Aboukhadijeh <https://feross.org>
     * @license  MIT
     *)
  
  deep-rename-keys/index.js:
    (*!
     * deep-rename-keys <https://github.com/jonschlinkert/deep-rename-keys>
     *
     * Copyright (c) 2015 Jon Schlinkert, contributors.
     * Licensed under the MIT license.
     *)
  
  @tscircuit/curvy-trace-solver/dist/index.js:
  @tscircuit/find-convex-regions/dist/index.js:
    (*! Bundled license information:
    
    is-buffer/index.js:
      (*!
       * Determine if an object is a Buffer
       *
       * @author   Feross Aboukhadijeh <https://feross.org>
       * @license  MIT
       *)
    
    deep-rename-keys/index.js:
      (*!
       * deep-rename-keys <https://github.com/jonschlinkert/deep-rename-keys>
       *
       * Copyright (c) 2015 Jon Schlinkert, contributors.
       * Licensed under the MIT license.
       *)
    *)
  
  @tscircuit/hypergraph/dist/index.js:
    (*! Bundled license information:
    
    @tscircuit/find-convex-regions/dist/index.js:
      (*! Bundled license information:
      
      is-buffer/index.js:
        (*!
         * Determine if an object is a Buffer
         *
         * @author   Feross Aboukhadijeh <https://feross.org>
         * @license  MIT
         *)
      
      deep-rename-keys/index.js:
        (*!
         * deep-rename-keys <https://github.com/jonschlinkert/deep-rename-keys>
         *
         * Copyright (c) 2015 Jon Schlinkert, contributors.
         * Licensed under the MIT license.
         *)
      *)
    *)
  *)
*/