@ohtaman/washi 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.ja.md +22 -24
  2. package/README.md +20 -22
  3. package/README.zh-CN.md +25 -27
  4. package/dist/browser/{__vite-browser-external-rTVKos2U.js → solvers/highs-__vite-browser-external-Dn-83hnF.js} +1 -1
  5. package/dist/browser/{browser-runtime-AG5QFtKf.js → solvers/highs-browser-runtime-0Bgq5ksG.js} +1 -1
  6. package/dist/browser/{loader-i3FnqMes.js → solvers/highs-loader-BLY3wzDH.js} +25 -18
  7. package/dist/browser/{highs-worker.js → solvers/highs-worker.js} +1 -1
  8. package/dist/browser/solvers/highs.js +1414 -0
  9. package/dist/browser/washi.js +1090 -1473
  10. package/dist/browser/washi.min.js +4 -4
  11. package/dist/lib/solvers/glpk.js +34 -32
  12. package/dist/lib/{highs-node-runtime.js → solvers/highs-node-runtime.js} +1 -1
  13. package/dist/lib/solvers/highs.js +410 -0
  14. package/dist/lib/solvers/lp-writer-CLScMFbS.js +115 -0
  15. package/dist/lib/solvers/pumpkin-node-runtime.js +1 -1
  16. package/dist/lib/solvers/pumpkin-worker.js +1 -1
  17. package/dist/lib/solvers/pumpkin.js +247 -1146
  18. package/dist/lib/solvers/registry-CrYRRk9q.js +907 -0
  19. package/dist/lib/solvers/types-BGqPkxwu.js +12 -0
  20. package/dist/lib/solvers/z3.js +125 -123
  21. package/dist/lib/washi.js +2426 -1340
  22. package/dist/types/index.d.ts +1 -2
  23. package/dist/types/index.d.ts.map +1 -1
  24. package/dist/types/modeler/index.d.ts +0 -1
  25. package/dist/types/modeler/index.d.ts.map +1 -1
  26. package/dist/types/modeler/model.d.ts +6 -7
  27. package/dist/types/modeler/model.d.ts.map +1 -1
  28. package/dist/types/modeler/solvers/index.d.ts +2 -1
  29. package/dist/types/modeler/solvers/index.d.ts.map +1 -1
  30. package/dist/types/modeler/solvers/registry.d.ts.map +1 -1
  31. package/docs/examples/diet-sensitivity.md +33 -14
  32. package/docs/examples/ecommerce-coupons.md +17 -9
  33. package/docs/examples/index.md +34 -30
  34. package/docs/examples/knapsack.md +11 -5
  35. package/docs/examples/portfolio-qp.md +21 -8
  36. package/docs/examples/production.md +10 -5
  37. package/docs/examples/project-scheduling.md +25 -12
  38. package/docs/examples/shift-scheduling.md +27 -19
  39. package/docs/examples/smt-security.md +27 -12
  40. package/docs/examples/transportation.md +23 -13
  41. package/docs/examples/traveling-salesperson.md +34 -22
  42. package/docs/examples/unsat-core.md +27 -15
  43. package/docs/examples/vehicle-routing.md +74 -28
  44. package/docs/getting-started/ai-agents.md +129 -90
  45. package/docs/getting-started/coding-agents.md +60 -41
  46. package/docs/getting-started/cross-origin.md +27 -14
  47. package/docs/getting-started/index.md +23 -16
  48. package/docs/getting-started/runtimes.md +70 -40
  49. package/docs/guide/constraint-programming.md +74 -44
  50. package/docs/guide/constraints.md +71 -39
  51. package/docs/guide/decomposition.md +72 -42
  52. package/docs/guide/expressions.md +79 -48
  53. package/docs/guide/formulation-tips.md +46 -27
  54. package/docs/guide/objectives.md +55 -31
  55. package/docs/guide/unsat-core.md +56 -53
  56. package/docs/guide/variables.md +61 -28
  57. package/docs/solvers/custom-solver.md +155 -119
  58. package/docs/solvers/glpk.md +58 -17
  59. package/docs/solvers/highs.md +115 -43
  60. package/docs/solvers/index.md +33 -26
  61. package/docs/solvers/pumpkin.md +71 -63
  62. package/docs/solvers/z3.md +63 -25
  63. package/llms-full.txt +1623 -953
  64. package/llms.txt +125 -93
  65. package/package.json +29 -20
  66. package/skills/washi/SKILL.md +43 -22
  67. package/dist/browser/solvers/pumpkin.min.js +0 -1
  68. package/dist/lib/registry-dx7x4e5c.js +0 -1694
  69. /package/dist/browser/{highs.wasm → solvers/highs.wasm} +0 -0
  70. /package/dist/browser/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  71. /package/dist/lib/{__vite-browser-external-oLchLuMx.js → solvers/__vite-browser-external-oLchLuMx.js} +0 -0
  72. /package/dist/lib/{highs-assets.js → solvers/highs-assets.js} +0 -0
  73. /package/dist/lib/{highs-browser-runtime.js → solvers/highs-browser-runtime.js} +0 -0
  74. /package/dist/lib/{highs-runtime.js → solvers/highs-runtime.js} +0 -0
  75. /package/dist/lib/{highs-worker-factory.js → solvers/highs-worker-factory.js} +0 -0
  76. /package/dist/lib/{highs-worker.js → solvers/highs-worker.js} +0 -0
  77. /package/dist/lib/{highs.wasm → solvers/highs.wasm} +0 -0
  78. /package/dist/lib/{highs.wasm.LICENSE → solvers/highs.wasm.LICENSE} +0 -0
  79. /package/dist/lib/{loader-CDpPXN_F.js → solvers/loader-CDpPXN_F.js} +0 -0
  80. /package/dist/lib/solvers/{pumpkin-loader-Ow74Fa1B.js → loader-Ow74Fa1B.js} +0 -0
  81. /package/dist/lib/{rolldown-runtime-DtPi1Y-2.js → solvers/rolldown-runtime-DtPi1Y-2.js} +0 -0
@@ -1,6 +1,6 @@
1
- var Washi=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.defineProperty,n=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},r=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r};function i(e){if(e===void 0)return`Minimize`;if(typeof e==`string`){let t=e.toLowerCase();if(t===`maximize`)return`Maximize`;if(t===`minimize`)return`Minimize`}throw Error(`Invalid optimization sense "${String(e)}": expected "Maximize", "Minimize", "maximize", or "minimize".`)}var a=0;function o(e,t){if(e instanceof s||e instanceof R)return e;throw typeof e==`object`&&e&&(`terms`in e||`quadTerms`in e)?Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical operator "${t}". Use a comparison constraint such as expr\`\${x} <= 10\` or a BoolVar/BoolExpr.`):typeof e==`object`&&e&&`id`in e&&`name`in e&&`lb`in e&&`ub`in e&&!(`sense`in e)?Error(`Invalid operand passed to logical operator "${t}": expected a BoolVar, BoolExpr, or Constraint, but received numeric variable "${e.name}". Use m.bool() for propositional variables, add a comparison such as expr\`\${x} == 1\`, or use m.indicator(binVar, constraint) for 0-1 Big-M indicator constraints.`):Error(`Invalid operand passed to logical operator "${t}": expected a BoolVar, BoolExpr, or Constraint.`)}var s=class{and(e){return new l(`and`,[this,o(e,`and`)])}or(e){return new l(`or`,[this,o(e,`or`)])}implies(e){return new l(`implies`,[this,o(e,`implies`)])}xor(e){return new l(`xor`,[this,o(e,`xor`)])}not(){return new l(`not`,[this])}},c=class extends s{id;type=`Boolean`;name;value=null;constructor(e){super(),this.id=++a,this.name=e||`p_${this.id}`}toString(){return this.name}},l=class extends s{op;children;constructor(e,t){super(),this.op=e,this.children=t.map(t=>o(t,e))}toString(){return this.op===`not`?`not(${this.children[0].toString()})`:`(${this.children.map(e=>e.toString()).join(` ${this.op} `)})`}};function u(...e){if(e.length===0)throw Error(`and() requires at least one expression`);return new l(`and`,e)}function d(...e){if(e.length===0)throw Error(`or() requires at least one expression`);return new l(`or`,e)}function f(e){return new l(`not`,[e])}function p(e,t){return new l(`implies`,[e,t])}function m(...e){if(e.length===0)throw Error(`xor() requires at least one expression`);return new l(`xor`,e)}var h=class extends s{spec;discreteVars;constructor(e,t){super(),this.spec=e,this.discreteVars=t}toString(){switch(this.spec.kind){case`distinct`:return`distinct(${this.spec.args.map(e=>e.toString()).join(`, `)})`;case`disjoint`:return`disjoint([${this.spec.tasks.map(e=>`{ start: ${e.start.toString()}, duration: ${e.duration} }`).join(`, `)}])`;case`cumulative`:return`cumulative([${this.spec.tasks.map(e=>`{ start: ${e.start.toString()}, duration: ${e.duration}, demand: ${e.demand} }`).join(`, `)}], ${this.spec.capacity})`;case`allowed`:return`allowed([${this.spec.vars.map(e=>e.toString()).join(`, `)}], [${this.spec.tuples.map(e=>`[${e.join(`, `)}]`).join(`, `)}])`}}};function g(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof R||e instanceof s||e instanceof V)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function _(e){return typeof e==`number`||e instanceof R||e instanceof V||typeof e==`object`&&!!e&&(`terms`in e&&e.terms instanceof Map||`quadTerms`in e&&e.quadTerms instanceof Map||`id`in e&&`name`in e&&`lb`in e&&`ub`in e&&!(`sense`in e))}function v(...e){if(e.length===0)throw Error(`distinct() requires at least one expression or container.`);let t=[],n=new Set,r=(e,i)=>{if(e==null)throw Error(`Unsupported nullish item in distinct(): expected an integer-valued expression.`);if(_(e)){let r=pe(e,`distinct()`);B(r,`distinct()`,n),t.push(r);return}if(Array.isArray(e)){if(i>=2)throw Error(`Nested containers deeper than 2D are not supported in distinct().`);for(let t=0;t<e.length;t++){if(!(t in e))throw Error(`Unsupported item in distinct(): sparse array hole at index ${t}.`);r(e[t],i+1)}return}if(typeof e==`object`&&!(e instanceof String)&&!(e instanceof Map)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`){if(i>=2)throw Error(`Nested containers deeper than 2D are not supported in distinct().`);for(let t of e)r(t,i+1);return}if(g(e)){if(i>=2)throw Error(`Nested containers deeper than 2D are not supported in distinct().`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in distinct().`);for(let t of Object.keys(e))r(e[t],i+1);return}throw Error(`Unsupported item in distinct(): expected an integer-valued expression or container.`)};for(let t of e)r(t,0);return new h({kind:`distinct`,args:t},n)}function y(e,t){if(e==null)throw Error(`${t}(tasks) requires an Array, Iterable, or Record of task objects.`);if(Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++){if(!(r in e))throw Error(`${t}(tasks) encountered sparse array hole at index ${r}.`);n.push(e[r])}return n}if(typeof e==`object`&&!(e instanceof String)&&!(e instanceof Map)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`)return Array.from(e);if(g(e)){if(`start`in e&&`duration`in e)throw Error(`${t}(tasks) expects an Array, Iterable, or Record of task objects, not a single task object.`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in ${t}().`);return Object.keys(e).map(t=>e[t])}throw Error(`${t}(tasks) requires an Array, Iterable, or Record of task objects.`)}function b(e){let t=y(e,`disjoint`),n=new Set,r=[];for(let e=0;e<t.length;e++){let i=t[e];if(typeof i!=`object`||!i||!(`start`in i)||!(`duration`in i))throw Error(`disjoint() task at index ${e} must be an object with { start, duration }.`);let a=i,o=pe(a.start,`disjoint() task[${e}].start`);if(B(o,`disjoint() task[${e}].start`,n),typeof a.duration!=`number`||!Number.isSafeInteger(a.duration)||a.duration<0)throw Error(`disjoint() task[${e}].duration must be a finite non-negative integer, received ${String(a.duration)}.`);r.push({start:o,duration:Object.is(a.duration,-0)?0:a.duration})}return new h({kind:`disjoint`,tasks:r},n)}function x(e,t){if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw Error(`cumulative() capacity must be a finite non-negative integer, received ${String(t)}.`);let n=y(e,`cumulative`),r=new Set,i=[];for(let e=0;e<n.length;e++){let t=n[e];if(typeof t!=`object`||!t||!(`start`in t)||!(`duration`in t)||!(`demand`in t))throw Error(`cumulative() task at index ${e} must be an object with { start, duration, demand }.`);let a=t,o=pe(a.start,`cumulative() task[${e}].start`);if(B(o,`cumulative() task[${e}].start`,r),typeof a.duration!=`number`||!Number.isSafeInteger(a.duration)||a.duration<0)throw Error(`cumulative() task[${e}].duration must be a finite non-negative integer, received ${String(a.duration)}.`);if(typeof a.demand!=`number`||!Number.isSafeInteger(a.demand)||a.demand<0)throw Error(`cumulative() task[${e}].demand must be a finite non-negative integer, received ${String(a.demand)}.`);i.push({start:o,duration:Object.is(a.duration,-0)?0:a.duration,demand:Object.is(a.demand,-0)?0:a.demand})}return new h({kind:`cumulative`,tasks:i,capacity:Object.is(t,-0)?0:t},r)}function S(e,t){if(!Array.isArray(e)||e.length===0)throw Error(`allowed(vars, tuples) requires a non-empty Array of expressions as its first argument.`);let n=new Set,r=Array(e.length);for(let t=0;t<e.length;t++){if(!(t in e))throw Error(`allowed() vars encountered sparse array hole at index ${t}.`);let i=pe(e[t],`allowed() vars[${t}]`);B(i,`allowed() vars[${t}]`,n),r[t]=i}if(typeof t!=`object`||!t||t instanceof String||!(Symbol.iterator in t)||typeof t[Symbol.iterator]!=`function`)throw Error(`allowed(vars, tuples) requires an Iterable of integer tuples as its second argument.`);let i=[],a=0;for(let n of t){if(!Array.isArray(n)||n.length!==e.length)throw Error(`allowed() tuple at index ${a} must be an Array of length ${e.length}.`);let t=Array(e.length);for(let r=0;r<e.length;r++){if(!(r in n))throw Error(`allowed() tuple[${a}] encountered sparse array hole at index ${r}.`);let e=n[r];if(typeof e!=`number`||!Number.isSafeInteger(e))throw Error(`allowed() tuple[${a}][${r}] must be a safe integer, received ${String(e)}.`);t[r]=Object.is(e,-0)?0:e}i.push(t),a++}return new h({kind:`allowed`,vars:r,tuples:i},n)}function C(e,t){let n=e.id,r=t.id;return n<=r?`${n}:${r}`:`${r}:${n}`}var w=class e{kind=`quadratic`;linearTerms;quadTerms;constant;nonlinearTerms;constructor(e=new Map,t=new Map,n=0,r=[]){this.linearTerms=new Map(e),this.quadTerms=new Map;for(let[e,n]of t)this.quadTerms.set(e,{...n});this.constant=n,this.nonlinearTerms=r.filter(e=>e.coeff!==0).map(e=>({atom:z(e.atom),coeff:e.coeff}))}hasNonlinearTerms(){return this.nonlinearTerms.length>0}clone(){return new e(this.linearTerms,this.quadTerms,this.constant,this.nonlinearTerms)}getQuadCoeff(e,t){let n=C(e,t),r=this.quadTerms.get(n);return r?r.coeff:0}add(t){if(le(t))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);let n=this.clone();if(typeof t==`number`)return n.constant+=t,n;if(t instanceof e){for(let[e,r]of t.quadTerms){let t=n.quadTerms.get(e),i=(t?t.coeff:0)+r.coeff;i===0?n.quadTerms.delete(e):n.quadTerms.set(e,{var1:r.var1,var2:r.var2,coeff:i})}for(let[e,r]of t.linearTerms){let t=(n.linearTerms.get(e)??0)+r;t===0?n.linearTerms.delete(e):n.linearTerms.set(e,t)}if(n.constant+=t.constant,Array.isArray(t.nonlinearTerms))for(let e of t.nonlinearTerms)e.coeff!==0&&n.nonlinearTerms.push({atom:z(e.atom),coeff:e.coeff});return n}if(`terms`in t&&t.terms instanceof Map){for(let[e,r]of t.terms){let t=(n.linearTerms.get(e)??0)+r;t===0?n.linearTerms.delete(e):n.linearTerms.set(e,t)}if(n.constant+=t.constant,Array.isArray(t.nonlinearTerms))for(let e of t.nonlinearTerms)e.coeff!==0&&n.nonlinearTerms.push({atom:z(e.atom),coeff:e.coeff});return n}let r=t,i=(n.linearTerms.get(r)??0)+1;return i===0?n.linearTerms.delete(r):n.linearTerms.set(r,i),n}sub(e){if(le(e))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);return typeof e==`number`?this.add(-e):this.add(e.mul(-1))}mul(t){if(le(t))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);if(typeof t==`number`){let n=this.linearTerms.size>0||this.quadTerms.size>0||this.nonlinearTerms.length>0,r=this.constant===0&&n?0:this.constant*t;if(this.constant!==0&&t!==0&&r===0)throw Error(`Constant multiplication underflows to zero.`);let i=new e(new Map,new Map,r);for(let[e,n]of this.linearTerms){let r=n*t;if(n!==0&&t!==0&&r===0)throw Error(`Coefficient multiplication underflows to zero.`);r!==0&&i.linearTerms.set(e,r)}for(let[e,n]of this.quadTerms){let r=n.coeff*t;if(n.coeff!==0&&t!==0&&r===0)throw Error(`Coefficient multiplication underflows to zero.`);r!==0&&i.quadTerms.set(e,{var1:n.var1,var2:n.var2,coeff:r})}if(t!==0)for(let e of this.nonlinearTerms){let n=e.coeff*t;if(e.coeff!==0&&n===0)throw Error(`Coefficient multiplication underflows to zero.`);n!==0&&i.nonlinearTerms.push({atom:z(e.atom),coeff:n})}return i}let n=`id`in t&&`name`in t&&!(`terms`in t)&&!(`quadTerms`in t),r=`quadTerms`in t?t.quadTerms.size:0,i=!n&&`nonlinearTerms`in t&&Array.isArray(t.nonlinearTerms)?t.nonlinearTerms.length:0,a=n?new Map([[t,1]]):`quadTerms`in t?t.linearTerms:t.terms,o=n?0:t.constant;if(this.nonlinearTerms.length>0){if(!n&&r===0&&a.size===0&&i===0)return this.mul(o);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}if(i>0){if(this.quadTerms.size===0&&this.linearTerms.size===0){let n=t.mul(this.constant);return`quadTerms`in n?n:new e(n.terms,new Map,n.constant,n.nonlinearTerms)}throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}if(this.quadTerms.size>0&&(r>0||a.size>0)||r>0&&this.linearTerms.size>0)throw Error(`Multiplication creates a non-linear term of degree > 2 (not allowed in MILP/LP/QP)`);if(r===0&&a.size===0)return this.mul(o);if(this.quadTerms.size===0&&this.linearTerms.size===0&&!n){let n=t.mul(this.constant);return`quadTerms`in n?n:new e(n.terms,new Map,n.constant,n.nonlinearTerms)}return e.multiplyLinearTerms(this.constant,this.linearTerms,o,a)}div(t){let n=e.extractScalarDivisor(t,`QuadExpr.div()`);return this.mul(1/n)}neg(){return this.mul(-1)}get value(){let e=this.constant;for(let[t,n]of this.linearTerms){if(t.value===null)return null;e+=n*t.value}for(let t of this.quadTerms.values()){if(t.var1.value===null||t.var2.value===null)return null;e+=t.coeff*t.var1.value*t.var2.value}for(let t of this.nonlinearTerms){let n=de(t.atom);if(n===null)return null;e+=t.coeff*n}return e}le(e,t){return this.toConstraint(`<=`,e,t)}ge(e,t){return this.toConstraint(`>=`,e,t)}eq(e,t){return this.toConstraint(`==`,e,t)}lt(e,t){return this.toDiscreteComparison(`<`,e,t)}gt(e,t){return this.toDiscreteComparison(`>`,e,t)}ne(e,t){return this.toDiscreteComparison(`!=`,e,t)}toDiscreteComparison(e,t,n){if(this.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in discrete comparisons (${e}): quadratic terms are only allowed in objectives.`);let r=new V(this.linearTerms,this.constant,this.nonlinearTerms);return e===`<`?r.lt(t,n):e===`>`?r.gt(t,n):r.ne(t,n)}toConstraint(e,t,n){if(this.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in linear constraints (${e}): quadratic terms are only allowed in objectives.`);let r=new V(this.linearTerms,this.constant,this.nonlinearTerms);return e===`<=`?r.le(t,n):e===`>=`?r.ge(t,n):r.eq(t,n)}and(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'and': expected a BoolVar, Constraint, or BoolOp.`)}or(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'or': expected a BoolVar, Constraint, or BoolOp.`)}implies(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'implies': expected a BoolVar, Constraint, or BoolOp.`)}xor(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'xor': expected a BoolVar, Constraint, or BoolOp.`)}not(){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'not': expected a BoolVar, Constraint, or BoolOp.`)}toString(){let e=[],t=!0;for(let n of this.quadTerms.values()){let r=n.coeff,i=r>=0?t?``:`+ `:`- `,a=Math.abs(r),o=a===1?``:`${a} `;n.var1===n.var2?e.push(`${i}${o}${n.var1.name}^2`):e.push(`${i}${o}${n.var1.name} * ${n.var2.name}`),t=!1}for(let[n,r]of this.linearTerms){let i=r>=0?t?``:`+ `:`- `,a=Math.abs(r),o=a===1?``:`${a} `;e.push(`${i}${o}${n.name}`),t=!1}if(this.nonlinearTerms.length>0){let n=new V(new Map,0,this.nonlinearTerms).toString();n!==`0`&&(e.push(t?n:n.startsWith(`-`)?`- ${n.slice(2)}`:`+ ${n}`),t=!1)}if(this.constant!==0||e.length===0){let n=this.constant>=0?t?``:`+ `:`- `;e.push(`${n}${Math.abs(this.constant)}`)}return e.join(` `)||`0`}static fromProduct(t,n,r=1){let i=new e;if(r===0)return i;let a=C(t,n);return i.quadTerms.set(a,{var1:t.id<=n.id?t:n,var2:t.id<=n.id?n:t,coeff:r}),i}static multiplyLinearTerms(t,n,r,i){let a=n.size>0||i.size>0,o=(t===0||r===0)&&a?0:t*r;if(t!==0&&r!==0&&o===0)throw Error(`Constant multiplication underflows to zero.`);let s=new e(new Map,new Map,o===0?0:o);if(r!==0)for(let[e,t]of n){let n=t*r;if(t!==0&&n===0)throw Error(`Coefficient multiplication underflows to zero.`);n!==0&&s.linearTerms.set(e,n)}if(t!==0)for(let[e,n]of i){let r=s.linearTerms.get(e)??0,i=n*t;if(n!==0&&i===0)throw Error(`Coefficient multiplication underflows to zero.`);let a=r+i;a===0?s.linearTerms.delete(e):s.linearTerms.set(e,a)}for(let[t,r]of n)for(let[n,a]of i){let i=r*a;if(r!==0&&a!==0&&i===0)throw Error(`Coefficient multiplication underflows to zero.`);s=s.add(e.fromProduct(t,n,i))}return s}static extractScalarDivisor(e,t){if(le(e))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);if(typeof e==`number`){if(e===0)throw Error(`Division by zero in ${t}`);return e}let n=`quadTerms`in e?e.linearTerms.size:e.terms.size,r=`quadTerms`in e?e.quadTerms.size:0,i=`nonlinearTerms`in e&&Array.isArray(e.nonlinearTerms)?e.nonlinearTerms.length:0;if(n>0||r>0||i>0)throw Error(`Cannot divide by variable in expression`);if(e.constant===0)throw Error(`Division by zero in ${t}`);return e.constant}},T=new WeakMap,E=new WeakMap,D=new WeakMap,ee=new WeakMap;function O(e,t){ee.set(e,t)}function k(e){e&&ee.get(e)?.()}function A(e,t,n){if(e instanceof l)for(let r of e.children)A(r,t,n);else if(e instanceof R){let r=e.ownerModel,i=E.get(e);(r!==t||i!==t)&&(n&&n.push(()=>{e.ownerModel=r,i?E.set(e,i):E.delete(e)}),e.ownerModel=t,E.set(e,t))}}function te(e,t){let n=T.get(e);if(n&&n!==t)throw Error(`Variable "${e.name}" already belongs to model "${n.name}" and cannot be added to model "${t.name}".`);T.set(e,t)}function ne(e,t){let n=D.get(e);if(n)throw Error(n===t?`Constraint "${e.name}" is already registered in model "${t.name}".`:`Constraint "${e.name}" already belongs to model "${n.name}" and cannot be added to model "${t.name}".`);let r=E.get(e);if(r&&r!==t)throw Error(`Constraint "${e.name}" already belongs to model "${r.name}" and cannot be added to model "${t.name}".`);return D.set(e,t),E.set(e,t),r}function re(e,t){T.get(e)===t&&T.delete(e)}function ie(e,t,n){D.get(e)===t&&D.delete(e),E.get(e)===t&&(n?E.set(e,n):E.delete(e))}var j=1e-6;function M(e){if(typeof e.lb!=`number`||Number.isNaN(e.lb))throw Error(`Variable "${e.name}" has invalid lower bound: ${e.lb} (NaN or non-numeric bound is not allowed).`);if(e.lb===1/0)throw Error(`Variable "${e.name}" has invalid lower bound: +Infinity is not allowed as a lower bound.`);if(typeof e.ub!=`number`||Number.isNaN(e.ub))throw Error(`Variable "${e.name}" has invalid upper bound: ${e.ub} (NaN or non-numeric bound is not allowed).`);if(e.ub===-1/0)throw Error(`Variable "${e.name}" has invalid upper bound: -Infinity is not allowed as an upper bound.`);if(e.lb>e.ub)throw Error(`Variable "${e.name}" has invalid bounds: lower bound (${e.lb}) is strictly greater than upper bound (${e.ub}).`);if(e.initialValue!==void 0){if(typeof e.initialValue!=`number`||!Number.isFinite(e.initialValue))throw Error(`Variable "${e.name}" has invalid initialValue: ${String(e.initialValue)} (initialValue must be a finite number).`);let t=e.type===`Binary`?Math.max(0,e.lb):e.lb,n=e.type===`Binary`?Math.min(1,e.ub):e.ub;if(e.initialValue<t-1e-6||e.initialValue>n+1e-6)throw Error(`Variable "${e.name}" has initialValue (${e.initialValue}) outside its bounds [${t}, ${n}] (tolerance ${j}).`);if(e.type===`Integer`||e.type===`Binary`){let r=Math.round(e.initialValue);if(Math.abs(e.initialValue-r)>1e-6||r<t||r>n)throw Error(`Variable "${e.name}" of type "${e.type}" has non-integral or out-of-domain initialValue: ${e.initialValue} (must be within ${j} of an integer in [${t}, ${n}]).`)}}}function ae(e){if(e.initialValue===void 0)return;if(M(e),e.type===`Integer`||e.type===`Binary`){let t=Math.round(e.initialValue);return Object.is(t,-0)?0:t}let t=Math.min(e.ub,Math.max(e.lb,e.initialValue));return Object.is(t,-0)?0:t}function N(e,t){if(e){for(let n of e)if(n.type!==`Integer`&&n.type!==`Binary`)throw Error(`${t} requires Integer or Binary variables, but variable "${n.name}" has type "${n.type}".`)}}function oe(e,t,n,r){if(e&&e.length!==0)for(let i of e){if(!Number.isFinite(i.coeff))throw Error(`Nonlinear expression in ${t} has invalid coefficient: ${i.coeff}. Coefficients must be finite numbers.`);let e=i.atom;if(e.kind===`abs`)P(e.arg,t,n,r);else if(e.kind===`max`||e.kind===`min`)for(let i of e.args)P(i,t,n,r);else if(e.kind===`at`){N(e.discreteVars,`at() index in ${t}`),P(e.index,t,n,r);for(let i of e.array)P(i,t,n,r)}}}function P(e,t,n,r,i){if(e.constant!==void 0&&!Number.isFinite(e.constant)){let n=i?.constantPrefix??t,r=i?.constantKind??`constant`;throw Error(`${n} has invalid ${r}: ${e.constant}. Constant must be a finite number.`)}let a=i?.varLocationPhrase??`in ${t}`;for(let[i,o]of e.terms){if(!r(i))throw Error(`Variable "${i.name}" ${a} does not belong to model "${n}". All variables must belong to the model by object identity.`);if(!Number.isFinite(o))throw Error(`Variable "${i.name}" in ${t} has invalid coefficient: ${o}. Coefficients must be finite numbers.`)}oe(e.nonlinearTerms,t,n,r)}function F(e,t,n){if(e instanceof w){if(!Number.isFinite(e.constant))throw Error(`Objective function has invalid constant: ${e.constant}. Constant must be a finite number.`);for(let[r,i]of e.linearTerms){if(!n(r))throw Error(`Variable "${r.name}" in objective function does not belong to model "${t}". All variables must belong to the model by object identity.`);if(!Number.isFinite(i))throw Error(`Variable "${r.name}" in objective function has invalid coefficient: ${i}. Coefficients must be finite numbers.`)}for(let[,r]of e.quadTerms){if(!n(r.var1))throw Error(`Variable "${r.var1.name}" in quadratic objective function does not belong to model "${t}". All variables must belong to the model by object identity.`);if(!n(r.var2))throw Error(`Variable "${r.var2.name}" in quadratic objective function does not belong to model "${t}". All variables must belong to the model by object identity.`);if(!Number.isFinite(r.coeff)||!Number.isFinite(r.coeff*2))throw Error(`Quadratic term (${r.var1.name} * ${r.var2.name}) in objective function has invalid coefficient: ${r.coeff}.`)}oe(e.nonlinearTerms,`objective function`,t,n)}else`terms`in e&&P(e,`objective function`,t,n,{constantPrefix:`Objective function`})}function se(e,t,n,r=e.name){if(!Number.isFinite(e.rhs))throw Error(`Constraint "${r}" has invalid right-hand side (RHS): ${e.rhs}. RHS must be a finite number.`);if(N(e._requiredDiscreteVars,`Discrete constraint "${r}"`),P(e.lhs,`constraint "${r}"`,t,n),e.sense===`!=`){if(!Number.isSafeInteger(e.rhs))throw Error(`Discrete "!=" in constraint "${r}" requires a safe integer RHS, received ${e.rhs}.`);B(e.lhs,`Discrete "!=" in constraint "${r}"`)}if(e._indicatorMeta){let i=e._indicatorMeta.binVar;if(!n(i))throw Error(`Indicator binary variable "${i.name}" in constraint "${r}" does not belong to model "${t}".`);if(!(i.type===`Binary`||i.type===`Integer`&&i.lb===0&&i.ub===1))throw Error(`Indicator variable "${i.name}" in constraint "${r}" has invalid type "${i.type}" or bounds [${i.lb}, ${i.ub}]: expected Binary or Integer [0, 1].`)}}function I(e,t,n,r,i,a){if(e instanceof c){if(!i(e))throw Error(`Boolean variable "${e.name}" in logical constraint "${t}" does not belong to model "${n}".`)}else if(e instanceof l)for(let o of e.children)I(o,t,n,r,i,a);else if(e instanceof h){N(e.discreteVars,`Global constraint "${t}"`);let i=`logical constraint "${t}"`;switch(e.spec.kind){case`distinct`:for(let t of e.spec.args)P(t,i,n,r);break;case`disjoint`:for(let t of e.spec.tasks)P(t.start,i,n,r);break;case`cumulative`:for(let t of e.spec.tasks)P(t.start,i,n,r);break;case`allowed`:for(let t of e.spec.vars)P(t,i,n,r)}}else if(e instanceof R){if(a){let r=E.get(e)??e.ownerModel??void 0;if(r&&r!==a)throw Error(`Constraint "${e.name}" embedded in logical constraint "${t}" already belongs to model "${r.name??`another model`}" and cannot be added to model "${n}".`)}if(!Number.isFinite(e.rhs))throw Error(`Constraint "${e.name}" embedded in logical constraint "${t}" has invalid RHS: ${e.rhs}.`);if(N(e._requiredDiscreteVars,`Discrete constraint "${e.name}" embedded in logical constraint "${t}"`),P(e.lhs,`constraint "${e.name}" embedded in logical constraint "${t}"`,n,r,{constantPrefix:`Constraint "${e.name}" embedded in logical constraint "${t}"`,constantKind:`LHS constant`,varLocationPhrase:`embedded in logical constraint "${t}"`}),e.sense===`!=`){if(!Number.isSafeInteger(e.rhs))throw Error(`Discrete "!=" in constraint "${e.name}" embedded in logical constraint "${t}" requires a safe integer RHS, received ${e.rhs}.`);B(e.lhs,`Discrete "!=" in constraint "${e.name}" embedded in logical constraint "${t}"`)}}}function L(e){let{model:t}=e,n=new Set,r=new Set;for(let i of e.variables){M(i);let a=T.get(i);if(a&&a!==t||n.has(i.name)||e.getVarByName(i.name)!==i)throw Error(`Variable "${i.name}" is duplicated or not canonically registered in model "${e.name}".`);n.add(i.name),r.add(i)}let i=new Set,a=new Set;for(let t of e.boolVars){if(i.has(t.name)||e.getBoolVarByName(t.name)!==t)throw Error(`Boolean variable "${t.name}" is duplicated or not canonically registered in model "${e.name}".`);i.add(t.name),a.add(t)}let o=new Set;for(let t of e.constraints){if(i.has(t.name))throw Error(`Constraint name "${t.name}" conflicts with Boolean variable "${t.name}" in model "${e.name}".`);if(o.has(t.name))throw Error(`Duplicate constraint name "${t.name}" in model "${e.name}".`);o.add(t.name)}for(let t of e.logicalConstraints){if(i.has(t.name))throw Error(`Logical constraint name "${t.name}" conflicts with Boolean variable "${t.name}" in model "${e.name}".`);if(o.has(t.name))throw Error(`Conflicting constraint name "${t.name}" across arithmetic and logical constraints in model "${e.name}".`);o.add(t.name)}for(let n of e.constraints){let r=E.get(n);if(r&&r!==t||e.getConstraintByName(n.name)!==n)throw Error(`Constraint "${n.name}" is duplicated or not canonically registered in model "${e.name}".`)}for(let t of e.logicalConstraints)if(e.getLogicalConstraintByName(t.name)!==t)throw Error(`Logical constraint "${t.name}" is duplicated or not canonically registered in model "${e.name}".`);e.objectiveExpr&&F(e.objectiveExpr,e.name,e=>r.has(e));for(let t of e.constraints)se(t,e.name,e=>r.has(e));for(let n of e.logicalConstraints)I(n.expr,n.name,e.name,e=>r.has(e),e=>a.has(e),t)}var ce=0,R=class e{kind=`constraint`;id;_lhs;_sense;_rhs;_name;hasExplicitName;ownerModel=null;_indicatorOrigin;_indicatorSnapshot;_discreteVars;slack=null;dual=null;addTerm(e,t){return t===0?this:(this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._lhs.addTerm(e,t),k(this.ownerModel),this)}setTerm(e,t){return this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._lhs.setTerm(e,t),k(this.ownerModel),this}constructor(e,t,n,r){this.id=++ce,this._lhs=e,this._sense=t,this._rhs=n;let i=typeof r==`string`?r.trim():void 0;i&&i.length>0?(this._name=i,this.hasExplicitName=!0):(this._name=`c_${this.id}`,this.hasExplicitName=!1)}get lhs(){return this._lhs}set lhs(e){this._lhs!==e&&(this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._lhs=e,k(this.ownerModel))}get sense(){return this._sense}set sense(e){if(e===`!=`&&!Number.isSafeInteger(this._rhs))throw Error(`Discrete "!=" in constraint "${this._name}" requires a safe integer RHS, received ${this._rhs}.`);this._sense!==e&&(this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._sense=e,k(this.ownerModel))}get rhs(){return this._rhs}set rhs(e){if(this._sense===`!=`&&!Number.isSafeInteger(e))throw Error(`Discrete "!=" in constraint "${this._name}" requires a safe integer RHS, received ${e}.`);Object.is(this._rhs,e)||(this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._rhs=e,k(this.ownerModel))}get name(){return this._name}set name(e){this._name!==e&&(this._name=e,k(this.ownerModel)),this.hasExplicitName=!0}get _indicatorMeta(){let e=this._indicatorOrigin,t=this._indicatorSnapshot;if(!e||!t)return;if(this._lhs!==t.lhsRef||this._sense!==t.sense||!Object.is(this._rhs,t.rhs)||!Object.is(this._lhs.constant,t.constant)||this._lhs.nonlinearTerms.length>0||this._lhs.terms.size!==t.terms.size){this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0;return}for(let[e,n]of t.terms)if(!this._lhs.terms.has(e)||!Object.is(this._lhs.terms.get(e),n)){this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0;return}let n=e.targetRhs-(e.targetLhs.constant??0),r=0;for(let[t,n]of e.targetLhs.terms){if(n===0)continue;let i=e.targetSense===`<=`?n>0?t.ub:t.lb:n>0?t.lb:t.ub;if(!Number.isFinite(i)||(r+=n*i,!Number.isFinite(r)))return}if(!((e.targetSense===`<=`?r-n:n-r)>e.derivedM+1e-9))return e}_setIndicatorOrigin(e){if(!e){this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0;return}this._indicatorOrigin=e,this._indicatorSnapshot={lhsRef:this._lhs,terms:new Map(this._lhs.terms),constant:this._lhs.constant,sense:this._sense,rhs:this._rhs}}get _requiredDiscreteVars(){return this._discreteVars}_setDiscreteVars(e){this._discreteVars=e}_assignModelName(e,t){this._name=e,this.hasExplicitName=t}and(e){return new l(`and`,[this,e])}or(e){return new l(`or`,[this,e])}implies(e){return new l(`implies`,[this,e])}xor(e){return new l(`xor`,[this,e])}not(){return new l(`not`,[this])}add(e){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}sub(e){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}mul(e){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}div(e){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}neg(){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}le(e,t){throw Error(`Cannot compare a Constraint in (<=): expected a number, Var, or LinExpr.`)}ge(e,t){throw Error(`Cannot compare a Constraint in (>=): expected a number, Var, or LinExpr.`)}eq(e,t){throw Error(`Cannot compare a Constraint in (==): expected a number, Var, or LinExpr.`)}lt(e,t){throw Error(`Cannot compare a Constraint in (<): expected a number, Var, or LinExpr.`)}gt(e,t){throw Error(`Cannot compare a Constraint in (>): expected a number, Var, or LinExpr.`)}ne(e,t){throw Error(`Cannot compare a Constraint in (!=): expected a number, Var, or LinExpr.`)}get value(){throw Error(`Cannot read numeric value of a Constraint: expected a Var, LinExpr, or QuadExpr.`)}get constant(){throw Error(`Cannot read numeric constant of a Constraint: expected a LinExpr or QuadExpr.`)}clone(){let t=new e(this._lhs.clone(),this._sense,this._rhs,this.hasExplicitName?this._name:void 0);return this._discreteVars&&t._setDiscreteVars(new Set(this._discreteVars)),t}toString(){let e=this.sense===`==`?`=`:this.sense;return`${this.name}: ${this.lhs.toString()} ${e} ${this.rhs}`}};function le(e){return e instanceof R||typeof e==`object`&&!!e&&`sense`in e&&`lhs`in e&&`rhs`in e}function z(e){switch(e.kind){case`abs`:return{kind:`abs`,arg:e.arg.clone()};case`max`:return{kind:`max`,args:e.args.map(e=>e.clone())};case`min`:return{kind:`min`,args:e.args.map(e=>e.clone())};case`at`:return{kind:`at`,array:e.array.map(e=>e.clone()),index:e.index.clone(),discreteVars:new Set(e.discreteVars)}}}function ue(e){switch(e.kind){case`abs`:return`abs(${e.arg.toString()})`;case`max`:return`max(${e.args.map(e=>e.toString()).join(`, `)})`;case`min`:return`min(${e.args.map(e=>e.toString()).join(`, `)})`;case`at`:return`at([${e.array.map(e=>e.toString()).join(`, `)}], ${e.index.toString()})`}}function de(e){switch(e.kind){case`abs`:{let t=e.arg.value;return t===null?null:Math.abs(t)}case`max`:{let t=-1/0;for(let n of e.args){let e=n.value;if(e===null)return null;e>t&&(t=e)}return t}case`min`:{let t=1/0;for(let n of e.args){let e=n.value;if(e===null)return null;e<t&&(t=e)}return t}case`at`:{let t=e.index.value;if(t===null||!Number.isFinite(t))return null;let n=Math.round(t);return Math.abs(t-n)>1e-6||n<0||n>=e.array.length?null:e.array[n].value}}}function fe(e){return e instanceof W||typeof e==`object`&&!!e&&!le(e)&&typeof e.id==`number`&&typeof e.name==`string`&&typeof e.lb==`number`&&typeof e.ub==`number`&&typeof e.type==`string`&&typeof e.mul==`function`}function B(e,t,n=new Set){if(typeof e==`number`){if(!Number.isSafeInteger(e))throw Error(`${t} requires Integer or Binary variables and integer constants/coefficients, but received constant ${e}.`);return n}if(le(e))throw Error(`${t} cannot accept a Constraint comparison.`);if(e instanceof w||`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map&&typeof e.constant==`number`){let r=e;if(r.quadTerms.size>0)throw Error(`${t} does not support quadratic expressions.`);return B(new V(r.linearTerms,r.constant,r.nonlinearTerms??[]),t,n)}if(fe(e)){if(e.type!==`Integer`&&e.type!==`Binary`)throw Error(`${t} requires Integer or Binary variables, but involves Continuous variable "${e.name}".`);return n.add(e),n}if(`terms`in e&&e.terms instanceof Map){let r=e,i=r.constant??0;if(!Number.isSafeInteger(i))throw Error(`${t} requires Integer or Binary variables and integer constants/coefficients, but received constant ${i}.`);for(let[e,i]of r.terms)if(i!==0){if(e.type!==`Integer`&&e.type!==`Binary`)throw Error(`${t} requires Integer or Binary variables, but involves Continuous variable "${e.name}".`);if(!Number.isSafeInteger(i))throw Error(`${t} requires integer coefficients, but variable "${e.name}" has coefficient ${i}.`);n.add(e)}for(let e of r.nonlinearTerms??[]){if(e.coeff===0)continue;if(!Number.isSafeInteger(e.coeff))throw Error(`${t} requires integer coefficients on nonlinear expressions, received ${e.coeff}.`);let r=e.atom;if(r.kind===`abs`)B(r.arg,t,n);else if(r.kind===`max`||r.kind===`min`)for(let e of r.args)B(e,t,n);else if(r.kind===`at`){B(r.index,t,n);for(let e of r.array)B(e,t,n)}}return n}throw Error(`${t} expected an integer-valued scalar expression.`)}function pe(e,t){if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid non-finite number "${e}" in ${t}.`);return new V(new Map,Object.is(e,-0)?0:e)}if(le(e))throw t.startsWith(`sum`)?Error(`Cannot sum a constraint comparison (<=, >=, ==, !=, <, >): expected arithmetic expressions in ${t}.`):Error(`Cannot use a constraint comparison (<=, >=, ==, !=, <, >) in ${t}: expected a finite number, Var, or LinExpr.`);if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map){let n=e;if(n.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in ${t}.`);if(!Number.isFinite(n.constant))throw Error(`Invalid non-finite constant "${n.constant}" in ${t}.`);for(let[,e]of n.linearTerms)if(!Number.isFinite(e))throw Error(`Invalid non-finite coefficient "${e}" in ${t}.`);return new V(n.linearTerms,n.constant,n.nonlinearTerms??[])}if(e instanceof V||typeof e==`object`&&e&&`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`){let n=e;if(!Number.isFinite(n.constant))throw Error(`Invalid non-finite constant "${n.constant}" in ${t}.`);for(let[,e]of n.terms)if(!Number.isFinite(e))throw Error(`Invalid non-finite coefficient "${e}" in ${t}.`);return n.clone()}if(fe(e))return new V(new Map([[e,1]]),0);throw Error(`Unsupported item in ${t}: expected a finite number, Var, or LinExpr.`)}var V=class e{kind=`linear`;terms;constant;nonlinearTerms;constructor(e=new Map,t=0,n=[]){this.terms=new Map(e),this.constant=t,this.nonlinearTerms=n.filter(e=>e.coeff!==0).map(e=>({atom:z(e.atom),coeff:e.coeff}))}hasNonlinearTerms(){return this.nonlinearTerms.length>0}setTerm(e,t){return t===0?this.terms.delete(e):this.terms.set(e,t),this}addTerm(e,t){let n=(this.terms.get(e)??0)+t;return n===0?this.terms.delete(e):this.terms.set(e,n),this}clone(){return new e(this.terms,this.constant,this.nonlinearTerms)}add(e){if(le(e))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);if(e instanceof w)return e.add(this);let t=this.clone();if(typeof e==`number`)t.constant+=e;else if(`terms`in e){for(let[n,r]of e.terms){let e=(t.terms.get(n)??0)+r;e===0?t.terms.delete(n):t.terms.set(n,e)}if(t.constant+=e.constant,Array.isArray(e.nonlinearTerms))for(let n of e.nonlinearTerms)n.coeff!==0&&t.nonlinearTerms.push({atom:z(n.atom),coeff:n.coeff})}else{let n=(t.terms.get(e)??0)+1;n===0?t.terms.delete(e):t.terms.set(e,n)}return t}sub(e){if(le(e))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);return e instanceof w?e.neg().add(this):typeof e==`number`?this.add(-e):this.add(e.mul(-1))}mul(t){if(le(t))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);if(typeof t==`number`){let n=this.terms.size>0||this.nonlinearTerms.length>0,r=this.constant===0&&n?0:this.constant*t;if(this.constant!==0&&t!==0&&r===0)throw Error(`Constant multiplication underflows to zero.`);let i=new e(new Map,r);for(let[e,n]of this.terms){let r=n*t;if(n!==0&&t!==0&&r===0)throw Error(`Coefficient multiplication underflows to zero.`);r!==0&&i.terms.set(e,r)}if(t!==0)for(let e of this.nonlinearTerms){let n=e.coeff*t;if(e.coeff!==0&&n===0)throw Error(`Coefficient multiplication underflows to zero.`);n!==0&&i.nonlinearTerms.push({atom:z(e.atom),coeff:n})}return i}if(t instanceof W||typeof t==`object`&&t&&`id`in t&&!(`terms`in t)&&!(`quadTerms`in t)){if(this.hasNonlinearTerms())throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`);return w.multiplyLinearTerms(this.constant,this.terms,0,new Map([[t,1]]))}if(t instanceof w){let e=t.linearTerms.size>0||t.quadTerms.size>0||t.hasNonlinearTerms();if(this.hasNonlinearTerms()){if(!e)return this.mul(t.constant);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}if(t.hasNonlinearTerms()){if(this.terms.size===0)return t.mul(this.constant);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}return this.terms.size===0?t.mul(this.constant):new w(this.terms,new Map,this.constant).mul(t)}let n=Array.isArray(t.nonlinearTerms)&&t.nonlinearTerms.length>0;if(this.hasNonlinearTerms()){if(t.terms.size===0&&!n)return this.mul(t.constant);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}if(n){if(this.terms.size===0)return t.mul(this.constant);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}return this.terms.size===0?t.mul(this.constant):t.terms.size===0?this.mul(t.constant):w.multiplyLinearTerms(this.constant,this.terms,t.constant,t.terms)}div(e){let t=w.extractScalarDivisor(e,`LinExpr.div()`);return this.mul(1/t)}neg(){return this.mul(-1)}get value(){let e=this.constant;for(let[t,n]of this.terms){if(t.value===null)return null;e+=n*t.value}for(let t of this.nonlinearTerms){let n=de(t.atom);if(n===null)return null;e+=t.coeff*n}return e}le(e,t){return this.toConstraint(`<=`,e,t)}ge(e,t){return this.toConstraint(`>=`,e,t)}eq(e,t){return this.toConstraint(`==`,e,t)}lt(e,t){return this.toDiscreteComparison(`<`,e,t)}gt(e,t){return this.toDiscreteComparison(`>`,e,t)}ne(e,t){return this.toDiscreteComparison(`!=`,e,t)}toDiscreteComparison(e,t,n){if(t instanceof R||typeof t==`object`&&t&&`sense`in t&&`lhs`in t)throw Error(`Cannot compare against a Constraint in (${e}): expected a finite integer, discrete Var, or discrete LinExpr.`);let r=`discrete ${e}`,i=new Set;B(this,r,i),B(t,r,i);let a=this.toConstraint(e===`<`?`<=`:e===`>`?`>=`:`!=`,t,n);if(e===`<`){let e=a.rhs-1;if(!Number.isSafeInteger(e))throw Error(`Discrete comparison (<) adjusted right-hand side (${e}) exceeds safe integer range.`);a.rhs=e}else if(e===`>`){let e=a.rhs+1;if(!Number.isSafeInteger(e))throw Error(`Discrete comparison (>) adjusted right-hand side (${e}) exceeds safe integer range.`);a.rhs=e}else if(!Number.isSafeInteger(a.rhs))throw Error(`Discrete comparison (!=) adjusted right-hand side (${a.rhs}) exceeds safe integer range.`);return a._setDiscreteVars(i),a}toConstraint(t,n,r){let i=this.clone(),a=0;if(typeof n==`number`)a=n;else if(n instanceof R||typeof n==`object`&&n&&`sense`in n&&`lhs`in n)throw Error(`Cannot compare against a Constraint in (${t}): expected a number, Var, or LinExpr.`);else if(n instanceof w||typeof n==`object`&&n&&`quadTerms`in n){let r=n;if(r.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in linear constraints (${t}): quadratic terms are only allowed in objectives.`);i=i.sub(new e(r.linearTerms,0,r.nonlinearTerms??[])),a=r.constant}else`terms`in n?(i=i.sub(new e(n.terms,0,n.nonlinearTerms??[])),a=n.constant):i=i.sub(n);let o=a-i.constant;return i.constant=0,new R(i,t,o,r)}and(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'and': expected a BoolVar, Constraint, or BoolOp.`)}or(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'or': expected a BoolVar, Constraint, or BoolOp.`)}implies(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'implies': expected a BoolVar, Constraint, or BoolOp.`)}xor(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'xor': expected a BoolVar, Constraint, or BoolOp.`)}not(){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'not': expected a BoolVar, Constraint, or BoolOp.`)}toString(){let e=[],t=!0;for(let[n,r]of this.terms){let i=r>=0?t?``:`+ `:`- `,a=Math.abs(r),o=a===1?``:`${a} `;e.push(`${i}${o}${n.name}`),t=!1}for(let n of this.nonlinearTerms){let r=n.coeff,i=r>=0?t?``:`+ `:`- `,a=Math.abs(r),o=a===1?``:`${a} `;e.push(`${i}${o}${ue(n.atom)}`),t=!1}if(this.constant!==0||e.length===0){let n=this.constant>=0?t?``:`+ `:`- `;e.push(`${n}${Math.abs(this.constant)}`)}return e.join(` `)||`0`}};function H(e,t){let n=new Map,r=[],i=0;function a(e){return e instanceof R||e.kind===`constraint`||`sense`in e&&(e.sense===`<=`||e.sense===`>=`||e.sense===`==`||e.sense===`!=`)&&`lhs`in e&&`rhs`in e&&typeof e.rhs==`number`&&typeof e.lhs==`object`&&e.lhs!==null&&`terms`in e.lhs&&e.lhs.terms instanceof Map}function o(e){return e instanceof w||`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map&&typeof e.constant==`number`}function s(e){return e instanceof V||`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`}function c(e){return e instanceof W||!a(e)&&typeof e.id==`number`&&typeof e.name==`string`&&typeof e.lb==`number`&&typeof e.ub==`number`&&typeof e.type==`string`&&typeof e.mul==`function`}function l(e){return a(e)||o(e)||s(e)||c(e)}function u(e){if(typeof e!=`object`||!e||Array.isArray(e)||l(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function d(e){if(e!=null){if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid non-finite number "${e}" in sum().`);let t=i+e;if(!Number.isFinite(t))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);i=t}else if(typeof e==`object`&&a(e))throw Error(`Cannot sum a constraint comparison (<=, >=, ==) in sum(): expected a number, Var, or LinExpr.`);else if(typeof e==`object`&&o(e)){let t=e;if(t.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in sum(): sum() produces a linear expression (LinExpr).`);if(!Number.isFinite(t.constant))throw Error(`Invalid non-finite constant "${t.constant}" in sum().`);for(let[e,r]of t.linearTerms){if(!Number.isFinite(r))throw Error(`Invalid non-finite coefficient "${r}" in sum().`);let t=(n.get(e)??0)+r;if(!Number.isFinite(t))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);n.set(e,t)}let a=i+t.constant;if(!Number.isFinite(a))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);if(i=a,Array.isArray(t.nonlinearTerms))for(let e of t.nonlinearTerms){if(!Number.isFinite(e.coeff))throw Error(`Invalid non-finite coefficient "${e.coeff}" in sum().`);e.coeff!==0&&r.push({atom:z(e.atom),coeff:e.coeff})}}else if(typeof e==`object`&&s(e)){let t=e;if(!Number.isFinite(t.constant))throw Error(`Invalid non-finite constant "${t.constant}" in sum().`);for(let[e,r]of t.terms){if(!Number.isFinite(r))throw Error(`Invalid non-finite coefficient "${r}" in sum().`);let t=(n.get(e)??0)+r;if(!Number.isFinite(t))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);n.set(e,t)}let a=i+t.constant;if(!Number.isFinite(a))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);if(i=a,Array.isArray(t.nonlinearTerms))for(let e of t.nonlinearTerms){if(!Number.isFinite(e.coeff))throw Error(`Invalid non-finite coefficient "${e.coeff}" in sum().`);e.coeff!==0&&r.push({atom:z(e.atom),coeff:e.coeff})}}else if(typeof e==`object`&&c(e)){let t=e,r=(n.get(t)??0)+1;if(!Number.isFinite(r))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);n.set(t,r)}else throw Error(`Unsupported item in sum(): expected a number, Var, or LinExpr.`)}}function f(e,t=0){if(e!=null){if(typeof e==`number`){d(e);return}if(typeof e==`object`){if(l(e)){d(e);return}if(!(e instanceof String)&&!(e instanceof Map)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`){if(t>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);for(let n of e)f(n,t+1);return}if(u(e)){if(t>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in sum().`);for(let n of Object.keys(e))f(e[n],t+1);return}}d(e)}}if(typeof e==`number`){if(typeof t!=`function`)throw Error(`sum(count, mapFn) requires a mapping function as the second argument.`);if(!Number.isInteger(e)||e<0)throw Error(`sum(count, mapFn) requires a non-negative integer count.`);let n=e;for(let e=0;e<n;e++)f(t(e,e),0)}else if(typeof e==`object`&&e&&!(e instanceof String)&&(!(e instanceof Map)||typeof t==`function`)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`){let n=0;for(let r of e)t?f(t(r,n++),0):f(r,1)}else if(u(e)){if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in sum().`);let n=0;for(let r of Object.keys(e)){let i=e[r];t?f(t(i,n++),0):f(i,1)}}else throw Error(`Unsupported item in sum(): expected an Iterable, Record, or (count, mapFn).`);for(let[e,t]of n)t===0&&n.delete(e);return new V(n,i,r)}function me(e,t){let n=new Map,r=[],i=0;function a(e){return typeof e==`object`&&!!e&&!(e instanceof R)&&typeof e.id==`number`&&typeof e.name==`string`&&typeof e.lb==`number`&&typeof e.ub==`number`&&typeof e.type==`string`&&typeof e.mul==`function`&&typeof e.le==`function`}function o(e){return a(e)||e instanceof V||e instanceof w}function s(e,t,o){if(!Number.isFinite(e))throw Error(`Invalid non-finite coefficient "${e}" in dot() at '${o||`root`}'.`);if(t instanceof w)throw Error(`Quadratic expressions are not supported in dot() at '${o||`root`}': dot() produces a linear expression (LinExpr).`);if(t instanceof V){if(!Number.isFinite(t.constant))throw Error(`Invalid non-finite constant "${t.constant}" in dot() at '${o||`root`}'.`);let a=e===0||t.constant===0?0:e*t.constant;if(e!==0&&t.constant!==0&&a===0)throw Error(`Constant multiplication underflows to zero.`);if(!Number.isFinite(a))throw Error(`Coefficient multiplication overflows finite floating-point range in dot() at '${o||`root`}'.`);let s=i+a;if(!Number.isFinite(s))throw Error(`Constant accumulation overflows finite floating-point range in dot() at '${o||`root`}'.`);i=s;for(let[r,i]of t.terms){if(!Number.isFinite(i))throw Error(`Invalid non-finite coefficient "${i}" in dot() at '${o||`root`}'.`);let t=e*i;if(e!==0&&i!==0&&t===0)throw Error(`Coefficient multiplication underflows to zero.`);if(!Number.isFinite(t))throw Error(`Coefficient multiplication overflows finite floating-point range in dot() at '${o||`root`}'.`);let a=(n.get(r)??0)+t;if(!Number.isFinite(a))throw Error(`Coefficient accumulation overflows finite floating-point range in dot() at '${o||`root`}'.`);n.set(r,a)}if(Array.isArray(t.nonlinearTerms)&&e!==0)for(let n of t.nonlinearTerms){if(!Number.isFinite(n.coeff))throw Error(`Invalid non-finite coefficient "${n.coeff}" in dot() at '${o||`root`}'.`);let t=e*n.coeff;if(n.coeff!==0&&t===0)throw Error(`Coefficient multiplication underflows to zero.`);if(!Number.isFinite(t))throw Error(`Coefficient multiplication overflows finite floating-point range in dot() at '${o||`root`}'.`);t!==0&&r.push({atom:z(n.atom),coeff:t})}}else if(a(t)){let r=t,i=(n.get(r)??0)+e;if(!Number.isFinite(i))throw Error(`Coefficient accumulation overflows finite floating-point range in dot() at '${o||`root`}'.`);n.set(r,i)}else throw Error(`Cannot multiply number by non-variable/expression operand in dot() at '${o||`root`}'.`)}function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!o(e)&&!(e instanceof R)&&e.kind!==`constraint`}function l(e,t,n=``){if(e===void 0||t===void 0||e===null||t===null)throw Error(`Nullish or undefined operand encountered in dot() at '${n||`root`}'.`);if(typeof e==`number`&&typeof t==`number`)throw Error(`Cannot multiply two numbers in dot() at '${n||`root`}': expected one numeric coefficient and one Var or LinExpr.`);if(typeof e==`number`){s(e,t,n);return}if(typeof t==`number`){s(t,e,n);return}if(Array.isArray(e)||Array.isArray(t)){if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)throw Error(`Array length mismatch in dot() at '${n||`root`}': received lengths ${e.length} and ${t.length}.`);for(let r=0;r<e.length;r++)l(e[r],t[r],n?`${n}[${r}]`:`[${r}]`);return}let r=Array.isArray(e)?e:t,i=Array.isArray(e)?t:e;if(c(i)){if(Object.getOwnPropertySymbols(i).length>0)throw Error(`Symbol keys are not supported in dot() at '${n||`root`}'.`);let a=Object.keys(i);if(a.length===r.length&&a.every(e=>/^(?:0|[1-9]\d*)$/.test(e))){let a=[];for(let e=0;e<r.length;e++)Object.prototype.hasOwnProperty.call(i,e)||a.push(e);if(a.length>0)throw Error(`Key mismatch in dot() at '${n||`root`}': missing indices [${a.join(`, `)}] in numeric record.`);for(let i=0;i<r.length;i++)l(e[i],t[i],n?`${n}[${i}]`:`[${i}]`);return}throw a.length>0&&a.every(e=>/^(?:0|[1-9]\d*)$/.test(e))?Error(`Array length mismatch in dot() at '${n||`root`}': array has length ${r.length}, but object has ${a.length} indices.`):Error(`Type mismatch in dot() at '${n||`root`}': one operand is an Array while the other is an Object with keys [${a.slice(0,5).join(`, `)}].`)}throw Error(`Type mismatch in dot() at '${n||`root`}': one operand is an Array while the other is not.`)}if(c(e)&&c(t)){if(Object.getOwnPropertySymbols(e).length>0||Object.getOwnPropertySymbols(t).length>0)throw Error(`Symbol keys are not supported in dot() at '${n||`root`}'.`);let r=Object.keys(e),i=Object.keys(t),a=r.filter(e=>!Object.prototype.hasOwnProperty.call(t,e)),o=i.filter(t=>!Object.prototype.hasOwnProperty.call(e,t));if(a.length>0||o.length>0){let e=[];throw a.length>0&&e.push(`missing in second operand: [${a.join(`, `)}]`),o.length>0&&e.push(`missing in first operand: [${o.join(`, `)}]`),Error(`Key mismatch in dot() at '${n||`root`}': ${e.join(`; `)}.`)}for(let i of r)l(e[i],t[i],n?`${n}.${i}`:i);return}throw Error(`Unsupported operand types in dot() at '${n||`root`}'.`)}l(e,t);for(let[e,t]of n)t===0&&n.delete(e);return new V(n,i,r)}function he(e){let t=pe(e,`abs()`);return t.terms.size===0&&t.nonlinearTerms.length===0?new V(new Map,Math.abs(t.constant)+0):new V(new Map,0,[{atom:{kind:`abs`,arg:t},coeff:1}])}function ge(e,t){if(t.length===0)throw Error(`${e}() requires at least one expression.`);let n=[],r=e=>typeof e==`number`||le(e)||fe(e)||e instanceof V||e instanceof w||typeof e==`object`&&!!e&&(`terms`in e&&e.terms instanceof Map||`quadTerms`in e&&e.quadTerms instanceof Map),i=e=>{if(typeof e!=`object`||!e||Array.isArray(e)||r(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},a=t=>{n.push(pe(t,`${e}()`))},o=(t,n)=>{if(t==null)throw Error(`Unsupported nullish item in ${e}(): expected a finite number, Var, or LinExpr.`);if(typeof t==`number`||r(t)){a(t);return}if(Array.isArray(t)){if(n>=2)throw Error(`Nested containers deeper than 2D are not supported in ${e}().`);for(let r=0;r<t.length;r++){if(!(r in t))throw Error(`Unsupported item in ${e}(): sparse array hole at index ${r}.`);o(t[r],n+1)}return}if(typeof t==`object`&&!(t instanceof String)&&!(t instanceof Map)&&Symbol.iterator in t&&typeof t[Symbol.iterator]==`function`){if(n>=2)throw Error(`Nested containers deeper than 2D are not supported in ${e}().`);for(let e of t)o(e,n+1);return}if(i(t)){if(n>=2)throw Error(`Nested containers deeper than 2D are not supported in ${e}().`);if(Object.getOwnPropertySymbols(t).length>0)throw Error(`Symbol keys are not supported in ${e}().`);for(let e of Object.keys(t))o(t[e],n+1);return}throw Error(`Unsupported item in ${e}(): expected a finite number, Var, or LinExpr.`)};if(t.length===2&&typeof t[1]==`function`){let n=t[0],r=t[1];if(typeof n==`number`){if(!Number.isInteger(n)||n<0)throw Error(`${e}(count, mapFn) requires a non-negative integer count.`);for(let e=0;e<n;e++)o(r(e,e),0)}else if(Array.isArray(n))for(let t=0;t<n.length;t++){if(!(t in n))throw Error(`Unsupported item in ${e}(): sparse array hole at index ${t}.`);o(r(n[t],t),0)}else if(typeof n==`object`&&n&&!(n instanceof String)&&Symbol.iterator in n&&typeof n[Symbol.iterator]==`function`){let e=0;for(let t of n)o(r(t,e++),0)}else if(i(n)){if(Object.getOwnPropertySymbols(n).length>0)throw Error(`Symbol keys are not supported in ${e}().`);let t=0;for(let e of Object.keys(n))o(r(n[e],t++),0)}else throw Error(`Invalid first argument in ${e}(itemsOrCount, mapFn): expected an Iterable, Record, or non-negative integer count.`)}else for(let n of t){if(typeof n==`function`)throw Error(`Function interpolation in ${e}() is only supported as ${e}(itemsOrCount, mapFn).`);o(n,0)}if(n.length===0)throw Error(`${e}() requires at least one expression.`);return n}function _e(e,t){if(t.length===1)return t[0].clone();if(t.every(e=>e.terms.size===0&&e.nonlinearTerms.length===0)){let n=t.map(e=>e.constant),r=e===`max`?Math.max(...n):Math.min(...n);return new V(new Map,Object.is(r,-0)?0:r)}return new V(new Map,0,[{atom:{kind:e,args:t},coeff:1}])}function ve(...e){return _e(`max`,ge(`max`,e))}function ye(...e){return _e(`min`,ge(`min`,e))}function U(e,t){if(!Array.isArray(e))throw Error(`at(array, index) requires an Array as its first argument.`);if(e.length===0)throw Error(`at(array, index) requires an array with at least 1 element.`);let n=Array(e.length);for(let t=0;t<e.length;t++){if(!(t in e))throw Error(`at(array, index) encountered sparse array hole at index ${t}.`);n[t]=pe(e[t],`at() array[${t}]`)}let r=pe(t,`at() index`),i=B(r,`at() index`);return new V(new Map,0,[{atom:{kind:`at`,array:n,index:r,discreteVars:i},coeff:1}])}var be=0;function xe(e){if(e===void 0)return`Continuous`;if(typeof e==`string`){let t=e.toLowerCase();if(t===`binary`||t===`bin`)return`Binary`;if(t===`integer`||t===`int`)return`Integer`;if(t===`continuous`||t===`cont`)return`Continuous`}throw Error(`Invalid variable type "${String(e)}": expected "Continuous", "Integer", or "Binary".`)}var W=class{id;_name;prefix;hasExplicitName;ownerModel=null;_type;_lb;_ub;_initialValue;value=null;reducedCost=null;constructor(e={}){this.id=++be;let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.prefix==`string`?e.prefix.trim():``;this.prefix=n.length>0?n:`x`,this.hasExplicitName=t.length>0,this._name=this.hasExplicitName?t:`${this.prefix}_${this.id}`,this._type=xe(e.type),this._type===`Binary`?(this._lb=0,this._ub=1):(this._lb=e.lb===void 0?0:e.lb,this._ub=e.ub===void 0?1/0:e.ub),this._initialValue=e.initialValue===void 0?void 0:Object.is(e.initialValue,-0)?0:e.initialValue,this._initialValue!==void 0&&M(this)}get name(){return this._name}get type(){return this._type}set type(e){let t=xe(e);this._type!==t&&(this._type=t,k(this.ownerModel))}get lb(){return this._lb}set lb(e){Object.is(this._lb,e)||(this._lb=e,k(this.ownerModel))}get ub(){return this._ub}set ub(e){Object.is(this._ub,e)||(this._ub=e,k(this.ownerModel))}get initialValue(){return this._initialValue}set initialValue(e){let t=e!==void 0&&Object.is(e,-0)?0:e;Object.is(this._initialValue,t)||(this._initialValue=t,k(this.ownerModel))}_assignModelName(e){this._name=e}mul(e){return typeof e==`number`?new V(new Map([[this,1]]),0).mul(e):new w(new Map([[this,1]]),new Map,0).mul(e)}add(e){return e instanceof w?e.add(this):new V(new Map([[this,1]]),0).add(e)}sub(e){return e instanceof w?e.neg().add(this):new V(new Map([[this,1]]),0).sub(e)}neg(){return this.mul(-1)}le(e,t){return new V(new Map([[this,1]]),0).le(e,t)}ge(e,t){return new V(new Map([[this,1]]),0).ge(e,t)}eq(e,t){return new V(new Map([[this,1]]),0).eq(e,t)}lt(e,t){return new V(new Map([[this,1]]),0).lt(e,t)}gt(e,t){return new V(new Map([[this,1]]),0).gt(e,t)}ne(e,t){return new V(new Map([[this,1]]),0).ne(e,t)}toString(){return this.name}};function G(e){return typeof e==`object`&&!!e&&e.kind===`container`}var Se=/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/;function Ce(e,t){let n=[],r=0,i=e.length;for(;r<i;){let a=e[r];if(/\s/.test(a)){r++;continue}if(a===`+`)n.push({type:`PLUS`,value:`+`}),r++;else if(a===`-`)n.push({type:`MINUS`,value:`-`}),r++;else if(a===`*`)r+1<i&&e[r+1]===`*`?(n.push({type:`CARET`,value:`**`}),r+=2):(n.push({type:`STAR`,value:`*`}),r++);else if(a===`^`)n.push({type:`CARET`,value:`^`}),r++;else if(a===`/`)n.push({type:`SLASH`,value:`/`}),r++;else if(a===`(`)n.push({type:`LPAREN`,value:`(`}),r++;else if(a===`)`)n.push({type:`RPAREN`,value:`)`}),r++;else if(a===`,`)n.push({type:`COMMA`,value:`,`}),r++;else if(a===`<`||a===`>`||a===`=`||a===`!`){let t=a;if(r+1<i&&(e[r+1]===`=`||a!==`!`&&(e[r+1]===`<`||e[r+1]===`>`))?(t+=e[r+1],r+=2):r++,t===`!`)throw Error(`Unexpected character '!' at position ${r-1} in: "${e}"`);n.push({type:`COMP`,value:t})}else if(/[0-9.]/.test(a)){let t=r,a=``;for(;r<i&&/[0-9]/.test(e[r]);)a+=e[r++];if(r<i&&e[r]===`.`)for(a+=e[r++];r<i&&/[0-9]/.test(e[r]);)a+=e[r++];if(r<i&&(e[r]===`e`||e[r]===`E`)){let t=r+1<i?e[r+1]:``;if(!/[a-zA-Z_]/.test(t)){for(a+=e[r++],r<i&&(e[r]===`+`||e[r]===`-`)&&(a+=e[r++]);r<i&&/[0-9]/.test(e[r]);)a+=e[r++];for(;r<i&&(e[r]===`.`||e[r]===`e`||e[r]===`E`||/[0-9]/.test(e[r]));)a+=e[r++]}}else for(;r<i&&(e[r]===`.`||/[0-9]/.test(e[r]));)a+=e[r++];if(!Se.test(a))throw Error(`Invalid numeric literal '${a}' at position ${t} in: "${e}"`);let o=Number(a);if(!Number.isFinite(o))throw Error(`Numeric literal '${a}' overflows finite floating-point range in: "${e}"`);if(o===0&&!/^[0.]+(?:[eE][+-]?\d+)?$/.test(a))throw Error(`Numeric literal '${a}' underflows to zero at position ${t} in: "${e}"`);n.push({type:`NUMBER`,value:a,numericValue:o})}else if(/[a-zA-Z_]/.test(a)){let a=``;for(;r<i&&/[a-zA-Z0-9_]/.test(e[r]);)a+=e[r],r++;if(t&&t.has(a)){let e=t.get(a);n.push({type:`NUMBER`,value:String(e),numericValue:e})}else n.push({type:`IDENT`,value:a})}else throw Error(`Unexpected character '${a}' at position ${r} in: "${e}"`)}return n}function we(e){return e instanceof w&&e.quadTerms.size===0?new V(e.linearTerms,e.constant,e.nonlinearTerms):e}function Te(e){return typeof e==`number`||e instanceof W||e instanceof V||e instanceof w||ze(e)}function Ee(e){return typeof e==`number`?new V(new Map,e):e instanceof W||`id`in e&&!(`terms`in e)&&!(`quadTerms`in e)?new V(new Map([[e,1]]),0):e.clone()}function De(e,t,n){if(typeof e==`number`&&typeof t==`number`){if(n===`+`){let n=e+t;if(!Number.isFinite(n))throw Error(`Invalid non-finite constant "${n}" in expression.`);return n}if(n===`-`){let n=e-t;if(!Number.isFinite(n))throw Error(`Invalid non-finite constant "${n}" in expression.`);return n}if(n===`*`){let n=e*t;if(e!==0&&t!==0&&n===0)throw Error(`Constant multiplication underflows to zero.`);if(!Number.isFinite(n))throw Error(`Invalid non-finite constant "${n}" in expression.`);return n}if(t===0)throw Error(`Division by zero`);let r=1/t*e;if(e!==0&&r===0)throw Error(`Constant multiplication underflows to zero.`);if(!Number.isFinite(r))throw Error(`Invalid non-finite constant "${r}" in expression.`);return r}let r=Ee(e),i=Ee(t),a;a=n===`+`?r.add(i):n===`-`?r.sub(i):n===`*`?r.mul(i):r.div(i);let o=we(a);return X(o),o}function K(e,t){if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++){let i=e[r];n[r]=Te(i)?t(i):K(i,t)}return n}let n=Object.create(null);for(let r of Object.keys(e)){let i=e[r];n[r]=Te(i)?t(i):K(i,t)}return n}function Oe(e,t,n,r=``){let i=Te(e),a=Te(t);if(i&&a)return De(e,t,n);if(i||a)throw Error(`Dimension mismatch in template expression at '${r||`root`}': cannot combine scalar element with sub-container.`);if(Array.isArray(e)||Array.isArray(t)){if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)throw Error(`Array length mismatch in template expression at '${r||`root`}': received lengths ${e.length} and ${t.length}.`);let i=Array(e.length);for(let a=0;a<e.length;a++)i[a]=Oe(e[a],t[a],n,r?`${r}[${a}]`:`[${a}]`);return i}let i=Array.isArray(e)?e:t,a=Array.isArray(e)?t:e,o=Object.keys(a);if(o.length===i.length&&o.every(e=>/^(?:0|[1-9]\d*)$/.test(e))){let o=[];for(let e=0;e<i.length;e++)Object.prototype.hasOwnProperty.call(a,e)||o.push(e);if(o.length>0)throw Error(`Key mismatch in template expression at '${r||`root`}': missing indices [${o.join(`, `)}] in numeric record.`);let s=Array(i.length);for(let a=0;a<i.length;a++){let i=e[a],o=t[a];s[a]=Oe(i,o,n,r?`${r}[${a}]`:`[${a}]`)}return s}throw o.length>0&&o.every(e=>/^(?:0|[1-9]\d*)$/.test(e))?Error(`Array length mismatch in template expression at '${r||`root`}': array has length ${i.length}, but object has ${o.length} indices.`):Error(`Type mismatch in template expression at '${r||`root`}': one operand is an Array while the other is an Object with keys [${o.slice(0,5).join(`, `)}].`)}let o=e,s=t,c=Object.keys(o),l=Object.keys(s),u=c.filter(e=>!Object.prototype.hasOwnProperty.call(s,e)),d=l.filter(e=>!Object.prototype.hasOwnProperty.call(o,e));if(u.length>0||d.length>0){let e=[];throw u.length>0&&e.push(`missing in second operand: [${u.join(`, `)}]`),d.length>0&&e.push(`missing in first operand: [${d.join(`, `)}]`),Error(`Key mismatch in template expression at '${r||`root`}': ${e.join(`; `)}.`)}let f=Object.create(null);for(let e of c)f[e]=Oe(o[e],s[e],n,r?`${r}.${e}`:e);return f}function q(e,t,n){let r=G(e),i=G(t);if(!r&&!i)return De(e,t,n);if(r&&!i)return{kind:`container`,data:K(e.data,e=>De(e,t,n)),fromNonArrayIterable:e.fromNonArrayIterable};if(!r&&i)return{kind:`container`,data:K(t.data,t=>De(e,t,n)),fromNonArrayIterable:t.fromNonArrayIterable};let a=e,o=t;return{kind:`container`,data:Oe(a.data,o.data,n),fromNonArrayIterable:a.fromNonArrayIterable||o.fromNonArrayIterable}}function ke(e){return typeof e==`number`?-e:G(e)?{kind:`container`,data:K(e.data,e=>typeof e==`number`?-e:Ee(e).neg()),fromNonArrayIterable:e.fromNonArrayIterable}:e.neg()}function Ae(e,t){let n=e instanceof w,r=n?e.quadTerms.size:0,i=n?e.linearTerms.size:e.terms.size,a=Array.isArray(e.nonlinearTerms)?e.nonlinearTerms.length:0;if(r===0&&i===0&&a===0){let n=e.constant**+t;if(e.constant!==0&&t>0&&n===0)throw Error(`Constant exponentiation underflows to zero.`);return new V(new Map,n)}if(t===0)return new V(new Map,1);if(t===1)return e;if(a>0)throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`);if(t===2)return e.mul(e);throw Error(`Exponent ${t} creates a non-linear term of degree > 2 (not allowed in MILP/LP/QP)`)}function je(e){if(typeof e!=`object`||!e||Array.isArray(e)||ze(e)||Be(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Me(e){if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid numeric value "${e}" in template expression: interpolated numbers must be finite.`);return e}if(Be(e))throw Error(`Cannot interpolate a constraint comparison (<=, >=, ==) inside a template expression: expected a finite number, Var, LinExpr, or QuadExpr.`);if(ze(e))return X(e),e instanceof W||`id`in e&&!(`terms`in e)&&!(`quadTerms`in e)?e:e.clone();throw Error(`Unsupported interpolation value in template expression: expected a finite number, Var, LinExpr, or QuadExpr.`)}function Ne(e){return typeof e==`object`&&!!e&&!(e instanceof String)&&!(e instanceof Map)&&!ze(e)&&!Be(e)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`}function Pe(e,t=0){if(Array.isArray(e)){let n=!1,r=Array(e.length);for(let i=0;i<e.length;i++){if(!(i in e))throw Error(`Unsupported interpolation value in template expression: sparse array hole at index ${i}.`);let a=e[i];if(Array.isArray(a)||je(a)||Ne(a)){if(t>=1)throw Error(`Nested containers deeper than 2D are not supported in template expressions.`);let e=Pe(a,t+1);e.fromNonArrayIterable&&(n=!0),r[i]=e.data}else r[i]=Me(a)}return{kind:`container`,data:r,fromNonArrayIterable:n}}if(Ne(e))return{kind:`container`,data:Array.from(e).map(e=>{if(Array.isArray(e)||je(e)||Ne(e)){if(t>=1)throw Error(`Nested containers deeper than 2D are not supported in template expressions.`);return Pe(e,t+1).data}return Me(e)}),fromNonArrayIterable:!0};if(je(e)){if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in template expression at 'root'.`);let n=!1,r=Object.create(null);for(let i of Object.keys(e)){let a=e[i];if(Array.isArray(a)||je(a)||Ne(a)){if(t>=1)throw Error(`Nested containers deeper than 2D are not supported in template expressions.`);let e=Pe(a,t+1);e.fromNonArrayIterable&&(n=!0),r[i]=e.data}else r[i]=Me(a)}return{kind:`container`,data:r,fromNonArrayIterable:n}}throw Error(`Unsupported interpolation value in template expression: expected a finite number, Var, LinExpr, or QuadExpr.`)}var Fe=class{tokens;pos=0;resolver;templateCtx;constructor(e,t,n){this.tokens=e,this.resolver=t,this.templateCtx=n}peek(){return this.tokens[this.pos]}consume(e){let t=this.tokens[this.pos++];if(!t)throw Error(`Unexpected end of input`);if(e&&t.value!==e&&t.type!==e)throw Error(`Expected '${e}', but found '${t.value}'`);return t}parseExpression(){let e=this.parseExpressionNode();if(G(e))throw Error(`Container expression (Array or Record) cannot be used directly as a scalar expression or constraint; wrap it in sum(...) or use dot(a, b).`);return typeof e==`number`?new V(new Map,e):we(e)}parseExpressionNode(){let e=this.parseTermNode();for(;this.pos<this.tokens.length;){let t=this.peek();if(!t)break;if(t.type===`PLUS`)this.consume(),e=q(e,this.parseTermNode(),`+`);else if(t.type===`MINUS`)this.consume(),e=q(e,this.parseTermNode(),`-`);else break}return G(e)||typeof e==`number`?e:we(e)}parseTermNode(){let e=this.parseFactorNode();for(;this.pos<this.tokens.length;){let t=this.peek();if(!t)break;if(t.type===`STAR`)this.consume(),e=q(e,this.parseFactorNode(),`*`);else if(t.type===`SLASH`)this.consume(),e=q(e,this.parseFactorNode(),`/`);else break}return e}parseFactorNode(){let e=this.peek();if(!e)throw Error(`Unexpected end of expression`);if(e.type===`PLUS`)return this.consume(),this.parseFactorNode();if(e.type===`MINUS`)return this.consume(),ke(this.parseFactorNode());let t;if(e.type===`NUMBER`){this.consume();let n=e.numericValue??Number(e.value);if(this.peek()?.type===`IDENT`||this.peek()?.type===`LPAREN`){let e=this.parsePrimaryNode();return q(this.applyPowerNode(e),n,`*`)}t=n}else if(e.type===`IDENT`||e.type===`LPAREN`)t=this.parsePrimaryNode();else throw Error(`Unexpected token '${e.value}' in expression`);return this.applyPowerNode(t)}parsePrimaryNode(){if(this.peek()?.type===`IDENT`){let e=this.consume();return(e.value===`sum`||e.value===`dot`||e.value===`abs`||e.value===`max`||e.value===`min`||e.value===`at`)&&this.peek()?.type===`LPAREN`?this.parseFunctionCall(e.value):this.resolveNode(e.value)}this.consume(`LPAREN`);let e=this.parseExpressionNode();return this.consume(`RPAREN`),e}parseFunctionCall(e){this.consume(`LPAREN`);let t=1;for(let n=this.pos;n<this.tokens.length&&t>0;n++){let r=this.tokens[n];if(r.type===`LPAREN`)t++;else if(r.type===`RPAREN`)t--;else if(r.type===`COMP`)throw Error(e===`sum`?`Cannot sum a constraint comparison (<=, >=, ==, !=, <, >) in sum(): expected arithmetic expressions.`:e===`dot`?`Cannot use a constraint comparison (<=, >=, ==, !=, <, >) in dot(): expected 1D or 2D Array or Record containers.`:`Cannot use a constraint comparison (<=, >=, ==, !=, <, >) in ${e}(): expected arithmetic expressions.`)}if(this.peek()?.type===`RPAREN`)throw this.consume(`RPAREN`),Error(e===`dot`?`dot() in template expression requires exactly 2 arguments: dot(a, b).`:e===`at`?`at() in template expression requires exactly 2 arguments: at(array, index).`:e===`abs`?`abs() in template expression requires 1 argument.`:`${e}() in template expression requires at least 1 argument.`);if(e===`abs`){let e=this.parseExpressionNode();if(this.peek()?.type===`COMMA`)throw Error(`abs() in template expression accepts exactly 1 argument.`);return this.consume(`RPAREN`),G(e)?{kind:`container`,data:K(e.data,e=>he(e)),fromNonArrayIterable:e.fromNonArrayIterable}:he(e)}if(e===`at`){let e=this.parseExpressionNode();if(this.peek()?.type!==`COMMA`)throw Error(`at() in template expression requires exactly 2 arguments: at(array, index).`);this.consume(`COMMA`);let t=this.parseExpressionNode();if(this.peek()?.type===`COMMA`)throw Error(`at() in template expression requires exactly 2 arguments: at(array, index).`);if(this.consume(`RPAREN`),!G(e)||e.fromNonArrayIterable||!Array.isArray(e.data))throw Error(`at(array, index) requires a 1D Array as its first argument.`);if(G(t))throw Error(`at(array, index) requires a discrete scalar expression as its index.`);let n=U(e.data,t);return X(n),n}if(e===`max`||e===`min`){let t=this.pos,n=0;for(;this.tokens[t]?.type===`LPAREN`;)n++,t++;if(this.tokens[t]?.type===`IDENT`&&this.templateCtx?.rawContainerMap.has(this.tokens[t].value)){let r=this.tokens[t].value,i=t+1,a=0;for(;a<n&&this.tokens[i]?.type===`RPAREN`;)a++,i++;if(a===n&&this.tokens[i]?.type===`COMMA`){let t=this.tokens[i+1];if(t?.type===`IDENT`&&this.templateCtx.functionMap.has(t.value)&&this.tokens[i+2]?.type===`RPAREN`){this.pos=i+2,this.consume(`RPAREN`);let n=this.templateCtx.functionMap.get(t.value);return this.evalExtremumWithMapper(e,this.templateCtx.rawContainerMap.get(r),n)}}}if(this.tokens[this.pos]?.type===`IDENT`&&this.templateCtx?.rawContainerMap.has(this.tokens[this.pos].value)&&this.tokens[this.pos+1]?.type===`RPAREN`){let t=this.consume();this.consume(`RPAREN`);let n=this.templateCtx.rawContainerMap.get(t.value),r=e===`max`?ve(n):ye(n);return X(r),r}let r=this.parseExpressionNode();if(this.peek()?.type===`COMMA`){let t=this.tokens[this.pos+1];if(t&&t.type===`IDENT`&&this.templateCtx?.functionMap.has(t.value)){this.consume(`COMMA`);let t=this.consume();if(this.peek()?.type===`COMMA`)throw Error(`${e}(itemsOrCount, mapFn) accepts at most 2 arguments when using a mapper.`);this.consume(`RPAREN`);let n=this.templateCtx.functionMap.get(t.value);if(typeof r==`number`)return this.evalExtremumWithMapper(e,r,n);if(!G(r)&&r instanceof V&&r.terms.size===0&&r.nonlinearTerms.length===0)return this.evalExtremumWithMapper(e,r.constant,n);if(G(r))return this.evalExtremumWithMapper(e,r.data,n);throw Error(`Invalid first argument in ${e}(itemsOrCount, mapFn): expected an Iterable, Record, or non-negative integer count.`)}let n=[G(r)?r.data:r];for(;this.peek()?.type===`COMMA`;){this.consume(`COMMA`);let e=this.parseExpressionNode();n.push(G(e)?e.data:e)}this.consume(`RPAREN`);let i=e===`max`?ve(...n):ye(...n);return X(i),i}this.consume(`RPAREN`);let i=G(r)?r.data:r,a=e===`max`?ve(i):ye(i);return X(a),a}if(e===`sum`){if(this.tokens[this.pos]?.type===`IDENT`&&this.templateCtx?.rawContainerMap.has(this.tokens[this.pos].value)&&this.tokens[this.pos+1]?.type===`RPAREN`){let e=this.consume();this.consume(`RPAREN`);let t=this.templateCtx.rawContainerMap.get(e.value);return this.accumulateSumItems(e=>{e(t,0)})}let e=this.pos,t=0;for(;this.tokens[e]?.type===`LPAREN`;)t++,e++;if(this.tokens[e]?.type===`IDENT`&&this.templateCtx?.rawContainerMap.has(this.tokens[e].value)){let n=this.tokens[e].value,r=e+1,i=0;for(;i<t&&this.tokens[r]?.type===`RPAREN`;)i++,r++;if(i===t&&this.tokens[r]?.type===`COMMA`){this.pos=r+1;let e=this.peek();if(!e||e.type!==`IDENT`||!this.templateCtx.functionMap.has(e.value))throw Error(`Second argument to sum() must be a mapping function: sum(itemsOrCount, mapFn).`);if(this.consume(),this.peek()?.type===`COMMA`)throw Error(`sum() in template expression accepts at most 2 arguments: sum(container) or sum(itemsOrCount, mapFn).`);return this.consume(`RPAREN`),this.evalSumWithMapper(this.templateCtx.rawContainerMap.get(n),this.templateCtx.functionMap.get(e.value))}}let n=this.parseExpressionNode();if(this.peek()?.type===`COMMA`){this.consume(`COMMA`);let e=this.peek();if(!e||e.type!==`IDENT`||!this.templateCtx?.functionMap.has(e.value))throw Error(`Second argument to sum() must be a mapping function: sum(itemsOrCount, mapFn).`);if(this.consume(),this.peek()?.type===`COMMA`)throw Error(`sum() in template expression accepts at most 2 arguments: sum(container) or sum(itemsOrCount, mapFn).`);this.consume(`RPAREN`);let t=this.templateCtx.functionMap.get(e.value);if(typeof n==`number`)return this.evalSumWithMapper(n,t);if(!G(n)&&n instanceof V&&n.terms.size===0)return this.evalSumWithMapper(n.constant,t);if(G(n))return this.evalSumWithMapper(n.data,t);throw Error(`Invalid first argument in sum(itemsOrCount, mapFn): expected an Iterable, Record, or non-negative integer count.`)}return this.consume(`RPAREN`),this.evalSumSingle(n)}let n=this.parseExpressionNode();if(this.peek()?.type!==`COMMA`)throw Error(`dot() in template expression requires exactly 2 arguments: dot(a, b).`);this.consume(`COMMA`);let r=this.parseExpressionNode();if(this.peek()?.type===`COMMA`)throw Error(`dot() in template expression requires exactly 2 arguments: dot(a, b).`);return this.consume(`RPAREN`),this.evalDot(n,r)}accumulateSumItems(e){let t=new Map,n=new Map,r=[],i=0,a=(e,o=0)=>{if(e!=null){if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid non-finite number "${e}" in sum().`);let t=i+e;if(!Number.isFinite(t))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);i=t;return}if(Be(e))throw Error(`Cannot sum a constraint comparison (<=, >=, ==) in sum(): expected a number, Var, LinExpr, or QuadExpr.`);if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map){let a=e;X(a);let o=i+a.constant;if(!Number.isFinite(o))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);i=o;for(let[e,n]of a.linearTerms){let r=(t.get(e)??0)+n;if(!Number.isFinite(r))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);t.set(e,r)}for(let[e,t]of a.quadTerms){let r=n.get(e);if(r){let i=r.coeff+t.coeff;if(!Number.isFinite(i))throw Error(`Quadratic coefficient accumulation overflows finite floating-point range in sum().`);n.set(e,{var1:t.var1,var2:t.var2,coeff:i})}else n.set(e,{var1:t.var1,var2:t.var2,coeff:t.coeff})}if(Array.isArray(a.nonlinearTerms))for(let e of a.nonlinearTerms)e.coeff!==0&&r.push({atom:z(e.atom),coeff:e.coeff});return}if(e instanceof V||typeof e==`object`&&e&&`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`){let n=e;X(n);let a=i+n.constant;if(!Number.isFinite(a))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);i=a;for(let[e,r]of n.terms){let n=(t.get(e)??0)+r;if(!Number.isFinite(n))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);t.set(e,n)}if(Array.isArray(n.nonlinearTerms))for(let e of n.nonlinearTerms)e.coeff!==0&&r.push({atom:z(e.atom),coeff:e.coeff});return}if(ze(e)){let n=e,r=(t.get(n)??0)+1;if(!Number.isFinite(r))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);t.set(n,r);return}if(Array.isArray(e)){if(o>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);for(let t=0;t<e.length;t++){if(!(t in e))throw Error(`Unsupported item in sum(): sparse array hole at index ${t}.`);a(e[t],o+1)}return}if(Ne(e)){if(o>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);for(let t of e)a(t,o+1);return}if(je(e)){if(o>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in sum().`);for(let t of Object.keys(e))a(e[t],o+1);return}throw Error(`Unsupported item in sum(): expected a number, Var, LinExpr, or QuadExpr.`)}};e(a);for(let[e,n]of t)n===0&&t.delete(e);for(let[e,t]of n)t.coeff===0&&n.delete(e);return n.size>0?new w(t,n,i,r):new V(t,i,r)}evalExtremumWithMapper(e,t,n){let r=e===`max`?ve(t,n):ye(t,n);return X(r),r}evalSumSingle(e){if(!G(e))throw Error(`sum() requires a container (Array, Iterable, or Record) or (itemsOrCount, mapFn).`);return this.accumulateSumItems(t=>{t(e.data,0)})}evalSumWithMapper(e,t){return this.accumulateSumItems(n=>{if(typeof e==`number`){if(!Number.isInteger(e)||e<0)throw Error(`sum(count, mapFn) requires a non-negative integer count.`);for(let r=0;r<e;r++)n(t(r,r));return}if(Array.isArray(e)){for(let r=0;r<e.length;r++){if(!(r in e))throw Error(`Unsupported item in sum(): sparse array hole at index ${r}.`);n(t(e[r],r))}return}if(typeof e==`object`&&e&&!(e instanceof String)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`){let r=0;for(let i of e)n(t(i,r++));return}if(je(e)){if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in sum().`);let r=0;for(let i of Object.keys(e))n(t(e[i],r++));return}throw Error(`Invalid first argument in sum(itemsOrCount, mapFn): expected an Iterable, Record, or non-negative integer count.`)})}evalDot(e,t){if(!G(e)||!G(t))throw Error(`dot() in template expression requires 1D or 2D Array or Record containers as arguments.`);if(e.fromNonArrayIterable||t.fromNonArrayIterable)throw Error(`Unsupported operand types in dot() at 'root': dot() requires Array or Record containers (use sum() for general Iterables).`);let n=me(e.data,t.data);return X(n),n}applyPowerNode(e){if(this.peek()?.type!==`CARET`)return e;let t=[];for(;this.peek()?.type===`CARET`;){this.consume();let e=this.tokens[this.pos]?.type===`LPAREN`&&this.tokens[this.pos+1]?.type===`NUMBER`&&this.tokens[this.pos+2]?.type===`RPAREN`;e&&this.consume(`LPAREN`);let n=this.peek();if(!n||n.type!==`NUMBER`)throw Error(`Exponent must be a non-negative integer number`);this.consume(),e&&this.consume(`RPAREN`);let r=n.numericValue??Number(n.value);if(!Number.isInteger(r)||r<0)throw Error(`Exponent must be a non-negative integer`);t.push(r)}let n=t[t.length-1];for(let e=t.length-2;e>=0;e--)n=t[e]**+n;if(!Number.isFinite(n)||n<0)throw Error(`Exponent creates an invalid or out-of-range power`);if(typeof e==`number`){let t=e**+n;if(e!==0&&n>0&&t===0)throw Error(`Constant exponentiation underflows to zero.`);if(!Number.isFinite(t))throw Error(`Invalid non-finite constant "${t}" in expression.`);return t}return G(e)?{kind:`container`,data:K(e.data,e=>{if(typeof e==`number`){let t=e**+n;if(e!==0&&n>0&&t===0)throw Error(`Constant exponentiation underflows to zero.`);if(!Number.isFinite(t))throw Error(`Constant exponentiation overflows finite floating-point range.`);return t}let t=we(Ae(Ee(e),n));return X(t),t}),fromNonArrayIterable:e.fromNonArrayIterable}:Ae(e,n)}getRemainingToken(){return this.peek()}resolveNode(e){if(this.templateCtx?.functionMap.has(e))throw Error(`Function interpolation is only supported as the second argument of sum(itemsOrCount, mapFn) in template expressions.`);if(this.templateCtx?.rawContainerMap.has(e))return Pe(this.templateCtx.rawContainerMap.get(e));let t=this.resolver(e);if(!t)throw Error(`Unknown variable '${e}' in expression`);return t instanceof W||`id`in t&&!(`terms`in t)&&!(`quadTerms`in t)?new V(new Map([[t,1]]),0):t.clone()}};function J(e,t,n,r){let i=new Fe(Ce(e,n),t,r),a=i.parseExpression(),o=i.getRemainingToken();if(o)throw Error(`Unexpected token '${o.value}' after expression in "${e}"`);return X(a),a}function Ie(e,t){return J(e,t)}function Y(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`(`)t++;else if(r===`)`)t>0&&t--;else if(t===0){let t=e.slice(n,n+2);if(t===`<=`||t===`>=`||t===`==`||t===`!=`||t===`=<`||t===`=>`)return{rawOp:t,index:n};if(r===`=`||r===`<`||r===`>`)return{rawOp:r,index:n}}}return null}function Le(e,t,n,r,i){let a=Y(e);if(!a)throw Error(`Constraint must contain a comparison operator (<=, >=, ==, !=, <, >): "${e}"`);let o=a.rawOp,s=a.index,c=e.substring(0,s).trim(),l=e.substring(s+o.length).trim(),u;if(o===`<=`||o===`=<`)u=`<=`;else if(o===`>=`||o===`=>`)u=`>=`;else if(o===`==`||o===`=`)u=`==`;else if(o===`!=`)u=`!=`;else if(o===`<`)u=`<`;else if(o===`>`)u=`>`;else throw Error(`Unsupported operator "${o}"`);let d=J(c,t,r,i),f=J(l,t,r,i);if(d instanceof w&&d.quadTerms.size>0||f instanceof w&&f.quadTerms.size>0)throw Error(`Quadratic constraints are not supported (only linear constraints are allowed in MILP/LP/QP)`);let p=d instanceof w?new V(d.linearTerms,d.constant,d.nonlinearTerms):d,m=f instanceof w?new V(f.linearTerms,f.constant,f.nonlinearTerms):f,h;if(h=u===`<=`?p.le(m,n):u===`>=`?p.ge(m,n):u===`==`?p.eq(m,n):u===`!=`?p.ne(m,n):u===`<`?p.lt(m,n):p.gt(m,n),X(h.lhs),!Number.isFinite(h.rhs))throw Error(`Invalid non-finite right-hand side "${h.rhs}" in constraint.`);return h}function Re(e,t,n){return Le(e,t,n)}function ze(e){return e instanceof W||e instanceof V||e instanceof w?!0:typeof e!=`object`||!e||Be(e)?!1:`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`||`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map&&typeof e.constant==`number`||typeof e.id==`number`&&typeof e.name==`string`&&typeof e.lb==`number`&&typeof e.ub==`number`&&typeof e.type==`string`&&typeof e.mul==`function`}function X(e){if(`constant`in e&&!Number.isFinite(e.constant))throw Error(`Invalid non-finite constant "${e.constant}" in expression.`);if(`terms`in e&&e.terms instanceof Map){for(let[,t]of e.terms)if(!Number.isFinite(t))throw Error(`Invalid non-finite coefficient "${t}" in expression.`)}if(`linearTerms`in e&&e.linearTerms instanceof Map){for(let[,t]of e.linearTerms)if(!Number.isFinite(t))throw Error(`Invalid non-finite coefficient "${t}" in expression.`)}if(`quadTerms`in e&&e.quadTerms instanceof Map){for(let[,t]of e.quadTerms)if(!Number.isFinite(t.coeff))throw Error(`Invalid non-finite quadratic coefficient "${t.coeff}" in expression.`)}if(`nonlinearTerms`in e&&Array.isArray(e.nonlinearTerms))for(let t of e.nonlinearTerms){if(!Number.isFinite(t.coeff))throw Error(`Invalid non-finite coefficient "${t.coeff}" in expression.`);if(t.atom.kind===`abs`)X(t.atom.arg);else if(t.atom.kind===`max`||t.atom.kind===`min`)for(let e of t.atom.args)X(e);else if(t.atom.kind===`at`){X(t.atom.index);for(let e of t.atom.array)X(e)}}}function Be(e){return e instanceof R?!0:typeof e!=`object`||!e?!1:e.kind===`constraint`||`sense`in e&&(e.sense===`<=`||e.sense===`>=`||e.sense===`==`||e.sense===`!=`)&&`lhs`in e&&`rhs`in e&&typeof e.rhs==`number`&&typeof e.lhs==`object`&&e.lhs!==null&&`terms`in e.lhs&&e.lhs.terms instanceof Map}function Ve(e,t){let n=new Map,r=new Map,i=new Map,a=new Map,o=e.join(``),s=`__washi_`;for(;o.includes(s);)s+=`_`;let c=``;for(let o=0;o<e.length;o++)if(c+=e[o],o<t.length){let e=t[o];if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid numeric value "${e}" in template expression: interpolated numbers must be finite.`);let t=`${s}num_${o}__`;r.set(t,e),c+=`(${t})`}else if(Be(e))throw Error(`Cannot interpolate a constraint comparison (<=, >=, ==) inside a template expression: expected a finite number, Var, LinExpr, or QuadExpr.`);else if(ze(e)){X(e);let t=`${s}ph_${o}__`;n.set(t,e),c+=` ${t} `}else if(typeof e==`function`){let t=`${s}fn_${o}__`;a.set(t,e),c+=` ${t} `}else if(Array.isArray(e)||Ne(e)||e instanceof Map||je(e)){let t=`${s}ph_${o}__`;i.set(t,e),c+=` ${t} `}else throw Error(`Unsupported interpolation value in template expression: expected a finite number, Var, LinExpr, or QuadExpr.`)}return{fullText:c,resolver:e=>n.get(e),numberMap:r,templateCtx:{rawContainerMap:i,functionMap:a}}}function He(e,...t){let{fullText:n,resolver:r,numberMap:i,templateCtx:a}=Ve(e,t);return Y(n)?Le(n,r,void 0,i,a):J(n,r,i,a)}function Ue(e){return typeof e==`object`&&!!e&&typeof e.lpString==`string`&&e.nameToVar instanceof Map&&e.nameToConstraint instanceof Map}function We(e,t=`x`,n=0){let r=e.replace(/[^a-zA-Z0-9_]/g,`_`);return/^[0-9]/.test(r)&&(r=`${t}_${r}`),(!r||r.length===0)&&(r=`${t}_${n}`),r}function Ge(e){let t=e.variables||[],n=e.constraints||[],r=new Map,i=new Map,a=new Map,o=new Map,s=new Map,c=new Set;for(let e=0;e<t.length;e++){let n=t[e];s.set(n,e);let a=We(n.name,`x`,e),o=a,l=1;for(;c.has(o);)o=`${a}_${l++}`;c.add(o),i.set(n,o),r.set(o,n)}let l=new Set;for(let e=0;e<n.length;e++){let t=n[e],r=We(t.name,`c`,e+1),i=r,s=1;for(;l.has(i);)i=`${r}_${s++}`;l.add(i),o.set(t,i),a.set(i,t)}return{nameToVar:r,varToName:i,nameToConstraint:a,constraintToName:o,constrToName:o,varOrder:s}}function Ke(e,t){let{sense:n,objective:r,constraints:i,variables:a}=e;if(typeof r.hasNonlinearTerms==`function`&&r.hasNonlinearTerms())throw Error(`generateLpString() received an unlowered nonlinear objective (max/min/abs/at). Lower via Model.toLpString() or linearizeModelForMip() first.`);let o=t?.relax===!0,{nameToVar:s,varToName:c,nameToConstraint:l,constrToName:u,varOrder:d}=Ge(e),f=[];f.push(n&&n.toLowerCase()===`maximize`?`Maximize`:`Minimize`);let p=[],m=!0,h=r instanceof w?r.linearTerms:r.terms;if(h)for(let[e,t]of h){if(t===0)continue;let n=c.get(e),r=t>=0?m?``:`+ `:`- `,i=Math.abs(t),a=i===1?``:`${i} `;p.push(`${r}${a}${n}`),m=!1}if(r instanceof w&&r.quadTerms.size>0){let e=[],t=!0,n=Array.from(r.quadTerms.values()).filter(e=>e.coeff!==0).map(e=>{let t=d.get(e.var1)??e.var1.id,n=d.get(e.var2)??e.var2.id,[r,i,a,o]=t<=n?[e.var1,e.var2,t,n]:[e.var2,e.var1,n,t];return{firstVar:r,secondVar:i,firstIdx:a,secondIdx:o,coeff:e.coeff}}).sort((e,t)=>e.firstIdx-t.firstIdx||e.secondIdx-t.secondIdx);for(let r of n){let n=2*r.coeff,i=n>=0?t?``:`+ `:`- `,a=Math.abs(n),o=a===1?``:`${a} `,s=c.get(r.firstVar),l=c.get(r.secondVar);r.firstVar===r.secondVar?e.push(`${i}${o}${s} ^ 2`):e.push(`${i}${o}${s} * ${l}`),t=!1}if(e.length>0){let t=`[ ${e.join(` `)} ] / 2`;p.length>0?p.push(`+`,t):p.push(t)}}let g=p.length>0?p.join(` `):`0`;f.push(` obj: ${g}`),f.push(`Subject To`);for(let e of i){if(e.sense===`!=`||e.lhs.hasNonlinearTerms())throw Error(`generateLpString() received unlowered constraint "${e.name}" (${e.sense===`!=`?`discrete !=`:`nonlinear max/min/abs/at`}). Lower via Model.toLpString() or linearizeModelForMip() first.`);let t=u.get(e),n=[],r=!0;for(let[t,i]of e.lhs.terms){if(i===0)continue;let e=c.get(t),a=i>=0?r?``:`+ `:`- `,o=Math.abs(i),s=o===1?``:`${o} `;n.push(`${a}${s}${e}`),r=!1}let i=n.length>0?n.join(` `):`0`,a=e.sense===`==`?`=`:e.sense;f.push(` ${t}: ${i} ${a} ${e.rhs}`)}f.push(`Bounds`);let _=[],v=[];for(let e of a){let t=c.get(e);if(!o&&e.type===`Binary`){v.push(t);continue}!o&&e.type===`Integer`&&_.push(t);let n=e.lb===-1/0,r=e.ub===1/0;n&&r?f.push(` ${t} free`):n&&!r?f.push(` -infinity <= ${t} <= ${e.ub}`):!n&&r?(e.lb!==0||e.initialValue!==void 0)&&f.push(` ${t} >= ${e.lb}`):f.push(` ${e.lb} <= ${t} <= ${e.ub}`)}if(_.length>0){f.push(`Generals`);for(let e=0;e<_.length;e+=10)f.push(` `+_.slice(e,e+10).join(` `))}if(v.length>0){f.push(`Binary`);for(let e=0;e<v.length;e+=10)f.push(` `+v.slice(e,e+10).join(` `))}return f.push(`End`),{lpString:f.join(`
1
+ var Washi=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.defineProperty,n=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},r=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r};function i(e){if(e===void 0)return`Minimize`;if(typeof e==`string`){let t=e.toLowerCase();if(t===`maximize`)return`Maximize`;if(t===`minimize`)return`Minimize`}throw Error(`Invalid optimization sense "${String(e)}": expected "Maximize", "Minimize", "maximize", or "minimize".`)}var a=0;function o(e,t){if(e instanceof s||e instanceof F)return e;throw typeof e==`object`&&e&&(`terms`in e||`quadTerms`in e)?Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical operator "${t}". Use a comparison constraint such as expr\`\${x} <= 10\` or a BoolVar/BoolExpr.`):typeof e==`object`&&e&&`id`in e&&`name`in e&&`lb`in e&&`ub`in e&&!(`sense`in e)?Error(`Invalid operand passed to logical operator "${t}": expected a BoolVar, BoolExpr, or Constraint, but received numeric variable "${e.name}". Use m.bool() for propositional variables, add a comparison such as expr\`\${x} == 1\`, or use m.indicator(binVar, constraint) for 0-1 Big-M indicator constraints.`):Error(`Invalid operand passed to logical operator "${t}": expected a BoolVar, BoolExpr, or Constraint.`)}var s=class{and(e){return new l(`and`,[this,o(e,`and`)])}or(e){return new l(`or`,[this,o(e,`or`)])}implies(e){return new l(`implies`,[this,o(e,`implies`)])}xor(e){return new l(`xor`,[this,o(e,`xor`)])}not(){return new l(`not`,[this])}},c=class extends s{id;type=`Boolean`;name;value=null;constructor(e){super(),this.id=++a,this.name=e||`p_${this.id}`}toString(){return this.name}},l=class extends s{op;children;constructor(e,t){super(),this.op=e,this.children=t.map(t=>o(t,e))}toString(){return this.op===`not`?`not(${this.children[0].toString()})`:`(${this.children.map(e=>e.toString()).join(` ${this.op} `)})`}};function u(...e){if(e.length===0)throw Error(`and() requires at least one expression`);return new l(`and`,e)}function d(...e){if(e.length===0)throw Error(`or() requires at least one expression`);return new l(`or`,e)}function f(e){return new l(`not`,[e])}function p(e,t){return new l(`implies`,[e,t])}function m(...e){if(e.length===0)throw Error(`xor() requires at least one expression`);return new l(`xor`,e)}var h=class extends s{spec;discreteVars;constructor(e,t){super(),this.spec=e,this.discreteVars=t}toString(){switch(this.spec.kind){case`distinct`:return`distinct(${this.spec.args.map(e=>e.toString()).join(`, `)})`;case`disjoint`:return`disjoint([${this.spec.tasks.map(e=>`{ start: ${e.start.toString()}, duration: ${e.duration} }`).join(`, `)}])`;case`cumulative`:return`cumulative([${this.spec.tasks.map(e=>`{ start: ${e.start.toString()}, duration: ${e.duration}, demand: ${e.demand} }`).join(`, `)}], ${this.spec.capacity})`;case`allowed`:return`allowed([${this.spec.vars.map(e=>e.toString()).join(`, `)}], [${this.spec.tuples.map(e=>`[${e.join(`, `)}]`).join(`, `)}])`}}};function g(e){if(typeof e!=`object`||!e||Array.isArray(e)||e instanceof F||e instanceof s||e instanceof R)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function _(e){return typeof e==`number`||e instanceof F||e instanceof R||typeof e==`object`&&!!e&&(`terms`in e&&e.terms instanceof Map||`quadTerms`in e&&e.quadTerms instanceof Map||`id`in e&&`name`in e&&`lb`in e&&`ub`in e&&!(`sense`in e))}function v(...e){if(e.length===0)throw Error(`distinct() requires at least one expression or container.`);let t=[],n=new Set,r=(e,i)=>{if(e==null)throw Error(`Unsupported nullish item in distinct(): expected an integer-valued expression.`);if(_(e)){let r=ge(e,`distinct()`);L(r,`distinct()`,n),t.push(r);return}if(Array.isArray(e)){if(i>=2)throw Error(`Nested containers deeper than 2D are not supported in distinct().`);for(let t=0;t<e.length;t++){if(!(t in e))throw Error(`Unsupported item in distinct(): sparse array hole at index ${t}.`);r(e[t],i+1)}return}if(typeof e==`object`&&!(e instanceof String)&&!(e instanceof Map)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`){if(i>=2)throw Error(`Nested containers deeper than 2D are not supported in distinct().`);for(let t of e)r(t,i+1);return}if(g(e)){if(i>=2)throw Error(`Nested containers deeper than 2D are not supported in distinct().`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in distinct().`);for(let t of Object.keys(e))r(e[t],i+1);return}throw Error(`Unsupported item in distinct(): expected an integer-valued expression or container.`)};for(let t of e)r(t,0);return new h({kind:`distinct`,args:t},n)}function y(e,t){if(e==null)throw Error(`${t}(tasks) requires an Array, Iterable, or Record of task objects.`);if(Array.isArray(e)){let n=[];for(let r=0;r<e.length;r++){if(!(r in e))throw Error(`${t}(tasks) encountered sparse array hole at index ${r}.`);n.push(e[r])}return n}if(typeof e==`object`&&!(e instanceof String)&&!(e instanceof Map)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`)return Array.from(e);if(g(e)){if(`start`in e&&`duration`in e)throw Error(`${t}(tasks) expects an Array, Iterable, or Record of task objects, not a single task object.`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in ${t}().`);return Object.keys(e).map(t=>e[t])}throw Error(`${t}(tasks) requires an Array, Iterable, or Record of task objects.`)}function b(e){let t=y(e,`disjoint`),n=new Set,r=[];for(let e=0;e<t.length;e++){let i=t[e];if(typeof i!=`object`||!i||!(`start`in i)||!(`duration`in i))throw Error(`disjoint() task at index ${e} must be an object with { start, duration }.`);let a=i,o=ge(a.start,`disjoint() task[${e}].start`);if(L(o,`disjoint() task[${e}].start`,n),typeof a.duration!=`number`||!Number.isSafeInteger(a.duration)||a.duration<0)throw Error(`disjoint() task[${e}].duration must be a finite non-negative integer, received ${String(a.duration)}.`);r.push({start:o,duration:Object.is(a.duration,-0)?0:a.duration})}return new h({kind:`disjoint`,tasks:r},n)}function x(e,t){if(typeof t!=`number`||!Number.isSafeInteger(t)||t<0)throw Error(`cumulative() capacity must be a finite non-negative integer, received ${String(t)}.`);let n=y(e,`cumulative`),r=new Set,i=[];for(let e=0;e<n.length;e++){let t=n[e];if(typeof t!=`object`||!t||!(`start`in t)||!(`duration`in t)||!(`demand`in t))throw Error(`cumulative() task at index ${e} must be an object with { start, duration, demand }.`);let a=t,o=ge(a.start,`cumulative() task[${e}].start`);if(L(o,`cumulative() task[${e}].start`,r),typeof a.duration!=`number`||!Number.isSafeInteger(a.duration)||a.duration<0)throw Error(`cumulative() task[${e}].duration must be a finite non-negative integer, received ${String(a.duration)}.`);if(typeof a.demand!=`number`||!Number.isSafeInteger(a.demand)||a.demand<0)throw Error(`cumulative() task[${e}].demand must be a finite non-negative integer, received ${String(a.demand)}.`);i.push({start:o,duration:Object.is(a.duration,-0)?0:a.duration,demand:Object.is(a.demand,-0)?0:a.demand})}return new h({kind:`cumulative`,tasks:i,capacity:Object.is(t,-0)?0:t},r)}function S(e,t){if(!Array.isArray(e)||e.length===0)throw Error(`allowed(vars, tuples) requires a non-empty Array of expressions as its first argument.`);let n=new Set,r=Array(e.length);for(let t=0;t<e.length;t++){if(!(t in e))throw Error(`allowed() vars encountered sparse array hole at index ${t}.`);let i=ge(e[t],`allowed() vars[${t}]`);L(i,`allowed() vars[${t}]`,n),r[t]=i}if(typeof t!=`object`||!t||t instanceof String||!(Symbol.iterator in t)||typeof t[Symbol.iterator]!=`function`)throw Error(`allowed(vars, tuples) requires an Iterable of integer tuples as its second argument.`);let i=[],a=0;for(let n of t){if(!Array.isArray(n)||n.length!==e.length)throw Error(`allowed() tuple at index ${a} must be an Array of length ${e.length}.`);let t=Array(e.length);for(let r=0;r<e.length;r++){if(!(r in n))throw Error(`allowed() tuple[${a}] encountered sparse array hole at index ${r}.`);let e=n[r];if(typeof e!=`number`||!Number.isSafeInteger(e))throw Error(`allowed() tuple[${a}][${r}] must be a safe integer, received ${String(e)}.`);t[r]=Object.is(e,-0)?0:e}i.push(t),a++}return new h({kind:`allowed`,vars:r,tuples:i},n)}function C(e,t){let n=e.id,r=t.id;return n<=r?`${n}:${r}`:`${r}:${n}`}var w=class e{kind=`quadratic`;linearTerms;quadTerms;constant;nonlinearTerms;constructor(e=new Map,t=new Map,n=0,r=[]){this.linearTerms=new Map(e),this.quadTerms=new Map;for(let[e,n]of t)this.quadTerms.set(e,{...n});this.constant=n,this.nonlinearTerms=r.filter(e=>e.coeff!==0).map(e=>({atom:I(e.atom),coeff:e.coeff}))}hasNonlinearTerms(){return this.nonlinearTerms.length>0}clone(){return new e(this.linearTerms,this.quadTerms,this.constant,this.nonlinearTerms)}getQuadCoeff(e,t){let n=C(e,t),r=this.quadTerms.get(n);return r?r.coeff:0}add(t){if(fe(t))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);let n=this.clone();if(typeof t==`number`)return n.constant+=t,n;if(t instanceof e){for(let[e,r]of t.quadTerms){let t=n.quadTerms.get(e),i=(t?t.coeff:0)+r.coeff;i===0?n.quadTerms.delete(e):n.quadTerms.set(e,{var1:r.var1,var2:r.var2,coeff:i})}for(let[e,r]of t.linearTerms){let t=(n.linearTerms.get(e)??0)+r;t===0?n.linearTerms.delete(e):n.linearTerms.set(e,t)}if(n.constant+=t.constant,Array.isArray(t.nonlinearTerms))for(let e of t.nonlinearTerms)e.coeff!==0&&n.nonlinearTerms.push({atom:I(e.atom),coeff:e.coeff});return n}if(`terms`in t&&t.terms instanceof Map){for(let[e,r]of t.terms){let t=(n.linearTerms.get(e)??0)+r;t===0?n.linearTerms.delete(e):n.linearTerms.set(e,t)}if(n.constant+=t.constant,Array.isArray(t.nonlinearTerms))for(let e of t.nonlinearTerms)e.coeff!==0&&n.nonlinearTerms.push({atom:I(e.atom),coeff:e.coeff});return n}let r=t,i=(n.linearTerms.get(r)??0)+1;return i===0?n.linearTerms.delete(r):n.linearTerms.set(r,i),n}sub(e){if(fe(e))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);return typeof e==`number`?this.add(-e):this.add(e.mul(-1))}mul(t){if(fe(t))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);if(typeof t==`number`){let n=this.linearTerms.size>0||this.quadTerms.size>0||this.nonlinearTerms.length>0,r=this.constant===0&&n?0:this.constant*t;if(this.constant!==0&&t!==0&&r===0)throw Error(`Constant multiplication underflows to zero.`);let i=new e(new Map,new Map,r);for(let[e,n]of this.linearTerms){let r=n*t;if(n!==0&&t!==0&&r===0)throw Error(`Coefficient multiplication underflows to zero.`);r!==0&&i.linearTerms.set(e,r)}for(let[e,n]of this.quadTerms){let r=n.coeff*t;if(n.coeff!==0&&t!==0&&r===0)throw Error(`Coefficient multiplication underflows to zero.`);r!==0&&i.quadTerms.set(e,{var1:n.var1,var2:n.var2,coeff:r})}if(t!==0)for(let e of this.nonlinearTerms){let n=e.coeff*t;if(e.coeff!==0&&n===0)throw Error(`Coefficient multiplication underflows to zero.`);n!==0&&i.nonlinearTerms.push({atom:I(e.atom),coeff:n})}return i}let n=`id`in t&&`name`in t&&!(`terms`in t)&&!(`quadTerms`in t),r=`quadTerms`in t?t.quadTerms.size:0,i=!n&&`nonlinearTerms`in t&&Array.isArray(t.nonlinearTerms)?t.nonlinearTerms.length:0,a=n?new Map([[t,1]]):`quadTerms`in t?t.linearTerms:t.terms,o=n?0:t.constant;if(this.nonlinearTerms.length>0){if(!n&&r===0&&a.size===0&&i===0)return this.mul(o);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}if(i>0){if(this.quadTerms.size===0&&this.linearTerms.size===0){let n=t.mul(this.constant);return`quadTerms`in n?n:new e(n.terms,new Map,n.constant,n.nonlinearTerms)}throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}if(this.quadTerms.size>0&&(r>0||a.size>0)||r>0&&this.linearTerms.size>0)throw Error(`Multiplication creates a non-linear term of degree > 2 (not allowed in MILP/LP/QP)`);if(r===0&&a.size===0)return this.mul(o);if(this.quadTerms.size===0&&this.linearTerms.size===0&&!n){let n=t.mul(this.constant);return`quadTerms`in n?n:new e(n.terms,new Map,n.constant,n.nonlinearTerms)}return e.multiplyLinearTerms(this.constant,this.linearTerms,o,a)}div(t){let n=e.extractScalarDivisor(t,`QuadExpr.div()`);return this.mul(1/n)}neg(){return this.mul(-1)}get value(){let e=this.constant;for(let[t,n]of this.linearTerms){if(t.value===null)return null;e+=n*t.value}for(let t of this.quadTerms.values()){if(t.var1.value===null||t.var2.value===null)return null;e+=t.coeff*t.var1.value*t.var2.value}for(let t of this.nonlinearTerms){let n=me(t.atom);if(n===null)return null;e+=t.coeff*n}return e}le(e,t){return this.toConstraint(`<=`,e,t)}ge(e,t){return this.toConstraint(`>=`,e,t)}eq(e,t){return this.toConstraint(`==`,e,t)}lt(e,t){return this.toDiscreteComparison(`<`,e,t)}gt(e,t){return this.toDiscreteComparison(`>`,e,t)}ne(e,t){return this.toDiscreteComparison(`!=`,e,t)}toDiscreteComparison(e,t,n){if(this.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in discrete comparisons (${e}): quadratic terms are only allowed in objectives.`);let r=new R(this.linearTerms,this.constant,this.nonlinearTerms);return e===`<`?r.lt(t,n):e===`>`?r.gt(t,n):r.ne(t,n)}toConstraint(e,t,n){if(this.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in linear constraints (${e}): quadratic terms are only allowed in objectives.`);let r=new R(this.linearTerms,this.constant,this.nonlinearTerms);return e===`<=`?r.le(t,n):e===`>=`?r.ge(t,n):r.eq(t,n)}and(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'and': expected a BoolVar, Constraint, or BoolOp.`)}or(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'or': expected a BoolVar, Constraint, or BoolOp.`)}implies(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'implies': expected a BoolVar, Constraint, or BoolOp.`)}xor(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'xor': expected a BoolVar, Constraint, or BoolOp.`)}not(){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==) in logical 'not': expected a BoolVar, Constraint, or BoolOp.`)}toString(){let e=[],t=!0;for(let n of this.quadTerms.values()){let r=n.coeff,i=r>=0?t?``:`+ `:`- `,a=Math.abs(r),o=a===1?``:`${a} `;n.var1===n.var2?e.push(`${i}${o}${n.var1.name}^2`):e.push(`${i}${o}${n.var1.name} * ${n.var2.name}`),t=!1}for(let[n,r]of this.linearTerms){let i=r>=0?t?``:`+ `:`- `,a=Math.abs(r),o=a===1?``:`${a} `;e.push(`${i}${o}${n.name}`),t=!1}if(this.nonlinearTerms.length>0){let n=new R(new Map,0,this.nonlinearTerms).toString();n!==`0`&&(e.push(t?n:n.startsWith(`-`)?`- ${n.slice(2)}`:`+ ${n}`),t=!1)}if(this.constant!==0||e.length===0){let n=this.constant>=0?t?``:`+ `:`- `;e.push(`${n}${Math.abs(this.constant)}`)}return e.join(` `)||`0`}static fromProduct(t,n,r=1){let i=new e;if(r===0)return i;let a=C(t,n);return i.quadTerms.set(a,{var1:t.id<=n.id?t:n,var2:t.id<=n.id?n:t,coeff:r}),i}static multiplyLinearTerms(t,n,r,i){let a=n.size>0||i.size>0,o=(t===0||r===0)&&a?0:t*r;if(t!==0&&r!==0&&o===0)throw Error(`Constant multiplication underflows to zero.`);let s=new e(new Map,new Map,o===0?0:o);if(r!==0)for(let[e,t]of n){let n=t*r;if(t!==0&&n===0)throw Error(`Coefficient multiplication underflows to zero.`);n!==0&&s.linearTerms.set(e,n)}if(t!==0)for(let[e,n]of i){let r=s.linearTerms.get(e)??0,i=n*t;if(n!==0&&i===0)throw Error(`Coefficient multiplication underflows to zero.`);let a=r+i;a===0?s.linearTerms.delete(e):s.linearTerms.set(e,a)}for(let[t,r]of n)for(let[n,a]of i){let i=r*a;if(r!==0&&a!==0&&i===0)throw Error(`Coefficient multiplication underflows to zero.`);s=s.add(e.fromProduct(t,n,i))}return s}static extractScalarDivisor(e,t){if(fe(e))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);if(typeof e==`number`){if(e===0)throw Error(`Division by zero in ${t}`);return e}let n=`quadTerms`in e?e.linearTerms.size:e.terms.size,r=`quadTerms`in e?e.quadTerms.size:0,i=`nonlinearTerms`in e&&Array.isArray(e.nonlinearTerms)?e.nonlinearTerms.length:0;if(n>0||r>0||i>0)throw Error(`Cannot divide by variable in expression`);if(e.constant===0)throw Error(`Division by zero in ${t}`);return e.constant}},T=new WeakMap,E=new WeakMap,D=new WeakMap,ee=new WeakMap;function O(e,t){ee.set(e,t)}function k(e){e&&ee.get(e)?.()}function A(e,t,n){if(e instanceof l)for(let r of e.children)A(r,t,n);else if(e instanceof F){let r=e.ownerModel,i=E.get(e);(r!==t||i!==t)&&(n&&n.push(()=>{e.ownerModel=r,i?E.set(e,i):E.delete(e)}),e.ownerModel=t,E.set(e,t))}}function te(e,t){let n=T.get(e);if(n&&n!==t)throw Error(`Variable "${e.name}" already belongs to model "${n.name}" and cannot be added to model "${t.name}".`);T.set(e,t)}function ne(e,t){let n=D.get(e);if(n)throw Error(n===t?`Constraint "${e.name}" is already registered in model "${t.name}".`:`Constraint "${e.name}" already belongs to model "${n.name}" and cannot be added to model "${t.name}".`);let r=E.get(e);if(r&&r!==t)throw Error(`Constraint "${e.name}" already belongs to model "${r.name}" and cannot be added to model "${t.name}".`);return D.set(e,t),E.set(e,t),r}function re(e,t){T.get(e)===t&&T.delete(e)}function ie(e,t,n){D.get(e)===t&&D.delete(e),E.get(e)===t&&(n?E.set(e,n):E.delete(e))}var j=1e-6;function M(e){if(typeof e.lb!=`number`||Number.isNaN(e.lb))throw Error(`Variable "${e.name}" has invalid lower bound: ${e.lb} (NaN or non-numeric bound is not allowed).`);if(e.lb===1/0)throw Error(`Variable "${e.name}" has invalid lower bound: +Infinity is not allowed as a lower bound.`);if(typeof e.ub!=`number`||Number.isNaN(e.ub))throw Error(`Variable "${e.name}" has invalid upper bound: ${e.ub} (NaN or non-numeric bound is not allowed).`);if(e.ub===-1/0)throw Error(`Variable "${e.name}" has invalid upper bound: -Infinity is not allowed as an upper bound.`);if(e.lb>e.ub)throw Error(`Variable "${e.name}" has invalid bounds: lower bound (${e.lb}) is strictly greater than upper bound (${e.ub}).`);if(e.initialValue!==void 0){if(typeof e.initialValue!=`number`||!Number.isFinite(e.initialValue))throw Error(`Variable "${e.name}" has invalid initialValue: ${String(e.initialValue)} (initialValue must be a finite number).`);let t=e.type===`Binary`?Math.max(0,e.lb):e.lb,n=e.type===`Binary`?Math.min(1,e.ub):e.ub;if(e.initialValue<t-1e-6||e.initialValue>n+1e-6)throw Error(`Variable "${e.name}" has initialValue (${e.initialValue}) outside its bounds [${t}, ${n}] (tolerance ${j}).`);if(e.type===`Integer`||e.type===`Binary`){let r=Math.round(e.initialValue);if(Math.abs(e.initialValue-r)>1e-6||r<t||r>n)throw Error(`Variable "${e.name}" of type "${e.type}" has non-integral or out-of-domain initialValue: ${e.initialValue} (must be within ${j} of an integer in [${t}, ${n}]).`)}}}function ae(e){if(e.initialValue===void 0)return;if(M(e),e.type===`Integer`||e.type===`Binary`){let t=Math.round(e.initialValue);return Object.is(t,-0)?0:t}let t=Math.min(e.ub,Math.max(e.lb,e.initialValue));return Object.is(t,-0)?0:t}function oe(e,t){if(e){for(let n of e)if(n.type!==`Integer`&&n.type!==`Binary`)throw Error(`${t} requires Integer or Binary variables, but variable "${n.name}" has type "${n.type}".`)}}function se(e,t,n,r){if(e&&e.length!==0)for(let i of e){if(!Number.isFinite(i.coeff))throw Error(`Nonlinear expression in ${t} has invalid coefficient: ${i.coeff}. Coefficients must be finite numbers.`);let e=i.atom;if(e.kind===`abs`)N(e.arg,t,n,r);else if(e.kind===`max`||e.kind===`min`)for(let i of e.args)N(i,t,n,r);else if(e.kind===`at`){oe(e.discreteVars,`at() index in ${t}`),N(e.index,t,n,r);for(let i of e.array)N(i,t,n,r)}}}function N(e,t,n,r,i){if(e.constant!==void 0&&!Number.isFinite(e.constant)){let n=i?.constantPrefix??t,r=i?.constantKind??`constant`;throw Error(`${n} has invalid ${r}: ${e.constant}. Constant must be a finite number.`)}let a=i?.varLocationPhrase??`in ${t}`;for(let[i,o]of e.terms){if(!r(i))throw Error(`Variable "${i.name}" ${a} does not belong to model "${n}". All variables must belong to the model by object identity.`);if(!Number.isFinite(o))throw Error(`Variable "${i.name}" in ${t} has invalid coefficient: ${o}. Coefficients must be finite numbers.`)}se(e.nonlinearTerms,t,n,r)}function P(e,t,n){if(e instanceof w){if(!Number.isFinite(e.constant))throw Error(`Objective function has invalid constant: ${e.constant}. Constant must be a finite number.`);for(let[r,i]of e.linearTerms){if(!n(r))throw Error(`Variable "${r.name}" in objective function does not belong to model "${t}". All variables must belong to the model by object identity.`);if(!Number.isFinite(i))throw Error(`Variable "${r.name}" in objective function has invalid coefficient: ${i}. Coefficients must be finite numbers.`)}for(let[,r]of e.quadTerms){if(!n(r.var1))throw Error(`Variable "${r.var1.name}" in quadratic objective function does not belong to model "${t}". All variables must belong to the model by object identity.`);if(!n(r.var2))throw Error(`Variable "${r.var2.name}" in quadratic objective function does not belong to model "${t}". All variables must belong to the model by object identity.`);if(!Number.isFinite(r.coeff)||!Number.isFinite(r.coeff*2))throw Error(`Quadratic term (${r.var1.name} * ${r.var2.name}) in objective function has invalid coefficient: ${r.coeff}.`)}se(e.nonlinearTerms,`objective function`,t,n)}else`terms`in e&&N(e,`objective function`,t,n,{constantPrefix:`Objective function`})}function ce(e,t,n,r=e.name){if(!Number.isFinite(e.rhs))throw Error(`Constraint "${r}" has invalid right-hand side (RHS): ${e.rhs}. RHS must be a finite number.`);if(oe(e._requiredDiscreteVars,`Discrete constraint "${r}"`),N(e.lhs,`constraint "${r}"`,t,n),e.sense===`!=`){if(!Number.isSafeInteger(e.rhs))throw Error(`Discrete "!=" in constraint "${r}" requires a safe integer RHS, received ${e.rhs}.`);L(e.lhs,`Discrete "!=" in constraint "${r}"`)}if(e._indicatorMeta){let i=e._indicatorMeta.binVar;if(!n(i))throw Error(`Indicator binary variable "${i.name}" in constraint "${r}" does not belong to model "${t}".`);if(!(i.type===`Binary`||i.type===`Integer`&&i.lb===0&&i.ub===1))throw Error(`Indicator variable "${i.name}" in constraint "${r}" has invalid type "${i.type}" or bounds [${i.lb}, ${i.ub}]: expected Binary or Integer [0, 1].`)}}function le(e,t,n,r,i,a){if(e instanceof c){if(!i(e))throw Error(`Boolean variable "${e.name}" in logical constraint "${t}" does not belong to model "${n}".`)}else if(e instanceof l)for(let o of e.children)le(o,t,n,r,i,a);else if(e instanceof h){oe(e.discreteVars,`Global constraint "${t}"`);let i=`logical constraint "${t}"`;switch(e.spec.kind){case`distinct`:for(let t of e.spec.args)N(t,i,n,r);break;case`disjoint`:for(let t of e.spec.tasks)N(t.start,i,n,r);break;case`cumulative`:for(let t of e.spec.tasks)N(t.start,i,n,r);break;case`allowed`:for(let t of e.spec.vars)N(t,i,n,r)}}else if(e instanceof F){if(a){let r=E.get(e)??e.ownerModel??void 0;if(r&&r!==a)throw Error(`Constraint "${e.name}" embedded in logical constraint "${t}" already belongs to model "${r.name??`another model`}" and cannot be added to model "${n}".`)}if(!Number.isFinite(e.rhs))throw Error(`Constraint "${e.name}" embedded in logical constraint "${t}" has invalid RHS: ${e.rhs}.`);if(oe(e._requiredDiscreteVars,`Discrete constraint "${e.name}" embedded in logical constraint "${t}"`),N(e.lhs,`constraint "${e.name}" embedded in logical constraint "${t}"`,n,r,{constantPrefix:`Constraint "${e.name}" embedded in logical constraint "${t}"`,constantKind:`LHS constant`,varLocationPhrase:`embedded in logical constraint "${t}"`}),e.sense===`!=`){if(!Number.isSafeInteger(e.rhs))throw Error(`Discrete "!=" in constraint "${e.name}" embedded in logical constraint "${t}" requires a safe integer RHS, received ${e.rhs}.`);L(e.lhs,`Discrete "!=" in constraint "${e.name}" embedded in logical constraint "${t}"`)}}}function ue(e){let{model:t}=e,n=new Set,r=new Set;for(let i of e.variables){M(i);let a=T.get(i);if(a&&a!==t||n.has(i.name)||e.getVarByName(i.name)!==i)throw Error(`Variable "${i.name}" is duplicated or not canonically registered in model "${e.name}".`);n.add(i.name),r.add(i)}let i=new Set,a=new Set;for(let t of e.boolVars){if(i.has(t.name)||e.getBoolVarByName(t.name)!==t)throw Error(`Boolean variable "${t.name}" is duplicated or not canonically registered in model "${e.name}".`);i.add(t.name),a.add(t)}let o=new Set;for(let t of e.constraints){if(i.has(t.name))throw Error(`Constraint name "${t.name}" conflicts with Boolean variable "${t.name}" in model "${e.name}".`);if(o.has(t.name))throw Error(`Duplicate constraint name "${t.name}" in model "${e.name}".`);o.add(t.name)}for(let t of e.logicalConstraints){if(i.has(t.name))throw Error(`Logical constraint name "${t.name}" conflicts with Boolean variable "${t.name}" in model "${e.name}".`);if(o.has(t.name))throw Error(`Conflicting constraint name "${t.name}" across arithmetic and logical constraints in model "${e.name}".`);o.add(t.name)}for(let n of e.constraints){let r=E.get(n);if(r&&r!==t||e.getConstraintByName(n.name)!==n)throw Error(`Constraint "${n.name}" is duplicated or not canonically registered in model "${e.name}".`)}for(let t of e.logicalConstraints)if(e.getLogicalConstraintByName(t.name)!==t)throw Error(`Logical constraint "${t.name}" is duplicated or not canonically registered in model "${e.name}".`);e.objectiveExpr&&P(e.objectiveExpr,e.name,e=>r.has(e));for(let t of e.constraints)ce(t,e.name,e=>r.has(e));for(let n of e.logicalConstraints)le(n.expr,n.name,e.name,e=>r.has(e),e=>a.has(e),t)}var de=0,F=class e{kind=`constraint`;id;_lhs;_sense;_rhs;_name;hasExplicitName;ownerModel=null;_indicatorOrigin;_indicatorSnapshot;_discreteVars;slack=null;dual=null;addTerm(e,t){return t===0?this:(this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._lhs.addTerm(e,t),k(this.ownerModel),this)}setTerm(e,t){return this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._lhs.setTerm(e,t),k(this.ownerModel),this}constructor(e,t,n,r){this.id=++de,this._lhs=e,this._sense=t,this._rhs=n;let i=typeof r==`string`?r.trim():void 0;i&&i.length>0?(this._name=i,this.hasExplicitName=!0):(this._name=`c_${this.id}`,this.hasExplicitName=!1)}get lhs(){return this._lhs}set lhs(e){this._lhs!==e&&(this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._lhs=e,k(this.ownerModel))}get sense(){return this._sense}set sense(e){if(e===`!=`&&!Number.isSafeInteger(this._rhs))throw Error(`Discrete "!=" in constraint "${this._name}" requires a safe integer RHS, received ${this._rhs}.`);this._sense!==e&&(this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._sense=e,k(this.ownerModel))}get rhs(){return this._rhs}set rhs(e){if(this._sense===`!=`&&!Number.isSafeInteger(e))throw Error(`Discrete "!=" in constraint "${this._name}" requires a safe integer RHS, received ${e}.`);Object.is(this._rhs,e)||(this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0,this._rhs=e,k(this.ownerModel))}get name(){return this._name}set name(e){this._name!==e&&(this._name=e,k(this.ownerModel)),this.hasExplicitName=!0}get _indicatorMeta(){let e=this._indicatorOrigin,t=this._indicatorSnapshot;if(!e||!t)return;if(this._lhs!==t.lhsRef||this._sense!==t.sense||!Object.is(this._rhs,t.rhs)||!Object.is(this._lhs.constant,t.constant)||this._lhs.nonlinearTerms.length>0||this._lhs.terms.size!==t.terms.size){this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0;return}for(let[e,n]of t.terms)if(!this._lhs.terms.has(e)||!Object.is(this._lhs.terms.get(e),n)){this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0;return}let n=e.targetRhs-(e.targetLhs.constant??0),r=0;for(let[t,n]of e.targetLhs.terms){if(n===0)continue;let i=e.targetSense===`<=`?n>0?t.ub:t.lb:n>0?t.lb:t.ub;if(!Number.isFinite(i)||(r+=n*i,!Number.isFinite(r)))return}if(!((e.targetSense===`<=`?r-n:n-r)>e.derivedM+1e-9))return e}_setIndicatorOrigin(e){if(!e){this._indicatorOrigin=void 0,this._indicatorSnapshot=void 0;return}this._indicatorOrigin=e,this._indicatorSnapshot={lhsRef:this._lhs,terms:new Map(this._lhs.terms),constant:this._lhs.constant,sense:this._sense,rhs:this._rhs}}get _requiredDiscreteVars(){return this._discreteVars}_setDiscreteVars(e){this._discreteVars=e}_assignModelName(e,t){this._name=e,this.hasExplicitName=t}and(e){return new l(`and`,[this,e])}or(e){return new l(`or`,[this,e])}implies(e){return new l(`implies`,[this,e])}xor(e){return new l(`xor`,[this,e])}not(){return new l(`not`,[this])}add(e){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}sub(e){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}mul(e){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}div(e){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}neg(){throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`)}le(e,t){throw Error(`Cannot compare a Constraint in (<=): expected a number, Var, or LinExpr.`)}ge(e,t){throw Error(`Cannot compare a Constraint in (>=): expected a number, Var, or LinExpr.`)}eq(e,t){throw Error(`Cannot compare a Constraint in (==): expected a number, Var, or LinExpr.`)}lt(e,t){throw Error(`Cannot compare a Constraint in (<): expected a number, Var, or LinExpr.`)}gt(e,t){throw Error(`Cannot compare a Constraint in (>): expected a number, Var, or LinExpr.`)}ne(e,t){throw Error(`Cannot compare a Constraint in (!=): expected a number, Var, or LinExpr.`)}get value(){throw Error(`Cannot read numeric value of a Constraint: expected a Var, LinExpr, or QuadExpr.`)}get constant(){throw Error(`Cannot read numeric constant of a Constraint: expected a LinExpr or QuadExpr.`)}clone(){let t=new e(this._lhs.clone(),this._sense,this._rhs,this.hasExplicitName?this._name:void 0);return this._discreteVars&&t._setDiscreteVars(new Set(this._discreteVars)),t}toString(){let e=this.sense===`==`?`=`:this.sense;return`${this.name}: ${this.lhs.toString()} ${e} ${this.rhs}`}};function fe(e){return e instanceof F||typeof e==`object`&&!!e&&`sense`in e&&`lhs`in e&&`rhs`in e}function I(e){switch(e.kind){case`abs`:return{kind:`abs`,arg:e.arg.clone()};case`max`:return{kind:`max`,args:e.args.map(e=>e.clone())};case`min`:return{kind:`min`,args:e.args.map(e=>e.clone())};case`at`:return{kind:`at`,array:e.array.map(e=>e.clone()),index:e.index.clone(),discreteVars:new Set(e.discreteVars)}}}function pe(e){switch(e.kind){case`abs`:return`abs(${e.arg.toString()})`;case`max`:return`max(${e.args.map(e=>e.toString()).join(`, `)})`;case`min`:return`min(${e.args.map(e=>e.toString()).join(`, `)})`;case`at`:return`at([${e.array.map(e=>e.toString()).join(`, `)}], ${e.index.toString()})`}}function me(e){switch(e.kind){case`abs`:{let t=e.arg.value;return t===null?null:Math.abs(t)}case`max`:{let t=-1/0;for(let n of e.args){let e=n.value;if(e===null)return null;e>t&&(t=e)}return t}case`min`:{let t=1/0;for(let n of e.args){let e=n.value;if(e===null)return null;e<t&&(t=e)}return t}case`at`:{let t=e.index.value;if(t===null||!Number.isFinite(t))return null;let n=Math.round(t);return Math.abs(t-n)>1e-6||n<0||n>=e.array.length?null:e.array[n].value}}}function he(e){return e instanceof V||typeof e==`object`&&!!e&&!fe(e)&&typeof e.id==`number`&&typeof e.name==`string`&&typeof e.lb==`number`&&typeof e.ub==`number`&&typeof e.type==`string`&&typeof e.mul==`function`}function L(e,t,n=new Set){if(typeof e==`number`){if(!Number.isSafeInteger(e))throw Error(`${t} requires Integer or Binary variables and integer constants/coefficients, but received constant ${e}.`);return n}if(fe(e))throw Error(`${t} cannot accept a Constraint comparison.`);if(e instanceof w||`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map&&typeof e.constant==`number`){let r=e;if(r.quadTerms.size>0)throw Error(`${t} does not support quadratic expressions.`);return L(new R(r.linearTerms,r.constant,r.nonlinearTerms??[]),t,n)}if(he(e)){if(e.type!==`Integer`&&e.type!==`Binary`)throw Error(`${t} requires Integer or Binary variables, but involves Continuous variable "${e.name}".`);return n.add(e),n}if(`terms`in e&&e.terms instanceof Map){let r=e,i=r.constant??0;if(!Number.isSafeInteger(i))throw Error(`${t} requires Integer or Binary variables and integer constants/coefficients, but received constant ${i}.`);for(let[e,i]of r.terms)if(i!==0){if(e.type!==`Integer`&&e.type!==`Binary`)throw Error(`${t} requires Integer or Binary variables, but involves Continuous variable "${e.name}".`);if(!Number.isSafeInteger(i))throw Error(`${t} requires integer coefficients, but variable "${e.name}" has coefficient ${i}.`);n.add(e)}for(let e of r.nonlinearTerms??[]){if(e.coeff===0)continue;if(!Number.isSafeInteger(e.coeff))throw Error(`${t} requires integer coefficients on nonlinear expressions, received ${e.coeff}.`);let r=e.atom;if(r.kind===`abs`)L(r.arg,t,n);else if(r.kind===`max`||r.kind===`min`)for(let e of r.args)L(e,t,n);else if(r.kind===`at`){L(r.index,t,n);for(let e of r.array)L(e,t,n)}}return n}throw Error(`${t} expected an integer-valued scalar expression.`)}function ge(e,t){if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid non-finite number "${e}" in ${t}.`);return new R(new Map,Object.is(e,-0)?0:e)}if(fe(e))throw t.startsWith(`sum`)?Error(`Cannot sum a constraint comparison (<=, >=, ==, !=, <, >): expected arithmetic expressions in ${t}.`):Error(`Cannot use a constraint comparison (<=, >=, ==, !=, <, >) in ${t}: expected a finite number, Var, or LinExpr.`);if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map){let n=e;if(n.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in ${t}.`);if(!Number.isFinite(n.constant))throw Error(`Invalid non-finite constant "${n.constant}" in ${t}.`);for(let[,e]of n.linearTerms)if(!Number.isFinite(e))throw Error(`Invalid non-finite coefficient "${e}" in ${t}.`);return new R(n.linearTerms,n.constant,n.nonlinearTerms??[])}if(e instanceof R||typeof e==`object`&&e&&`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`){let n=e;if(!Number.isFinite(n.constant))throw Error(`Invalid non-finite constant "${n.constant}" in ${t}.`);for(let[,e]of n.terms)if(!Number.isFinite(e))throw Error(`Invalid non-finite coefficient "${e}" in ${t}.`);return n.clone()}if(he(e))return new R(new Map([[e,1]]),0);throw Error(`Unsupported item in ${t}: expected a finite number, Var, or LinExpr.`)}var R=class e{kind=`linear`;terms;constant;nonlinearTerms;constructor(e=new Map,t=0,n=[]){this.terms=new Map(e),this.constant=t,this.nonlinearTerms=n.filter(e=>e.coeff!==0).map(e=>({atom:I(e.atom),coeff:e.coeff}))}hasNonlinearTerms(){return this.nonlinearTerms.length>0}setTerm(e,t){return t===0?this.terms.delete(e):this.terms.set(e,t),this}addTerm(e,t){let n=(this.terms.get(e)??0)+t;return n===0?this.terms.delete(e):this.terms.set(e,n),this}clone(){return new e(this.terms,this.constant,this.nonlinearTerms)}add(e){if(fe(e))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);if(e instanceof w)return e.add(this);let t=this.clone();if(typeof e==`number`)t.constant+=e;else if(`terms`in e){for(let[n,r]of e.terms){let e=(t.terms.get(n)??0)+r;e===0?t.terms.delete(n):t.terms.set(n,e)}if(t.constant+=e.constant,Array.isArray(e.nonlinearTerms))for(let n of e.nonlinearTerms)n.coeff!==0&&t.nonlinearTerms.push({atom:I(n.atom),coeff:n.coeff})}else{let n=(t.terms.get(e)??0)+1;n===0?t.terms.delete(e):t.terms.set(e,n)}return t}sub(e){if(fe(e))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);return e instanceof w?e.neg().add(this):typeof e==`number`?this.add(-e):this.add(e.mul(-1))}mul(t){if(fe(t))throw Error(`Cannot perform arithmetic on a Constraint: expected a number, Var, LinExpr, or QuadExpr.`);if(typeof t==`number`){let n=this.terms.size>0||this.nonlinearTerms.length>0,r=this.constant===0&&n?0:this.constant*t;if(this.constant!==0&&t!==0&&r===0)throw Error(`Constant multiplication underflows to zero.`);let i=new e(new Map,r);for(let[e,n]of this.terms){let r=n*t;if(n!==0&&t!==0&&r===0)throw Error(`Coefficient multiplication underflows to zero.`);r!==0&&i.terms.set(e,r)}if(t!==0)for(let e of this.nonlinearTerms){let n=e.coeff*t;if(e.coeff!==0&&n===0)throw Error(`Coefficient multiplication underflows to zero.`);n!==0&&i.nonlinearTerms.push({atom:I(e.atom),coeff:n})}return i}if(t instanceof V||typeof t==`object`&&t&&`id`in t&&!(`terms`in t)&&!(`quadTerms`in t)){if(this.hasNonlinearTerms())throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`);return w.multiplyLinearTerms(this.constant,this.terms,0,new Map([[t,1]]))}if(t instanceof w){let e=t.linearTerms.size>0||t.quadTerms.size>0||t.hasNonlinearTerms();if(this.hasNonlinearTerms()){if(!e)return this.mul(t.constant);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}if(t.hasNonlinearTerms()){if(this.terms.size===0)return t.mul(this.constant);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}return this.terms.size===0?t.mul(this.constant):new w(this.terms,new Map,this.constant).mul(t)}let n=Array.isArray(t.nonlinearTerms)&&t.nonlinearTerms.length>0;if(this.hasNonlinearTerms()){if(t.terms.size===0&&!n)return this.mul(t.constant);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}if(n){if(this.terms.size===0)return t.mul(this.constant);throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`)}return this.terms.size===0?t.mul(this.constant):t.terms.size===0?this.mul(t.constant):w.multiplyLinearTerms(this.constant,this.terms,t.constant,t.terms)}div(e){let t=w.extractScalarDivisor(e,`LinExpr.div()`);return this.mul(1/t)}neg(){return this.mul(-1)}get value(){let e=this.constant;for(let[t,n]of this.terms){if(t.value===null)return null;e+=n*t.value}for(let t of this.nonlinearTerms){let n=me(t.atom);if(n===null)return null;e+=t.coeff*n}return e}le(e,t){return this.toConstraint(`<=`,e,t)}ge(e,t){return this.toConstraint(`>=`,e,t)}eq(e,t){return this.toConstraint(`==`,e,t)}lt(e,t){return this.toDiscreteComparison(`<`,e,t)}gt(e,t){return this.toDiscreteComparison(`>`,e,t)}ne(e,t){return this.toDiscreteComparison(`!=`,e,t)}toDiscreteComparison(e,t,n){if(t instanceof F||typeof t==`object`&&t&&`sense`in t&&`lhs`in t)throw Error(`Cannot compare against a Constraint in (${e}): expected a finite integer, discrete Var, or discrete LinExpr.`);let r=`discrete ${e}`,i=new Set;L(this,r,i),L(t,r,i);let a=this.toConstraint(e===`<`?`<=`:e===`>`?`>=`:`!=`,t,n);if(e===`<`){let e=a.rhs-1;if(!Number.isSafeInteger(e))throw Error(`Discrete comparison (<) adjusted right-hand side (${e}) exceeds safe integer range.`);a.rhs=e}else if(e===`>`){let e=a.rhs+1;if(!Number.isSafeInteger(e))throw Error(`Discrete comparison (>) adjusted right-hand side (${e}) exceeds safe integer range.`);a.rhs=e}else if(!Number.isSafeInteger(a.rhs))throw Error(`Discrete comparison (!=) adjusted right-hand side (${a.rhs}) exceeds safe integer range.`);return a._setDiscreteVars(i),a}toConstraint(t,n,r){let i=this.clone(),a=0;if(typeof n==`number`)a=n;else if(n instanceof F||typeof n==`object`&&n&&`sense`in n&&`lhs`in n)throw Error(`Cannot compare against a Constraint in (${t}): expected a number, Var, or LinExpr.`);else if(n instanceof w||typeof n==`object`&&n&&`quadTerms`in n){let r=n;if(r.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in linear constraints (${t}): quadratic terms are only allowed in objectives.`);i=i.sub(new e(r.linearTerms,0,r.nonlinearTerms??[])),a=r.constant}else`terms`in n?(i=i.sub(new e(n.terms,0,n.nonlinearTerms??[])),a=n.constant):i=i.sub(n);let o=a-i.constant;return i.constant=0,new F(i,t,o,r)}and(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'and': expected a BoolVar, Constraint, or BoolOp.`)}or(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'or': expected a BoolVar, Constraint, or BoolOp.`)}implies(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'implies': expected a BoolVar, Constraint, or BoolOp.`)}xor(e){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'xor': expected a BoolVar, Constraint, or BoolOp.`)}not(){throw Error(`Cannot use an arithmetic expression without a comparison operator (<=, >=, ==, !=, <, >) in logical 'not': expected a BoolVar, Constraint, or BoolOp.`)}toString(){let e=[],t=!0;for(let[n,r]of this.terms){let i=r>=0?t?``:`+ `:`- `,a=Math.abs(r),o=a===1?``:`${a} `;e.push(`${i}${o}${n.name}`),t=!1}for(let n of this.nonlinearTerms){let r=n.coeff,i=r>=0?t?``:`+ `:`- `,a=Math.abs(r),o=a===1?``:`${a} `;e.push(`${i}${o}${pe(n.atom)}`),t=!1}if(this.constant!==0||e.length===0){let n=this.constant>=0?t?``:`+ `:`- `;e.push(`${n}${Math.abs(this.constant)}`)}return e.join(` `)||`0`}};function z(e,t){let n=new Map,r=[],i=0;function a(e){return e instanceof F||e.kind===`constraint`||`sense`in e&&(e.sense===`<=`||e.sense===`>=`||e.sense===`==`||e.sense===`!=`)&&`lhs`in e&&`rhs`in e&&typeof e.rhs==`number`&&typeof e.lhs==`object`&&e.lhs!==null&&`terms`in e.lhs&&e.lhs.terms instanceof Map}function o(e){return e instanceof w||`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map&&typeof e.constant==`number`}function s(e){return e instanceof R||`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`}function c(e){return e instanceof V||!a(e)&&typeof e.id==`number`&&typeof e.name==`string`&&typeof e.lb==`number`&&typeof e.ub==`number`&&typeof e.type==`string`&&typeof e.mul==`function`}function l(e){return a(e)||o(e)||s(e)||c(e)}function u(e){if(typeof e!=`object`||!e||Array.isArray(e)||l(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function d(e){if(e!=null){if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid non-finite number "${e}" in sum().`);let t=i+e;if(!Number.isFinite(t))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);i=t}else if(typeof e==`object`&&a(e))throw Error(`Cannot sum a constraint comparison (<=, >=, ==) in sum(): expected a number, Var, or LinExpr.`);else if(typeof e==`object`&&o(e)){let t=e;if(t.quadTerms.size>0)throw Error(`Quadratic expressions are not supported in sum(): sum() produces a linear expression (LinExpr).`);if(!Number.isFinite(t.constant))throw Error(`Invalid non-finite constant "${t.constant}" in sum().`);for(let[e,r]of t.linearTerms){if(!Number.isFinite(r))throw Error(`Invalid non-finite coefficient "${r}" in sum().`);let t=(n.get(e)??0)+r;if(!Number.isFinite(t))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);n.set(e,t)}let a=i+t.constant;if(!Number.isFinite(a))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);if(i=a,Array.isArray(t.nonlinearTerms))for(let e of t.nonlinearTerms){if(!Number.isFinite(e.coeff))throw Error(`Invalid non-finite coefficient "${e.coeff}" in sum().`);e.coeff!==0&&r.push({atom:I(e.atom),coeff:e.coeff})}}else if(typeof e==`object`&&s(e)){let t=e;if(!Number.isFinite(t.constant))throw Error(`Invalid non-finite constant "${t.constant}" in sum().`);for(let[e,r]of t.terms){if(!Number.isFinite(r))throw Error(`Invalid non-finite coefficient "${r}" in sum().`);let t=(n.get(e)??0)+r;if(!Number.isFinite(t))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);n.set(e,t)}let a=i+t.constant;if(!Number.isFinite(a))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);if(i=a,Array.isArray(t.nonlinearTerms))for(let e of t.nonlinearTerms){if(!Number.isFinite(e.coeff))throw Error(`Invalid non-finite coefficient "${e.coeff}" in sum().`);e.coeff!==0&&r.push({atom:I(e.atom),coeff:e.coeff})}}else if(typeof e==`object`&&c(e)){let t=e,r=(n.get(t)??0)+1;if(!Number.isFinite(r))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);n.set(t,r)}else throw Error(`Unsupported item in sum(): expected a number, Var, or LinExpr.`)}}function f(e,t=0){if(e!=null){if(typeof e==`number`){d(e);return}if(typeof e==`object`){if(l(e)){d(e);return}if(!(e instanceof String)&&!(e instanceof Map)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`){if(t>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);for(let n of e)f(n,t+1);return}if(u(e)){if(t>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in sum().`);for(let n of Object.keys(e))f(e[n],t+1);return}}d(e)}}if(typeof e==`number`){if(typeof t!=`function`)throw Error(`sum(count, mapFn) requires a mapping function as the second argument.`);if(!Number.isInteger(e)||e<0)throw Error(`sum(count, mapFn) requires a non-negative integer count.`);let n=e;for(let e=0;e<n;e++)f(t(e,e),0)}else if(typeof e==`object`&&e&&!(e instanceof String)&&(!(e instanceof Map)||typeof t==`function`)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`){let n=0;for(let r of e)t?f(t(r,n++),0):f(r,1)}else if(u(e)){if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in sum().`);let n=0;for(let r of Object.keys(e)){let i=e[r];t?f(t(i,n++),0):f(i,1)}}else throw Error(`Unsupported item in sum(): expected an Iterable, Record, or (count, mapFn).`);for(let[e,t]of n)t===0&&n.delete(e);return new R(n,i,r)}function _e(e,t){let n=new Map,r=[],i=0;function a(e){return typeof e==`object`&&!!e&&!(e instanceof F)&&typeof e.id==`number`&&typeof e.name==`string`&&typeof e.lb==`number`&&typeof e.ub==`number`&&typeof e.type==`string`&&typeof e.mul==`function`&&typeof e.le==`function`}function o(e){return a(e)||e instanceof R||e instanceof w}function s(e,t,o){if(!Number.isFinite(e))throw Error(`Invalid non-finite coefficient "${e}" in dot() at '${o||`root`}'.`);if(t instanceof w)throw Error(`Quadratic expressions are not supported in dot() at '${o||`root`}': dot() produces a linear expression (LinExpr).`);if(t instanceof R){if(!Number.isFinite(t.constant))throw Error(`Invalid non-finite constant "${t.constant}" in dot() at '${o||`root`}'.`);let a=e===0||t.constant===0?0:e*t.constant;if(e!==0&&t.constant!==0&&a===0)throw Error(`Constant multiplication underflows to zero.`);if(!Number.isFinite(a))throw Error(`Coefficient multiplication overflows finite floating-point range in dot() at '${o||`root`}'.`);let s=i+a;if(!Number.isFinite(s))throw Error(`Constant accumulation overflows finite floating-point range in dot() at '${o||`root`}'.`);i=s;for(let[r,i]of t.terms){if(!Number.isFinite(i))throw Error(`Invalid non-finite coefficient "${i}" in dot() at '${o||`root`}'.`);let t=e*i;if(e!==0&&i!==0&&t===0)throw Error(`Coefficient multiplication underflows to zero.`);if(!Number.isFinite(t))throw Error(`Coefficient multiplication overflows finite floating-point range in dot() at '${o||`root`}'.`);let a=(n.get(r)??0)+t;if(!Number.isFinite(a))throw Error(`Coefficient accumulation overflows finite floating-point range in dot() at '${o||`root`}'.`);n.set(r,a)}if(Array.isArray(t.nonlinearTerms)&&e!==0)for(let n of t.nonlinearTerms){if(!Number.isFinite(n.coeff))throw Error(`Invalid non-finite coefficient "${n.coeff}" in dot() at '${o||`root`}'.`);let t=e*n.coeff;if(n.coeff!==0&&t===0)throw Error(`Coefficient multiplication underflows to zero.`);if(!Number.isFinite(t))throw Error(`Coefficient multiplication overflows finite floating-point range in dot() at '${o||`root`}'.`);t!==0&&r.push({atom:I(n.atom),coeff:t})}}else if(a(t)){let r=t,i=(n.get(r)??0)+e;if(!Number.isFinite(i))throw Error(`Coefficient accumulation overflows finite floating-point range in dot() at '${o||`root`}'.`);n.set(r,i)}else throw Error(`Cannot multiply number by non-variable/expression operand in dot() at '${o||`root`}'.`)}function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!o(e)&&!(e instanceof F)&&e.kind!==`constraint`}function l(e,t,n=``){if(e===void 0||t===void 0||e===null||t===null)throw Error(`Nullish or undefined operand encountered in dot() at '${n||`root`}'.`);if(typeof e==`number`&&typeof t==`number`)throw Error(`Cannot multiply two numbers in dot() at '${n||`root`}': expected one numeric coefficient and one Var or LinExpr.`);if(typeof e==`number`){s(e,t,n);return}if(typeof t==`number`){s(t,e,n);return}if(Array.isArray(e)||Array.isArray(t)){if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)throw Error(`Array length mismatch in dot() at '${n||`root`}': received lengths ${e.length} and ${t.length}.`);for(let r=0;r<e.length;r++)l(e[r],t[r],n?`${n}[${r}]`:`[${r}]`);return}let r=Array.isArray(e)?e:t,i=Array.isArray(e)?t:e;if(c(i)){if(Object.getOwnPropertySymbols(i).length>0)throw Error(`Symbol keys are not supported in dot() at '${n||`root`}'.`);let a=Object.keys(i);if(a.length===r.length&&a.every(e=>/^(?:0|[1-9]\d*)$/.test(e))){let a=[];for(let e=0;e<r.length;e++)Object.prototype.hasOwnProperty.call(i,e)||a.push(e);if(a.length>0)throw Error(`Key mismatch in dot() at '${n||`root`}': missing indices [${a.join(`, `)}] in numeric record.`);for(let i=0;i<r.length;i++)l(e[i],t[i],n?`${n}[${i}]`:`[${i}]`);return}throw a.length>0&&a.every(e=>/^(?:0|[1-9]\d*)$/.test(e))?Error(`Array length mismatch in dot() at '${n||`root`}': array has length ${r.length}, but object has ${a.length} indices.`):Error(`Type mismatch in dot() at '${n||`root`}': one operand is an Array while the other is an Object with keys [${a.slice(0,5).join(`, `)}].`)}throw Error(`Type mismatch in dot() at '${n||`root`}': one operand is an Array while the other is not.`)}if(c(e)&&c(t)){if(Object.getOwnPropertySymbols(e).length>0||Object.getOwnPropertySymbols(t).length>0)throw Error(`Symbol keys are not supported in dot() at '${n||`root`}'.`);let r=Object.keys(e),i=Object.keys(t),a=r.filter(e=>!Object.prototype.hasOwnProperty.call(t,e)),o=i.filter(t=>!Object.prototype.hasOwnProperty.call(e,t));if(a.length>0||o.length>0){let e=[];throw a.length>0&&e.push(`missing in second operand: [${a.join(`, `)}]`),o.length>0&&e.push(`missing in first operand: [${o.join(`, `)}]`),Error(`Key mismatch in dot() at '${n||`root`}': ${e.join(`; `)}.`)}for(let i of r)l(e[i],t[i],n?`${n}.${i}`:i);return}throw Error(`Unsupported operand types in dot() at '${n||`root`}'.`)}l(e,t);for(let[e,t]of n)t===0&&n.delete(e);return new R(n,i,r)}function ve(e){let t=ge(e,`abs()`);return t.terms.size===0&&t.nonlinearTerms.length===0?new R(new Map,Math.abs(t.constant)+0):new R(new Map,0,[{atom:{kind:`abs`,arg:t},coeff:1}])}function ye(e,t){if(t.length===0)throw Error(`${e}() requires at least one expression.`);let n=[],r=e=>typeof e==`number`||fe(e)||he(e)||e instanceof R||e instanceof w||typeof e==`object`&&!!e&&(`terms`in e&&e.terms instanceof Map||`quadTerms`in e&&e.quadTerms instanceof Map),i=e=>{if(typeof e!=`object`||!e||Array.isArray(e)||r(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},a=t=>{n.push(ge(t,`${e}()`))},o=(t,n)=>{if(t==null)throw Error(`Unsupported nullish item in ${e}(): expected a finite number, Var, or LinExpr.`);if(typeof t==`number`||r(t)){a(t);return}if(Array.isArray(t)){if(n>=2)throw Error(`Nested containers deeper than 2D are not supported in ${e}().`);for(let r=0;r<t.length;r++){if(!(r in t))throw Error(`Unsupported item in ${e}(): sparse array hole at index ${r}.`);o(t[r],n+1)}return}if(typeof t==`object`&&!(t instanceof String)&&!(t instanceof Map)&&Symbol.iterator in t&&typeof t[Symbol.iterator]==`function`){if(n>=2)throw Error(`Nested containers deeper than 2D are not supported in ${e}().`);for(let e of t)o(e,n+1);return}if(i(t)){if(n>=2)throw Error(`Nested containers deeper than 2D are not supported in ${e}().`);if(Object.getOwnPropertySymbols(t).length>0)throw Error(`Symbol keys are not supported in ${e}().`);for(let e of Object.keys(t))o(t[e],n+1);return}throw Error(`Unsupported item in ${e}(): expected a finite number, Var, or LinExpr.`)};if(t.length===2&&typeof t[1]==`function`){let n=t[0],r=t[1];if(typeof n==`number`){if(!Number.isInteger(n)||n<0)throw Error(`${e}(count, mapFn) requires a non-negative integer count.`);for(let e=0;e<n;e++)o(r(e,e),0)}else if(Array.isArray(n))for(let t=0;t<n.length;t++){if(!(t in n))throw Error(`Unsupported item in ${e}(): sparse array hole at index ${t}.`);o(r(n[t],t),0)}else if(typeof n==`object`&&n&&!(n instanceof String)&&Symbol.iterator in n&&typeof n[Symbol.iterator]==`function`){let e=0;for(let t of n)o(r(t,e++),0)}else if(i(n)){if(Object.getOwnPropertySymbols(n).length>0)throw Error(`Symbol keys are not supported in ${e}().`);let t=0;for(let e of Object.keys(n))o(r(n[e],t++),0)}else throw Error(`Invalid first argument in ${e}(itemsOrCount, mapFn): expected an Iterable, Record, or non-negative integer count.`)}else for(let n of t){if(typeof n==`function`)throw Error(`Function interpolation in ${e}() is only supported as ${e}(itemsOrCount, mapFn).`);o(n,0)}if(n.length===0)throw Error(`${e}() requires at least one expression.`);return n}function be(e,t){if(t.length===1)return t[0].clone();if(t.every(e=>e.terms.size===0&&e.nonlinearTerms.length===0)){let n=t.map(e=>e.constant),r=e===`max`?Math.max(...n):Math.min(...n);return new R(new Map,Object.is(r,-0)?0:r)}return new R(new Map,0,[{atom:{kind:e,args:t},coeff:1}])}function xe(...e){return be(`max`,ye(`max`,e))}function Se(...e){return be(`min`,ye(`min`,e))}function B(e,t){if(!Array.isArray(e))throw Error(`at(array, index) requires an Array as its first argument.`);if(e.length===0)throw Error(`at(array, index) requires an array with at least 1 element.`);let n=Array(e.length);for(let t=0;t<e.length;t++){if(!(t in e))throw Error(`at(array, index) encountered sparse array hole at index ${t}.`);n[t]=ge(e[t],`at() array[${t}]`)}let r=ge(t,`at() index`),i=L(r,`at() index`);return new R(new Map,0,[{atom:{kind:`at`,array:n,index:r,discreteVars:i},coeff:1}])}var Ce=0;function we(e){if(e===void 0)return`Continuous`;if(typeof e==`string`){let t=e.toLowerCase();if(t===`binary`||t===`bin`)return`Binary`;if(t===`integer`||t===`int`)return`Integer`;if(t===`continuous`||t===`cont`)return`Continuous`}throw Error(`Invalid variable type "${String(e)}": expected "Continuous", "Integer", or "Binary".`)}var V=class{id;_name;prefix;hasExplicitName;ownerModel=null;_type;_lb;_ub;_initialValue;value=null;reducedCost=null;constructor(e={}){this.id=++Ce;let t=typeof e.name==`string`?e.name.trim():``,n=typeof e.prefix==`string`?e.prefix.trim():``;this.prefix=n.length>0?n:`x`,this.hasExplicitName=t.length>0,this._name=this.hasExplicitName?t:`${this.prefix}_${this.id}`,this._type=we(e.type),this._type===`Binary`?(this._lb=0,this._ub=1):(this._lb=e.lb===void 0?0:e.lb,this._ub=e.ub===void 0?1/0:e.ub),this._initialValue=e.initialValue===void 0?void 0:Object.is(e.initialValue,-0)?0:e.initialValue,this._initialValue!==void 0&&M(this)}get name(){return this._name}get type(){return this._type}set type(e){let t=we(e);this._type!==t&&(this._type=t,k(this.ownerModel))}get lb(){return this._lb}set lb(e){Object.is(this._lb,e)||(this._lb=e,k(this.ownerModel))}get ub(){return this._ub}set ub(e){Object.is(this._ub,e)||(this._ub=e,k(this.ownerModel))}get initialValue(){return this._initialValue}set initialValue(e){let t=e!==void 0&&Object.is(e,-0)?0:e;Object.is(this._initialValue,t)||(this._initialValue=t,k(this.ownerModel))}_assignModelName(e){this._name=e}mul(e){return typeof e==`number`?new R(new Map([[this,1]]),0).mul(e):new w(new Map([[this,1]]),new Map,0).mul(e)}add(e){return e instanceof w?e.add(this):new R(new Map([[this,1]]),0).add(e)}sub(e){return e instanceof w?e.neg().add(this):new R(new Map([[this,1]]),0).sub(e)}neg(){return this.mul(-1)}le(e,t){return new R(new Map([[this,1]]),0).le(e,t)}ge(e,t){return new R(new Map([[this,1]]),0).ge(e,t)}eq(e,t){return new R(new Map([[this,1]]),0).eq(e,t)}lt(e,t){return new R(new Map([[this,1]]),0).lt(e,t)}gt(e,t){return new R(new Map([[this,1]]),0).gt(e,t)}ne(e,t){return new R(new Map([[this,1]]),0).ne(e,t)}toString(){return this.name}};function H(e){return typeof e==`object`&&!!e&&e.kind===`container`}var Te=/^(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/;function Ee(e,t){let n=[],r=0,i=e.length;for(;r<i;){let a=e[r];if(/\s/.test(a)){r++;continue}if(a===`+`)n.push({type:`PLUS`,value:`+`}),r++;else if(a===`-`)n.push({type:`MINUS`,value:`-`}),r++;else if(a===`*`)r+1<i&&e[r+1]===`*`?(n.push({type:`CARET`,value:`**`}),r+=2):(n.push({type:`STAR`,value:`*`}),r++);else if(a===`^`)n.push({type:`CARET`,value:`^`}),r++;else if(a===`/`)n.push({type:`SLASH`,value:`/`}),r++;else if(a===`(`)n.push({type:`LPAREN`,value:`(`}),r++;else if(a===`)`)n.push({type:`RPAREN`,value:`)`}),r++;else if(a===`,`)n.push({type:`COMMA`,value:`,`}),r++;else if(a===`<`||a===`>`||a===`=`||a===`!`){let t=a;if(r+1<i&&(e[r+1]===`=`||a!==`!`&&(e[r+1]===`<`||e[r+1]===`>`))?(t+=e[r+1],r+=2):r++,t===`!`)throw Error(`Unexpected character '!' at position ${r-1} in: "${e}"`);n.push({type:`COMP`,value:t})}else if(/[0-9.]/.test(a)){let t=r,a=``;for(;r<i&&/[0-9]/.test(e[r]);)a+=e[r++];if(r<i&&e[r]===`.`)for(a+=e[r++];r<i&&/[0-9]/.test(e[r]);)a+=e[r++];if(r<i&&(e[r]===`e`||e[r]===`E`)){let t=r+1<i?e[r+1]:``;if(!/[a-zA-Z_]/.test(t)){for(a+=e[r++],r<i&&(e[r]===`+`||e[r]===`-`)&&(a+=e[r++]);r<i&&/[0-9]/.test(e[r]);)a+=e[r++];for(;r<i&&(e[r]===`.`||e[r]===`e`||e[r]===`E`||/[0-9]/.test(e[r]));)a+=e[r++]}}else for(;r<i&&(e[r]===`.`||/[0-9]/.test(e[r]));)a+=e[r++];if(!Te.test(a))throw Error(`Invalid numeric literal '${a}' at position ${t} in: "${e}"`);let o=Number(a);if(!Number.isFinite(o))throw Error(`Numeric literal '${a}' overflows finite floating-point range in: "${e}"`);if(o===0&&!/^[0.]+(?:[eE][+-]?\d+)?$/.test(a))throw Error(`Numeric literal '${a}' underflows to zero at position ${t} in: "${e}"`);n.push({type:`NUMBER`,value:a,numericValue:o})}else if(/[a-zA-Z_]/.test(a)){let a=``;for(;r<i&&/[a-zA-Z0-9_]/.test(e[r]);)a+=e[r],r++;if(t&&t.has(a)){let e=t.get(a);n.push({type:`NUMBER`,value:String(e),numericValue:e})}else n.push({type:`IDENT`,value:a})}else throw Error(`Unexpected character '${a}' at position ${r} in: "${e}"`)}return n}function De(e){return e instanceof w&&e.quadTerms.size===0?new R(e.linearTerms,e.constant,e.nonlinearTerms):e}function Oe(e){return typeof e==`number`||e instanceof V||e instanceof R||e instanceof w||He(e)}function ke(e){return typeof e==`number`?new R(new Map,e):e instanceof V||`id`in e&&!(`terms`in e)&&!(`quadTerms`in e)?new R(new Map([[e,1]]),0):e.clone()}function Ae(e,t,n){if(typeof e==`number`&&typeof t==`number`){if(n===`+`){let n=e+t;if(!Number.isFinite(n))throw Error(`Invalid non-finite constant "${n}" in expression.`);return n}if(n===`-`){let n=e-t;if(!Number.isFinite(n))throw Error(`Invalid non-finite constant "${n}" in expression.`);return n}if(n===`*`){let n=e*t;if(e!==0&&t!==0&&n===0)throw Error(`Constant multiplication underflows to zero.`);if(!Number.isFinite(n))throw Error(`Invalid non-finite constant "${n}" in expression.`);return n}if(t===0)throw Error(`Division by zero`);let r=1/t*e;if(e!==0&&r===0)throw Error(`Constant multiplication underflows to zero.`);if(!Number.isFinite(r))throw Error(`Invalid non-finite constant "${r}" in expression.`);return r}let r=ke(e),i=ke(t),a;a=n===`+`?r.add(i):n===`-`?r.sub(i):n===`*`?r.mul(i):r.div(i);let o=De(a);return q(o),o}function U(e,t){if(Array.isArray(e)){let n=Array(e.length);for(let r=0;r<e.length;r++){let i=e[r];n[r]=Oe(i)?t(i):U(i,t)}return n}let n=Object.create(null);for(let r of Object.keys(e)){let i=e[r];n[r]=Oe(i)?t(i):U(i,t)}return n}function je(e,t,n,r=``){let i=Oe(e),a=Oe(t);if(i&&a)return Ae(e,t,n);if(i||a)throw Error(`Dimension mismatch in template expression at '${r||`root`}': cannot combine scalar element with sub-container.`);if(Array.isArray(e)||Array.isArray(t)){if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)throw Error(`Array length mismatch in template expression at '${r||`root`}': received lengths ${e.length} and ${t.length}.`);let i=Array(e.length);for(let a=0;a<e.length;a++)i[a]=je(e[a],t[a],n,r?`${r}[${a}]`:`[${a}]`);return i}let i=Array.isArray(e)?e:t,a=Array.isArray(e)?t:e,o=Object.keys(a);if(o.length===i.length&&o.every(e=>/^(?:0|[1-9]\d*)$/.test(e))){let o=[];for(let e=0;e<i.length;e++)Object.prototype.hasOwnProperty.call(a,e)||o.push(e);if(o.length>0)throw Error(`Key mismatch in template expression at '${r||`root`}': missing indices [${o.join(`, `)}] in numeric record.`);let s=Array(i.length);for(let a=0;a<i.length;a++){let i=e[a],o=t[a];s[a]=je(i,o,n,r?`${r}[${a}]`:`[${a}]`)}return s}throw o.length>0&&o.every(e=>/^(?:0|[1-9]\d*)$/.test(e))?Error(`Array length mismatch in template expression at '${r||`root`}': array has length ${i.length}, but object has ${o.length} indices.`):Error(`Type mismatch in template expression at '${r||`root`}': one operand is an Array while the other is an Object with keys [${o.slice(0,5).join(`, `)}].`)}let o=e,s=t,c=Object.keys(o),l=Object.keys(s),u=c.filter(e=>!Object.prototype.hasOwnProperty.call(s,e)),d=l.filter(e=>!Object.prototype.hasOwnProperty.call(o,e));if(u.length>0||d.length>0){let e=[];throw u.length>0&&e.push(`missing in second operand: [${u.join(`, `)}]`),d.length>0&&e.push(`missing in first operand: [${d.join(`, `)}]`),Error(`Key mismatch in template expression at '${r||`root`}': ${e.join(`; `)}.`)}let f=Object.create(null);for(let e of c)f[e]=je(o[e],s[e],n,r?`${r}.${e}`:e);return f}function W(e,t,n){let r=H(e),i=H(t);if(!r&&!i)return Ae(e,t,n);if(r&&!i)return{kind:`container`,data:U(e.data,e=>Ae(e,t,n)),fromNonArrayIterable:e.fromNonArrayIterable};if(!r&&i)return{kind:`container`,data:U(t.data,t=>Ae(e,t,n)),fromNonArrayIterable:t.fromNonArrayIterable};let a=e,o=t;return{kind:`container`,data:je(a.data,o.data,n),fromNonArrayIterable:a.fromNonArrayIterable||o.fromNonArrayIterable}}function Me(e){return typeof e==`number`?-e:H(e)?{kind:`container`,data:U(e.data,e=>typeof e==`number`?-e:ke(e).neg()),fromNonArrayIterable:e.fromNonArrayIterable}:e.neg()}function Ne(e,t){let n=e instanceof w,r=n?e.quadTerms.size:0,i=n?e.linearTerms.size:e.terms.size,a=Array.isArray(e.nonlinearTerms)?e.nonlinearTerms.length:0;if(r===0&&i===0&&a===0){let n=e.constant**+t;if(e.constant!==0&&t>0&&n===0)throw Error(`Constant exponentiation underflows to zero.`);return new R(new Map,n)}if(t===0)return new R(new Map,1);if(t===1)return e;if(a>0)throw Error(`Cannot multiply nonlinear expression (max, min, abs, or at) by a variable expression: only scalar multiplication is supported.`);if(t===2)return e.mul(e);throw Error(`Exponent ${t} creates a non-linear term of degree > 2 (not allowed in MILP/LP/QP)`)}function Pe(e){if(typeof e!=`object`||!e||Array.isArray(e)||He(e)||Ue(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Fe(e){if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid numeric value "${e}" in template expression: interpolated numbers must be finite.`);return e}if(Ue(e))throw Error(`Cannot interpolate a constraint comparison (<=, >=, ==) inside a template expression: expected a finite number, Var, LinExpr, or QuadExpr.`);if(He(e))return q(e),e instanceof V||`id`in e&&!(`terms`in e)&&!(`quadTerms`in e)?e:e.clone();throw Error(`Unsupported interpolation value in template expression: expected a finite number, Var, LinExpr, or QuadExpr.`)}function Ie(e){return typeof e==`object`&&!!e&&!(e instanceof String)&&!(e instanceof Map)&&!He(e)&&!Ue(e)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`}function Le(e,t=0){if(Array.isArray(e)){let n=!1,r=Array(e.length);for(let i=0;i<e.length;i++){if(!(i in e))throw Error(`Unsupported interpolation value in template expression: sparse array hole at index ${i}.`);let a=e[i];if(Array.isArray(a)||Pe(a)||Ie(a)){if(t>=1)throw Error(`Nested containers deeper than 2D are not supported in template expressions.`);let e=Le(a,t+1);e.fromNonArrayIterable&&(n=!0),r[i]=e.data}else r[i]=Fe(a)}return{kind:`container`,data:r,fromNonArrayIterable:n}}if(Ie(e))return{kind:`container`,data:Array.from(e).map(e=>{if(Array.isArray(e)||Pe(e)||Ie(e)){if(t>=1)throw Error(`Nested containers deeper than 2D are not supported in template expressions.`);return Le(e,t+1).data}return Fe(e)}),fromNonArrayIterable:!0};if(Pe(e)){if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in template expression at 'root'.`);let n=!1,r=Object.create(null);for(let i of Object.keys(e)){let a=e[i];if(Array.isArray(a)||Pe(a)||Ie(a)){if(t>=1)throw Error(`Nested containers deeper than 2D are not supported in template expressions.`);let e=Le(a,t+1);e.fromNonArrayIterable&&(n=!0),r[i]=e.data}else r[i]=Fe(a)}return{kind:`container`,data:r,fromNonArrayIterable:n}}throw Error(`Unsupported interpolation value in template expression: expected a finite number, Var, LinExpr, or QuadExpr.`)}var Re=class{tokens;pos=0;resolver;templateCtx;constructor(e,t,n){this.tokens=e,this.resolver=t,this.templateCtx=n}peek(){return this.tokens[this.pos]}consume(e){let t=this.tokens[this.pos++];if(!t)throw Error(`Unexpected end of input`);if(e&&t.value!==e&&t.type!==e)throw Error(`Expected '${e}', but found '${t.value}'`);return t}parseExpression(){let e=this.parseExpressionNode();if(H(e))throw Error(`Container expression (Array or Record) cannot be used directly as a scalar expression or constraint; wrap it in sum(...) or use dot(a, b).`);return typeof e==`number`?new R(new Map,e):De(e)}parseExpressionNode(){let e=this.parseTermNode();for(;this.pos<this.tokens.length;){let t=this.peek();if(!t)break;if(t.type===`PLUS`)this.consume(),e=W(e,this.parseTermNode(),`+`);else if(t.type===`MINUS`)this.consume(),e=W(e,this.parseTermNode(),`-`);else break}return H(e)||typeof e==`number`?e:De(e)}parseTermNode(){let e=this.parseFactorNode();for(;this.pos<this.tokens.length;){let t=this.peek();if(!t)break;if(t.type===`STAR`)this.consume(),e=W(e,this.parseFactorNode(),`*`);else if(t.type===`SLASH`)this.consume(),e=W(e,this.parseFactorNode(),`/`);else break}return e}parseFactorNode(){let e=this.peek();if(!e)throw Error(`Unexpected end of expression`);if(e.type===`PLUS`)return this.consume(),this.parseFactorNode();if(e.type===`MINUS`)return this.consume(),Me(this.parseFactorNode());let t;if(e.type===`NUMBER`){this.consume();let n=e.numericValue??Number(e.value);if(this.peek()?.type===`IDENT`||this.peek()?.type===`LPAREN`){let e=this.parsePrimaryNode();return W(this.applyPowerNode(e),n,`*`)}t=n}else if(e.type===`IDENT`||e.type===`LPAREN`)t=this.parsePrimaryNode();else throw Error(`Unexpected token '${e.value}' in expression`);return this.applyPowerNode(t)}parsePrimaryNode(){if(this.peek()?.type===`IDENT`){let e=this.consume();return(e.value===`sum`||e.value===`dot`||e.value===`abs`||e.value===`max`||e.value===`min`||e.value===`at`)&&this.peek()?.type===`LPAREN`?this.parseFunctionCall(e.value):this.resolveNode(e.value)}this.consume(`LPAREN`);let e=this.parseExpressionNode();return this.consume(`RPAREN`),e}parseFunctionCall(e){this.consume(`LPAREN`);let t=1;for(let n=this.pos;n<this.tokens.length&&t>0;n++){let r=this.tokens[n];if(r.type===`LPAREN`)t++;else if(r.type===`RPAREN`)t--;else if(r.type===`COMP`)throw Error(e===`sum`?`Cannot sum a constraint comparison (<=, >=, ==, !=, <, >) in sum(): expected arithmetic expressions.`:e===`dot`?`Cannot use a constraint comparison (<=, >=, ==, !=, <, >) in dot(): expected 1D or 2D Array or Record containers.`:`Cannot use a constraint comparison (<=, >=, ==, !=, <, >) in ${e}(): expected arithmetic expressions.`)}if(this.peek()?.type===`RPAREN`)throw this.consume(`RPAREN`),Error(e===`dot`?`dot() in template expression requires exactly 2 arguments: dot(a, b).`:e===`at`?`at() in template expression requires exactly 2 arguments: at(array, index).`:e===`abs`?`abs() in template expression requires 1 argument.`:`${e}() in template expression requires at least 1 argument.`);if(e===`abs`){let e=this.parseExpressionNode();if(this.peek()?.type===`COMMA`)throw Error(`abs() in template expression accepts exactly 1 argument.`);return this.consume(`RPAREN`),H(e)?{kind:`container`,data:U(e.data,e=>ve(e)),fromNonArrayIterable:e.fromNonArrayIterable}:ve(e)}if(e===`at`){let e=this.parseExpressionNode();if(this.peek()?.type!==`COMMA`)throw Error(`at() in template expression requires exactly 2 arguments: at(array, index).`);this.consume(`COMMA`);let t=this.parseExpressionNode();if(this.peek()?.type===`COMMA`)throw Error(`at() in template expression requires exactly 2 arguments: at(array, index).`);if(this.consume(`RPAREN`),!H(e)||e.fromNonArrayIterable||!Array.isArray(e.data))throw Error(`at(array, index) requires a 1D Array as its first argument.`);if(H(t))throw Error(`at(array, index) requires a discrete scalar expression as its index.`);let n=B(e.data,t);return q(n),n}if(e===`max`||e===`min`){let t=this.pos,n=0;for(;this.tokens[t]?.type===`LPAREN`;)n++,t++;if(this.tokens[t]?.type===`IDENT`&&this.templateCtx?.rawContainerMap.has(this.tokens[t].value)){let r=this.tokens[t].value,i=t+1,a=0;for(;a<n&&this.tokens[i]?.type===`RPAREN`;)a++,i++;if(a===n&&this.tokens[i]?.type===`COMMA`){let t=this.tokens[i+1];if(t?.type===`IDENT`&&this.templateCtx.functionMap.has(t.value)&&this.tokens[i+2]?.type===`RPAREN`){this.pos=i+2,this.consume(`RPAREN`);let n=this.templateCtx.functionMap.get(t.value);return this.evalExtremumWithMapper(e,this.templateCtx.rawContainerMap.get(r),n)}}}if(this.tokens[this.pos]?.type===`IDENT`&&this.templateCtx?.rawContainerMap.has(this.tokens[this.pos].value)&&this.tokens[this.pos+1]?.type===`RPAREN`){let t=this.consume();this.consume(`RPAREN`);let n=this.templateCtx.rawContainerMap.get(t.value),r=e===`max`?xe(n):Se(n);return q(r),r}let r=this.parseExpressionNode();if(this.peek()?.type===`COMMA`){let t=this.tokens[this.pos+1];if(t&&t.type===`IDENT`&&this.templateCtx?.functionMap.has(t.value)){this.consume(`COMMA`);let t=this.consume();if(this.peek()?.type===`COMMA`)throw Error(`${e}(itemsOrCount, mapFn) accepts at most 2 arguments when using a mapper.`);this.consume(`RPAREN`);let n=this.templateCtx.functionMap.get(t.value);if(typeof r==`number`)return this.evalExtremumWithMapper(e,r,n);if(!H(r)&&r instanceof R&&r.terms.size===0&&r.nonlinearTerms.length===0)return this.evalExtremumWithMapper(e,r.constant,n);if(H(r))return this.evalExtremumWithMapper(e,r.data,n);throw Error(`Invalid first argument in ${e}(itemsOrCount, mapFn): expected an Iterable, Record, or non-negative integer count.`)}let n=[H(r)?r.data:r];for(;this.peek()?.type===`COMMA`;){this.consume(`COMMA`);let e=this.parseExpressionNode();n.push(H(e)?e.data:e)}this.consume(`RPAREN`);let i=e===`max`?xe(...n):Se(...n);return q(i),i}this.consume(`RPAREN`);let i=H(r)?r.data:r,a=e===`max`?xe(i):Se(i);return q(a),a}if(e===`sum`){if(this.tokens[this.pos]?.type===`IDENT`&&this.templateCtx?.rawContainerMap.has(this.tokens[this.pos].value)&&this.tokens[this.pos+1]?.type===`RPAREN`){let e=this.consume();this.consume(`RPAREN`);let t=this.templateCtx.rawContainerMap.get(e.value);return this.accumulateSumItems(e=>{e(t,0)})}let e=this.pos,t=0;for(;this.tokens[e]?.type===`LPAREN`;)t++,e++;if(this.tokens[e]?.type===`IDENT`&&this.templateCtx?.rawContainerMap.has(this.tokens[e].value)){let n=this.tokens[e].value,r=e+1,i=0;for(;i<t&&this.tokens[r]?.type===`RPAREN`;)i++,r++;if(i===t&&this.tokens[r]?.type===`COMMA`){this.pos=r+1;let e=this.peek();if(!e||e.type!==`IDENT`||!this.templateCtx.functionMap.has(e.value))throw Error(`Second argument to sum() must be a mapping function: sum(itemsOrCount, mapFn).`);if(this.consume(),this.peek()?.type===`COMMA`)throw Error(`sum() in template expression accepts at most 2 arguments: sum(container) or sum(itemsOrCount, mapFn).`);return this.consume(`RPAREN`),this.evalSumWithMapper(this.templateCtx.rawContainerMap.get(n),this.templateCtx.functionMap.get(e.value))}}let n=this.parseExpressionNode();if(this.peek()?.type===`COMMA`){this.consume(`COMMA`);let e=this.peek();if(!e||e.type!==`IDENT`||!this.templateCtx?.functionMap.has(e.value))throw Error(`Second argument to sum() must be a mapping function: sum(itemsOrCount, mapFn).`);if(this.consume(),this.peek()?.type===`COMMA`)throw Error(`sum() in template expression accepts at most 2 arguments: sum(container) or sum(itemsOrCount, mapFn).`);this.consume(`RPAREN`);let t=this.templateCtx.functionMap.get(e.value);if(typeof n==`number`)return this.evalSumWithMapper(n,t);if(!H(n)&&n instanceof R&&n.terms.size===0)return this.evalSumWithMapper(n.constant,t);if(H(n))return this.evalSumWithMapper(n.data,t);throw Error(`Invalid first argument in sum(itemsOrCount, mapFn): expected an Iterable, Record, or non-negative integer count.`)}return this.consume(`RPAREN`),this.evalSumSingle(n)}let n=this.parseExpressionNode();if(this.peek()?.type!==`COMMA`)throw Error(`dot() in template expression requires exactly 2 arguments: dot(a, b).`);this.consume(`COMMA`);let r=this.parseExpressionNode();if(this.peek()?.type===`COMMA`)throw Error(`dot() in template expression requires exactly 2 arguments: dot(a, b).`);return this.consume(`RPAREN`),this.evalDot(n,r)}accumulateSumItems(e){let t=new Map,n=new Map,r=[],i=0,a=(e,o=0)=>{if(e!=null){if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid non-finite number "${e}" in sum().`);let t=i+e;if(!Number.isFinite(t))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);i=t;return}if(Ue(e))throw Error(`Cannot sum a constraint comparison (<=, >=, ==) in sum(): expected a number, Var, LinExpr, or QuadExpr.`);if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map){let a=e;q(a);let o=i+a.constant;if(!Number.isFinite(o))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);i=o;for(let[e,n]of a.linearTerms){let r=(t.get(e)??0)+n;if(!Number.isFinite(r))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);t.set(e,r)}for(let[e,t]of a.quadTerms){let r=n.get(e);if(r){let i=r.coeff+t.coeff;if(!Number.isFinite(i))throw Error(`Quadratic coefficient accumulation overflows finite floating-point range in sum().`);n.set(e,{var1:t.var1,var2:t.var2,coeff:i})}else n.set(e,{var1:t.var1,var2:t.var2,coeff:t.coeff})}if(Array.isArray(a.nonlinearTerms))for(let e of a.nonlinearTerms)e.coeff!==0&&r.push({atom:I(e.atom),coeff:e.coeff});return}if(e instanceof R||typeof e==`object`&&e&&`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`){let n=e;q(n);let a=i+n.constant;if(!Number.isFinite(a))throw Error(`Constant accumulation overflows finite floating-point range in sum().`);i=a;for(let[e,r]of n.terms){let n=(t.get(e)??0)+r;if(!Number.isFinite(n))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);t.set(e,n)}if(Array.isArray(n.nonlinearTerms))for(let e of n.nonlinearTerms)e.coeff!==0&&r.push({atom:I(e.atom),coeff:e.coeff});return}if(He(e)){let n=e,r=(t.get(n)??0)+1;if(!Number.isFinite(r))throw Error(`Coefficient accumulation overflows finite floating-point range in sum().`);t.set(n,r);return}if(Array.isArray(e)){if(o>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);for(let t=0;t<e.length;t++){if(!(t in e))throw Error(`Unsupported item in sum(): sparse array hole at index ${t}.`);a(e[t],o+1)}return}if(Ie(e)){if(o>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);for(let t of e)a(t,o+1);return}if(Pe(e)){if(o>=2)throw Error(`Nested containers deeper than 2D are not supported in sum().`);if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in sum().`);for(let t of Object.keys(e))a(e[t],o+1);return}throw Error(`Unsupported item in sum(): expected a number, Var, LinExpr, or QuadExpr.`)}};e(a);for(let[e,n]of t)n===0&&t.delete(e);for(let[e,t]of n)t.coeff===0&&n.delete(e);return n.size>0?new w(t,n,i,r):new R(t,i,r)}evalExtremumWithMapper(e,t,n){let r=e===`max`?xe(t,n):Se(t,n);return q(r),r}evalSumSingle(e){if(!H(e))throw Error(`sum() requires a container (Array, Iterable, or Record) or (itemsOrCount, mapFn).`);return this.accumulateSumItems(t=>{t(e.data,0)})}evalSumWithMapper(e,t){return this.accumulateSumItems(n=>{if(typeof e==`number`){if(!Number.isInteger(e)||e<0)throw Error(`sum(count, mapFn) requires a non-negative integer count.`);for(let r=0;r<e;r++)n(t(r,r));return}if(Array.isArray(e)){for(let r=0;r<e.length;r++){if(!(r in e))throw Error(`Unsupported item in sum(): sparse array hole at index ${r}.`);n(t(e[r],r))}return}if(typeof e==`object`&&e&&!(e instanceof String)&&Symbol.iterator in e&&typeof e[Symbol.iterator]==`function`){let r=0;for(let i of e)n(t(i,r++));return}if(Pe(e)){if(Object.getOwnPropertySymbols(e).length>0)throw Error(`Symbol keys are not supported in sum().`);let r=0;for(let i of Object.keys(e))n(t(e[i],r++));return}throw Error(`Invalid first argument in sum(itemsOrCount, mapFn): expected an Iterable, Record, or non-negative integer count.`)})}evalDot(e,t){if(!H(e)||!H(t))throw Error(`dot() in template expression requires 1D or 2D Array or Record containers as arguments.`);if(e.fromNonArrayIterable||t.fromNonArrayIterable)throw Error(`Unsupported operand types in dot() at 'root': dot() requires Array or Record containers (use sum() for general Iterables).`);let n=_e(e.data,t.data);return q(n),n}applyPowerNode(e){if(this.peek()?.type!==`CARET`)return e;let t=[];for(;this.peek()?.type===`CARET`;){this.consume();let e=this.tokens[this.pos]?.type===`LPAREN`&&this.tokens[this.pos+1]?.type===`NUMBER`&&this.tokens[this.pos+2]?.type===`RPAREN`;e&&this.consume(`LPAREN`);let n=this.peek();if(!n||n.type!==`NUMBER`)throw Error(`Exponent must be a non-negative integer number`);this.consume(),e&&this.consume(`RPAREN`);let r=n.numericValue??Number(n.value);if(!Number.isInteger(r)||r<0)throw Error(`Exponent must be a non-negative integer`);t.push(r)}let n=t[t.length-1];for(let e=t.length-2;e>=0;e--)n=t[e]**+n;if(!Number.isFinite(n)||n<0)throw Error(`Exponent creates an invalid or out-of-range power`);if(typeof e==`number`){let t=e**+n;if(e!==0&&n>0&&t===0)throw Error(`Constant exponentiation underflows to zero.`);if(!Number.isFinite(t))throw Error(`Invalid non-finite constant "${t}" in expression.`);return t}return H(e)?{kind:`container`,data:U(e.data,e=>{if(typeof e==`number`){let t=e**+n;if(e!==0&&n>0&&t===0)throw Error(`Constant exponentiation underflows to zero.`);if(!Number.isFinite(t))throw Error(`Constant exponentiation overflows finite floating-point range.`);return t}let t=De(Ne(ke(e),n));return q(t),t}),fromNonArrayIterable:e.fromNonArrayIterable}:Ne(e,n)}getRemainingToken(){return this.peek()}resolveNode(e){if(this.templateCtx?.functionMap.has(e))throw Error(`Function interpolation is only supported as the second argument of sum(itemsOrCount, mapFn) in template expressions.`);if(this.templateCtx?.rawContainerMap.has(e))return Le(this.templateCtx.rawContainerMap.get(e));let t=this.resolver(e);if(!t)throw Error(`Unknown variable '${e}' in expression`);return t instanceof V||`id`in t&&!(`terms`in t)&&!(`quadTerms`in t)?new R(new Map([[t,1]]),0):t.clone()}};function G(e,t,n,r){let i=new Re(Ee(e,n),t,r),a=i.parseExpression(),o=i.getRemainingToken();if(o)throw Error(`Unexpected token '${o.value}' after expression in "${e}"`);return q(a),a}function ze(e,t){return G(e,t)}function K(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`(`)t++;else if(r===`)`)t>0&&t--;else if(t===0){let t=e.slice(n,n+2);if(t===`<=`||t===`>=`||t===`==`||t===`!=`||t===`=<`||t===`=>`)return{rawOp:t,index:n};if(r===`=`||r===`<`||r===`>`)return{rawOp:r,index:n}}}return null}function Be(e,t,n,r,i){let a=K(e);if(!a)throw Error(`Constraint must contain a comparison operator (<=, >=, ==, !=, <, >): "${e}"`);let o=a.rawOp,s=a.index,c=e.substring(0,s).trim(),l=e.substring(s+o.length).trim(),u;if(o===`<=`||o===`=<`)u=`<=`;else if(o===`>=`||o===`=>`)u=`>=`;else if(o===`==`||o===`=`)u=`==`;else if(o===`!=`)u=`!=`;else if(o===`<`)u=`<`;else if(o===`>`)u=`>`;else throw Error(`Unsupported operator "${o}"`);let d=G(c,t,r,i),f=G(l,t,r,i);if(d instanceof w&&d.quadTerms.size>0||f instanceof w&&f.quadTerms.size>0)throw Error(`Quadratic constraints are not supported (only linear constraints are allowed in MILP/LP/QP)`);let p=d instanceof w?new R(d.linearTerms,d.constant,d.nonlinearTerms):d,m=f instanceof w?new R(f.linearTerms,f.constant,f.nonlinearTerms):f,h;if(h=u===`<=`?p.le(m,n):u===`>=`?p.ge(m,n):u===`==`?p.eq(m,n):u===`!=`?p.ne(m,n):u===`<`?p.lt(m,n):p.gt(m,n),q(h.lhs),!Number.isFinite(h.rhs))throw Error(`Invalid non-finite right-hand side "${h.rhs}" in constraint.`);return h}function Ve(e,t,n){return Be(e,t,n)}function He(e){return e instanceof V||e instanceof R||e instanceof w?!0:typeof e!=`object`||!e||Ue(e)?!1:`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`||`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map&&typeof e.constant==`number`||typeof e.id==`number`&&typeof e.name==`string`&&typeof e.lb==`number`&&typeof e.ub==`number`&&typeof e.type==`string`&&typeof e.mul==`function`}function q(e){if(`constant`in e&&!Number.isFinite(e.constant))throw Error(`Invalid non-finite constant "${e.constant}" in expression.`);if(`terms`in e&&e.terms instanceof Map){for(let[,t]of e.terms)if(!Number.isFinite(t))throw Error(`Invalid non-finite coefficient "${t}" in expression.`)}if(`linearTerms`in e&&e.linearTerms instanceof Map){for(let[,t]of e.linearTerms)if(!Number.isFinite(t))throw Error(`Invalid non-finite coefficient "${t}" in expression.`)}if(`quadTerms`in e&&e.quadTerms instanceof Map){for(let[,t]of e.quadTerms)if(!Number.isFinite(t.coeff))throw Error(`Invalid non-finite quadratic coefficient "${t.coeff}" in expression.`)}if(`nonlinearTerms`in e&&Array.isArray(e.nonlinearTerms))for(let t of e.nonlinearTerms){if(!Number.isFinite(t.coeff))throw Error(`Invalid non-finite coefficient "${t.coeff}" in expression.`);if(t.atom.kind===`abs`)q(t.atom.arg);else if(t.atom.kind===`max`||t.atom.kind===`min`)for(let e of t.atom.args)q(e);else if(t.atom.kind===`at`){q(t.atom.index);for(let e of t.atom.array)q(e)}}}function Ue(e){return e instanceof F?!0:typeof e!=`object`||!e?!1:e.kind===`constraint`||`sense`in e&&(e.sense===`<=`||e.sense===`>=`||e.sense===`==`||e.sense===`!=`)&&`lhs`in e&&`rhs`in e&&typeof e.rhs==`number`&&typeof e.lhs==`object`&&e.lhs!==null&&`terms`in e.lhs&&e.lhs.terms instanceof Map}function We(e,t){let n=new Map,r=new Map,i=new Map,a=new Map,o=e.join(``),s=`__washi_`;for(;o.includes(s);)s+=`_`;let c=``;for(let o=0;o<e.length;o++)if(c+=e[o],o<t.length){let e=t[o];if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`Invalid numeric value "${e}" in template expression: interpolated numbers must be finite.`);let t=`${s}num_${o}__`;r.set(t,e),c+=`(${t})`}else if(Ue(e))throw Error(`Cannot interpolate a constraint comparison (<=, >=, ==) inside a template expression: expected a finite number, Var, LinExpr, or QuadExpr.`);else if(He(e)){q(e);let t=`${s}ph_${o}__`;n.set(t,e),c+=` ${t} `}else if(typeof e==`function`){let t=`${s}fn_${o}__`;a.set(t,e),c+=` ${t} `}else if(Array.isArray(e)||Ie(e)||e instanceof Map||Pe(e)){let t=`${s}ph_${o}__`;i.set(t,e),c+=` ${t} `}else throw Error(`Unsupported interpolation value in template expression: expected a finite number, Var, LinExpr, or QuadExpr.`)}return{fullText:c,resolver:e=>n.get(e),numberMap:r,templateCtx:{rawContainerMap:i,functionMap:a}}}function Ge(e,...t){let{fullText:n,resolver:r,numberMap:i,templateCtx:a}=We(e,t);return K(n)?Be(n,r,void 0,i,a):G(n,r,i,a)}function Ke(e){return typeof e==`object`&&!!e&&typeof e.lpString==`string`&&e.nameToVar instanceof Map&&e.nameToConstraint instanceof Map}function qe(e,t=`x`,n=0){let r=e.replace(/[^a-zA-Z0-9_]/g,`_`);return/^[0-9]/.test(r)&&(r=`${t}_${r}`),(!r||r.length===0)&&(r=`${t}_${n}`),r}function Je(e){let t=e.variables||[],n=e.constraints||[],r=new Map,i=new Map,a=new Map,o=new Map,s=new Map,c=new Set;for(let e=0;e<t.length;e++){let n=t[e];s.set(n,e);let a=qe(n.name,`x`,e),o=a,l=1;for(;c.has(o);)o=`${a}_${l++}`;c.add(o),i.set(n,o),r.set(o,n)}let l=new Set;for(let e=0;e<n.length;e++){let t=n[e],r=qe(t.name,`c`,e+1),i=r,s=1;for(;l.has(i);)i=`${r}_${s++}`;l.add(i),o.set(t,i),a.set(i,t)}return{nameToVar:r,varToName:i,nameToConstraint:a,constraintToName:o,constrToName:o,varOrder:s}}function Ye(e,t){let{sense:n,objective:r,constraints:i,variables:a}=e;if(typeof r.hasNonlinearTerms==`function`&&r.hasNonlinearTerms())throw Error(`generateLpString() received an unlowered nonlinear objective (max/min/abs/at). Lower via Model.toLpString() or linearizeModelForMip() first.`);let o=t?.relax===!0,{nameToVar:s,varToName:c,nameToConstraint:l,constrToName:u,varOrder:d}=Je(e),f=[];f.push(n&&n.toLowerCase()===`maximize`?`Maximize`:`Minimize`);let p=[],m=!0,h=r instanceof w?r.linearTerms:r.terms;if(h)for(let[e,t]of h){if(t===0)continue;let n=c.get(e),r=t>=0?m?``:`+ `:`- `,i=Math.abs(t),a=i===1?``:`${i} `;p.push(`${r}${a}${n}`),m=!1}if(r instanceof w&&r.quadTerms.size>0){let e=[],t=!0,n=Array.from(r.quadTerms.values()).filter(e=>e.coeff!==0).map(e=>{let t=d.get(e.var1)??e.var1.id,n=d.get(e.var2)??e.var2.id,[r,i,a,o]=t<=n?[e.var1,e.var2,t,n]:[e.var2,e.var1,n,t];return{firstVar:r,secondVar:i,firstIdx:a,secondIdx:o,coeff:e.coeff}}).sort((e,t)=>e.firstIdx-t.firstIdx||e.secondIdx-t.secondIdx);for(let r of n){let n=2*r.coeff,i=n>=0?t?``:`+ `:`- `,a=Math.abs(n),o=a===1?``:`${a} `,s=c.get(r.firstVar),l=c.get(r.secondVar);r.firstVar===r.secondVar?e.push(`${i}${o}${s} ^ 2`):e.push(`${i}${o}${s} * ${l}`),t=!1}if(e.length>0){let t=`[ ${e.join(` `)} ] / 2`;p.length>0?p.push(`+`,t):p.push(t)}}let g=p.length>0?p.join(` `):`0`;f.push(` obj: ${g}`),f.push(`Subject To`);for(let e of i){if(e.sense===`!=`||e.lhs.hasNonlinearTerms())throw Error(`generateLpString() received unlowered constraint "${e.name}" (${e.sense===`!=`?`discrete !=`:`nonlinear max/min/abs/at`}). Lower via Model.toLpString() or linearizeModelForMip() first.`);let t=u.get(e),n=[],r=!0;for(let[t,i]of e.lhs.terms){if(i===0)continue;let e=c.get(t),a=i>=0?r?``:`+ `:`- `,o=Math.abs(i),s=o===1?``:`${o} `;n.push(`${a}${s}${e}`),r=!1}let i=n.length>0?n.join(` `):`0`,a=e.sense===`==`?`=`:e.sense;f.push(` ${t}: ${i} ${a} ${e.rhs}`)}f.push(`Bounds`);let _=[],v=[];for(let e of a){let t=c.get(e);if(!o&&e.type===`Binary`){v.push(t);continue}!o&&e.type===`Integer`&&_.push(t);let n=e.lb===-1/0,r=e.ub===1/0;n&&r?f.push(` ${t} free`):n&&!r?f.push(` -infinity <= ${t} <= ${e.ub}`):!n&&r?(e.lb!==0||e.initialValue!==void 0)&&f.push(` ${t} >= ${e.lb}`):f.push(` ${e.lb} <= ${t} <= ${e.ub}`)}if(_.length>0){f.push(`Generals`);for(let e=0;e<_.length;e+=10)f.push(` `+_.slice(e,e+10).join(` `))}if(v.length>0){f.push(`Binary`);for(let e=0;e<v.length;e+=10)f.push(` `+v.slice(e,e+10).join(` `))}return f.push(`End`),{lpString:f.join(`
2
2
  `)+`
3
- `,nameToVar:s,nameToConstraint:l}}var qe=Symbol.for(`washi.solverRegistry`),Je=Symbol.for(`washi.defaultSolverFactory`),Ye=globalThis;Ye[qe]||(Ye[qe]=new Map);var Xe=Ye[qe];function Ze(e,t){Xe.set(e.toLowerCase(),t)}function Qe(e){if(typeof e==`string`){let t=Xe.get(e.toLowerCase());if(!t)throw Error(`Solver '${e}' is not registered.`);Ye[Je]=t}else Ye[Je]=typeof e==`function`?e:()=>e}function $e(e,t){if(!e){let e=Ye[Je]||Xe.get(`highs`);if(!e)throw Error(`No default solver available. Available solvers: ${et().join(`, `)}`);return e(t)}if(typeof e==`string`){let n=e.toLowerCase(),r=Xe.get(n);if(!r)throw Error(n===`glpk`?`Solver 'glpk' not found. Available solvers: ${et().join(`, `)}. Please import '@ohtaman/washi/solvers/glpk' before selecting this solver.`:n===`z3`?`Solver 'z3' not found. Available solvers: ${et().join(`, `)}. Please import '@ohtaman/washi/solvers/z3' before selecting this solver.`:n===`pumpkin`?`Solver 'pumpkin' not found. Available solvers: ${et().join(`, `)}. Please import '@ohtaman/washi/solvers/pumpkin' before selecting this solver.`:`Solver '${e}' not found. Available solvers: ${et().join(`, `)}`);return r(t)}return e}function et(){return Array.from(Xe.keys())}var tt=typeof document<`u`?document.currentScript?.src:null,nt=tt?new URL(`.`,tt).href:null;function rt(e){if(!nt)throw Error(`[WaSHI] Load the browser IIFE using an external script src, or use the browser ESM build.`);return new URL(e,nt).href}function it(){return rt(`highs.wasm`)}function at(){throw Error(`This distribution is for browsers. Use the npm entry in Node.js.`)}function ot(e,t,n){if(n<=0||!t)return new Float64Array;let r=e.wasmMemory?e.wasmMemory.buffer:e.HEAPF64?e.HEAPF64.buffer:e.HEAP8?.buffer;if(r)return new Float64Array(r,t,n).slice();let i=new Float64Array(n);for(let r=0;r<n;r++)i[r]=e.getValue(t+r*8,`double`);return i}function st(e){return{create:e.cwrap(`Highs_create`,`number`,[]),destroy:e.cwrap(`Highs_destroy`,`void`,[`number`]),clearModel:e.cwrap(`Highs_clearModel`,`number`,[`number`]),version:e.cwrap(`Highs_version`,`string`,[]),readModel:e.cwrap(`Highs_readModel`,`number`,[`number`,`string`]),run:e.cwrap(`Highs_run`,`number`,[`number`]),getNumCol:e.cwrap(`Highs_getNumCol`,`number`,[`number`]),getNumRow:e.cwrap(`Highs_getNumRow`,`number`,[`number`]),getNumNz:e.cwrap(`Highs_getNumNz`,`number`,[`number`]),getObjectiveValue:e.cwrap(`Highs_getObjectiveValue`,`number`,[`number`]),getModelStatus:e.cwrap(`Highs_getModelStatus`,`number`,[`number`]),getSolution:e.cwrap(`Highs_getSolution`,`number`,[`number`,`number`,`number`,`number`,`number`]),getColName:e.cwrap(`Highs_getColName`,`number`,[`number`,`number`,`number`]),getRowName:e.cwrap(`Highs_getRowName`,`number`,[`number`,`number`,`number`]),getColIntegrality:e.cwrap(`Highs_getColIntegrality`,`number`,[`number`,`number`,`number`]),changeObjectiveOffset:e.cwrap(`Highs_changeObjectiveOffset`,`number`,[`number`,`number`]),getObjectiveOffset:e.cwrap(`Highs_getObjectiveOffset`,`number`,[`number`,`number`]),setBoolOptionValue:e.cwrap(`Highs_setBoolOptionValue`,`number`,[`number`,`string`,`number`]),setIntOptionValue:e.cwrap(`Highs_setIntOptionValue`,`number`,[`number`,`string`,`number`]),setDoubleOptionValue:e.cwrap(`Highs_setDoubleOptionValue`,`number`,[`number`,`string`,`number`]),setStringOptionValue:e.cwrap(`Highs_setStringOptionValue`,`number`,[`number`,`string`,`string`]),setSolution:e.cwrap(`Highs_setSolution`,`number`,[`number`,`number`,`number`,`number`,`number`]),setSparseSolution:e.cwrap(`Highs_setSparseSolution`,`number`,[`number`,`number`,`number`,`number`]),getIntInfoValue:e.cwrap(`Highs_getIntInfoValue`,`number`,[`number`,`string`,`number`]),getDoubleInfoValue:e.cwrap(`Highs_getDoubleInfoValue`,`number`,[`number`,`string`,`number`]),getInt64InfoValue:e.cwrap(`Highs_getInt64InfoValue`,`number`,[`number`,`string`,`number`]),setCallback:e.cwrap(`Highs_setCallback`,`number`,[`number`,`number`,`number`]),startCallback:e.cwrap(`Highs_startCallback`,`number`,[`number`,`number`]),stopCallback:e.cwrap(`Highs_stopCallback`,`number`,[`number`,`number`])}}var ct,lt,ut,dt,ft,pt,mt,ht=n((()=>{ct=class extends Error{constructor(e){super(e),this.name=`HighsError`}},lt=class extends ct{constructor(e){super(e),this.name=`HighsUnsupportedOptionError`}},ut={0:`Not Set`,1:`Load error`,2:`Model error`,3:`Presolve error`,4:`Solve error`,5:`Postsolve error`,6:`Empty`,7:`Optimal`,8:`Infeasible`,9:`Primal infeasible or unbounded`,10:`Unbounded`,11:`Bound on objective reached`,12:`Target for objective reached`,13:`Time limit reached`,14:`Iteration limit reached`,15:`Unknown`,16:`Solution limit reached`,17:`Interrupted`,18:`Memory limit reached`},dt={callbackType:{logging:0,simplexInterrupt:1,ipmInterrupt:2,mipSolution:3,mipImprovingSolution:4,mipLogging:5,mipInterrupt:6,mipGetCutPool:7,mipDefineLazyConstraints:8,mipUserSolution:9},solutionStatus:{none:0,infeasible:1,feasible:2},modelStatus:{notSet:0,loadError:1,modelError:2,presolveError:3,solveError:4,postsolveError:5,modelEmpty:6,optimal:7,infeasible:8,unboundedOrInfeasible:9,unbounded:10,objectiveBound:11,objectiveTarget:12,timeLimit:13,iterationLimit:14,unknown:15,solutionLimit:16,interrupt:17}},ft=0,pt=class{highs;module;bindings;stringBuf;isDestroyed=!1;constructor(e,t,n){this.module=e,this.bindings=t,this.highs=n??t.create(),this.stringBuf=e._malloc(512)}changeObjectiveOffset(e){let t=this.bindings.changeObjectiveOffset(this.highs,e);if(t!==0)throw new ct(`Highs_changeObjectiveOffset failed with status ${t}`)}getObjectiveOffset(){let e=this.module._malloc(8);try{return this.bindings.getObjectiveOffset(this.highs,e),this.module.getValue(e,`double`)}finally{this.module._free(e)}}options={set:(e,t)=>{let n=-1;if(typeof t==`boolean`?n=this.bindings.setBoolOptionValue(this.highs,e,+!!t):typeof t==`number`?Number.isInteger(t)?(n=this.bindings.setIntOptionValue(this.highs,e,t),n!==0&&(n=this.bindings.setDoubleOptionValue(this.highs,e,t))):n=this.bindings.setDoubleOptionValue(this.highs,e,t):typeof t==`string`&&(n=this.bindings.setStringOptionValue(this.highs,e,t)),n!==0)throw new lt(`Option "${e}" with value ${JSON.stringify(t)} is not supported or invalid in HiGHS`)}};getDimensions(){return{numCols:this.bindings.getNumCol(this.highs),numRows:this.bindings.getNumRow(this.highs)}}getColIntegrality(e){let t=this.module._malloc(4);try{return this.bindings.getColIntegrality(this.highs,e,t),this.module.getValue(t,`i32`)}finally{this.module._free(t)}}getColName(e){return this.bindings.getColName(this.highs,e,this.stringBuf),this.module.UTF8ToString(this.stringBuf)}getRowName(e){return this.bindings.getRowName(this.highs,e,this.stringBuf),this.module.UTF8ToString(this.stringBuf)}setSolution(e){if(e.colValue&&Array.isArray(e.colValue)){let t=e.colValue.length,n=this.module._malloc(t*8);try{for(let r=0;r<t;r++)this.module.setValue(n+r*8,e.colValue[r],`double`);let r=this.bindings.setSolution(this.highs,n,0,0,0);if(r!==0)throw new ct(`Highs_setSolution failed with status ${r}`)}finally{this.module._free(n)}return}if(e.indices&&e.values&&e.indices.length===e.values.length){let t=e.indices.length,n=this.module._malloc(t*4),r=this.module._malloc(t*8);try{for(let i=0;i<t;i++)this.module.setValue(n+i*4,e.indices[i],`i32`),this.module.setValue(r+i*8,e.values[i],`double`);let i=this.bindings.setSparseSolution(this.highs,t,n,r);if(i!==0)throw new ct(`Highs_setSparseSolution failed with status ${i}`)}finally{this.module._free(n),this.module._free(r)}return}throw new ct(`Invalid argument to setSolution (expected { colValue } or { indices, values })`)}run(e){let t=0,n=[];if(e){if(typeof this.module.addFunction!=`function`)throw new ct(`HiGHS WebAssembly runtime does not support module.addFunction; progress and interrupt callbacks are unavailable.`);t=this.module.addFunction((t,n,r,i)=>{let a=e[t];if(!a)return;let o={};if(r){let e=this.module.getValue(r+8,`double`),t=this.module.getValue(r+16,`i32`),n=this.module.getValue(r+20,`i32`),i=this.module.getValue(r+24,`i32`),a=this.module.getValue(r+32,`double`),s=Number(this.module.getValue(r+40,`i32`)),c=Number(this.module.getValue(r+48,`i32`)),l=this.module.getValue(r+56,`double`),u=this.module.getValue(r+64,`double`),d=this.module.getValue(r+72,`double`),f=this.module.getValue(r+80,`i32`),p=this.module.getValue(r+84,`i32`),m;f&&p>0&&(m=ot(this.module,f,p)),o={running_time:e,simplex_iteration_count:t,ipm_iteration_count:n,pdlp_iteration_count:i,objective_function_value:a,mip_node_count:s,mip_total_lp_iterations:c,mip_primal_bound:l,mip_dual_bound:u,mip_gap:d,...m?{mip_solution:m}:{}}}let s=n?this.module.UTF8ToString(n):``;a({data:o,message:s,interrupt:()=>{i&&this.module.setValue(i,1,`i32`)}})},`vipppp`),this.bindings.setCallback(this.highs,t,0);for(let t of Object.keys(e)){let e=Number(t);this.bindings.startCallback(this.highs,e),n.push(e)}}try{return this.bindings.run(this.highs)}finally{if(t){for(let e of n)try{this.bindings.stopCallback(this.highs,e)}catch{}try{this.module.removeFunction(t)}catch{}}}}getModelStatus(){return this.bindings.getModelStatus(this.highs)}info={get:e=>{let t=this.module._malloc(8);try{if(this.bindings.getDoubleInfoValue(this.highs,e,t)===0)return this.module.getValue(t,`double`)}finally{this.module._free(t)}let n=this.module._malloc(4);try{if(this.bindings.getIntInfoValue(this.highs,e,n)===0)return this.module.getValue(n,`i32`)}finally{this.module._free(n)}throw new ct(`Info item "${e}" not available or unknown in HiGHS`)}};getSolution(){let e=this.getDimensions(),t=e.numCols>0?this.module._malloc(e.numCols*8):0,n=e.numCols>0?this.module._malloc(e.numCols*8):0,r=e.numRows>0?this.module._malloc(e.numRows*8):0,i=e.numRows>0?this.module._malloc(e.numRows*8):0;try{return this.bindings.getSolution(this.highs,t,n,r,i),{colValue:ot(this.module,t,e.numCols),colDual:ot(this.module,n,e.numCols),rowValue:ot(this.module,r,e.numRows),rowDual:ot(this.module,i,e.numRows)}}finally{t&&this.module._free(t),n&&this.module._free(n),r&&this.module._free(r),i&&this.module._free(i)}}getObjectiveValue(){return this.bindings.getObjectiveValue(this.highs)}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.module._free(this.stringBuf)}catch{}try{this.bindings.destroy(this.highs)}catch{}}}[Symbol.dispose](){this.destroy()}},mt=class{module;bindings;constants=dt;errors={HighsError:ct,HighsUnsupportedOptionError:lt};constructor(e){this.module=e,this.bindings=st(e)}withModel(e,t){let n=this.bindings.create(),r=new pt(this.module,this.bindings,n),i=`/model_${++ft}.${e.format}`;if(!this.module.FS)throw new ct(`Emscripten FS is not initialized on this HiGHS module instance`);let a=this.module.FS;try{a.writeFile(i,e.data);let o=this.bindings.readModel(n,i);if(o!==0)throw new ct(`Failed to load ${e.format.toUpperCase()} model into HiGHS (status ${o})`);return t(r)}finally{try{a.unlink(i)}catch{}r.destroy()}}solve(e,t={}){return this.withModel({format:`lp`,data:e},e=>{for(let[n,r]of Object.entries(t))e.options.set(n,r);e.run();let n=e.getModelStatus(),r=e.getDimensions(),i=e.getSolution(),a={};for(let t=0;t<r.numCols;t++){let n=e.getColName(t);a[n]={Index:t,Name:n,Primal:i.colValue[t],Dual:i.colDual[t]}}return{Status:ut[n]??`Unknown`,StatusCode:n,ObjectiveValue:e.getObjectiveValue(),Columns:a}})}}})),gt,_t=n((()=>{gt=(()=>{var e={}.url;return(async function(t={}){var n=t,r,i;n.ready=new Promise((e,t)=>{r=e,i=t});var a=Object.assign({},n),o=`./this.program`,s=(e,t)=>{throw t},c=typeof window==`object`,l=typeof importScripts==`function`,u=``;function d(e){return n.locateFile?n.locateFile(e,u):u+e}var f,p,m;(c||l)&&(l?u=self.location.href:typeof document<`u`&&document.currentScript&&(u=document.currentScript.src),e&&(u=e),u=u.indexOf(`blob:`)===0?``:u.substr(0,u.replace(/[?#].*/,``).lastIndexOf(`/`)+1),f=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.send(null),t.responseText},l&&(m=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),p=(e,t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{if(r.status==200||r.status==0&&r.response){t(r.response);return}n()},r.onerror=n,r.send(null)});var h=n.print||console.log.bind(console),g=n.printErr||console.error.bind(console);Object.assign(n,a),a=null,n.arguments&&n.arguments,n.thisProgram&&(o=n.thisProgram),n.quit&&(s=n.quit);var _;n.wasmBinary&&(_=n.wasmBinary),typeof WebAssembly!=`object`&&L(`no native wasm support detected`);var v,y=!1;function b(e,t){e||L(t)}var x,S,C,w,T,E,D;function ee(){var e=v.buffer;n.HEAP8=x=new Int8Array(e),n.HEAP16=C=new Int16Array(e),n.HEAPU8=S=new Uint8Array(e),n.HEAPU16=new Uint16Array(e),n.HEAP32=w=new Int32Array(e),n.HEAPU32=T=new Uint32Array(e),n.HEAPF32=E=new Float32Array(e),n.HEAPF64=D=new Float64Array(e)}var O=[],k=[],A=[],te=!1;function ne(){if(n.preRun)for(typeof n.preRun==`function`&&(n.preRun=[n.preRun]);n.preRun.length;)j(n.preRun.shift());he(O)}function re(){te=!0,!n.noFSInit&&!J.init.initialized&&J.init(),J.ignorePermissions=!1,K.init(),he(k)}function ie(){if(n.postRun)for(typeof n.postRun==`function`&&(n.postRun=[n.postRun]);n.postRun.length;)ae(n.postRun.shift());he(A)}function j(e){O.unshift(e)}function M(e){k.unshift(e)}function ae(e){A.unshift(e)}var N=0,oe=null,P=null;function F(e){return e}function se(e){N++,n.monitorRunDependencies&&n.monitorRunDependencies(N)}function I(e){if(N--,n.monitorRunDependencies&&n.monitorRunDependencies(N),N==0&&(oe!==null&&(clearInterval(oe),oe=null),P)){var t=P;P=null,t()}}function L(e){n.onAbort&&n.onAbort(e),e=`Aborted(`+e+`)`,g(e),y=!0,e+=`. Build with -sASSERTIONS for more info.`,te&&xn();var t=new WebAssembly.RuntimeError(e);throw i(t),t}var ce=`data:application/octet-stream;base64,`,R=e=>e.startsWith(ce),le=e=>e.startsWith(`file://`),z;n.locateFile?(z=`highs.wasm`,R(z)||(z=d(z))):z=new URL(`highs.wasm`,``+{}.url).href;function ue(e){if(e==z&&_)return new Uint8Array(_);if(m)return m(e);throw`both async and sync fetching of the wasm failed`}function de(e){if(!_&&(c||l)){if(typeof fetch==`function`&&!le(e))return fetch(e,{credentials:`same-origin`}).then(t=>{if(!t.ok)throw`failed to load wasm binary file at '`+e+`'`;return t.arrayBuffer()}).catch(()=>ue(e));if(p)return new Promise((t,n)=>{p(e,e=>t(new Uint8Array(e)),n)})}return Promise.resolve().then(()=>ue(e))}function fe(e,t,n){return de(e).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(n,e=>{g(`failed to asynchronously prepare wasm: ${e}`),L(e)})}function B(e,t,n,r){return!e&&typeof WebAssembly.instantiateStreaming==`function`&&!R(t)&&!le(t)&&typeof fetch==`function`?fetch(t,{credentials:`same-origin`}).then(e=>WebAssembly.instantiateStreaming(e,n).then(r,function(e){return g(`wasm streaming compile failed: ${e}`),g(`falling back to ArrayBuffer instantiation`),fe(t,n,r)})):fe(t,n,r)}function pe(){var e={a:Ht};function t(e,t){return Q=e.exports,v=Q.s,n.wasmMemory=v,ee(),At=Q.ca,M(Q.t),I(`wasm-instantiate`),Q}se(`wasm-instantiate`);function r(e){t(e.instance)}if(n.instantiateWasm)try{return n.instantiateWasm(e,t)}catch(e){g(`Module.instantiateWasm callback failed with error: ${e}`),i(e)}return B(_,z,e,r).catch(i),{}}var V,H;function me(e){this.name=`ExitStatus`,this.message=`Program terminated with exit(${e})`,this.status=e}var he=e=>{for(;e.length>0;)e.shift()(n)};function ge(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:return x[e>>0];case`i8`:return x[e>>0];case`i16`:return C[e>>1];case`i32`:return w[e>>2];case`i64`:L(`to do getValue(i64) use WASM_BIGINT`);case`float`:return E[e>>2];case`double`:return D[e>>3];case`*`:return T[e>>2];default:L(`invalid type for getValue: ${t}`)}}var _e=n.noExitRuntime||!0;function ve(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:x[e>>0]=t;break;case`i8`:x[e>>0]=t;break;case`i16`:C[e>>1]=t;break;case`i32`:w[e>>2]=t;break;case`i64`:L(`to do setValue(i64) use WASM_BIGINT`);case`float`:E[e>>2]=t;break;case`double`:D[e>>3]=t;break;case`*`:T[e>>2]=t;break;default:L(`invalid type for setValue: ${n}`)}}var ye=e=>(w[vn()>>2]=e,e),U={isAbs:e=>e.charAt(0)===`/`,splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];i===`.`?e.splice(r,1):i===`..`?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift(`..`);return e},normalize:e=>{var t=U.isAbs(e),n=e.substr(-1)===`/`;return e=U.normalizeArray(e.split(`/`).filter(e=>!!e),!t).join(`/`),!e&&!t&&(e=`.`),e&&n&&(e+=`/`),(t?`/`:``)+e},dirname:e=>{var t=U.splitPath(e),n=t[0],r=t[1];return!n&&!r?`.`:(r&&=r.substr(0,r.length-1),n+r)},basename:e=>{if(e===`/`)return`/`;e=U.normalize(e),e=e.replace(/\/$/,``);var t=e.lastIndexOf(`/`);return t===-1?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return U.normalize(e.join(`/`))},join2:(e,t)=>U.normalize(e+`/`+t)},be=()=>{if(typeof crypto==`object`&&typeof crypto.getRandomValues==`function`)return e=>crypto.getRandomValues(e);L(`initRandomDevice`)},xe=e=>(xe=be())(e),W={resolve:function(){for(var e=``,t=!1,n=arguments.length-1;n>=-1&&!t;n--){var r=n>=0?arguments[n]:J.cwd();if(typeof r!=`string`)throw TypeError(`Arguments to path.resolve must be strings`);if(!r)return``;e=r+`/`+e,t=U.isAbs(r)}return e=U.normalizeArray(e.split(`/`).filter(e=>!!e),!t).join(`/`),(t?`/`:``)+e||`.`},relative:(e,t)=>{e=W.resolve(e).substr(1),t=W.resolve(t).substr(1);function n(e){for(var t=0;t<e.length&&e[t]===``;t++);for(var n=e.length-1;n>=0&&e[n]===``;n--);return t>n?[]:e.slice(t,n-t+1)}for(var r=n(e.split(`/`)),i=n(t.split(`/`)),a=Math.min(r.length,i.length),o=a,s=0;s<a;s++)if(r[s]!==i[s]){o=s;break}for(var c=[],s=o;s<r.length;s++)c.push(`..`);return c=c.concat(i.slice(o)),c.join(`/`)}},G=typeof TextDecoder<`u`?new TextDecoder(`utf8`):void 0,Se=(e,t,n)=>{for(var r=t+n,i=t;e[i]&&!(i>=r);)++i;if(i-t>16&&e.buffer&&G)return G.decode(e.subarray(t,i));for(var a=``;t<i;){var o=e[t++];if(!(o&128)){a+=String.fromCharCode(o);continue}var s=e[t++]&63;if((o&224)==192){a+=String.fromCharCode((o&31)<<6|s);continue}var c=e[t++]&63;if(o=(o&240)==224?(o&15)<<12|s<<6|c:(o&7)<<18|s<<12|c<<6|e[t++]&63,o<65536)a+=String.fromCharCode(o);else{var l=o-65536;a+=String.fromCharCode(55296|l>>10,56320|l&1023)}}return a},Ce=[],we=e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);r<=127?t++:r<=2047?t+=2:r>=55296&&r<=57343?(t+=4,++n):t+=3}return t},Te=(e,t,n,r)=>{if(!(r>0))return 0;for(var i=n,a=n+r-1,o=0;o<e.length;++o){var s=e.charCodeAt(o);if(s>=55296&&s<=57343){var c=e.charCodeAt(++o);s=65536+((s&1023)<<10)|c&1023}if(s<=127){if(n>=a)break;t[n++]=s}else if(s<=2047){if(n+1>=a)break;t[n++]=192|s>>6,t[n++]=128|s&63}else if(s<=65535){if(n+2>=a)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|s&63}else{if(n+3>=a)break;t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|s&63}}return t[n]=0,n-i};function Ee(e,t,n){var r=n>0?n:we(e)+1,i=Array(r),a=Te(e,i,0,i.length);return t&&(i.length=a),i}var De=()=>{if(!Ce.length){var e=null;if(typeof window<`u`&&typeof window.prompt==`function`?(e=window.prompt(`Input: `),e!==null&&(e+=`
3
+ `,nameToVar:s,nameToConstraint:l}}var Xe=Symbol.for(`washi.solverRegistry`),Ze=Symbol.for(`washi.defaultSolverFactory`),Qe=globalThis;Qe[Xe]||(Qe[Xe]=new Map);var $e=Qe[Xe];function et(e,t){$e.set(e.toLowerCase(),t)}function tt(e){if(typeof e==`string`){let t=$e.get(e.toLowerCase());if(!t)throw Error(`Solver '${e}' is not registered.`);Qe[Ze]=t}else Qe[Ze]=typeof e==`function`?e:()=>e}function nt(e,t){if(!e){let e=Qe[Ze]||$e.get(`highs`);if(!e)throw Error(`No default solver available. Available solvers: ${rt().join(`, `)}`);return e(t)}if(typeof e==`string`){let n=e.toLowerCase(),r=$e.get(n);if(!r)throw Error(n===`glpk`?`Solver 'glpk' not found. Available solvers: ${rt().join(`, `)}. Please import '@ohtaman/washi/solvers/glpk' before selecting this solver.`:n===`z3`?`Solver 'z3' not found. Available solvers: ${rt().join(`, `)}. Please import '@ohtaman/washi/solvers/z3' before selecting this solver.`:`Solver '${e}' not found. Available solvers: ${rt().join(`, `)}`);return r(t)}return e}function rt(){return Array.from($e.keys())}var it=class{name;capabilities;options;constructor(e={}){this.name=e.name||`MockSolver`,this.capabilities=e.capabilities||{supportsMIP:!0,supportsQP:!0,supportsWarmStart:!0},this.options=e}async solve(e,t={},n={}){let r=Ke(t)?n:t,i={...this.options,...r},a=!!(i.values&&Object.keys(i.values).length>0||i.boolValues&&Object.keys(i.boolValues).length>0);if(i.signal?.aborted)return{status:`Unknown`,terminationStatus:`Interrupted`,hasPrimalSolution:!1,objectiveValue:null,values:{},runTime:0,raw:{mock:!0}};if(i.delayMs&&i.delayMs>0&&(await new Promise(e=>{let t=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},i.delayMs),n=()=>{clearTimeout(t),e()};i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.aborted)){let e=!!(i.hasPrimalSolution??a);return{status:e?`Feasible`:`Unknown`,terminationStatus:`Interrupted`,hasPrimalSolution:e,objectiveValue:e?i.objectiveValue??0:null,...i.objectiveBound===void 0?{}:{objectiveBound:i.objectiveBound},...i.relativeGap===void 0?{}:{relativeGap:i.relativeGap},...i.absoluteGap===void 0?{}:{absoluteGap:i.absoluteGap},values:e&&i.values||{},...e&&i.boolValues!==void 0?{boolValues:i.boolValues}:{},runTime:.001,raw:{mock:!0}}}if(i.onProgress&&Array.isArray(i.progressEvents))for(let e of i.progressEvents){if(i.signal?.aborted)break;i.onProgress(e)}let o=i.status||`Optimal`,s=i.terminationStatus??o,c=i.hasPrimalSolution===void 0?o===`Optimal`||o===`Feasible`||o===`Sat`||(o===`TimeLimit`||o===`IterationLimit`||s===`Interrupted`)&&a:i.hasPrimalSolution;if(i.onProgress&&!Array.isArray(i.progressEvents)&&!i.signal?.aborted){let e=c?i.objectiveValue??0:void 0;i.onProgress({elapsedTime:.001,elapsedSeconds:.001,...typeof e==`number`&&Number.isFinite(e)?{objectiveValue:e}:{},...i.objectiveBound===void 0?{}:{objectiveBound:i.objectiveBound},...i.relativeGap===void 0?{}:{relativeGap:i.relativeGap},...i.absoluteGap===void 0?{}:{absoluteGap:i.absoluteGap}})}return i.signal?.aborted&&(s=`Interrupted`,c=i.hasPrimalSolution===void 0?a:i.hasPrimalSolution,o=c?`Feasible`:`Unknown`),{status:o,terminationStatus:s,hasPrimalSolution:c,objectiveValue:c?i.objectiveValue??0:null,...i.objectiveBound===void 0?{}:{objectiveBound:i.objectiveBound},...i.relativeGap===void 0?{}:{relativeGap:i.relativeGap},...i.absoluteGap===void 0?{}:{absoluteGap:i.absoluteGap},values:c&&i.values||{},...c&&i.boolValues!==void 0?{boolValues:i.boolValues}:{},reducedCosts:i.reducedCosts,duals:i.duals,slacks:i.slacks,runTime:.001,raw:{mock:!0}}}};function at(){et(`mock`,e=>new it(e))}at();var ot=typeof document<`u`?document.currentScript?.src:null,st=ot?new URL(`.`,ot).href:null;function ct(e){if(!st)throw Error(`[WaSHI] Load the browser IIFE using an external script src, or use the browser ESM build.`);return new URL(e,st).href}function lt(){return ct(`solvers/highs.wasm`)}function ut(){throw Error(`This distribution is for browsers. Use the npm entry in Node.js.`)}function dt(e,t,n){if(n<=0||!t)return new Float64Array;let r=e.wasmMemory?e.wasmMemory.buffer:e.HEAPF64?e.HEAPF64.buffer:e.HEAP8?.buffer;if(r)return new Float64Array(r,t,n).slice();let i=new Float64Array(n);for(let r=0;r<n;r++)i[r]=e.getValue(t+r*8,`double`);return i}function ft(e){return{create:e.cwrap(`Highs_create`,`number`,[]),destroy:e.cwrap(`Highs_destroy`,`void`,[`number`]),clearModel:e.cwrap(`Highs_clearModel`,`number`,[`number`]),version:e.cwrap(`Highs_version`,`string`,[]),readModel:e.cwrap(`Highs_readModel`,`number`,[`number`,`string`]),run:e.cwrap(`Highs_run`,`number`,[`number`]),getNumCol:e.cwrap(`Highs_getNumCol`,`number`,[`number`]),getNumRow:e.cwrap(`Highs_getNumRow`,`number`,[`number`]),getNumNz:e.cwrap(`Highs_getNumNz`,`number`,[`number`]),getObjectiveValue:e.cwrap(`Highs_getObjectiveValue`,`number`,[`number`]),getModelStatus:e.cwrap(`Highs_getModelStatus`,`number`,[`number`]),getSolution:e.cwrap(`Highs_getSolution`,`number`,[`number`,`number`,`number`,`number`,`number`]),getColName:e.cwrap(`Highs_getColName`,`number`,[`number`,`number`,`number`]),getRowName:e.cwrap(`Highs_getRowName`,`number`,[`number`,`number`,`number`]),getColIntegrality:e.cwrap(`Highs_getColIntegrality`,`number`,[`number`,`number`,`number`]),changeObjectiveOffset:e.cwrap(`Highs_changeObjectiveOffset`,`number`,[`number`,`number`]),getObjectiveOffset:e.cwrap(`Highs_getObjectiveOffset`,`number`,[`number`,`number`]),setBoolOptionValue:e.cwrap(`Highs_setBoolOptionValue`,`number`,[`number`,`string`,`number`]),setIntOptionValue:e.cwrap(`Highs_setIntOptionValue`,`number`,[`number`,`string`,`number`]),setDoubleOptionValue:e.cwrap(`Highs_setDoubleOptionValue`,`number`,[`number`,`string`,`number`]),setStringOptionValue:e.cwrap(`Highs_setStringOptionValue`,`number`,[`number`,`string`,`string`]),setSolution:e.cwrap(`Highs_setSolution`,`number`,[`number`,`number`,`number`,`number`,`number`]),setSparseSolution:e.cwrap(`Highs_setSparseSolution`,`number`,[`number`,`number`,`number`,`number`]),getIntInfoValue:e.cwrap(`Highs_getIntInfoValue`,`number`,[`number`,`string`,`number`]),getDoubleInfoValue:e.cwrap(`Highs_getDoubleInfoValue`,`number`,[`number`,`string`,`number`]),getInt64InfoValue:e.cwrap(`Highs_getInt64InfoValue`,`number`,[`number`,`string`,`number`]),setCallback:e.cwrap(`Highs_setCallback`,`number`,[`number`,`number`,`number`]),startCallback:e.cwrap(`Highs_startCallback`,`number`,[`number`,`number`]),stopCallback:e.cwrap(`Highs_stopCallback`,`number`,[`number`,`number`])}}var pt,mt,ht,gt,_t,vt,yt,bt=n((()=>{pt=class extends Error{constructor(e){super(e),this.name=`HighsError`}},mt=class extends pt{constructor(e){super(e),this.name=`HighsUnsupportedOptionError`}},ht={0:`Not Set`,1:`Load error`,2:`Model error`,3:`Presolve error`,4:`Solve error`,5:`Postsolve error`,6:`Empty`,7:`Optimal`,8:`Infeasible`,9:`Primal infeasible or unbounded`,10:`Unbounded`,11:`Bound on objective reached`,12:`Target for objective reached`,13:`Time limit reached`,14:`Iteration limit reached`,15:`Unknown`,16:`Solution limit reached`,17:`Interrupted`,18:`Memory limit reached`},gt={callbackType:{logging:0,simplexInterrupt:1,ipmInterrupt:2,mipSolution:3,mipImprovingSolution:4,mipLogging:5,mipInterrupt:6,mipGetCutPool:7,mipDefineLazyConstraints:8,mipUserSolution:9},solutionStatus:{none:0,infeasible:1,feasible:2},modelStatus:{notSet:0,loadError:1,modelError:2,presolveError:3,solveError:4,postsolveError:5,modelEmpty:6,optimal:7,infeasible:8,unboundedOrInfeasible:9,unbounded:10,objectiveBound:11,objectiveTarget:12,timeLimit:13,iterationLimit:14,unknown:15,solutionLimit:16,interrupt:17}},_t=0,vt=class{highs;module;bindings;stringBuf;isDestroyed=!1;constructor(e,t,n){this.module=e,this.bindings=t,this.highs=n??t.create(),this.stringBuf=e._malloc(512)}changeObjectiveOffset(e){let t=this.bindings.changeObjectiveOffset(this.highs,e);if(t!==0)throw new pt(`Highs_changeObjectiveOffset failed with status ${t}`)}getObjectiveOffset(){let e=this.module._malloc(8);try{return this.bindings.getObjectiveOffset(this.highs,e),this.module.getValue(e,`double`)}finally{this.module._free(e)}}options={set:(e,t)=>{let n=-1;if(typeof t==`boolean`?n=this.bindings.setBoolOptionValue(this.highs,e,+!!t):typeof t==`number`?Number.isInteger(t)?(n=this.bindings.setIntOptionValue(this.highs,e,t),n!==0&&(n=this.bindings.setDoubleOptionValue(this.highs,e,t))):n=this.bindings.setDoubleOptionValue(this.highs,e,t):typeof t==`string`&&(n=this.bindings.setStringOptionValue(this.highs,e,t)),n!==0)throw new mt(`Option "${e}" with value ${JSON.stringify(t)} is not supported or invalid in HiGHS`)}};getDimensions(){return{numCols:this.bindings.getNumCol(this.highs),numRows:this.bindings.getNumRow(this.highs)}}getColIntegrality(e){let t=this.module._malloc(4);try{return this.bindings.getColIntegrality(this.highs,e,t),this.module.getValue(t,`i32`)}finally{this.module._free(t)}}getColName(e){return this.bindings.getColName(this.highs,e,this.stringBuf),this.module.UTF8ToString(this.stringBuf)}getRowName(e){return this.bindings.getRowName(this.highs,e,this.stringBuf),this.module.UTF8ToString(this.stringBuf)}setSolution(e){if(e.colValue&&Array.isArray(e.colValue)){let t=e.colValue.length,n=this.module._malloc(t*8);try{for(let r=0;r<t;r++)this.module.setValue(n+r*8,e.colValue[r],`double`);let r=this.bindings.setSolution(this.highs,n,0,0,0);if(r!==0)throw new pt(`Highs_setSolution failed with status ${r}`)}finally{this.module._free(n)}return}if(e.indices&&e.values&&e.indices.length===e.values.length){let t=e.indices.length,n=this.module._malloc(t*4),r=this.module._malloc(t*8);try{for(let i=0;i<t;i++)this.module.setValue(n+i*4,e.indices[i],`i32`),this.module.setValue(r+i*8,e.values[i],`double`);let i=this.bindings.setSparseSolution(this.highs,t,n,r);if(i!==0)throw new pt(`Highs_setSparseSolution failed with status ${i}`)}finally{this.module._free(n),this.module._free(r)}return}throw new pt(`Invalid argument to setSolution (expected { colValue } or { indices, values })`)}run(e){let t=0,n=[];if(e){if(typeof this.module.addFunction!=`function`)throw new pt(`HiGHS WebAssembly runtime does not support module.addFunction; progress and interrupt callbacks are unavailable.`);t=this.module.addFunction((t,n,r,i)=>{let a=e[t];if(!a)return;let o={};if(r){let e=this.module.getValue(r+8,`double`),t=this.module.getValue(r+16,`i32`),n=this.module.getValue(r+20,`i32`),i=this.module.getValue(r+24,`i32`),a=this.module.getValue(r+32,`double`),s=Number(this.module.getValue(r+40,`i32`)),c=Number(this.module.getValue(r+48,`i32`)),l=this.module.getValue(r+56,`double`),u=this.module.getValue(r+64,`double`),d=this.module.getValue(r+72,`double`),f=this.module.getValue(r+80,`i32`),p=this.module.getValue(r+84,`i32`),m;f&&p>0&&(m=dt(this.module,f,p)),o={running_time:e,simplex_iteration_count:t,ipm_iteration_count:n,pdlp_iteration_count:i,objective_function_value:a,mip_node_count:s,mip_total_lp_iterations:c,mip_primal_bound:l,mip_dual_bound:u,mip_gap:d,...m?{mip_solution:m}:{}}}let s=n?this.module.UTF8ToString(n):``;a({data:o,message:s,interrupt:()=>{i&&this.module.setValue(i,1,`i32`)}})},`vipppp`),this.bindings.setCallback(this.highs,t,0);for(let t of Object.keys(e)){let e=Number(t);this.bindings.startCallback(this.highs,e),n.push(e)}}try{return this.bindings.run(this.highs)}finally{if(t){for(let e of n)try{this.bindings.stopCallback(this.highs,e)}catch{}try{this.module.removeFunction(t)}catch{}}}}getModelStatus(){return this.bindings.getModelStatus(this.highs)}info={get:e=>{let t=this.module._malloc(8);try{if(this.bindings.getDoubleInfoValue(this.highs,e,t)===0)return this.module.getValue(t,`double`)}finally{this.module._free(t)}let n=this.module._malloc(4);try{if(this.bindings.getIntInfoValue(this.highs,e,n)===0)return this.module.getValue(n,`i32`)}finally{this.module._free(n)}throw new pt(`Info item "${e}" not available or unknown in HiGHS`)}};getSolution(){let e=this.getDimensions(),t=e.numCols>0?this.module._malloc(e.numCols*8):0,n=e.numCols>0?this.module._malloc(e.numCols*8):0,r=e.numRows>0?this.module._malloc(e.numRows*8):0,i=e.numRows>0?this.module._malloc(e.numRows*8):0;try{return this.bindings.getSolution(this.highs,t,n,r,i),{colValue:dt(this.module,t,e.numCols),colDual:dt(this.module,n,e.numCols),rowValue:dt(this.module,r,e.numRows),rowDual:dt(this.module,i,e.numRows)}}finally{t&&this.module._free(t),n&&this.module._free(n),r&&this.module._free(r),i&&this.module._free(i)}}getObjectiveValue(){return this.bindings.getObjectiveValue(this.highs)}destroy(){if(!this.isDestroyed){this.isDestroyed=!0;try{this.module._free(this.stringBuf)}catch{}try{this.bindings.destroy(this.highs)}catch{}}}[Symbol.dispose](){this.destroy()}},yt=class{module;bindings;constants=gt;errors={HighsError:pt,HighsUnsupportedOptionError:mt};constructor(e){this.module=e,this.bindings=ft(e)}withModel(e,t){let n=this.bindings.create(),r=new vt(this.module,this.bindings,n),i=`/model_${++_t}.${e.format}`;if(!this.module.FS)throw new pt(`Emscripten FS is not initialized on this HiGHS module instance`);let a=this.module.FS;try{a.writeFile(i,e.data);let o=this.bindings.readModel(n,i);if(o!==0)throw new pt(`Failed to load ${e.format.toUpperCase()} model into HiGHS (status ${o})`);return t(r)}finally{try{a.unlink(i)}catch{}r.destroy()}}solve(e,t={}){return this.withModel({format:`lp`,data:e},e=>{for(let[n,r]of Object.entries(t))e.options.set(n,r);e.run();let n=e.getModelStatus(),r=e.getDimensions(),i=e.getSolution(),a={};for(let t=0;t<r.numCols;t++){let n=e.getColName(t);a[n]={Index:t,Name:n,Primal:i.colValue[t],Dual:i.colDual[t]}}return{Status:ht[n]??`Unknown`,StatusCode:n,ObjectiveValue:e.getObjectiveValue(),Columns:a}})}}})),xt,St=n((()=>{xt=(()=>{var e={}.url;return(async function(t={}){var n=t,r,i;n.ready=new Promise((e,t)=>{r=e,i=t});var a=Object.assign({},n),o=`./this.program`,s=(e,t)=>{throw t},c=typeof window==`object`,l=typeof importScripts==`function`,u=``;function d(e){return n.locateFile?n.locateFile(e,u):u+e}var f,p,m;(c||l)&&(l?u=self.location.href:typeof document<`u`&&document.currentScript&&(u=document.currentScript.src),e&&(u=e),u=u.indexOf(`blob:`)===0?``:u.substr(0,u.replace(/[?#].*/,``).lastIndexOf(`/`)+1),f=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.send(null),t.responseText},l&&(m=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),p=(e,t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{if(r.status==200||r.status==0&&r.response){t(r.response);return}n()},r.onerror=n,r.send(null)});var h=n.print||console.log.bind(console),g=n.printErr||console.error.bind(console);Object.assign(n,a),a=null,n.arguments&&n.arguments,n.thisProgram&&(o=n.thisProgram),n.quit&&(s=n.quit);var _;n.wasmBinary&&(_=n.wasmBinary),typeof WebAssembly!=`object`&&ue(`no native wasm support detected`);var v,y=!1;function b(e,t){e||ue(t)}var x,S,C,w,T,E,D;function ee(){var e=v.buffer;n.HEAP8=x=new Int8Array(e),n.HEAP16=C=new Int16Array(e),n.HEAPU8=S=new Uint8Array(e),n.HEAPU16=new Uint16Array(e),n.HEAP32=w=new Int32Array(e),n.HEAPU32=T=new Uint32Array(e),n.HEAPF32=E=new Float32Array(e),n.HEAPF64=D=new Float64Array(e)}var O=[],k=[],A=[],te=!1;function ne(){if(n.preRun)for(typeof n.preRun==`function`&&(n.preRun=[n.preRun]);n.preRun.length;)j(n.preRun.shift());ve(O)}function re(){te=!0,!n.noFSInit&&!G.init.initialized&&G.init(),G.ignorePermissions=!1,U.init(),ve(k)}function ie(){if(n.postRun)for(typeof n.postRun==`function`&&(n.postRun=[n.postRun]);n.postRun.length;)ae(n.postRun.shift());ve(A)}function j(e){O.unshift(e)}function M(e){k.unshift(e)}function ae(e){A.unshift(e)}var oe=0,se=null,N=null;function P(e){return e}function ce(e){oe++,n.monitorRunDependencies&&n.monitorRunDependencies(oe)}function le(e){if(oe--,n.monitorRunDependencies&&n.monitorRunDependencies(oe),oe==0&&(se!==null&&(clearInterval(se),se=null),N)){var t=N;N=null,t()}}function ue(e){n.onAbort&&n.onAbort(e),e=`Aborted(`+e+`)`,g(e),y=!0,e+=`. Build with -sASSERTIONS for more info.`,te&&wn();var t=new WebAssembly.RuntimeError(e);throw i(t),t}var de=`data:application/octet-stream;base64,`,F=e=>e.startsWith(de),fe=e=>e.startsWith(`file://`),I;n.locateFile?(I=`highs.wasm`,F(I)||(I=d(I))):I=new URL(`highs.wasm`,``+{}.url).href;function pe(e){if(e==I&&_)return new Uint8Array(_);if(m)return m(e);throw`both async and sync fetching of the wasm failed`}function me(e){if(!_&&(c||l)){if(typeof fetch==`function`&&!fe(e))return fetch(e,{credentials:`same-origin`}).then(t=>{if(!t.ok)throw`failed to load wasm binary file at '`+e+`'`;return t.arrayBuffer()}).catch(()=>pe(e));if(p)return new Promise((t,n)=>{p(e,e=>t(new Uint8Array(e)),n)})}return Promise.resolve().then(()=>pe(e))}function he(e,t,n){return me(e).then(e=>WebAssembly.instantiate(e,t)).then(e=>e).then(n,e=>{g(`failed to asynchronously prepare wasm: ${e}`),ue(e)})}function L(e,t,n,r){return!e&&typeof WebAssembly.instantiateStreaming==`function`&&!F(t)&&!fe(t)&&typeof fetch==`function`?fetch(t,{credentials:`same-origin`}).then(e=>WebAssembly.instantiateStreaming(e,n).then(r,function(e){return g(`wasm streaming compile failed: ${e}`),g(`falling back to ArrayBuffer instantiation`),he(t,n,r)})):he(t,n,r)}function ge(){var e={a:Wt};function t(e,t){return X=e.exports,v=X.s,n.wasmMemory=v,ee(),Nt=X.ca,M(X.t),le(`wasm-instantiate`),X}ce(`wasm-instantiate`);function r(e){t(e.instance)}if(n.instantiateWasm)try{return n.instantiateWasm(e,t)}catch(e){g(`Module.instantiateWasm callback failed with error: ${e}`),i(e)}return L(_,I,e,r).catch(i),{}}var R,z;function _e(e){this.name=`ExitStatus`,this.message=`Program terminated with exit(${e})`,this.status=e}var ve=e=>{for(;e.length>0;)e.shift()(n)};function ye(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:return x[e>>0];case`i8`:return x[e>>0];case`i16`:return C[e>>1];case`i32`:return w[e>>2];case`i64`:ue(`to do getValue(i64) use WASM_BIGINT`);case`float`:return E[e>>2];case`double`:return D[e>>3];case`*`:return T[e>>2];default:ue(`invalid type for getValue: ${t}`)}}var be=n.noExitRuntime||!0;function xe(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:x[e>>0]=t;break;case`i8`:x[e>>0]=t;break;case`i16`:C[e>>1]=t;break;case`i32`:w[e>>2]=t;break;case`i64`:ue(`to do setValue(i64) use WASM_BIGINT`);case`float`:E[e>>2]=t;break;case`double`:D[e>>3]=t;break;case`*`:T[e>>2]=t;break;default:ue(`invalid type for setValue: ${n}`)}}var Se=e=>(w[xn()>>2]=e,e),B={isAbs:e=>e.charAt(0)===`/`,splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,t)=>{for(var n=0,r=e.length-1;r>=0;r--){var i=e[r];i===`.`?e.splice(r,1):i===`..`?(e.splice(r,1),n++):n&&(e.splice(r,1),n--)}if(t)for(;n;n--)e.unshift(`..`);return e},normalize:e=>{var t=B.isAbs(e),n=e.substr(-1)===`/`;return e=B.normalizeArray(e.split(`/`).filter(e=>!!e),!t).join(`/`),!e&&!t&&(e=`.`),e&&n&&(e+=`/`),(t?`/`:``)+e},dirname:e=>{var t=B.splitPath(e),n=t[0],r=t[1];return!n&&!r?`.`:(r&&=r.substr(0,r.length-1),n+r)},basename:e=>{if(e===`/`)return`/`;e=B.normalize(e),e=e.replace(/\/$/,``);var t=e.lastIndexOf(`/`);return t===-1?e:e.substr(t+1)},join:function(){var e=Array.prototype.slice.call(arguments);return B.normalize(e.join(`/`))},join2:(e,t)=>B.normalize(e+`/`+t)},Ce=()=>{if(typeof crypto==`object`&&typeof crypto.getRandomValues==`function`)return e=>crypto.getRandomValues(e);ue(`initRandomDevice`)},we=e=>(we=Ce())(e),V={resolve:function(){for(var e=``,t=!1,n=arguments.length-1;n>=-1&&!t;n--){var r=n>=0?arguments[n]:G.cwd();if(typeof r!=`string`)throw TypeError(`Arguments to path.resolve must be strings`);if(!r)return``;e=r+`/`+e,t=B.isAbs(r)}return e=B.normalizeArray(e.split(`/`).filter(e=>!!e),!t).join(`/`),(t?`/`:``)+e||`.`},relative:(e,t)=>{e=V.resolve(e).substr(1),t=V.resolve(t).substr(1);function n(e){for(var t=0;t<e.length&&e[t]===``;t++);for(var n=e.length-1;n>=0&&e[n]===``;n--);return t>n?[]:e.slice(t,n-t+1)}for(var r=n(e.split(`/`)),i=n(t.split(`/`)),a=Math.min(r.length,i.length),o=a,s=0;s<a;s++)if(r[s]!==i[s]){o=s;break}for(var c=[],s=o;s<r.length;s++)c.push(`..`);return c=c.concat(i.slice(o)),c.join(`/`)}},H=typeof TextDecoder<`u`?new TextDecoder(`utf8`):void 0,Te=(e,t,n)=>{for(var r=t+n,i=t;e[i]&&!(i>=r);)++i;if(i-t>16&&e.buffer&&H)return H.decode(e.subarray(t,i));for(var a=``;t<i;){var o=e[t++];if(!(o&128)){a+=String.fromCharCode(o);continue}var s=e[t++]&63;if((o&224)==192){a+=String.fromCharCode((o&31)<<6|s);continue}var c=e[t++]&63;if(o=(o&240)==224?(o&15)<<12|s<<6|c:(o&7)<<18|s<<12|c<<6|e[t++]&63,o<65536)a+=String.fromCharCode(o);else{var l=o-65536;a+=String.fromCharCode(55296|l>>10,56320|l&1023)}}return a},Ee=[],De=e=>{for(var t=0,n=0;n<e.length;++n){var r=e.charCodeAt(n);r<=127?t++:r<=2047?t+=2:r>=55296&&r<=57343?(t+=4,++n):t+=3}return t},Oe=(e,t,n,r)=>{if(!(r>0))return 0;for(var i=n,a=n+r-1,o=0;o<e.length;++o){var s=e.charCodeAt(o);if(s>=55296&&s<=57343){var c=e.charCodeAt(++o);s=65536+((s&1023)<<10)|c&1023}if(s<=127){if(n>=a)break;t[n++]=s}else if(s<=2047){if(n+1>=a)break;t[n++]=192|s>>6,t[n++]=128|s&63}else if(s<=65535){if(n+2>=a)break;t[n++]=224|s>>12,t[n++]=128|s>>6&63,t[n++]=128|s&63}else{if(n+3>=a)break;t[n++]=240|s>>18,t[n++]=128|s>>12&63,t[n++]=128|s>>6&63,t[n++]=128|s&63}}return t[n]=0,n-i};function ke(e,t,n){var r=n>0?n:De(e)+1,i=Array(r),a=Oe(e,i,0,i.length);return t&&(i.length=a),i}var Ae=()=>{if(!Ee.length){var e=null;if(typeof window<`u`&&typeof window.prompt==`function`?(e=window.prompt(`Input: `),e!==null&&(e+=`
4
4
  `)):typeof readline==`function`&&(e=readline(),e!==null&&(e+=`
5
- `)),!e)return null;Ce=Ee(e,!0)}return Ce.shift()},K={ttys:[],init(){},shutdown(){},register(e,t){K.ttys[e]={input:[],output:[],ops:t},J.registerDevice(e,K.stream_ops)},stream_ops:{open(e){var t=K.ttys[e.node.rdev];if(!t)throw new J.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,n,r,i){if(!e.tty||!e.tty.ops.get_char)throw new J.ErrnoError(60);for(var a=0,o=0;o<r;o++){var s;try{s=e.tty.ops.get_char(e.tty)}catch{throw new J.ErrnoError(29)}if(s===void 0&&a===0)throw new J.ErrnoError(6);if(s==null)break;a++,t[n+o]=s}return a&&(e.node.timestamp=Date.now()),a},write(e,t,n,r,i){if(!e.tty||!e.tty.ops.put_char)throw new J.ErrnoError(60);try{for(var a=0;a<r;a++)e.tty.ops.put_char(e.tty,t[n+a])}catch{throw new J.ErrnoError(29)}return r&&(e.node.timestamp=Date.now()),a}},default_tty_ops:{get_char(e){return De()},put_char(e,t){t===null||t===10?(h(Se(e.output,0)),e.output=[]):t!=0&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(h(Se(e.output,0)),e.output=[])},ioctl_tcgets(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(e,t,n){return 0},ioctl_tiocgwinsz(e){return[24,80]}},default_tty1_ops:{put_char(e,t){t===null||t===10?(g(Se(e.output,0)),e.output=[]):t!=0&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(g(Se(e.output,0)),e.output=[])}}},Oe=e=>{L()},q={ops_table:null,mount(e){return q.createNode(null,`/`,16895,0)},createNode(e,t,n,r){if(J.isBlkdev(n)||J.isFIFO(n))throw new J.ErrnoError(63);q.ops_table||={dir:{node:{getattr:q.node_ops.getattr,setattr:q.node_ops.setattr,lookup:q.node_ops.lookup,mknod:q.node_ops.mknod,rename:q.node_ops.rename,unlink:q.node_ops.unlink,rmdir:q.node_ops.rmdir,readdir:q.node_ops.readdir,symlink:q.node_ops.symlink},stream:{llseek:q.stream_ops.llseek}},file:{node:{getattr:q.node_ops.getattr,setattr:q.node_ops.setattr},stream:{llseek:q.stream_ops.llseek,read:q.stream_ops.read,write:q.stream_ops.write,allocate:q.stream_ops.allocate,mmap:q.stream_ops.mmap,msync:q.stream_ops.msync}},link:{node:{getattr:q.node_ops.getattr,setattr:q.node_ops.setattr,readlink:q.node_ops.readlink},stream:{}},chrdev:{node:{getattr:q.node_ops.getattr,setattr:q.node_ops.setattr},stream:J.chrdev_stream_ops}};var i=J.createNode(e,t,n,r);return J.isDir(i.mode)?(i.node_ops=q.ops_table.dir.node,i.stream_ops=q.ops_table.dir.stream,i.contents={}):J.isFile(i.mode)?(i.node_ops=q.ops_table.file.node,i.stream_ops=q.ops_table.file.stream,i.usedBytes=0,i.contents=null):J.isLink(i.mode)?(i.node_ops=q.ops_table.link.node,i.stream_ops=q.ops_table.link.stream):J.isChrdev(i.mode)&&(i.node_ops=q.ops_table.chrdev.node,i.stream_ops=q.ops_table.chrdev.stream),i.timestamp=Date.now(),e&&(e.contents[t]=i,e.timestamp=i.timestamp),i},getFileDataAsTypedArray(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array},expandFileStorage(e,t){var n=e.contents?e.contents.length:0;if(!(n>=t)){t=Math.max(t,n*(n<1048576?2:1.125)>>>0),n!=0&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t){if(t==0)e.contents=null,e.usedBytes=0;else{var n=e.contents;e.contents=new Uint8Array(t),n&&e.contents.set(n.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}}},node_ops:{getattr(e){var t={};return t.dev=J.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,t.size=J.isDir(e.mode)?4096:J.isFile(e.mode)?e.usedBytes:J.isLink(e.mode)?e.link.length:0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){t.mode!==void 0&&(e.mode=t.mode),t.timestamp!==void 0&&(e.timestamp=t.timestamp),t.size!==void 0&&q.resizeFileStorage(e,t.size)},lookup(e,t){throw J.genericErrors[44]},mknod(e,t,n,r){return q.createNode(e,t,n,r)},rename(e,t,n){if(J.isDir(e.mode)){var r;try{r=J.lookupNode(t,n)}catch{}if(r)for(var i in r.contents)throw new J.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=n,t.contents[n]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){for(var n in J.lookupNode(e,t).contents)throw new J.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[`.`,`..`];for(var n in e.contents)e.contents.hasOwnProperty(n)&&t.push(n);return t},symlink(e,t,n){var r=q.createNode(e,t,41471,0);return r.link=n,r},readlink(e){if(!J.isLink(e.mode))throw new J.ErrnoError(28);return e.link}},stream_ops:{read(e,t,n,r,i){var a=e.node.contents;if(i>=e.node.usedBytes)return 0;var o=Math.min(e.node.usedBytes-i,r);if(o>8&&a.subarray)t.set(a.subarray(i,i+o),n);else for(var s=0;s<o;s++)t[n+s]=a[i+s];return o},write(e,t,n,r,i,a){if(t.buffer===x.buffer&&(a=!1),!r)return 0;var o=e.node;if(o.timestamp=Date.now(),t.subarray&&(!o.contents||o.contents.subarray)){if(a)return o.contents=t.subarray(n,n+r),o.usedBytes=r,r;if(o.usedBytes===0&&i===0)return o.contents=t.slice(n,n+r),o.usedBytes=r,r;if(i+r<=o.usedBytes)return o.contents.set(t.subarray(n,n+r),i),r}if(q.expandFileStorage(o,i+r),o.contents.subarray&&t.subarray)o.contents.set(t.subarray(n,n+r),i);else for(var s=0;s<r;s++)o.contents[i+s]=t[n+s];return o.usedBytes=Math.max(o.usedBytes,i+r),r},llseek(e,t,n){var r=t;if(n===1?r+=e.position:n===2&&J.isFile(e.node.mode)&&(r+=e.node.usedBytes),r<0)throw new J.ErrnoError(28);return r},allocate(e,t,n){q.expandFileStorage(e.node,t+n),e.node.usedBytes=Math.max(e.node.usedBytes,t+n)},mmap(e,t,n,r,i){if(!J.isFile(e.node.mode))throw new J.ErrnoError(43);var a,o,s=e.node.contents;if(!(i&2)&&s.buffer===x.buffer)o=!1,a=s.byteOffset;else{if((n>0||n+t<s.length)&&(s=s.subarray?s.subarray(n,n+t):Array.prototype.slice.call(s,n,n+t)),o=!0,a=Oe(t),!a)throw new J.ErrnoError(48);x.set(s,a)}return{ptr:a,allocated:o}},msync(e,t,n,r,i){return q.stream_ops.write(e,t,0,r,n,!1),0}}},ke=(e,t,n,r)=>{var i=r?``:F(`al ${e}`);p(e,n=>{b(n,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(n)),i&&I(i)},t=>{if(n)n();else throw`Loading data file "${e}" failed.`}),i&&se(i)},Ae=(e,t,n,r,i,a)=>{J.createDataFile(e,t,n,r,i,a)},je=n.preloadPlugins||[],Me=(e,t,n,r)=>{typeof Browser<`u`&&Browser.init();var i=!1;return je.forEach(a=>{i||a.canHandle(t)&&(a.handle(e,t,n,r),i=!0)}),i},Ne=(e,t,n,r,i,a,o,s,c,l)=>{var u=t?W.resolve(U.join2(e,t)):e,d=F(`cp ${u}`);function f(n){function f(n){l&&l(),s||Ae(e,t,n,r,i,c),a&&a(),I(d)}Me(n,u,f,()=>{o&&o(),I(d)})||f(n)}se(d),typeof n==`string`?ke(n,e=>f(e),o):f(n)},Pe=e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(t===void 0)throw Error(`Unknown file open mode: ${e}`);return t},Fe=(e,t)=>{var n=0;return e&&(n|=365),t&&(n|=146),n},J={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:`/`,initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(e,t={}){if(e=W.resolve(e),!e)return{path:``,node:null};if(t=Object.assign({follow_mount:!0,recurse_count:0},t),t.recurse_count>8)throw new J.ErrnoError(32);for(var n=e.split(`/`).filter(e=>!!e),r=J.root,i=`/`,a=0;a<n.length;a++){var o=a===n.length-1;if(o&&t.parent)break;if(r=J.lookupNode(r,n[a]),i=U.join2(i,n[a]),J.isMountpoint(r)&&(!o||o&&t.follow_mount)&&(r=r.mounted.root),!o||t.follow)for(var s=0;J.isLink(r.mode);){var c=J.readlink(i);if(i=W.resolve(U.dirname(i),c),r=J.lookupPath(i,{recurse_count:t.recurse_count+1}).node,s++>40)throw new J.ErrnoError(32)}}return{path:i,node:r}},getPath(e){for(var t;;){if(J.isRoot(e)){var n=e.mount.mountpoint;return t?n[n.length-1]===`/`?n+t:`${n}/${t}`:n}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var n=0,r=0;r<t.length;r++)n=(n<<5)-n+t.charCodeAt(r)|0;return(e+n>>>0)%J.nameTable.length},hashAddNode(e){var t=J.hashName(e.parent.id,e.name);e.name_next=J.nameTable[t],J.nameTable[t]=e},hashRemoveNode(e){var t=J.hashName(e.parent.id,e.name);if(J.nameTable[t]===e)J.nameTable[t]=e.name_next;else for(var n=J.nameTable[t];n;){if(n.name_next===e){n.name_next=e.name_next;break}n=n.name_next}},lookupNode(e,t){var n=J.mayLookup(e);if(n)throw new J.ErrnoError(n,e);for(var r=J.hashName(e.id,t),i=J.nameTable[r];i;i=i.name_next){var a=i.name;if(i.parent.id===e.id&&a===t)return i}return J.lookup(e,t)},createNode(e,t,n,r){var i=new J.FSNode(e,t,n,r);return J.hashAddNode(i),i},destroyNode(e){J.hashRemoveNode(e)},isRoot(e){return e===e.parent},isMountpoint(e){return!!e.mounted},isFile(e){return(e&61440)==32768},isDir(e){return(e&61440)==16384},isLink(e){return(e&61440)==40960},isChrdev(e){return(e&61440)==8192},isBlkdev(e){return(e&61440)==24576},isFIFO(e){return(e&61440)==4096},isSocket(e){return(e&49152)==49152},flagsToPermissionString(e){var t=[`r`,`w`,`rw`][e&3];return e&512&&(t+=`w`),t},nodePermissions(e,t){return J.ignorePermissions?0:t.includes(`r`)&&!(e.mode&292)||t.includes(`w`)&&!(e.mode&146)||t.includes(`x`)&&!(e.mode&73)?2:0},mayLookup(e){return J.nodePermissions(e,`x`)||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{return J.lookupNode(e,t),20}catch{}return J.nodePermissions(e,`wx`)},mayDelete(e,t,n){var r;try{r=J.lookupNode(e,t)}catch(e){return e.errno}var i=J.nodePermissions(e,`wx`);if(i)return i;if(n){if(!J.isDir(r.mode))return 54;if(J.isRoot(r)||J.getPath(r)===J.cwd())return 10}else if(J.isDir(r.mode))return 31;return 0},mayOpen(e,t){return e?J.isLink(e.mode)?32:J.isDir(e.mode)&&(J.flagsToPermissionString(t)!==`r`||t&512)?31:J.nodePermissions(e,J.flagsToPermissionString(t)):44},MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=J.MAX_OPEN_FDS;e++)if(!J.streams[e])return e;throw new J.ErrnoError(33)},getStreamChecked(e){var t=J.getStream(e);if(!t)throw new J.ErrnoError(8);return t},getStream:e=>J.streams[e],createStream(e,t=-1){return J.FSStream||(J.FSStream=function(){this.shared={}},J.FSStream.prototype={},Object.defineProperties(J.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return(this.flags&2097155)!=1}},isWrite:{get(){return!!(this.flags&2097155)}},isAppend:{get(){return this.flags&1024}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new J.FSStream,e),t==-1&&(t=J.nextfd()),e.fd=t,J.streams[t]=e,e},closeStream(e){J.streams[e]=null},chrdev_stream_ops:{open(e){e.stream_ops=J.getDevice(e.node.rdev).stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek(){throw new J.ErrnoError(70)}},major:e=>e>>8,minor:e=>e&255,makedev:(e,t)=>e<<8|t,registerDevice(e,t){J.devices[e]={stream_ops:t}},getDevice:e=>J.devices[e],getMounts(e){for(var t=[],n=[e];n.length;){var r=n.pop();t.push(r),n.push.apply(n,r.mounts)}return t},syncfs(e,t){typeof e==`function`&&(t=e,e=!1),J.syncFSRequests++,J.syncFSRequests>1&&g(`warning: ${J.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var n=J.getMounts(J.root.mount),r=0;function i(e){return J.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,i(e));++r>=n.length&&i(null)}n.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,n){var r=n===`/`,i=!n,a;if(r&&J.root)throw new J.ErrnoError(10);if(!r&&!i){var o=J.lookupPath(n,{follow_mount:!1});if(n=o.path,a=o.node,J.isMountpoint(a))throw new J.ErrnoError(10);if(!J.isDir(a.mode))throw new J.ErrnoError(54)}var s={type:e,opts:t,mountpoint:n,mounts:[]},c=e.mount(s);return c.mount=s,s.root=c,r?J.root=c:a&&(a.mounted=s,a.mount&&a.mount.mounts.push(s)),c},unmount(e){var t=J.lookupPath(e,{follow_mount:!1});if(!J.isMountpoint(t.node))throw new J.ErrnoError(28);var n=t.node,r=n.mounted,i=J.getMounts(r);Object.keys(J.nameTable).forEach(e=>{for(var t=J.nameTable[e];t;){var n=t.name_next;i.includes(t.mount)&&J.destroyNode(t),t=n}}),n.mounted=null;var a=n.mount.mounts.indexOf(r);n.mount.mounts.splice(a,1)},lookup(e,t){return e.node_ops.lookup(e,t)},mknod(e,t,n){var r=J.lookupPath(e,{parent:!0}).node,i=U.basename(e);if(!i||i===`.`||i===`..`)throw new J.ErrnoError(28);var a=J.mayCreate(r,i);if(a)throw new J.ErrnoError(a);if(!r.node_ops.mknod)throw new J.ErrnoError(63);return r.node_ops.mknod(r,i,t,n)},create(e,t){return t=t===void 0?438:t,t&=4095,t|=32768,J.mknod(e,t,0)},mkdir(e,t){return t=t===void 0?511:t,t&=1023,t|=16384,J.mknod(e,t,0)},mkdirTree(e,t){for(var n=e.split(`/`),r=``,i=0;i<n.length;++i)if(n[i]){r+=`/`+n[i];try{J.mkdir(r,t)}catch(e){if(e.errno!=20)throw e}}},mkdev(e,t,n){return n===void 0&&(n=t,t=438),t|=8192,J.mknod(e,t,n)},symlink(e,t){if(!W.resolve(e))throw new J.ErrnoError(44);var n=J.lookupPath(t,{parent:!0}).node;if(!n)throw new J.ErrnoError(44);var r=U.basename(t),i=J.mayCreate(n,r);if(i)throw new J.ErrnoError(i);if(!n.node_ops.symlink)throw new J.ErrnoError(63);return n.node_ops.symlink(n,r,e)},rename(e,t){var n=U.dirname(e),r=U.dirname(t),i=U.basename(e),a=U.basename(t),o=J.lookupPath(e,{parent:!0}),s=o.node,c;if(o=J.lookupPath(t,{parent:!0}),c=o.node,!s||!c)throw new J.ErrnoError(44);if(s.mount!==c.mount)throw new J.ErrnoError(75);var l=J.lookupNode(s,i),u=W.relative(e,r);if(u.charAt(0)!==`.`)throw new J.ErrnoError(28);if(u=W.relative(t,n),u.charAt(0)!==`.`)throw new J.ErrnoError(55);var d;try{d=J.lookupNode(c,a)}catch{}if(l!==d){var f=J.isDir(l.mode),p=J.mayDelete(s,i,f);if(p||(p=d?J.mayDelete(c,a,f):J.mayCreate(c,a),p))throw new J.ErrnoError(p);if(!s.node_ops.rename)throw new J.ErrnoError(63);if(J.isMountpoint(l)||d&&J.isMountpoint(d))throw new J.ErrnoError(10);if(c!==s&&(p=J.nodePermissions(s,`w`),p))throw new J.ErrnoError(p);J.hashRemoveNode(l);try{s.node_ops.rename(l,c,a)}catch(e){throw e}finally{J.hashAddNode(l)}}},rmdir(e){var t=J.lookupPath(e,{parent:!0}).node,n=U.basename(e),r=J.lookupNode(t,n),i=J.mayDelete(t,n,!0);if(i)throw new J.ErrnoError(i);if(!t.node_ops.rmdir)throw new J.ErrnoError(63);if(J.isMountpoint(r))throw new J.ErrnoError(10);t.node_ops.rmdir(t,n),J.destroyNode(r)},readdir(e){var t=J.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new J.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=J.lookupPath(e,{parent:!0}).node;if(!t)throw new J.ErrnoError(44);var n=U.basename(e),r=J.lookupNode(t,n),i=J.mayDelete(t,n,!1);if(i)throw new J.ErrnoError(i);if(!t.node_ops.unlink)throw new J.ErrnoError(63);if(J.isMountpoint(r))throw new J.ErrnoError(10);t.node_ops.unlink(t,n),J.destroyNode(r)},readlink(e){var t=J.lookupPath(e).node;if(!t)throw new J.ErrnoError(44);if(!t.node_ops.readlink)throw new J.ErrnoError(28);return W.resolve(J.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var n=J.lookupPath(e,{follow:!t}).node;if(!n)throw new J.ErrnoError(44);if(!n.node_ops.getattr)throw new J.ErrnoError(63);return n.node_ops.getattr(n)},lstat(e){return J.stat(e,!0)},chmod(e,t,n){var r=typeof e==`string`?J.lookupPath(e,{follow:!n}).node:e;if(!r.node_ops.setattr)throw new J.ErrnoError(63);r.node_ops.setattr(r,{mode:t&4095|r.mode&-4096,timestamp:Date.now()})},lchmod(e,t){J.chmod(e,t,!0)},fchmod(e,t){var n=J.getStreamChecked(e);J.chmod(n.node,t)},chown(e,t,n,r){var i=typeof e==`string`?J.lookupPath(e,{follow:!r}).node:e;if(!i.node_ops.setattr)throw new J.ErrnoError(63);i.node_ops.setattr(i,{timestamp:Date.now()})},lchown(e,t,n){J.chown(e,t,n,!0)},fchown(e,t,n){var r=J.getStreamChecked(e);J.chown(r.node,t,n)},truncate(e,t){if(t<0)throw new J.ErrnoError(28);var n=typeof e==`string`?J.lookupPath(e,{follow:!0}).node:e;if(!n.node_ops.setattr)throw new J.ErrnoError(63);if(J.isDir(n.mode))throw new J.ErrnoError(31);if(!J.isFile(n.mode))throw new J.ErrnoError(28);var r=J.nodePermissions(n,`w`);if(r)throw new J.ErrnoError(r);n.node_ops.setattr(n,{size:t,timestamp:Date.now()})},ftruncate(e,t){var n=J.getStreamChecked(e);if(!(n.flags&2097155))throw new J.ErrnoError(28);J.truncate(n.node,t)},utime(e,t,n){var r=J.lookupPath(e,{follow:!0}).node;r.node_ops.setattr(r,{timestamp:Math.max(t,n)})},open(e,t,r){if(e===``)throw new J.ErrnoError(44);t=typeof t==`string`?Pe(t):t,r=r===void 0?438:r,r=t&64?r&4095|32768:0;var i;if(typeof e==`object`)i=e;else{e=U.normalize(e);try{i=J.lookupPath(e,{follow:!(t&131072)}).node}catch{}}var a=!1;if(t&64){if(i){if(t&128)throw new J.ErrnoError(20)}else i=J.mknod(e,r,0),a=!0}if(!i)throw new J.ErrnoError(44);if(J.isChrdev(i.mode)&&(t&=-513),t&65536&&!J.isDir(i.mode))throw new J.ErrnoError(54);if(!a){var o=J.mayOpen(i,t);if(o)throw new J.ErrnoError(o)}t&512&&!a&&J.truncate(i,0),t&=-131713;var s=J.createStream({node:i,path:J.getPath(i),flags:t,seekable:!0,position:0,stream_ops:i.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),n.logReadFiles&&!(t&1)&&(J.readFiles||={},e in J.readFiles||(J.readFiles[e]=1)),s},close(e){if(J.isClosed(e))throw new J.ErrnoError(8);e.getdents&&=null;try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{J.closeStream(e.fd)}e.fd=null},isClosed(e){return e.fd===null},llseek(e,t,n){if(J.isClosed(e))throw new J.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new J.ErrnoError(70);if(n!=0&&n!=1&&n!=2)throw new J.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,n),e.ungotten=[],e.position},read(e,t,n,r,i){if(r<0||i<0)throw new J.ErrnoError(28);if(J.isClosed(e)||(e.flags&2097155)==1)throw new J.ErrnoError(8);if(J.isDir(e.node.mode))throw new J.ErrnoError(31);if(!e.stream_ops.read)throw new J.ErrnoError(28);var a=i!==void 0;if(!a)i=e.position;else if(!e.seekable)throw new J.ErrnoError(70);var o=e.stream_ops.read(e,t,n,r,i);return a||(e.position+=o),o},write(e,t,n,r,i,a){if(r<0||i<0)throw new J.ErrnoError(28);if(J.isClosed(e)||!(e.flags&2097155))throw new J.ErrnoError(8);if(J.isDir(e.node.mode))throw new J.ErrnoError(31);if(!e.stream_ops.write)throw new J.ErrnoError(28);e.seekable&&e.flags&1024&&J.llseek(e,0,2);var o=i!==void 0;if(!o)i=e.position;else if(!e.seekable)throw new J.ErrnoError(70);var s=e.stream_ops.write(e,t,n,r,i,a);return o||(e.position+=s),s},allocate(e,t,n){if(J.isClosed(e))throw new J.ErrnoError(8);if(t<0||n<=0)throw new J.ErrnoError(28);if(!(e.flags&2097155))throw new J.ErrnoError(8);if(!J.isFile(e.node.mode)&&!J.isDir(e.node.mode))throw new J.ErrnoError(43);if(!e.stream_ops.allocate)throw new J.ErrnoError(138);e.stream_ops.allocate(e,t,n)},mmap(e,t,n,r,i){if(r&2&&!(i&2)&&(e.flags&2097155)!=2||(e.flags&2097155)==1)throw new J.ErrnoError(2);if(!e.stream_ops.mmap)throw new J.ErrnoError(43);return e.stream_ops.mmap(e,t,n,r,i)},msync(e,t,n,r,i){return e.stream_ops.msync?e.stream_ops.msync(e,t,n,r,i):0},munmap:e=>0,ioctl(e,t,n){if(!e.stream_ops.ioctl)throw new J.ErrnoError(59);return e.stream_ops.ioctl(e,t,n)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||`binary`,t.encoding!==`utf8`&&t.encoding!==`binary`)throw Error(`Invalid encoding type "${t.encoding}"`);var n,r=J.open(e,t.flags),i=J.stat(e).size,a=new Uint8Array(i);return J.read(r,a,0,i,0),t.encoding===`utf8`?n=Se(a,0):t.encoding===`binary`&&(n=a),J.close(r),n},writeFile(e,t,n={}){n.flags=n.flags||577;var r=J.open(e,n.flags,n.mode);if(typeof t==`string`){var i=new Uint8Array(we(t)+1),a=Te(t,i,0,i.length);J.write(r,i,0,a,void 0,n.canOwn)}else if(ArrayBuffer.isView(t))J.write(r,t,0,t.byteLength,void 0,n.canOwn);else throw Error(`Unsupported data type`);J.close(r)},cwd:()=>J.currentPath,chdir(e){var t=J.lookupPath(e,{follow:!0});if(t.node===null)throw new J.ErrnoError(44);if(!J.isDir(t.node.mode))throw new J.ErrnoError(54);var n=J.nodePermissions(t.node,`x`);if(n)throw new J.ErrnoError(n);J.currentPath=t.path},createDefaultDirectories(){J.mkdir(`/tmp`),J.mkdir(`/home`),J.mkdir(`/home/web_user`)},createDefaultDevices(){J.mkdir(`/dev`),J.registerDevice(J.makedev(1,3),{read:()=>0,write:(e,t,n,r,i)=>r}),J.mkdev(`/dev/null`,J.makedev(1,3)),K.register(J.makedev(5,0),K.default_tty_ops),K.register(J.makedev(6,0),K.default_tty1_ops),J.mkdev(`/dev/tty`,J.makedev(5,0)),J.mkdev(`/dev/tty1`,J.makedev(6,0));var e=new Uint8Array(1024),t=0,n=()=>(t===0&&(t=xe(e).byteLength),e[--t]);J.createDevice(`/dev`,`random`,n),J.createDevice(`/dev`,`urandom`,n),J.mkdir(`/dev/shm`),J.mkdir(`/dev/shm/tmp`)},createSpecialDirectories(){J.mkdir(`/proc`);var e=J.mkdir(`/proc/self`);J.mkdir(`/proc/self/fd`),J.mount({mount(){var t=J.createNode(e,`fd`,16895,73);return t.node_ops={lookup(e,t){var n=+t,r=J.getStreamChecked(n),i={parent:null,mount:{mountpoint:`fake`},node_ops:{readlink:()=>r.path}};return i.parent=i,i}},t}},{},`/proc/self/fd`)},createStandardStreams(){n.stdin?J.createDevice(`/dev`,`stdin`,n.stdin):J.symlink(`/dev/tty`,`/dev/stdin`),n.stdout?J.createDevice(`/dev`,`stdout`,null,n.stdout):J.symlink(`/dev/tty`,`/dev/stdout`),n.stderr?J.createDevice(`/dev`,`stderr`,null,n.stderr):J.symlink(`/dev/tty1`,`/dev/stderr`),J.open(`/dev/stdin`,0),J.open(`/dev/stdout`,1),J.open(`/dev/stderr`,1)},ensureErrnoError(){J.ErrnoError||(J.ErrnoError=function(e,t){this.name=`ErrnoError`,this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message=`FS error`},J.ErrnoError.prototype=Error(),J.ErrnoError.prototype.constructor=J.ErrnoError,[44].forEach(e=>{J.genericErrors[e]=new J.ErrnoError(e),J.genericErrors[e].stack=`<generic error, no stack>`}))},staticInit(){J.ensureErrnoError(),J.nameTable=Array(4096),J.mount(q,{},`/`),J.createDefaultDirectories(),J.createDefaultDevices(),J.createSpecialDirectories(),J.filesystems={MEMFS:q}},init(e,t,r){J.init.initialized=!0,J.ensureErrnoError(),n.stdin=e||n.stdin,n.stdout=t||n.stdout,n.stderr=r||n.stderr,J.createStandardStreams()},quit(){J.init.initialized=!1;for(var e=0;e<J.streams.length;e++){var t=J.streams[e];t&&J.close(t)}},findObject(e,t){var n=J.analyzePath(e,t);return n.exists?n.object:null},analyzePath(e,t){try{var n=J.lookupPath(e,{follow:!t});e=n.path}catch{}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var n=J.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=n.path,r.parentObject=n.node,r.name=U.basename(e),n=J.lookupPath(e,{follow:!t}),r.exists=!0,r.path=n.path,r.object=n.node,r.name=n.node.name,r.isRoot=n.path===`/`}catch(e){r.error=e.errno}return r},createPath(e,t,n,r){e=typeof e==`string`?e:J.getPath(e);for(var i=t.split(`/`).reverse();i.length;){var a=i.pop();if(a){var o=U.join2(e,a);try{J.mkdir(o)}catch{}e=o}}return o},createFile(e,t,n,r,i){var a=U.join2(typeof e==`string`?e:J.getPath(e),t),o=Fe(r,i);return J.create(a,o)},createDataFile(e,t,n,r,i,a){var o=t;e&&(e=typeof e==`string`?e:J.getPath(e),o=t?U.join2(e,t):e);var s=Fe(r,i),c=J.create(o,s);if(n){if(typeof n==`string`){for(var l=Array(n.length),u=0,d=n.length;u<d;++u)l[u]=n.charCodeAt(u);n=l}J.chmod(c,s|146);var f=J.open(c,577);J.write(f,n,0,n.length,0,a),J.close(f),J.chmod(c,s)}},createDevice(e,t,n,r){var i=U.join2(typeof e==`string`?e:J.getPath(e),t),a=Fe(!!n,!!r);J.createDevice.major||(J.createDevice.major=64);var o=J.makedev(J.createDevice.major++,0);return J.registerDevice(o,{open(e){e.seekable=!1},close(e){r&&r.buffer&&r.buffer.length&&r(10)},read(e,t,r,i,a){for(var o=0,s=0;s<i;s++){var c;try{c=n()}catch{throw new J.ErrnoError(29)}if(c===void 0&&o===0)throw new J.ErrnoError(6);if(c==null)break;o++,t[r+s]=c}return o&&(e.node.timestamp=Date.now()),o},write(e,t,n,i,a){for(var o=0;o<i;o++)try{r(t[n+o])}catch{throw new J.ErrnoError(29)}return i&&(e.node.timestamp=Date.now()),o}}),J.mkdev(i,a,o)},forceLoadFile(e){if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if(typeof XMLHttpRequest<`u`)throw Error(`Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.`);if(f)try{e.contents=Ee(f(e.url),!0),e.usedBytes=e.contents.length}catch{throw new J.ErrnoError(29)}else throw Error(`Cannot load without read() or XMLHttpRequest.`)},createLazyFile(e,t,n,r,i){function a(){this.lengthKnown=!1,this.chunks=[]}if(a.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,n=e/this.chunkSize|0;return this.getter(n)[t]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open(`HEAD`,n,!1),e.send(null),!(e.status>=200&&e.status<300||e.status===304))throw Error(`Couldn't load `+n+`. Status: `+e.status);var t=Number(e.getResponseHeader(`Content-length`)),r,i=(r=e.getResponseHeader(`Accept-Ranges`))&&r===`bytes`,a=(r=e.getResponseHeader(`Content-Encoding`))&&r===`gzip`,o=1048576;i||(o=t);var s=(e,r)=>{if(e>r)throw Error(`invalid range (`+e+`, `+r+`) or no bytes requested!`);if(r>t-1)throw Error(`only `+t+` bytes available! programmer error!`);var i=new XMLHttpRequest;if(i.open(`GET`,n,!1),t!==o&&i.setRequestHeader(`Range`,`bytes=`+e+`-`+r),i.responseType=`arraybuffer`,i.overrideMimeType&&i.overrideMimeType(`text/plain; charset=x-user-defined`),i.send(null),!(i.status>=200&&i.status<300||i.status===304))throw Error(`Couldn't load `+n+`. Status: `+i.status);return i.response===void 0?Ee(i.responseText||``,!0):new Uint8Array(i.response||[])},c=this;c.setDataGetter(e=>{var n=e*o,r=(e+1)*o-1;if(r=Math.min(r,t-1),c.chunks[e]===void 0&&(c.chunks[e]=s(n,r)),c.chunks[e]===void 0)throw Error(`doXHR failed!`);return c.chunks[e]}),(a||!t)&&(o=t=1,t=this.getter(0).length,o=t,h(`LazyFiles on gzip forces download of the whole file when length is accessed`)),this._length=t,this._chunkSize=o,this.lengthKnown=!0},typeof XMLHttpRequest<`u`){if(!l)throw`Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc`;var o=new a;Object.defineProperties(o,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:o}}else var s={isDevice:!1,url:n};var c=J.createFile(e,t,s,r,i);s.contents?c.contents=s.contents:s.url&&(c.contents=null,c.url=s.url),Object.defineProperties(c,{usedBytes:{get:function(){return this.contents.length}}});var u={};Object.keys(c.stream_ops).forEach(e=>{var t=c.stream_ops[e];u[e]=function(){return J.forceLoadFile(c),t.apply(null,arguments)}});function d(e,t,n,r,i){var a=e.node.contents;if(i>=a.length)return 0;var o=Math.min(a.length-i,r);if(a.slice)for(var s=0;s<o;s++)t[n+s]=a[i+s];else for(var s=0;s<o;s++)t[n+s]=a.get(i+s);return o}return u.read=(e,t,n,r,i)=>(J.forceLoadFile(c),d(e,t,n,r,i)),u.mmap=(e,t,n,r,i)=>{J.forceLoadFile(c);var a=Oe(t);if(!a)throw new J.ErrnoError(48);return d(e,x,a,t,n),{ptr:a,allocated:!0}},c.stream_ops=u,c}},Ie=(e,t)=>e?Se(S,e,t):``,Y={DEFAULT_POLLMASK:5,calculateAt(e,t,n){if(U.isAbs(t))return t;var r=e===-100?J.cwd():Y.getStreamFromFD(e).path;if(t.length==0){if(!n)throw new J.ErrnoError(44);return r}return U.join2(r,t)},doStat(e,t,n){try{var r=e(t)}catch(e){if(e&&e.node&&U.normalize(t)!==U.normalize(J.getPath(e.node)))return-54;throw e}w[n>>2]=r.dev,w[n+4>>2]=r.mode,T[n+8>>2]=r.nlink,w[n+12>>2]=r.uid,w[n+16>>2]=r.gid,w[n+20>>2]=r.rdev,H=[r.size>>>0,(V=r.size,+Math.abs(V)>=1?V>0?Math.floor(V/4294967296)>>>0:~~+Math.ceil((V-+(~~V>>>0))/4294967296)>>>0:0)],w[n+24>>2]=H[0],w[n+28>>2]=H[1],w[n+32>>2]=4096,w[n+36>>2]=r.blocks;var i=r.atime.getTime(),a=r.mtime.getTime(),o=r.ctime.getTime();return H=[Math.floor(i/1e3)>>>0,(V=Math.floor(i/1e3),+Math.abs(V)>=1?V>0?Math.floor(V/4294967296)>>>0:~~+Math.ceil((V-+(~~V>>>0))/4294967296)>>>0:0)],w[n+40>>2]=H[0],w[n+44>>2]=H[1],T[n+48>>2]=i%1e3*1e3,H=[Math.floor(a/1e3)>>>0,(V=Math.floor(a/1e3),+Math.abs(V)>=1?V>0?Math.floor(V/4294967296)>>>0:~~+Math.ceil((V-+(~~V>>>0))/4294967296)>>>0:0)],w[n+56>>2]=H[0],w[n+60>>2]=H[1],T[n+64>>2]=a%1e3*1e3,H=[Math.floor(o/1e3)>>>0,(V=Math.floor(o/1e3),+Math.abs(V)>=1?V>0?Math.floor(V/4294967296)>>>0:~~+Math.ceil((V-+(~~V>>>0))/4294967296)>>>0:0)],w[n+72>>2]=H[0],w[n+76>>2]=H[1],T[n+80>>2]=o%1e3*1e3,H=[r.ino>>>0,(V=r.ino,+Math.abs(V)>=1?V>0?Math.floor(V/4294967296)>>>0:~~+Math.ceil((V-+(~~V>>>0))/4294967296)>>>0:0)],w[n+88>>2]=H[0],w[n+92>>2]=H[1],0},doMsync(e,t,n,r,i){if(!J.isFile(t.node.mode))throw new J.ErrnoError(43);if(r&2)return 0;var a=S.slice(e,e+n);J.msync(t,a,i,n,r)},varargs:void 0,get(){var e=w[Y.varargs>>2];return Y.varargs+=4,e},getp(){return Y.get()},getStr(e){return Ie(e)},getStreamFromFD(e){return J.getStreamChecked(e)}};function Le(e,t,n){Y.varargs=n;try{var r=Y.getStreamFromFD(e);switch(t){case 0:var i=Y.get();if(i<0)return-28;for(;J.streams[i];)i++;return J.createStream(r,i).fd;case 1:case 2:return 0;case 3:return r.flags;case 4:var i=Y.get();return r.flags|=i,0;case 5:var i=Y.getp(),a=0;return C[i+a>>1]=2,0;case 6:case 7:return 0;case 16:case 8:return-28;case 9:return ye(28),-1;default:return-28}}catch(e){if(J===void 0||e.name!==`ErrnoError`)throw e;return-e.errno}}function Re(e,t,n){Y.varargs=n;try{var r=Y.getStreamFromFD(e);switch(t){case 21509:return r.tty?0:-59;case 21505:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcgets){var i=r.tty.ops.ioctl_tcgets(r),a=Y.getp();w[a>>2]=i.c_iflag||0,w[a+4>>2]=i.c_oflag||0,w[a+8>>2]=i.c_cflag||0,w[a+12>>2]=i.c_lflag||0;for(var o=0;o<32;o++)x[a+o+17>>0]=i.c_cc[o]||0;return 0}return 0;case 21510:case 21511:case 21512:return r.tty?0:-59;case 21506:case 21507:case 21508:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcsets){for(var a=Y.getp(),s=w[a>>2],c=w[a+4>>2],l=w[a+8>>2],u=w[a+12>>2],d=[],o=0;o<32;o++)d.push(x[a+o+17>>0]);return r.tty.ops.ioctl_tcsets(r.tty,t,{c_iflag:s,c_oflag:c,c_cflag:l,c_lflag:u,c_cc:d})}return 0;case 21519:if(!r.tty)return-59;var a=Y.getp();return w[a>>2]=0,0;case 21520:return r.tty?-28:-59;case 21531:var a=Y.getp();return J.ioctl(r,t,a);case 21523:if(!r.tty)return-59;if(r.tty.ops.ioctl_tiocgwinsz){var f=r.tty.ops.ioctl_tiocgwinsz(r.tty),a=Y.getp();C[a>>1]=f[0],C[a+2>>1]=f[1]}return 0;case 21524:return r.tty?0:-59;case 21515:return r.tty?0:-59;default:return-28}}catch(e){if(J===void 0||e.name!==`ErrnoError`)throw e;return-e.errno}}function ze(e,t,n,r){Y.varargs=r;try{t=Y.getStr(t),t=Y.calculateAt(e,t);var i=r?Y.get():0;return J.open(t,n,i).fd}catch(e){if(J===void 0||e.name!==`ErrnoError`)throw e;return-e.errno}}var X=1,Be=()=>X,Ve=()=>{L(``)},He=()=>Date.now(),Ue=()=>2147483648,We=()=>Ue(),Ge=()=>performance.now(),Ke=(e,t,n)=>S.copyWithin(e,t,t+n),qe=e=>{var t=(e-v.buffer.byteLength+65535)/65536;try{return v.grow(t),ee(),1}catch{}},Je=e=>{var t=S.length;e>>>=0;var n=Ue();if(e>n)return!1;for(var r=(e,t)=>e+(t-e%t)%t,i=1;i<=4;i*=2){var a=t*(1+.2/i);if(a=Math.min(a,e+100663296),qe(Math.min(n,r(Math.max(e,a),65536))))return!0}return!1},Ye={},Xe=()=>o||`./this.program`,Ze=()=>{if(!Ze.strings){var e={USER:`web_user`,LOGNAME:`web_user`,PATH:`/`,PWD:`/`,HOME:`/home/web_user`,LANG:(typeof navigator==`object`&&navigator.languages&&navigator.languages[0]||`C`).replace(`-`,`_`)+`.UTF-8`,_:Xe()};for(var t in Ye)Ye[t]===void 0?delete e[t]:e[t]=Ye[t];var n=[];for(var t in e)n.push(`${t}=${e[t]}`);Ze.strings=n}return Ze.strings},Qe=(e,t)=>{for(var n=0;n<e.length;++n)x[t++>>0]=e.charCodeAt(n);x[t>>0]=0},$e=(e,t)=>{var n=0;return Ze().forEach((r,i)=>{var a=t+n;T[e+i*4>>2]=a,Qe(r,a),n+=r.length+1}),0},et=(e,t)=>{var n=Ze();T[e>>2]=n.length;var r=0;return n.forEach(e=>r+=e.length+1),T[t>>2]=r,0},tt=0,nt=()=>_e||tt>0,rt=e=>{nt()||(n.onExit&&n.onExit(e),y=!0),s(e,new me(e))},it=(e,t)=>{rt(e)};function at(e){try{var t=Y.getStreamFromFD(e);return J.close(t),0}catch(e){if(J===void 0||e.name!==`ErrnoError`)throw e;return e.errno}}var ot=(e,t,n,r)=>{for(var i=0,a=0;a<n;a++){var o=T[t>>2],s=T[t+4>>2];t+=8;var c=J.read(e,x,o,s,r);if(c<0)return-1;if(i+=c,c<s)break;r!==void 0&&(r+=c)}return i};function st(e,t,n,r){try{var i=ot(Y.getStreamFromFD(e),t,n);return T[r>>2]=i,0}catch(e){if(J===void 0||e.name!==`ErrnoError`)throw e;return e.errno}}var ct=(e,t)=>t+2097152>>>0<4194305-!!e?(e>>>0)+t*4294967296:NaN;function lt(e,t,n,r,i){var a=ct(t,n);try{if(isNaN(a))return 61;var o=Y.getStreamFromFD(e);return J.llseek(o,a,r),H=[o.position>>>0,(V=o.position,+Math.abs(V)>=1?V>0?Math.floor(V/4294967296)>>>0:~~+Math.ceil((V-+(~~V>>>0))/4294967296)>>>0:0)],w[i>>2]=H[0],w[i+4>>2]=H[1],o.getdents&&a===0&&r===0&&(o.getdents=null),0}catch(e){if(J===void 0||e.name!==`ErrnoError`)throw e;return e.errno}}var ut=(e,t,n,r)=>{for(var i=0,a=0;a<n;a++){var o=T[t>>2],s=T[t+4>>2];t+=8;var c=J.write(e,x,o,s,r);if(c<0)return-1;i+=c,r!==void 0&&(r+=c)}return i};function dt(e,t,n,r){try{var i=ut(Y.getStreamFromFD(e),t,n);return T[r>>2]=i,0}catch(e){if(J===void 0||e.name!==`ErrnoError`)throw e;return e.errno}}var ft=e=>e%4==0&&(e%100!=0||e%400==0),pt=(e,t)=>{for(var n=0,r=0;r<=t;n+=e[r++]);return n},mt=[31,29,31,30,31,30,31,31,30,31,30,31],ht=[31,28,31,30,31,30,31,31,30,31,30,31],gt=(e,t)=>{for(var n=new Date(e.getTime());t>0;){var r=ft(n.getFullYear()),i=n.getMonth(),a=(r?mt:ht)[i];if(t>a-n.getDate())t-=a-n.getDate()+1,n.setDate(1),i<11?n.setMonth(i+1):(n.setMonth(0),n.setFullYear(n.getFullYear()+1));else return n.setDate(n.getDate()+t),n}return n},_t=(e,t)=>{x.set(e,t)},vt=(e,t,n,r)=>{var i=T[r+40>>2],a={tm_sec:w[r>>2],tm_min:w[r+4>>2],tm_hour:w[r+8>>2],tm_mday:w[r+12>>2],tm_mon:w[r+16>>2],tm_year:w[r+20>>2],tm_wday:w[r+24>>2],tm_yday:w[r+28>>2],tm_isdst:w[r+32>>2],tm_gmtoff:w[r+36>>2],tm_zone:i?Ie(i):``},o=Ie(n),s={"%c":`%a %b %d %H:%M:%S %Y`,"%D":`%m/%d/%y`,"%F":`%Y-%m-%d`,"%h":`%b`,"%r":`%I:%M:%S %p`,"%R":`%H:%M`,"%T":`%H:%M:%S`,"%x":`%m/%d/%y`,"%X":`%H:%M:%S`,"%Ec":`%c`,"%EC":`%C`,"%Ex":`%m/%d/%y`,"%EX":`%H:%M:%S`,"%Ey":`%y`,"%EY":`%Y`,"%Od":`%d`,"%Oe":`%e`,"%OH":`%H`,"%OI":`%I`,"%Om":`%m`,"%OM":`%M`,"%OS":`%S`,"%Ou":`%u`,"%OU":`%U`,"%OV":`%V`,"%Ow":`%w`,"%OW":`%W`,"%Oy":`%y`};for(var c in s)o=o.replace(new RegExp(c,`g`),s[c]);var l=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],u=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`];function d(e,t,n){for(var r=typeof e==`number`?e.toString():e||``;r.length<t;)r=n[0]+r;return r}function f(e,t){return d(e,t,`0`)}function p(e,t){function n(e){return e<0?-1:+(e>0)}var r;return(r=n(e.getFullYear()-t.getFullYear()))===0&&(r=n(e.getMonth()-t.getMonth()))===0&&(r=n(e.getDate()-t.getDate())),r}function m(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function h(e){var t=gt(new Date(e.tm_year+1900,0,1),e.tm_yday),n=new Date(t.getFullYear(),0,4),r=new Date(t.getFullYear()+1,0,4),i=m(n),a=m(r);return p(i,t)<=0?p(a,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var g={"%a":e=>l[e.tm_wday].substring(0,3),"%A":e=>l[e.tm_wday],"%b":e=>u[e.tm_mon].substring(0,3),"%B":e=>u[e.tm_mon],"%C":e=>f((e.tm_year+1900)/100|0,2),"%d":e=>f(e.tm_mday,2),"%e":e=>d(e.tm_mday,2,` `),"%g":e=>h(e).toString().substring(2),"%G":e=>h(e),"%H":e=>f(e.tm_hour,2),"%I":e=>{var t=e.tm_hour;return t==0?t=12:t>12&&(t-=12),f(t,2)},"%j":e=>f(e.tm_mday+pt(ft(e.tm_year+1900)?mt:ht,e.tm_mon-1),3),"%m":e=>f(e.tm_mon+1,2),"%M":e=>f(e.tm_min,2),"%n":()=>`
6
- `,"%p":e=>e.tm_hour>=0&&e.tm_hour<12?`AM`:`PM`,"%S":e=>f(e.tm_sec,2),"%t":()=>` `,"%u":e=>e.tm_wday||7,"%U":e=>{var t=e.tm_yday+7-e.tm_wday;return f(Math.floor(t/7),2)},"%V":e=>{var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,!t){t=52;var n=(e.tm_wday+7-e.tm_yday-1)%7;(n==4||n==5&&ft(e.tm_year%400-1))&&t++}else if(t==53){var r=(e.tm_wday+371-e.tm_yday)%7;r!=4&&(r!=3||!ft(e.tm_year))&&(t=1)}return f(t,2)},"%w":e=>e.tm_wday,"%W":e=>{var t=e.tm_yday+7-(e.tm_wday+6)%7;return f(Math.floor(t/7),2)},"%y":e=>(e.tm_year+1900).toString().substring(2),"%Y":e=>e.tm_year+1900,"%z":e=>{var t=e.tm_gmtoff,n=t>=0;return t=Math.abs(t)/60,t=t/60*100+t%60,(n?`+`:`-`)+String(`0000`+t).slice(-4)},"%Z":e=>e.tm_zone,"%%":()=>`%`};for(var c in o=o.replace(/%%/g,`\0\0`),g)o.includes(c)&&(o=o.replace(new RegExp(c,`g`),g[c](a)));o=o.replace(/\0\0/g,`%`);var _=Ee(o,!1);return _.length>t?0:(_t(_,e),_.length-1)},yt=(e,t,n,r,i)=>vt(e,t,n,r),bt=e=>n[`_`+e],xt=(e,t,n)=>Te(e,S,t,n),St=e=>{var t=we(e)+1,n=wn(t);return xt(e,n,t),n},Ct=(e,t,n,r,i)=>{var a={string:e=>{var t=0;return e!=null&&e!==0&&(t=St(e)),t},array:e=>{var t=wn(e.length);return _t(e,t),t}};function o(e){return t===`string`?Ie(e):t===`boolean`?!!e:e}var s=bt(e),c=[],l=0;if(r)for(var u=0;u<r.length;u++){var d=a[n[u]];d?(l===0&&(l=Sn()),c[u]=d(r[u])):c[u]=r[u]}var f=s.apply(null,c);function p(e){return l!==0&&Cn(l),o(e)}return f=p(f),f},wt=(e,t,n,r)=>{var i=!n||n.every(e=>e===`number`||e===`boolean`);return t!==`string`&&i&&!r?bt(e):function(){return Ct(e,t,n,arguments,r)}},Tt=(e,t)=>{e<128?t.push(e):t.push(e%128|128,e>>7)},Et=e=>{for(var t={i:`i32`,j:`i64`,f:`f32`,d:`f64`,e:`externref`,p:`i32`},n={parameters:[],results:e[0]==`v`?[]:[t[e[0]]]},r=1;r<e.length;++r)n.parameters.push(t[e[r]]);return n},Dt=(e,t)=>{var n=e.slice(0,1),r=e.slice(1),i={i:127,p:127,j:126,f:125,d:124,e:111};t.push(96),Tt(r.length,t);for(var a=0;a<r.length;++a)t.push(i[r[a]]);n==`v`?t.push(0):t.push(1,i[n])},Ot=(e,t)=>{if(typeof WebAssembly.Function==`function`)return new WebAssembly.Function(Et(t),e);var n=[1];Dt(t,n);var r=[0,97,115,109,1,0,0,0,1];Tt(n.length,r),r.push.apply(r,n),r.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var i=new WebAssembly.Module(new Uint8Array(r));return new WebAssembly.Instance(i,{e:{f:e}}).exports.f},kt=[],At,jt=e=>{var t=kt[e];return t||(e>=kt.length&&(kt.length=e+1),kt[e]=t=At.get(e)),t},Mt=(e,t)=>{if(Nt)for(var n=e;n<e+t;n++){var r=jt(n);r&&Nt.set(r,n)}},Nt,Pt=e=>(Nt||(Nt=new WeakMap,Mt(0,At.length)),Nt.get(e)||0),Ft=[],Z=()=>{if(Ft.length)return Ft.pop();try{At.grow(1)}catch(e){throw e instanceof RangeError?`Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.`:e}return At.length-1},It=(e,t)=>{At.set(e,t),kt[e]=At.get(e)},Lt=(e,t)=>{var n=Pt(e);if(n)return n;var r=Z();try{It(r,e)}catch(n){if(!(n instanceof TypeError))throw n;It(r,Ot(e,t))}return Nt.set(e,r),r},Rt=e=>{Nt.delete(jt(e)),It(e,null),Ft.push(e)},zt=function(e,t,n,r){e||=this,this.parent=e,this.mount=e.mount,this.mounted=null,this.id=J.nextInode++,this.name=t,this.mode=n,this.node_ops={},this.stream_ops={},this.rdev=r},Bt=365,Vt=146;Object.defineProperties(zt.prototype,{read:{get:function(){return(this.mode&Bt)===Bt},set:function(e){e?this.mode|=Bt:this.mode&=~Bt}},write:{get:function(){return(this.mode&Vt)===Vt},set:function(e){e?this.mode|=Vt:this.mode&=~Vt}},isFolder:{get:function(){return J.isDir(this.mode)}},isDevice:{get:function(){return J.isChrdev(this.mode)}}}),J.FSNode=zt,J.createPreloadedFile=Ne,J.staticInit();var Ht={g:Le,p:Re,h:ze,i:Be,c:Ve,e:He,j:We,b:Ge,q:Ke,r:Je,m:$e,n:et,a:it,f:at,o:st,k:lt,d:dt,l:yt},Q=pe(),Ut=n._Highs_create=()=>(Ut=n._Highs_create=Q.u)(),Wt=n._Highs_destroy=e=>(Wt=n._Highs_destroy=Q.v)(e),Gt=n._Highs_version=()=>(Gt=n._Highs_version=Q.w)(),Kt=n._Highs_run=e=>(Kt=n._Highs_run=Q.x)(e),qt=n._Highs_readModel=(e,t)=>(qt=n._Highs_readModel=Q.y)(e,t),Jt=n._Highs_getNumCol=e=>(Jt=n._Highs_getNumCol=Q.z)(e),Yt=n._Highs_clearModel=e=>(Yt=n._Highs_clearModel=Q.A)(e),Xt=n._Highs_setBoolOptionValue=(e,t,r)=>(Xt=n._Highs_setBoolOptionValue=Q.B)(e,t,r),Zt=n._Highs_setIntOptionValue=(e,t,r)=>(Zt=n._Highs_setIntOptionValue=Q.C)(e,t,r),Qt=n._Highs_setDoubleOptionValue=(e,t,r)=>(Qt=n._Highs_setDoubleOptionValue=Q.D)(e,t,r),$t=n._Highs_setStringOptionValue=(e,t,r)=>($t=n._Highs_setStringOptionValue=Q.E)(e,t,r),en=n._Highs_getIntInfoValue=(e,t,r)=>(en=n._Highs_getIntInfoValue=Q.F)(e,t,r),tn=n._Highs_getDoubleInfoValue=(e,t,r)=>(tn=n._Highs_getDoubleInfoValue=Q.G)(e,t,r),nn=n._Highs_getInt64InfoValue=(e,t,r)=>(nn=n._Highs_getInt64InfoValue=Q.H)(e,t,r),rn=n._Highs_getSolution=(e,t,r,i,a)=>(rn=n._Highs_getSolution=Q.I)(e,t,r,i,a),an=n._Highs_getModelStatus=e=>(an=n._Highs_getModelStatus=Q.J)(e),$=n._Highs_getObjectiveValue=e=>($=n._Highs_getObjectiveValue=Q.K)(e),on=n._Highs_getNumRow=e=>(on=n._Highs_getNumRow=Q.L)(e),sn=n._Highs_setSolution=(e,t,r,i,a)=>(sn=n._Highs_setSolution=Q.M)(e,t,r,i,a),cn=n._Highs_setSparseSolution=(e,t,r,i)=>(cn=n._Highs_setSparseSolution=Q.N)(e,t,r,i),ln=n._Highs_setCallback=(e,t,r)=>(ln=n._Highs_setCallback=Q.O)(e,t,r),un=n._Highs_startCallback=(e,t)=>(un=n._Highs_startCallback=Q.P)(e,t),dn=n._Highs_stopCallback=(e,t)=>(dn=n._Highs_stopCallback=Q.Q)(e,t),fn=n._Highs_changeObjectiveOffset=(e,t)=>(fn=n._Highs_changeObjectiveOffset=Q.R)(e,t),pn=n._Highs_getObjectiveOffset=(e,t)=>(pn=n._Highs_getObjectiveOffset=Q.S)(e,t),mn=n._Highs_getRowName=(e,t,r)=>(mn=n._Highs_getRowName=Q.T)(e,t,r),hn=n._Highs_getColName=(e,t,r)=>(hn=n._Highs_getColName=Q.U)(e,t,r),gn=n._Highs_getColIntegrality=(e,t,r)=>(gn=n._Highs_getColIntegrality=Q.V)(e,t,r),_n=n._Highs_getNumNz=e=>(_n=n._Highs_getNumNz=Q.W)(e),vn=()=>(vn=Q.X)(),yn=n._malloc=e=>(yn=n._malloc=Q.Y)(e),bn=n._free=e=>(bn=n._free=Q.Z)(e),xn=()=>(xn=Q._)(),Sn=()=>(Sn=Q.$)(),Cn=e=>(Cn=Q.aa)(e),wn=e=>(wn=Q.ba)(e);n.wasmMemory=v,n.ccall=Ct,n.cwrap=wt,n.addFunction=Lt,n.removeFunction=Rt,n.setValue=ve,n.getValue=ge,n.UTF8ToString=Ie,n.stringToUTF8=xt,n.FS=J;var Tn;P=function e(){Tn||En(),Tn||(P=e)};function En(){if(N>0||(ne(),N>0))return;function e(){Tn||(Tn=!0,n.calledRun=!0,!y&&(re(),r(n),n.onRuntimeInitialized&&n.onRuntimeInitialized(),ie()))}n.setStatus?(n.setStatus(`Running...`),setTimeout(function(){setTimeout(function(){n.setStatus(``)},1),e()},1)):e()}if(n.preInit)for(typeof n.preInit==`function`&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.pop()();return En(),t.ready})})()})),vt=r({default:()=>yt});async function yt(e={}){let t=await gt(e);return new mt(t)}var bt=n((()=>{_t(),ht()}));ht();var xt=[`mip_max_nodes`,`mip_max_improving_sols`,`mip_max_leaves`,`simplex_iteration_limit`,`ipm_iteration_limit`],St=new Set([`timeLimit`,`outputFlag`,`presolve`,`solver`,`relativeGap`,`absoluteGap`,`wasmUrl`,`signal`,`onProgress`,`onIncumbent`,`relax`,`useWorker`,`objectiveOffset`,`initialValues`,...xt]);function Ct(e={}){if(e.threads!==void 0)throw Error(`Solver "HiGHS" does not support option "threads" (HiGHS WebAssembly runs single-threaded).`);if(e.verbose!==void 0)throw Error(`Solver "HiGHS" does not support option "verbose"; use "outputFlag" instead.`);for(let[t,n]of Object.entries(e))if(n!==void 0&&!St.has(t))throw Error(`Solver "HiGHS" does not support option "${t}".`);if(e.useWorker!==void 0&&typeof e.useWorker!=`boolean`)throw Error(`Invalid HiGHS option "useWorker": expected boolean, got ${typeof e.useWorker}.`);if(e.outputFlag!==void 0&&typeof e.outputFlag!=`boolean`)throw Error(`Invalid HiGHS option "outputFlag": expected boolean, got ${typeof e.outputFlag}.`);if(e.relax!==void 0&&typeof e.relax!=`boolean`)throw Error(`Invalid HiGHS option "relax": expected boolean, got ${typeof e.relax}.`);if(e.presolve!==void 0&&e.presolve!==`on`&&e.presolve!==`off`&&e.presolve!==`choose`)throw Error(`Invalid HiGHS option "presolve" (${String(e.presolve)}): expected "on", "off", or "choose".`);if(e.timeLimit!==void 0&&(typeof e.timeLimit!=`number`||!Number.isFinite(e.timeLimit)||e.timeLimit<0))throw Error(`Invalid HiGHS option "timeLimit" (${String(e.timeLimit)}): expected a finite non-negative number of seconds.`);if(e.relativeGap!==void 0&&(typeof e.relativeGap!=`number`||!Number.isFinite(e.relativeGap)||e.relativeGap<0))throw Error(`Invalid HiGHS option "relativeGap" (${String(e.relativeGap)}): expected a finite non-negative number.`);if(e.absoluteGap!==void 0&&(typeof e.absoluteGap!=`number`||!Number.isFinite(e.absoluteGap)||e.absoluteGap<0))throw Error(`Invalid HiGHS option "absoluteGap" (${String(e.absoluteGap)}): expected a finite non-negative number.`);if(e.objectiveOffset!==void 0&&(typeof e.objectiveOffset!=`number`||!Number.isFinite(e.objectiveOffset)))throw Error(`Invalid HiGHS option "objectiveOffset" (${String(e.objectiveOffset)}): expected a finite number.`);if(e.wasmUrl!==void 0&&e.wasmUrl!==null&&(typeof e.wasmUrl!=`string`||e.wasmUrl===``))throw Error(`Invalid HiGHS option "wasmUrl": expected a non-empty string or null.`)}var wt=null,Tt=null,Et=null;function Dt(e){Et=e,wt=null,Tt=null}function Ot(){return Et}async function kt(e){return e||Et||it()}async function At(e={}){let t=await kt(e.wasmUrl);return{isNode:!1,wasmUrl:t,key:t??`node`}}async function jt(e={}){let{isNode:t,wasmUrl:n,key:r}=await At(e);if(wt&&Tt===r)return wt;Tt=r;let i=null;return i=(async()=>{let e=t?await at():(await Promise.resolve().then(()=>(bt(),vt))).default;return t?await e():await e({locateFile:e=>e.endsWith(`.wasm`)?n:e})})().then(e=>e).catch(e=>{wt===i&&(wt=null,Tt=null);let t=e instanceof Error?e.message:String(e);throw Error(`[WaSHI] Failed to initialize HiGHS${n?` from "${n}"`:``}. Deploy the package's WASM asset or explicitly set wasmUrl; no CDN fallback is attempted. ${t}`,{cause:e})}),wt=i,i}async function Mt(e,t={}){if(Ct(t),t.signal?.aborted)return{result:{Status:`Interrupted`,StatusCode:17,HasPrimalSolution:!1,ObjectiveValue:NaN,Columns:{},Rows:[]},runTime:0};let n=await jt(t);if(t.signal?.aborted)return{result:{Status:`Interrupted`,StatusCode:17,HasPrimalSolution:!1,ObjectiveValue:NaN,Columns:{},Rows:[]},runTime:0};let r=performance.now(),i={output_flag:t.outputFlag??!1};t.timeLimit!==void 0&&(i.time_limit=t.timeLimit),t.presolve!==void 0&&(i.presolve=t.presolve),t.solver!==void 0&&(i.solver=t.solver),t.relativeGap!==void 0&&(i.mip_rel_gap=t.relativeGap),t.absoluteGap!==void 0&&(i.mip_abs_gap=t.absoluteGap);for(let e of xt)t[e]!==void 0&&(i[e]=t[e]);let a=t.objectiveOffset??0,o=t.initialValues,s=!1;if(o){for(let[e,t]of Object.entries(o))if(t!==void 0){if(typeof t!=`number`||!Number.isFinite(t))throw Error(`Invalid initial value for column "${e}": ${String(t)} (must be a finite number).`);s=!0}}if(typeof n.withModel!=`function`)throw Error(`[WaSHI] HiGHS runtime is missing required withModel() API (legacy highs.solve fallback has been removed).`);return{result:n.withModel({format:`lp`,data:e},e=>{let c=!1;if(a!==0){if(typeof e.changeObjectiveOffset!=`function`)throw Error(`[WaSHI] HiGHS runtime does not support changeObjectiveOffset() for non-zero objectiveOffset.`);let t=typeof e.getObjectiveOffset==`function`?e.getObjectiveOffset():0;e.changeObjectiveOffset(t+a),c=!0}for(let[t,n]of Object.entries(i))e.options.set(t,n);let l=e.getDimensions(),u=[],d=!1;for(let t=0;t<l.numCols;t++){let n=e.getColIntegrality(t);n!==0&&(d=!0),u.push({name:e.getColName(t),type:n===1?`Integer`:`Continuous`})}if(s&&o){if(typeof e.setSolution!=`function`)throw Error(`HiGHS runtime does not support setting primal initial values (setSolution is unavailable).`);let t=new Map;for(let e=0;e<l.numCols;e++)t.set(u[e].name,e);for(let[e,n]of Object.entries(o))if(n!==void 0&&!t.has(e))throw Error(`Unknown column "${e}" in initialValues (column does not exist in the HiGHS LP model).`);let n=[],r=[];for(let e=0;e<l.numCols;e++){let t=u[e].name;if(Object.prototype.hasOwnProperty.call(o,t)){let i=o[t];i!==void 0&&(n.push(e),r.push(i))}}n.length>0&&(n.length===l.numCols?e.setSolution({colValue:r}):e.setSolution({indices:n,values:r}))}let f=null,p=null,m=0,h=e=>{let t=e?.data??{},n=typeof t.running_time==`number`&&Number.isFinite(t.running_time)?t.running_time:(performance.now()-r)/1e3,i=typeof t.mip_primal_bound==`number`&&Number.isFinite(t.mip_primal_bound)?t.mip_primal_bound:typeof t.objective_function_value==`number`&&Number.isFinite(t.objective_function_value)?t.objective_function_value:void 0,a=typeof t.mip_dual_bound==`number`&&Number.isFinite(t.mip_dual_bound)?t.mip_dual_bound:void 0,o=typeof t.mip_gap==`number`&&Number.isFinite(t.mip_gap)?t.mip_gap:void 0,s=i!==void 0&&a!==void 0?Math.abs(i-a):void 0,c=typeof t.mip_node_count==`bigint`?Number(t.mip_node_count):typeof t.mip_node_count==`number`&&Number.isFinite(t.mip_node_count)?t.mip_node_count:void 0,l=typeof t.mip_total_lp_iterations==`bigint`?Number(t.mip_total_lp_iterations):typeof t.simplex_iteration_count==`number`&&Number.isFinite(t.simplex_iteration_count)?t.simplex_iteration_count:typeof t.ipm_iteration_count==`number`&&Number.isFinite(t.ipm_iteration_count)?t.ipm_iteration_count:void 0,u=typeof e?.message==`string`&&e.message.trim().length>0?e.message.trim():void 0,d={elapsedTime:n,elapsedSeconds:n,...i===void 0?{}:{objectiveValue:i},...a===void 0?{}:{objectiveBound:a},...o===void 0?{}:{relativeGap:o},...s===void 0?{}:{absoluteGap:s},...c===void 0?{}:{nodes:c},...l===void 0?{}:{iterations:l},...u===void 0?{}:{message:u}};return p=d,d},g=e=>{let n=e?.data;if(!n||!(n.mip_solution instanceof Float64Array))return;let r=n.mip_solution,i={};for(let e=0;e<u.length&&e<r.length;e++)Object.defineProperty(i,u[e].name,{value:{Index:e,Type:u[e].type,Name:u[e].name,Primal:r[e]},enumerable:!0,writable:!0,configurable:!0});let a=typeof n.objective_function_value==`number`&&Number.isFinite(n.objective_function_value)?n.objective_function_value:typeof n.mip_primal_bound==`number`&&Number.isFinite(n.mip_primal_bound)?n.mip_primal_bound:NaN;Number.isFinite(a)&&(f={objectiveValue:a,...typeof n.mip_dual_bound==`number`&&Number.isFinite(n.mip_dual_bound)?{mipDualBound:n.mip_dual_bound}:{},...typeof n.mip_gap==`number`&&Number.isFinite(n.mip_gap)?{mipGap:n.mip_gap}:{},columns:i},t.onIncumbent?.(f))},_=!1;if(t.signal||t.onProgress||t.onIncumbent){let r=n.constants?.callbackType??{logging:0,simplexInterrupt:1,ipmInterrupt:2,mipSolution:3,mipImprovingSolution:4,mipLogging:5,mipInterrupt:6},i=e=>{if(t.signal?.aborted){_=!0,e.interrupt();return}t.onProgress&&(m++,t.onProgress(h(e)),t.signal?.aborted&&(_=!0,e.interrupt()))},a={[r.simplexInterrupt]:i,[r.ipmInterrupt]:i,[r.mipInterrupt]:i,[r.mipImprovingSolution]:e=>{g(e),t.onProgress&&!t.signal?.aborted&&(m++,t.onProgress(h(e)))},[r.mipLogging]:e=>{t.onProgress&&!t.signal?.aborted&&(m++,t.onProgress(h(e)))}};e.run(a)}else e.run();let v=e.getModelStatus();_&&(v=17);let y=ut[v]??`Unknown`,b=0,x=0;try{b=Number(e.info.get(`primal_solution_status`))}catch{}try{x=Number(e.info.get(`dual_solution_status`))}catch{}let S=n.constants?.solutionStatus?.feasible??2,C=b===S,w=x===S,T=C||w?e.getSolution():null,E=C,D={};if(!C&&f!==null)E=!0,D=f.columns;else for(let e=0;e<l.numCols;e++){let t=u[e],n={Index:e,Type:t.type,Name:t.name};C&&T&&(n.Primal=T.colValue[e]),!d&&w&&T&&(n.Dual=T.colDual[e]),Object.defineProperty(D,t.name,{value:n,enumerable:!0,writable:!0,configurable:!0})}let ee=[];for(let t=0;t<l.numRows;t++){let n=e.getRowName(t),r={Index:t,Name:n};C&&T&&(r.Primal=T.rowValue[t]),!d&&w&&T&&(r.Dual=T.rowDual[t]),ee.push(r)}let O=C?e.getObjectiveValue():f===null?NaN:f.objectiveValue,k,A;if(d){try{let t=Number(e.info.get(`mip_dual_bound`));Number.isFinite(t)&&(k=t)}catch{}k===void 0&&p&&p.objectiveBound!==void 0&&(k=p.objectiveBound);try{let t=Number(e.info.get(`mip_gap`));Number.isFinite(t)&&(A=t)}catch{}A===void 0&&p&&p.relativeGap!==void 0&&(A=p.relativeGap)}return{Status:ut[v]??y,StatusCode:v,PrimalSolutionStatus:b,DualSolutionStatus:x,HasPrimalSolution:E,IsMip:d,ObjectiveValue:O,ObjectiveOffsetApplied:c,MipDualBound:k,MipGap:A,Columns:D,Rows:ee}}),runTime:(performance.now()-r)/1e3}}function Nt(){let e=rt(`highs-worker.js`),t=typeof window.origin==`string`?window.origin:window.location?.origin;if(new URL(e).origin===t)return new Worker(e,{type:`module`});let n=URL.createObjectURL(new Blob([`import `+JSON.stringify(e)+`;`],{type:`text/javascript`}));try{let e=new Worker(n,{type:`module`}),t=()=>URL.revokeObjectURL(n);return e.addEventListener(`message`,t,{once:!0}),e.addEventListener(`error`,t,{once:!0}),e}catch(e){throw URL.revokeObjectURL(n),e}}var Pt=null,Ft=0,Z=new Map;function It(e,t){return e?{Status:`Interrupted`,StatusCode:17,HasPrimalSolution:!0,IsMip:!0,ObjectiveValue:e.objectiveValue,ObjectiveOffsetApplied:!0,...t?.objectiveBound===void 0?e.mipDualBound===void 0?{}:{MipDualBound:e.mipDualBound}:{MipDualBound:t.objectiveBound},...t?.relativeGap===void 0?e.mipGap===void 0?{}:{MipGap:e.mipGap}:{MipGap:t.relativeGap},Columns:e.columns,Rows:[]}:{Status:`Interrupted`,StatusCode:17,HasPrimalSolution:!1,ObjectiveValue:NaN,ObjectiveOffsetApplied:!0,...t?.objectiveBound===void 0?{}:{MipDualBound:t.objectiveBound},...t?.relativeGap===void 0?{}:{MipGap:t.relativeGap},Columns:{},Rows:[]}}function Lt(e){let t=Z.values().next().value;if(t&&!t.dispatched){t.dispatched=!0;try{t.kind===`WARMUP`?e.postMessage({type:`WARMUP`,id:t.id,options:t.workerOptions}):e.postMessage({type:`SOLVE`,id:t.id,lpString:t.lpString,options:t.workerOptions,...t.reportProgress?{reportProgress:!0}:{}})}catch(n){Z.delete(t.id),t.cleanupAbort?.(),t.reject(n),Lt(e)}}}function Rt(){let e=Pt;e&&(Pt=null,e.terminate());for(let e of Z.values())e.dispatched=!1;if(Z.size>0)try{let e=Bt();if(e)Lt(e);else{let e=Error(`[WaSHI] Failed to recreate HiGHS Worker after interruption.`);for(let t of Array.from(Z.values()))Z.delete(t.id),t.cleanupAbort?.(),t.reject(e)}}catch(e){for(let t of Array.from(Z.values()))Z.delete(t.id),t.cleanupAbort?.(),t.reject(e)}}function zt(){return typeof window<`u`&&typeof Worker<`u`&&typeof Worker?.prototype?.unref!=`function`}function Bt(){if(!zt())return null;if(!Pt){let e;try{e=Nt(),e.onmessage=t=>{let{type:n,id:r,result:i,runTime:a,error:o,progress:s,incumbent:c}=t.data,l=Z.get(r);if(l){if(n===`SOLVE_PROGRESS`){if(l.kind===`SOLVE`&&s){l.lastProgress=s;try{l.onProgress?.(s)}catch(e){let t=Z.get(r);if(t){let n=Z.keys().next().value;Z.delete(r),t.cleanupAbort?.(),n===r&&Rt(),t.reject(e)}}}return}if(n===`SOLVE_INCUMBENT`){l.kind===`SOLVE`&&c&&(l.lastIncumbent=c);return}Z.delete(r),l.cleanupAbort?.(),l.kind===`WARMUP`?n===`WARMUP_SUCCESS`?(Pt===e&&l.wasmUrl,l.resolve()):l.reject(Error(o||`Worker warmup failed`)):n===`SOLVE_SUCCESS`?(Pt===e&&l.wasmUrl,l.resolve({result:i,runTime:a})):l.reject(Error(o||`Worker solve failed`)),Pt===e&&Lt(e)}};let t=t=>{if(Pt===e){Pt=null,e.terminate();for(let e of Z.values())e.cleanupAbort?.(),e.reject(t);Z.clear()}};e.onerror=e=>t(Error(`[WaSHI] HiGHS Worker failed to load or execute. Check Worker assets, CORS and CSP. ${e?.message||``}`)),e.onmessageerror=()=>t(Error(`[WaSHI] Could not deserialize the HiGHS Worker response.`)),Pt=e}catch(e){throw Pt=null,e}}return Pt}function Vt(e){let t=typeof window<`u`?typeof window.origin==`string`?window.origin:window.location?.origin:void 0;return e.useWorker??(typeof window<`u`&&t!==`null`&&!t?.startsWith(`file:`))}function Ht(e){if(e.useWorker===!0&&!zt())throw Error(`[WaSHI] Web Worker execution was requested (useWorker: true), but browser Web Workers are unavailable in this environment.`);return Vt(e)?Bt():null}function Q(e,t){let{signal:n,onProgress:r,onIncumbent:i,...a}=e,o={};for(let[e,t]of Object.entries(a)){if(typeof t==`function`)throw Error(`[WaSHI] HiGHS Worker option "${e}" cannot be a function (functions cannot be cloned across Web Worker boundaries).`);o[e]=t}return o.wasmUrl=t,o}function Ut(e,t,n){if(!e)return;let r=()=>{let e=Z.get(t.id);if(!e)return;let r=Z.keys().next().value;Z.delete(t.id),e.cleanupAbort?.(),r===t.id&&Rt(),n()};e.addEventListener(`abort`,r,{once:!0}),t.cleanupAbort=()=>e.removeEventListener(`abort`,r)}async function Wt(e,t={}){if(Ct(t),t.signal?.aborted)return{result:It(),runTime:0};let n=await kt(t.wasmUrl);if(t.signal?.aborted)return{result:It(),runTime:0};let r=Ht(t);if(!r)return Mt(e,t);let{signal:i,onProgress:a}=t,o=Q(t,n),s=!!(a||i),c=`req_${++Ft}`,l=performance.now();return new Promise((t,u)=>{let d={kind:`SOLVE`,id:c,lpString:e,workerOptions:o,wasmUrl:n,reportProgress:s,startTime:l,onProgress:a,resolve:t,reject:u};Ut(i,d,()=>{let e=(performance.now()-d.startTime)/1e3;d.resolve({result:It(d.lastIncumbent,d.lastProgress),runTime:e})}),Z.set(c,d),Lt(r)})}function Gt(e,t){if(typeof t==`number`)switch(t){case 0:return`NotSolved`;case 1:case 2:case 3:case 4:case 5:return`Error`;case 6:return`Unknown`;case 7:return`Optimal`;case 8:return`Infeasible`;case 9:return`InfeasibleOrUnbounded`;case 10:return`Unbounded`;case 11:return`ObjectiveBound`;case 12:return`ObjectiveTarget`;case 13:return`TimeLimit`;case 14:return`IterationLimit`;case 15:return`Unknown`;case 16:return`SolutionLimit`;case 17:return`Interrupted`;case 18:return`MemoryLimit`}if(typeof e!=`string`)return`Unknown`;let n=e.trim();if(!n)return`Unknown`;switch(n){case`Optimal`:return`Optimal`;case`Infeasible`:return`Infeasible`;case`Unbounded`:return`Unbounded`;case`Primal infeasible or unbounded`:case`InfeasibleOrUnbounded`:return`InfeasibleOrUnbounded`;case`Time limit reached`:case`TimeLimit`:return`TimeLimit`;case`Iteration limit reached`:case`IterationLimit`:return`IterationLimit`;case`Solution limit reached`:case`SolutionLimit`:return`SolutionLimit`;case`Memory limit reached`:case`MemoryLimit`:return`MemoryLimit`;case`Bound on objective reached`:case`ObjectiveBound`:return`ObjectiveBound`;case`Target for objective reached`:case`ObjectiveTarget`:return`ObjectiveTarget`;case`Interrupted`:case`User interrupt`:return`Interrupted`;case`Feasible`:return`Feasible`;case`Not Set`:return`NotSolved`;case`Load error`:case`Model error`:case`Presolve error`:case`Solve error`:case`Postsolve error`:case`Error`:return`Error`;case`Empty`:case`Unknown`:return`Unknown`}return`Unknown`}function Kt(e,t,n){switch(Gt(e,t)){case`Optimal`:return`Optimal`;case`Infeasible`:return`Infeasible`;case`Unbounded`:return`Unbounded`;case`TimeLimit`:return`TimeLimit`;case`IterationLimit`:return`IterationLimit`;case`Feasible`:return`Feasible`;case`ObjectiveBound`:case`ObjectiveTarget`:case`SolutionLimit`:return n===!1?`Unknown`:`Feasible`;case`MemoryLimit`:case`Interrupted`:return n?`Feasible`:`Unknown`;case`NotSolved`:return`NotSolved`;case`Error`:return`Error`;default:return`Unknown`}}var qt=class e{static capabilities={supportsMIP:!0,supportsQP:!0,supportsWarmStart:!0};name=`HiGHS`;version=`1.15.1`;capabilities=e.capabilities;options;constructor(e={}){this.options=e}async solve(e,t={},n={}){let r=Ue(t),i=r?n:t,a={...this.options,...i};Ct(a);let o=e.objective?.constant??0;if(typeof o!=`number`||!Number.isFinite(o))throw Error(`Solver "${this.name}" encountered non-finite objective constant: ${String(o)}.`);let s=o===0?0:o;for(let t of e.variables)M(t);let{lpString:c,nameToVar:l,nameToConstraint:u}=r?t:Ke(e,{relax:a.relax}),d=Object.create(null),f=!1,p=new Set;for(let[e,t]of l.entries()){p.add(t);let n=ae(t);n!==void 0&&(d[e]=n,f=!0)}for(let t of e.variables)if(!p.has(t))throw Error(`LP export symbol map (nameToVar) is missing model variable "${t.name}".`);let m=a;(s!==0||f||m.initialValues!==void 0)&&(m={...m,...s===0?{}:{objectiveOffset:s},...f?{initialValues:d}:{}});let{result:h,runTime:g}=await Wt(c,m),_=h?.ObjectiveOffsetApplied?0:s,v=Gt(h?.Status,h?.StatusCode),y=a.relax?!1:typeof h?.IsMip==`boolean`?h.IsMip:e.variables.some(e=>e.type===`Integer`||e.type===`Binary`),b=h?.HasPrimalSolution===!0,x=Kt(h?.Status,h?.StatusCode,b),S=null;b&&typeof h?.ObjectiveValue==`number`&&Number.isFinite(h.ObjectiveValue)&&(S=h.ObjectiveValue+_);let C,w,T;if(typeof h?.MipDualBound==`number`&&Number.isFinite(h.MipDualBound)?C=h.MipDualBound+_:!y&&v===`Optimal`&&S!==null&&(C=S),S!==null&&C!==void 0&&Number.isFinite(C)&&(T=Math.abs(S-C)),_!==0&&y&&S!==null&&C!==void 0&&T!==void 0){if(T===0)w=0;else if(Math.abs(S)>0){let e=T/Math.abs(S);w=Number.isFinite(e)?e:void 0}else w=void 0}else typeof h?.MipGap==`number`&&Number.isFinite(h.MipGap)?w=h.MipGap:y&&v===`Optimal`&&b&&(T===void 0||T===0)&&(w=0);if(!b)return{status:x,terminationStatus:v,hasPrimalSolution:!1,objectiveValue:null,...C===void 0?{}:{objectiveBound:C},...w===void 0?{}:{relativeGap:w},...T===void 0?{}:{absoluteGap:T},values:{},reducedCosts:{},duals:{},slacks:{},runTime:g,raw:h};let E=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})},D={},ee={},O={},k={};if(h.Columns)for(let[e,t]of Object.entries(h.Columns)){let n=l.get(e);if(n){if(typeof t.Primal==`number`&&Number.isFinite(t.Primal)){let e=Math.abs(t.Primal)<1e-9?0:t.Primal;!a.relax&&(n.type===`Integer`||n.type===`Binary`)&&Math.abs(e-Math.round(e))<=1e-5&&(e=Math.round(e)+0),E(D,n.name,e)}typeof t.Dual==`number`&&Number.isFinite(t.Dual)&&E(O,n.name,Math.abs(t.Dual)<1e-9?0:t.Dual)}}if(h.Rows){let e=Array.isArray(h.Rows)?h.Rows:Object.values(h.Rows);for(let t of e){let e=t.Name,n=e?u.get(e):void 0;if(n&&(typeof t.Dual==`number`&&Number.isFinite(t.Dual)&&E(ee,n.name,Math.abs(t.Dual)<1e-9?0:t.Dual),typeof t.Primal==`number`&&Number.isFinite(t.Primal))){let e=n.rhs-t.Primal;E(k,n.name,Math.abs(e)<1e-9?0:e)}}}return{status:x,terminationStatus:v,hasPrimalSolution:!0,objectiveValue:S,...C===void 0?{}:{objectiveBound:C},...w===void 0?{}:{relativeGap:w},...T===void 0?{}:{absoluteGap:T},values:D,reducedCosts:O,duals:ee,slacks:k,runTime:g,raw:h}}},Jt=qt;function Yt(){Ze(`highs`,e=>new qt(e)),Qe(e=>new qt(e))}Yt(),ht();var Xt=class{name;capabilities;options;constructor(e={}){this.name=e.name||`MockSolver`,this.capabilities=e.capabilities||{supportsMIP:!0,supportsQP:!0,supportsWarmStart:!0},this.options=e}async solve(e,t={},n={}){let r=Ue(t)?n:t,i={...this.options,...r},a=!!(i.values&&Object.keys(i.values).length>0||i.boolValues&&Object.keys(i.boolValues).length>0);if(i.signal?.aborted)return{status:`Unknown`,terminationStatus:`Interrupted`,hasPrimalSolution:!1,objectiveValue:null,values:{},runTime:0,raw:{mock:!0}};if(i.delayMs&&i.delayMs>0&&(await new Promise(e=>{let t=setTimeout(()=>{i.signal?.removeEventListener(`abort`,n),e()},i.delayMs),n=()=>{clearTimeout(t),e()};i.signal?.addEventListener(`abort`,n,{once:!0})}),i.signal?.aborted)){let e=!!(i.hasPrimalSolution??a);return{status:e?`Feasible`:`Unknown`,terminationStatus:`Interrupted`,hasPrimalSolution:e,objectiveValue:e?i.objectiveValue??0:null,...i.objectiveBound===void 0?{}:{objectiveBound:i.objectiveBound},...i.relativeGap===void 0?{}:{relativeGap:i.relativeGap},...i.absoluteGap===void 0?{}:{absoluteGap:i.absoluteGap},values:e&&i.values||{},...e&&i.boolValues!==void 0?{boolValues:i.boolValues}:{},runTime:.001,raw:{mock:!0}}}if(i.onProgress&&Array.isArray(i.progressEvents))for(let e of i.progressEvents){if(i.signal?.aborted)break;i.onProgress(e)}let o=i.status||`Optimal`,s=i.terminationStatus??o,c=i.hasPrimalSolution===void 0?o===`Optimal`||o===`Feasible`||o===`Sat`||(o===`TimeLimit`||o===`IterationLimit`||s===`Interrupted`)&&a:i.hasPrimalSolution;if(i.onProgress&&!Array.isArray(i.progressEvents)&&!i.signal?.aborted){let e=c?i.objectiveValue??0:void 0;i.onProgress({elapsedTime:.001,elapsedSeconds:.001,...typeof e==`number`&&Number.isFinite(e)?{objectiveValue:e}:{},...i.objectiveBound===void 0?{}:{objectiveBound:i.objectiveBound},...i.relativeGap===void 0?{}:{relativeGap:i.relativeGap},...i.absoluteGap===void 0?{}:{absoluteGap:i.absoluteGap}})}return i.signal?.aborted&&(s=`Interrupted`,c=i.hasPrimalSolution===void 0?a:i.hasPrimalSolution,o=c?`Feasible`:`Unknown`),{status:o,terminationStatus:s,hasPrimalSolution:c,objectiveValue:c?i.objectiveValue??0:null,...i.objectiveBound===void 0?{}:{objectiveBound:i.objectiveBound},...i.relativeGap===void 0?{}:{relativeGap:i.relativeGap},...i.absoluteGap===void 0?{}:{absoluteGap:i.absoluteGap},values:c&&i.values||{},...c&&i.boolValues!==void 0?{boolValues:i.boolValues}:{},reducedCosts:i.reducedCosts,duals:i.duals,slacks:i.slacks,runTime:.001,raw:{mock:!0}}}};function Zt(){Ze(`mock`,e=>new Xt(e))}Zt();function Qt(e,t){if(e===void 0)return 1e-6;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw Error(`Invalid ${t}: expected a finite non-negative number, received ${String(e)}.`);return e}function $t(e,t={}){let n=Qt(t.feasibilityTolerance,`feasibilityTolerance`),r=Qt(t.integralityTolerance,`integralityTolerance`),i=t.evaluateLogicalConstraints===void 0||!!t.evaluateLogicalConstraints,a=t.values!==void 0&&t.values!==null;if(t.values!==void 0&&(typeof t.values!=`object`||t.values===null||Array.isArray(t.values)))throw Error(`Invalid values option: expected a plain object mapping variable names to values.`);let o=t.values,s=[],u=Object.create(null),d=[],f=[],p=0,m=e=>{typeof e==`number`&&!Number.isNaN(e)&&e>p&&(p=e)},g=e=>{s.push(e),Object.prototype.hasOwnProperty.call(u,e.name)||(u[e.name]=[]),u[e.name].push(e),e.type!==`missing_value`&&e.type!==`unchecked_constraint`&&m(e.violation)},_=[],v=[];for(let t of e.variables.values())t.type===`Boolean`?v.push(t):_.push(t);let y=[],b=[];for(let t of e.constraints.values())t instanceof R?y.push(t):b.push(t);let x=new Map,S=new Map,C=0,T=0,E=0,D=0;for(let e of _){let t=a?Object.prototype.hasOwnProperty.call(o,e.name)?o[e.name]:void 0:e.value;if(t==null){f.push(e.name),g({type:`missing_value`,target:`variable`,name:e.name,actual:t??null,violation:1/0,message:`Variable "${e.name}" has no assigned solution value.`});continue}if(typeof t!=`number`||!Number.isFinite(t)){g({type:`non_finite_value`,target:`variable`,name:e.name,actual:t,violation:1/0,message:`Variable "${e.name}" has non-finite or non-numeric value: ${String(t)}.`});continue}x.set(e,t),C++;let i=e.type===`Binary`||e.type===`BINARY`,s=i||e.type===`Integer`||e.type===`INTEGER`,c=i?Math.max(0,e.lb):e.lb,l=i?Math.min(1,e.ub):e.ub,u=typeof e.lb==`number`&&!Number.isNaN(e.lb)&&e.lb!==1/0,d=typeof e.ub==`number`&&!Number.isNaN(e.ub)&&e.ub!==-1/0;if(!u)g({type:`lower_bound`,target:`variable`,name:e.name,actual:t,limit:e.lb,violation:1/0,message:`Variable "${e.name}" has invalid lower bound (${String(e.lb)}).`});else if(c!==-1/0){let r=t-c,i=Math.max(0,c-t);m(i),i>n&&g({type:`lower_bound`,target:`variable`,name:e.name,actual:t,limit:c,violation:i,signedViolation:r,message:`Variable "${e.name}" value (${t}) violates lower bound (${c}) by ${i}.`})}if(!d)g({type:`upper_bound`,target:`variable`,name:e.name,actual:t,limit:e.ub,violation:1/0,message:`Variable "${e.name}" has invalid upper bound (${String(e.ub)}).`});else if(l!==1/0){let r=t-l,i=Math.max(0,t-l);m(i),i>n&&g({type:`upper_bound`,target:`variable`,name:e.name,actual:t,limit:l,violation:i,signedViolation:r,message:`Variable "${e.name}" value (${t}) violates upper bound (${l}) by ${i}.`})}if(u&&d&&c>l&&c-t<=n&&t-l<=n){let n=c-l;g({type:`lower_bound`,target:`variable`,name:e.name,actual:t,limit:c,violation:n,signedViolation:t-c,message:`Variable "${e.name}" has inverted bounds [${c}, ${l}].`})}if(s){let n=Math.round(t),a=t-n,o=Math.abs(a);m(o),o>r&&g({type:`integrality`,target:`variable`,name:e.name,varType:i?`Binary`:`Integer`,actual:t,nearestInteger:n,violation:o,signedViolation:a,message:`${i?`Binary`:`Integer`} variable "${e.name}" value (${t}) violates integrality by ${o} (nearest integer: ${n}).`})}}for(let e of v){let t=a?Object.prototype.hasOwnProperty.call(o,e.name)?o[e.name]:void 0:e.value;if(t==null){f.push(e.name),g({type:`missing_value`,target:`bool_variable`,name:e.name,actual:t??null,violation:1/0,message:`Boolean variable "${e.name}" has no assigned solution value.`});continue}if(typeof t!=`boolean`){g({type:`invalid_boolean_value`,target:`bool_variable`,name:e.name,actual:t,violation:1/0,message:`Boolean variable "${e.name}" has non-boolean value: ${String(t)}.`});continue}S.set(e,t),T++}let ee=e=>{switch(e.kind){case`abs`:{let t=O(e.arg);return t.ok?{ok:!0,value:Math.abs(t.value),...t.atDomainError?{atDomainError:t.atDomainError}:{}}:t}case`max`:{let t=-1/0,n;for(let r of e.args){let e=O(r);if(!e.ok)return e;!n&&e.atDomainError&&(n=e.atDomainError),e.value>t&&(t=e.value)}return{ok:!0,value:t,...n?{atDomainError:n}:{}}}case`min`:{let t=1/0,n;for(let r of e.args){let e=O(r);if(!e.ok)return e;!n&&e.atDomainError&&(n=e.atDomainError),e.value<t&&(t=e.value)}return{ok:!0,value:t,...n?{atDomainError:n}:{}}}case`at`:{let t=O(e.index);if(!t.ok)return t;let i=t.value,a=e.array.length-1,o=Math.max(0,-i),s=Math.max(0,i-a),c=Math.max(o,s),l=Math.abs(i-Math.round(i));if(c>n||l>r)return{ok:!0,value:0,atDomainError:{violation:Math.max(c,l),message:`at() index (${i}) violates valid integer range [0, ${a}].`}};let u=O(e.array[Math.round(i)]);return u.ok?{ok:!0,value:u.value,...t.atDomainError??u.atDomainError?{atDomainError:t.atDomainError??u.atDomainError}:{}}:u}}},O=e=>{let t=e.constant===void 0?0:e.constant;if(typeof t!=`number`||!Number.isFinite(t))return{ok:!1,reason:`non-finite constant (${String(t)})`};let n=t;for(let[t,r]of e.terms){if(typeof r!=`number`||!Number.isFinite(r))return{ok:!1,reason:`non-finite coefficient (${String(r)}) for variable "${t.name}"`};if(r!==0){if(!x.has(t))return{ok:!1,reason:`missing or invalid value for variable "${t.name}"`};if(n+=r*x.get(t),!Number.isFinite(n))return{ok:!1,reason:`linear expression evaluation overflowed finite range`}}}let r;for(let t of e.nonlinearTerms??[]){if(typeof t.coeff!=`number`||!Number.isFinite(t.coeff))return{ok:!1,reason:`non-finite nonlinear coefficient (${String(t.coeff)})`};let e=ee(t.atom);if(!e.ok)return e;if(!r&&e.atDomainError&&(r=e.atDomainError),t.coeff!==0&&(n+=t.coeff*e.value,!Number.isFinite(n)))return{ok:!1,reason:`expression evaluation overflowed finite range`}}return{ok:!0,value:n,...r?{atDomainError:r}:{}}},k=e=>{switch(e.kind){case`abs`:return A(e.arg);case`max`:case`min`:{let t=[];for(let n of e.args){let e=A(n);if(!e.ok)return e;t.push(...e.errors)}return{ok:!0,errors:t}}case`at`:{let t=[],i=A(e.index);if(!i.ok)return i;t.push(...i.errors);for(let n of e.array){let e=A(n);if(!e.ok)return e;t.push(...e.errors)}let a=O(e.index);if(!a.ok)return a;if(i.errors.length===0){let i=a.value,o=e.array.length-1,s=Math.max(0,-i),c=Math.max(0,i-o),l=Math.max(s,c),u=Math.abs(i-Math.round(i));if(l>n||u>r){let e=Math.max(l,u);t.push({violation:e,message:`at() index (${i}) violates valid integer range [0, ${o}].`})}}return{ok:!0,errors:t}}}},A=e=>{let t=[];for(let n of e.nonlinearTerms??[]){let e=k(n.atom);if(!e.ok)return e;t.push(...e.errors)}return{ok:!0,errors:t}},te=e=>{if(e instanceof c)return{ok:!0};if(e instanceof R){let t=A(e.lhs);return t.ok?{ok:!0,...t.errors.length>0?{firstError:t.errors[0]}:{}}:t}if(e instanceof h){let t=e.spec,n=t.kind===`distinct`?t.args:t.kind===`disjoint`||t.kind===`cumulative`?t.tasks.map(e=>e.start):t.vars;for(let e of n){let t=A(e);if(!t.ok)return t;if(t.errors.length>0)return{ok:!0,firstError:t.errors[0]}}return{ok:!0}}if(e instanceof l){let t;for(let n of e.children){let e=te(n);if(!e.ok)return e;!t&&e.firstError&&(t=e.firstError)}return{ok:!0,...t?{firstError:t}:{}}}return{ok:!0}},ne=(e,t=n)=>{if(typeof e.rhs!=`number`||!Number.isFinite(e.rhs))return{status:`unchecked`,reason:`non-finite right-hand side (${String(e.rhs)})`};let r=A(e.lhs);if(!r.ok)return{status:`unchecked`,reason:r.reason};let i=O(e.lhs);if(!i.ok)return{status:`unchecked`,reason:i.reason};if(r.errors.length>0||i.atDomainError){let t=r.errors[0]??i.atDomainError;return{status:`violated`,lhsVal:i.value,signed:i.value-e.rhs,violation:t.violation,message:`Constraint "${e.name}" invalid element lookup: ${t.message}`}}let a=i.value,o=a-e.rhs;if(!Number.isFinite(o))return{status:`unchecked`,reason:`constraint residual overflowed finite range`};let s=e.sense===`<=`?Math.max(0,o):e.sense===`>=`?Math.max(0,-o):e.sense===`!=`?Math.max(0,1-Math.abs(o)):Math.abs(o);return s>t?{status:`violated`,lhsVal:a,signed:o,violation:s,message:`Constraint "${e.name}" (${a} ${e.sense} ${e.rhs}) violated by ${s}.`}:{status:`satisfied`,lhsVal:a,signed:o,violation:s}},re=e.objective();if((re instanceof w||re instanceof V)&&re.nonlinearTerms.length>0){let e=A(new V(new Map,0,re.nonlinearTerms));if(e.ok)for(let t of e.errors)g({type:`linear_constraint`,target:`constraint`,name:`objective_at`,violation:t.violation,message:`Objective at() lookup failed: ${t.message}`})}for(let e of y){let t=ne(e);t.status===`unchecked`?(d.push(e.name),g({type:`unchecked_constraint`,target:`constraint`,name:e.name,sense:e.sense,limit:e.rhs,rhs:e.rhs,violation:1/0,message:`Constraint "${e.name}" could not be evaluated: ${t.reason}.`})):t.status===`violated`?(E++,g({type:`linear_constraint`,target:`constraint`,name:e.name,sense:e.sense,actual:t.lhsVal,limit:e.rhs,rhs:e.rhs,violation:t.violation,signedViolation:t.signed,message:t.message})):(E++,m(t.violation))}let ie=e=>{if(e instanceof c)return S.has(e)?{ok:!0,value:S.get(e),violation:0}:{ok:!1,reason:`missing or invalid value for Boolean variable "${e.name}"`};if(e instanceof R){if(e.sense===`!=`){let t=O(e.lhs);if(!t.ok)return{ok:!1,reason:t.reason};if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};let r=Math.abs(t.value-e.rhs);return r<=n?{ok:!0,value:!1,violation:0}:r>=1-n?{ok:!0,value:!0,violation:0}:{ok:!1,reason:`discrete comparison "${e.name}" lies between 0 and 1 (${t.value} != ${e.rhs})`}}let t=ne(e,0);if(t.status===`unchecked`)return{ok:!1,reason:t.reason};if(n>0){let r=Math.abs(t.lhsVal-e.rhs);if(r>0&&r<=n)return{ok:!1,reason:`numeric comparison "${e.name}" lies within feasibilityTolerance (${n}) of boundary (${t.lhsVal} vs ${e.rhs})`}}return{ok:!0,value:t.status===`satisfied`,violation:0}}if(e instanceof h){let t=e.spec;if(t.kind===`distinct`){let e=[];for(let n of t.args){let t=O(n);if(!t.ok)return t;if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};e.push(t.value)}for(let t=0;t<e.length;t++)for(let r=t+1;r<e.length;r++){let i=Math.abs(e[t]-e[r]);if(i<=n)return{ok:!0,value:!1,violation:0};if(i<1-n)return{ok:!1,reason:`distinct() operands at indices (${t}, ${r}) have fractional gap (${i})`}}return{ok:!0,value:!0,violation:0}}if(t.kind===`disjoint`){let e=[];for(let n of t.tasks){let t=O(n.start);if(!t.ok)return t;if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};e.push(t.value)}for(let r=0;r<t.tasks.length;r++)for(let i=r+1;i<t.tasks.length;i++){let a=e[r],o=t.tasks[r].duration,s=e[i],c=t.tasks[i].duration;if(!(a+o<=s+n||s+c<=a+n))return{ok:!0,value:!1,violation:0}}return{ok:!0,value:!0,violation:0}}if(t.kind===`cumulative`){let e=[];for(let n of t.tasks){let t=O(n.start);if(!t.ok)return t;if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};e.push(t.value)}let r=[];for(let n=0;n<t.tasks.length;n++){let i=t.tasks[n];if(i.duration>0&&i.demand>0){if(i.demand>t.capacity)return{ok:!0,value:!1,violation:0};r.push({start:e[n],duration:i.duration,demand:i.demand})}}for(let e=0;e<r.length;e++){let i=r[e].start,a=0;for(let e=0;e<r.length;e++){let t=r[e];t.start-n<=i&&i<t.start+t.duration-n&&(a+=t.demand)}if(a>t.capacity+n)return{ok:!0,value:!1,violation:0}}return{ok:!0,value:!0,violation:0}}if(t.kind===`allowed`){let e=[];for(let n of t.vars){let t=O(n);if(!t.ok)return t;if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};e.push(t.value)}return{ok:!0,value:t.tuples.some(t=>t.every((t,r)=>Math.abs(e[r]-t)<=n)),violation:0}}}if(e instanceof l)switch(e.op){case`not`:{let t=ie(e.children[0]);return t.ok?{ok:!0,value:!t.value,violation:0}:t}case`and`:{let t=0;for(let n of e.children){let e=ie(n);if(!e.ok)return e;if(!e.value)return{ok:!0,value:!1,violation:0};e.violation>t&&(t=e.violation)}return{ok:!0,value:!0,violation:t}}case`or`:{let t=!1,n=1/0;for(let r of e.children){let e=ie(r);if(!e.ok)return e;e.value&&(t=!0,e.violation<n&&(n=e.violation))}return{ok:!0,value:t,violation:t?n:0}}case`implies`:{let t=ie(e.children[0]);if(!t.ok)return t;if(!t.value)return{ok:!0,value:!0,violation:0};let n=ie(e.children[1]);return n.ok?{ok:!0,value:n.value,violation:n.value?n.violation:0}:n}case`xor`:{let t=!1,n=0;for(let r of e.children){let e=ie(r);if(!e.ok)return e;e.value&&(t=!t,e.violation>n&&(n=e.violation))}return{ok:!0,value:t,violation:t?n:0}}default:return{ok:!1,reason:`unsupported logical operator "${String(e.op)}"`}}return{ok:!1,reason:`unsupported logical expression node`}};for(let e=0;e<b.length;e++){let t=b[e],n=t.name||`lc_${e+1}`;if(!i){d.push(n),g({type:`unchecked_constraint`,target:`logical_constraint`,name:n,violation:1/0,message:`Logical constraint "${n}" was not evaluated because evaluateLogicalConstraints is false.`});continue}let r=te(t.expr);if(!r.ok){d.push(n),g({type:`unchecked_constraint`,target:`logical_constraint`,name:n,violation:1/0,message:`Logical constraint "${n}" could not be evaluated: ${r.reason}.`});continue}if(r.firstError){D++,g({type:`logical_constraint`,target:`logical_constraint`,name:n,actual:!1,limit:!0,violation:r.firstError.violation,signedViolation:-1,message:`Logical constraint "${n}" invalid element lookup: ${r.firstError.message}`});continue}let a=ie(t.expr);if(!a.ok){d.push(n),g({type:`unchecked_constraint`,target:`logical_constraint`,name:n,violation:1/0,message:`Logical constraint "${n}" could not be evaluated: ${a.reason}.`});continue}D++,a.value?m(a.violation):g({type:`logical_constraint`,target:`logical_constraint`,name:n,actual:!1,limit:!0,violation:1,signedViolation:-1,message:`Logical constraint "${n}" evaluated to false.`})}let j=C===_.length&&T===v.length&&E===y.length&&D===b.length&&d.length===0&&f.length===0;return{valid:j&&s.length===0,complete:j,violations:s,violationsByName:u,uncheckedConstraints:d,missingVariables:f,maxViolation:p,summary:{checkedVariables:C,totalVariables:_.length,checkedBoolVariables:T,totalBoolVariables:v.length,checkedLinearConstraints:E,totalLinearConstraints:y.length,checkedLogicalConstraints:D,totalLogicalConstraints:b.length}}}function en(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw Error(`Invalid Big-M value for indicator constraint "${t}": expected a finite positive number, received ${e}.`)}function tn(e,t,n){let r=e.constant===void 0?0:e.constant;if(!Number.isFinite(t)||!Number.isFinite(r))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": constraint contains non-finite constant (${r}) or right-hand side (${t}).`);let i=t-r;if(!Number.isFinite(i))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": effective right-hand side (${t} - ${r}) overflows finite floating-point range. Please rescale coefficients/constants.`);for(let[t,r]of e.terms){if(!Number.isFinite(r))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" has non-finite coefficient (${r}).`);if(Number.isNaN(t.lb)||Number.isNaN(t.ub)||t.lb===1/0||t.ub===-1/0||t.lb>t.ub)throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" has invalid bounds [${t.lb}, ${t.ub}].`)}return i}function nn(e,t,n){let r=tn(e,t,n),i=0;for(let[t,r]of e.terms){if(r===0)continue;let e;if(r>0){if(!Number.isFinite(t.ub))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" lacks a finite upper bound (required because coefficient ${r} is positive in <= constraint). Please set an explicit finite upper bound on the variable or specify { M } explicitly in indicator options.`);e=t.ub}else{if(!Number.isFinite(t.lb))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" lacks a finite lower bound (required because coefficient ${r} is negative in <= constraint). Please set an explicit finite lower bound on the variable or specify { M } explicitly in indicator options.`);e=t.lb}let a=r*e;if(i+=a,!Number.isFinite(a)||!Number.isFinite(i))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": numeric overflow while bounding contribution of variable "${t.name}". Please rescale coefficients/bounds or specify a finite { M } explicitly.`)}let a=i-r;if(!Number.isFinite(a))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": numeric overflow while computing Big-M (${i} - ${r}). Please rescale coefficients/bounds or specify a finite { M } explicitly.`);let o=Math.max(0,a);if(!Number.isFinite(o)||!Number.isFinite(r+o))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": derived Big-M (${o}) or shifted right-hand side overflows finite floating-point range. Please rescale coefficients/bounds or specify a finite { M } explicitly.`);return o}function rn(e,t,n){let r=tn(e,t,n),i=0;for(let[t,r]of e.terms){if(r===0)continue;let e;if(r>0){if(!Number.isFinite(t.lb))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" lacks a finite lower bound (required because coefficient ${r} is positive in >= constraint). Please set an explicit finite lower bound on the variable or specify { M } explicitly in indicator options.`);e=t.lb}else{if(!Number.isFinite(t.ub))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" lacks a finite upper bound (required because coefficient ${r} is negative in >= constraint). Please set an explicit finite upper bound on the variable or specify { M } explicitly in indicator options.`);e=t.ub}let a=r*e;if(i+=a,!Number.isFinite(a)||!Number.isFinite(i))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": numeric overflow while bounding contribution of variable "${t.name}". Please rescale coefficients/bounds or specify a finite { M } explicitly.`)}let a=r-i;if(!Number.isFinite(a))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": numeric overflow while computing Big-M (${r} - ${i}). Please rescale coefficients/bounds or specify a finite { M } explicitly.`);let o=Math.max(0,a);if(!Number.isFinite(o)||!Number.isFinite(r-o))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": derived Big-M (${o}) or shifted right-hand side overflows finite floating-point range. Please rescale coefficients/bounds or specify a finite { M } explicitly.`);return o}function an(e,t,n,r,i,a,o){if(!(e instanceof W&&(e.type===`Binary`||e.type===`Integer`&&e.lb===0&&e.ub===1)))throw Error(`Indicator variable "${e?.name??String(e)}" must be a Binary variable (or Integer variable with bounds [0, 1]), received "${e?.type??typeof e}" with bounds [${e?.lb}, ${e?.ub}].`);if(!Number.isFinite(e.lb)||!Number.isFinite(e.ub)||e.lb<0||e.ub>1||e.lb>e.ub)throw Error(`Binary indicator variable "${e.name}" has invalid bounds [${e.lb}, ${e.ub}]. Binary variables must stay within [0, 1] with lb <= ub.`);let s=tn(t,r,o);if(i!==0&&i!==1)throw Error(`Invalid activeValue: ${i}. Indicator activation value must be 0 or 1.`);if(n!==`<=`&&n!==`>=`)throw Error(`Invalid indicator sense for "${o}": expected "<=" or ">=", received "${String(n)}".`);if(!Number.isFinite(a)||a<0)throw Error(`Invalid Big-M value for indicator constraint "${o}": expected a finite non-negative number, received ${a}.`);let c=t.terms.get(e);if(c!==void 0&&c!==0)throw Error(`Indicator constraint "${o}" cannot include its own binary activation variable "${e.name}" in the linear expression.`);let l,u;if(i===1?n===`<=`?(l=a,u=s+a):(l=-a,u=s-a):n===`<=`?(l=-a,u=s):(l=a,u=s),!Number.isFinite(u))throw Error(`Cannot construct finite indicator constraint "${o}": shifted right-hand side overflows finite floating-point range. Please rescale coefficients/bounds or specify a smaller finite { M }.`);let d=new Map;for(let[e,n]of t.terms)n!==0&&d.set(e,n);return l!==0&&d.set(e,l),{lhs:new V(d,0),rhs:u}}function $(e,t=0){let n=new Map;for(let[t,r]of e){if(r===0)continue;let e=(n.get(t)??0)+r;e===0?n.delete(t):n.set(t,e)}return new V(n,t)}function on(e,t,n=1){if(n!==0){e.constant+=t.constant*n;for(let[r,i]of t.terms.entries())i!==0&&e.addTerm(r,i*n)}}var sn=5e3,cn=25e3;function ln(e,t,n,r,a){let o=[...e],s=[],u=new Map,d=new Map,f=new Set,p=[];for(let e of n)if(e.sense===`!=`||e.lhs.hasNonlinearTerms())p.push(e);else{let t=e;if(f.has(t.name)){let n=1;for(;f.has(`${e.name}_${n}`);)n++;t=new R(e.lhs,e.sense,e.rhs,`${e.name}_${n}`)}f.add(t.name),s.push(t),d.set(t,e.name)}let m=new Set(e.map(e=>e.name)),g=0;function _(e){let t;do t=`__washi_${e}_${++g}`;while(m.has(t));return m.add(t),t}function v(e,t){let n=e.name||`c`,r=n;if(f.has(r)){let t=1;for(;f.has(`${n}_${t}`);)t++;r=`${n}_${t}`,e=new R(e.lhs,e.sense,e.rhs,r)}f.add(r),s.push(e),d.set(e,t)}for(let e of t){let t=e.name;m.has(t)?t=_(`bool_${e.name}`):m.add(t);let n=new W({name:t,type:`Binary`,lb:0,ub:1});u.set(e,n),o.push(n)}function y(e,t){if(!Number.isFinite(e.constant))throw Error(`Cannot linearize piecewise expression in "${t}": non-finite constant (${e.constant}).`);let n=e.constant,r=e.constant,i=Number.isSafeInteger(e.constant);for(let[a,o]of e.terms.entries()){if(!Number.isFinite(o))throw Error(`Cannot linearize piecewise expression in "${t}": variable "${a.name}" has non-finite coefficient (${o}).`);if(o===0)continue;if(typeof a.lb!=`number`||typeof a.ub!=`number`||Number.isNaN(a.lb)||Number.isNaN(a.ub)||a.lb===-1/0||a.ub===1/0||a.lb>a.ub)throw Error(`Cannot linearize non-convex piecewise expression in "${t}": variable "${a.name}" has unbounded or invalid domain [${a.lb}, ${a.ub}]. Finite bounds are required.`);let e=a.lb,s=a.ub;if(a.type===`Binary`){let t=Math.max(0,Math.ceil(a.lb)),n=Math.min(1,Math.floor(a.ub));t<=n&&(e=t,s=n)}else if(a.type===`Integer`){let t=Math.ceil(a.lb),n=Math.floor(a.ub);t<=n&&(e=t,s=n)}let c=o*e,l=o*s;if(n+=Math.min(c,l),r+=Math.max(c,l),!Number.isFinite(n)||!Number.isFinite(r))throw Error(`Cannot linearize non-convex piecewise expression in "${t}": bound calculation overflowed.`);i&&=(a.type===`Integer`||a.type===`Binary`)&&Number.isSafeInteger(o)&&Number.isSafeInteger(e)&&Number.isSafeInteger(s)}return{lb:Object.is(n,-0)?0:n,ub:Object.is(r,-0)?0:r,isDiscrete:i}}function b(e,t){if(!e.hasNonlinearTerms())return e.clone();let n=new V(e.terms,e.constant);for(let r of e.nonlinearTerms)r.coeff!==0&&on(n,x(r.atom,t),r.coeff);return n}function x(e,t){switch(e.kind){case`abs`:{let n=b(e.arg,t),{lb:r,ub:i,isDiscrete:a}=y(n,t);if(r>=0)return n;if(i<=0)return n.mul(-1);let s=Math.max(-r,i),c=new W({name:_(`abs_t`),type:a?`Integer`:`Continuous`,lb:0,ub:s}),l=new W({name:_(`abs_z`),type:`Binary`,lb:0,ub:1});o.push(c,l);let u=$([[c,1]],0);return F(new R(n.sub(u),`<=`,0,`${t}_abs_pos`),t),F(new R(n.mul(-1).sub(u),`<=`,0,`${t}_abs_neg`),t),F(new R(u.sub(n).add($([[l,2*-r]],0)),`<=`,2*-r,`${t}_abs_hi_pos`),t),F(new R(u.add(n).sub($([[l,2*i]],0)),`<=`,0,`${t}_abs_hi_neg`),t),u}case`max`:{let n=e.args.map(e=>b(e,t));if(n.length===1)return n[0];let r=n.map(e=>y(e,t)),i=Math.max(...r.map(e=>e.lb)),a=Math.max(...r.map(e=>e.ub)),s=r.every(e=>e.isDiscrete),c=new W({name:_(`max_t`),type:s?`Integer`:`Continuous`,lb:i,ub:a});o.push(c);let l=$([[c,1]],0),u=[];for(let e=0;e<n.length;e++){let i=new W({name:_(`max_z_${e}`),type:`Binary`,lb:0,ub:1});o.push(i),u.push(i),F(new R(n[e].sub(l),`<=`,0,`${t}_max_lb_${e}`),t);let s=a-r[e].lb;F(new R(l.sub(n[e]).add($([[i,s]],0)),`<=`,s,`${t}_max_ub_${e}`),t)}return v(new R($(u.map(e=>[e,1]),0),`==`,1,`${t}_max_sos`),t),l}case`min`:{let n=e.args.map(e=>b(e,t));if(n.length===1)return n[0];let r=n.map(e=>y(e,t)),i=Math.min(...r.map(e=>e.lb)),a=Math.min(...r.map(e=>e.ub)),s=r.every(e=>e.isDiscrete),c=new W({name:_(`min_t`),type:s?`Integer`:`Continuous`,lb:i,ub:a});o.push(c);let l=$([[c,1]],0),u=[];for(let e=0;e<n.length;e++){let a=new W({name:_(`min_z_${e}`),type:`Binary`,lb:0,ub:1});o.push(a),u.push(a),F(new R(n[e].sub(l),`>=`,0,`${t}_min_ub_${e}`),t);let s=r[e].ub-i;F(new R(n[e].sub(l).add($([[a,s]],0)),`<=`,s,`${t}_min_lb_${e}`),t)}return v(new R($(u.map(e=>[e,1]),0),`==`,1,`${t}_min_sos`),t),l}case`at`:{let n=e.array.length,r=b(e.index,t),i=e.array.map(e=>b(e,t)),a=[];for(let e=0;e<n;e++){let t=new W({name:_(`at_lam_${e}`),type:`Binary`,lb:0,ub:1});o.push(t),a.push(t)}v(new R($(a.map(e=>[e,1]),0),`==`,1,`${t}_at_sos`),t);let s=r.clone();for(let e=1;e<n;e++)s.addTerm(a[e],-e);F(new R(s,`==`,0,`${t}_at_idx`),t);let c=new V(new Map,0);for(let e=0;e<n;e++){let n=i[e];if(n.terms.size===0)n.constant!==0&&c.addTerm(a[e],n.constant);else{let{lb:r,ub:i,isDiscrete:s}=y(n,t),l=new W({name:_(`at_w_${e}`),type:s?`Integer`:`Continuous`,lb:Math.min(0,r),ub:Math.max(0,i)});o.push(l);let u=$([[l,1]],0);F(new R($([[l,1],[a[e],-r]],0),`>=`,0,`${t}_at_mc1_${e}`),t),F(new R($([[l,1],[a[e],-i]],0),`<=`,0,`${t}_at_mc2_${e}`),t),F(new R(u.sub(n).add($([[a[e],-i]],0)),`>=`,-i,`${t}_at_mc3_${e}`),t),F(new R(u.sub(n).add($([[a[e],-r]],0)),`<=`,-r,`${t}_at_mc4_${e}`),t),c.addTerm(l,1)}}return c}}}function S(e,t,n){if(t===`upper`&&e.kind===`max`){let t=new W({name:_(`epi_max`),type:`Continuous`,lb:-1/0,ub:1/0});o.push(t);let r=$([[t,1]],0);for(let t=0;t<e.args.length;t++)T(e.args[t].sub(r),`<=`,0,`${n}_epi_max_${t}`,n);return r}if(t===`upper`&&e.kind===`abs`){let t=e.arg.hasNonlinearTerms()?b(e.arg,n):e.arg,r=new W({name:_(`epi_abs`),type:`Continuous`,lb:0,ub:1/0});o.push(r);let i=$([[r,1]],0);return F(new R(t.sub(i),`<=`,0,`${n}_epi_abs_pos`),n),F(new R(t.mul(-1).sub(i),`<=`,0,`${n}_epi_abs_neg`),n),i}if(t===`lower`&&e.kind===`min`){let t=new W({name:_(`epi_min`),type:`Continuous`,lb:-1/0,ub:1/0});o.push(t);let r=$([[t,1]],0);for(let t=0;t<e.args.length;t++)T(e.args[t].sub(r),`>=`,0,`${n}_epi_min_${t}`,n);return r}return x(e,n)}function C(e,t,n){if(!e.hasNonlinearTerms())return e;if(t===`==`||t===`!=`)return b(e,n);let r=new V(e.terms,e.constant);for(let i of e.nonlinearTerms){if(i.coeff===0)continue;let e=t===`<=`?i.coeff>0?`upper`:`lower`:i.coeff>0?`lower`:`upper`;on(r,S(i.atom,e,n),i.coeff)}return r}function T(e,t,n,r,i){let a=C(e,t,i);if(t===`!=`){se(new R(a,`==`,n,r),i);return}F(new R(a,t,n,r),i)}function E(e,t){return e.lhs.hasNonlinearTerms()?new R(b(e.lhs,t),e.sense,e.rhs,e.name):e}function D(e,t){if(e instanceof c){let n=u.get(e);if(!n)throw Error(`Unregistered BoolVar "${e.name}" in logical constraint "${t}".`);return n}let n=new W({name:_(`expr`),type:`Binary`,lb:0,ub:1});return o.push(n),O(n,e,t),n}function ee(e,t,n,r){v(new R($([[e,1],[t,-1],[n,-1]],0),`<=`,0,`${r}_xor_1`),r),v(new R($([[e,1],[t,-1],[n,1]],0),`>=`,0,`${r}_xor_2`),r),v(new R($([[e,1],[n,-1],[t,1]],0),`>=`,0,`${r}_xor_3`),r),v(new R($([[e,1],[t,1],[n,1]],0),`<=`,2,`${r}_xor_4`),r)}function O(e,t,n){if(t instanceof c){let r=u.get(t);v(new R($([[e,1],[r,-1]],0),`==`,0,`${n}_equiv`),n);return}if(t instanceof R){let r=E(t,n);I(e,r,0,`${n}_c_neg`,n),oe(e,r,1,`${n}_c_pos`,n);return}if(t instanceof h){ne(e,t,n);return}if(t instanceof l){if(t.op===`not`){let r=D(t.children[0],n);v(new R($([[e,1],[r,1]],0),`==`,1,`${n}_not`),n);return}if(t.op===`and`){let r=t.children.map(e=>D(e,n));for(let t=0;t<r.length;t++)v(new R($([[e,1],[r[t],-1]],0),`<=`,0,`${n}_and_ub_${t}`),n);v(new R($([[e,1],...r.map(e=>[e,-1])],0),`>=`,1-r.length,`${n}_and_lb`),n);return}if(t.op===`or`){let r=t.children.map(e=>D(e,n));for(let t=0;t<r.length;t++)v(new R($([[e,1],[r[t],-1]],0),`>=`,0,`${n}_or_lb_${t}`),n);v(new R($([[e,1],...r.map(e=>[e,-1])],0),`<=`,0,`${n}_or_ub`),n);return}if(t.op===`implies`){let r=D(t.children[0],n),i=D(t.children[1],n);v(new R($([[e,1],[r,1]],0),`>=`,1,`${n}_imp_1`),n),v(new R($([[e,1],[i,-1]],0),`>=`,0,`${n}_imp_2`),n),v(new R($([[e,1],[r,1],[i,-1]],0),`<=`,1,`${n}_imp_3`),n);return}if(t.op===`xor`){if(t.children.length===0){v(new R($([[e,1]],0),`==`,0,`${n}_xor_empty`),n);return}if(t.children.length===1){let r=D(t.children[0],n);v(new R($([[e,1],[r,-1]],0),`==`,0,`${n}_xor_single`),n);return}let r=t.children.map(e=>D(e,n)),i=r[0];for(let e=1;e<r.length-1;e++){let t=new W({name:_(`xor_fold_${e}`),type:`Binary`,lb:0,ub:1});o.push(t),ee(t,i,r[e],`${n}_xor_fold_${e}`),i=t}ee(e,i,r[r.length-1],n);return}}throw Error(`Unsupported logical element in equivalence linearization: ${t}`)}function k(e,t){let n=e.map(e=>b(e.start,t)),r=[];for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++)(e[t].duration>0||e[i].duration>0)&&r.push({i:t,j:i,sI:n[t],dI:e[t].duration,sJ:n[i],dJ:e[i].duration});return r}function A(e,t,n){let r=e.map(e=>({start:b(e.start,n),duration:e.duration,demand:e.demand})).filter(e=>e.duration>0&&e.demand>0);if(r.length===0)return{kind:`constant`,value:!0};let i=[];for(let e of r){let t=e.start.constant??0;if(!Number.isSafeInteger(t))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: task start offset (${t}) must be a safe integer.`);let r=t,a=t;for(let[t,i]of e.start.terms.entries()){if(i===0)continue;if(typeof t.lb!=`number`||typeof t.ub!=`number`||Number.isNaN(t.lb)||Number.isNaN(t.ub)||t.lb===-1/0||t.ub===1/0||t.lb>t.ub)throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: variable "${t.name}" has unbounded or invalid domain [${t.lb}, ${t.ub}]. Finite bounds are required.`);if(!Number.isSafeInteger(i))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: variable "${t.name}" coefficient (${i}) exceeds safe integer precision.`);let e=t.type===`Binary`?Math.max(0,Math.ceil(t.lb)):Math.ceil(t.lb),o=t.type===`Binary`?Math.min(1,Math.floor(t.ub)):Math.floor(t.ub);if(e>o)return{kind:`empty_domain`};if(!Number.isSafeInteger(e)||!Number.isSafeInteger(o))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: variable "${t.name}" integer bounds [${e}, ${o}] exceed JavaScript safe integer precision.`);let s=i*e,c=i*o;if(r+=Math.min(s,c),a+=Math.max(s,c),!Number.isSafeInteger(s)||!Number.isSafeInteger(c)||!Number.isSafeInteger(r)||!Number.isSafeInteger(a))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: task start time bounds exceed JavaScript safe integer precision.`)}let o=r+e.duration,s=a+e.duration;if(!Number.isSafeInteger(o)||!Number.isSafeInteger(s))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: task end time bounds [${r}, ${s}) exceed JavaScript safe integer precision.`);i.push({...e,est:Object.is(r,-0)?0:r,lst:Object.is(a,-0)?0:a})}return i.some(e=>e.demand>t)?{kind:`constant`,value:!1}:{kind:`tasks`,active:i}}function te(e,t,n){let r=e.spec;switch(r.kind){case`distinct`:{let e=r.args.map(e=>b(e,n));if(e.length<=1){t||P(n);return}if(t)for(let t=0;t<e.length;t++)for(let r=t+1;r<e.length;r++)T(e[t].sub(e[r]),`!=`,0,`${n}_neq_${t}_${r}`,n);else{let t=[];for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length;i++)t.push(new R(e[r].sub(e[i]),`==`,0,`${n}_eq_${r}_${i}`));M(new l(`or`,t),n)}return}case`disjoint`:{let e=k(r.tasks,n);if(e.length===0){t||P(n);return}if(t)for(let{i:t,j:r,sI:i,dI:a,sJ:s,dJ:c}of e){let e=new W({name:_(`disj_${t}_${r}`),type:`Binary`,lb:0,ub:1});o.push(e),ae(e,i.sub(s),`<=`,-a,1,`${n}_p_${t}_${r}`,n),ae(e,s.sub(i),`<=`,-c,0,`${n}_q_${t}_${r}`,n)}else M(new l(`or`,e.map(({i:e,j:t,sI:r,dI:i,sJ:a,dJ:o})=>new l(`and`,[new R(r.sub(a),`>=`,1-i,`${n}_ov1_${e}_${t}`),new R(a.sub(r),`>=`,1-o,`${n}_ov2_${e}_${t}`)]))),n);return}case`cumulative`:{let e=A(r.tasks,r.capacity,n);if(e.kind===`empty_domain`){P(n);return}if(e.kind===`constant`){e.value!==t&&P(n);return}let{active:i}=e;if(t){let e=1/0,t=-1/0,a=0;for(let n of i)n.est<e&&(e=n.est),n.lst+n.duration>t&&(t=n.lst+n.duration),a+=Math.max(0,n.lst-n.est+1);let s=t-e;if(!Number.isSafeInteger(s)||s>sn||a>cn)throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: time horizon [${e}, ${t}) (span ${s}, ${a} time-indexed variables) exceeds MIP limit. Tighten start bounds or use { solver: "pumpkin" }.`);let c=[];for(let e=0;e<i.length;e++){let t=i[e],r=new Map,a=[],s=t.start.clone();for(let n=t.est;n<=t.lst;n++){let t=new W({name:_(`cum_u_${e}_${n}`),type:`Binary`,lb:0,ub:1});o.push(t),r.set(n,t),a.push([t,1]),n!==0&&s.addTerm(t,-n)}if(a.length===0){P(n);return}v(new R($(a,0),`==`,1,`${n}_cum_sos_${e}`),n),F(new R(s,`==`,0,`${n}_cum_start_${e}`),n),c.push(r)}for(let a=e;a<t;a++){let e=[],t=0;for(let n=0;n<i.length;n++){let r=i[n],o=a<=r.est+r.duration-1?r.est:a-r.duration+1,s=Math.min(r.lst,a);if(o<=s){t+=r.demand;let i=c[n];for(let t=o;t<=s;t++){let n=i.get(t);n&&e.push([n,r.demand])}}}t>r.capacity&&e.length>0&&v(new R($(e,0),`<=`,r.capacity,`${n}_cum_t_${a}`),n)}return}let a=[];for(let e=0;e<i.length;e++){let t=i[e],s=[];for(let r=0;r<i.length;r++){if(r===e)continue;let a=i[r],c=new W({name:_(`cum_act_${r}_${e}`),type:`Binary`,lb:0,ub:1});o.push(c),O(c,new l(`and`,[new R(a.start.sub(t.start),`<=`,0,`${n}_act_le_${r}_${e}`),new R(t.start.sub(a.start),`<=`,a.duration-1,`${n}_act_ge_${r}_${e}`)]),n),s.push([c,a.demand])}let c=new R($(s,0),`>=`,r.capacity-t.demand+1,`${n}_overload_${e}`);a.push(new l(`and`,[c]))}M(new l(`or`,a),n);return}case`allowed`:{let e=r.vars.map(e=>b(e,n));if(r.tuples.length===0){t&&P(n);return}if(t){let t=[];for(let e=0;e<r.tuples.length;e++){let n=new W({name:_(`tbl_r_${e}`),type:`Binary`,lb:0,ub:1});o.push(n),t.push(n)}v(new R($(t.map(e=>[e,1]),0),`==`,1,`${n}_tbl_sos`),n);for(let i=0;i<e.length;i++){let a=e[i].clone();for(let e=0;e<r.tuples.length;e++){let n=r.tuples[e][i];n!==0&&a.addTerm(t[e],-n)}F(new R(a,`==`,0,`${n}_tbl_col_${i}`),n)}return}let i=e.map(e=>{let t=Array.from(e.terms.entries()).filter(([,e])=>e!==0);if(t.length!==1)return null;let[n,r]=t[0];if(Math.abs(r)!==1||!Number.isSafeInteger(n.lb)||!Number.isSafeInteger(n.ub)||n.ub-n.lb!==1)return null;let i=e.constant;if(!Number.isSafeInteger(i))return null;let a=r*n.lb+i,o=r*n.ub+i;return{expr:e,lo:Math.min(a,o),hi:Math.max(a,o)}});for(let t=0;t<r.tuples.length;t++){let a=r.tuples[t],o=!0,s=!1;for(let e=0;e<a.length;e++){let t=i[e];if(!t){o=!1;break}if(a[e]!==t.lo&&a[e]!==t.hi){s=!0;break}}if(!s){if(o){let e=new V(new Map,0);for(let t=0;t<a.length;t++){let n=i[t];a[t]===n.lo?on(e,n.expr.sub(n.lo),1):on(e,$([],n.hi).sub(n.expr),1)}F(new R(e,`>=`,1,`${n}_nogood_${t}`),n)}else M(new l(`or`,a.map((r,i)=>new R(e[i],`!=`,r,`${n}_ntbl_${t}_${i}`))),n,`${n}_ntbl_${t}`)}}return}}}function ne(e,t,n){let r=t.spec;switch(r.kind){case`distinct`:{let t=r.args.map(e=>b(e,n));if(t.length<=1){v(new R($([[e,1]],0),`==`,1,`${n}_distinct_triv`),n);return}let i=[];for(let e=0;e<t.length;e++)for(let r=e+1;r<t.length;r++)i.push(new R(t[e].sub(t[r]),`!=`,0,`${n}_d_${e}_${r}`));O(e,new l(`and`,i),n);return}case`disjoint`:{let t=k(r.tasks,n);if(t.length===0){v(new R($([[e,1]],0),`==`,1,`${n}_disjoint_triv`),n);return}O(e,new l(`and`,t.map(({i:e,j:t,sI:r,dI:i,sJ:a,dJ:o})=>new l(`or`,[new R(r.sub(a),`<=`,-i,`${n}_dj1_${e}_${t}`),new R(a.sub(r),`<=`,-o,`${n}_dj2_${e}_${t}`)]))),n);return}case`cumulative`:{let t=A(r.tasks,r.capacity,n);if(t.kind===`empty_domain`){P(n);return}if(t.kind===`constant`){v(new R($([[e,1]],0),`==`,+!!t.value,`${n}_cum_triv`),n);return}let{active:i}=t,a=[];for(let e=0;e<i.length;e++){let t=i[e],s=[];for(let r=0;r<i.length;r++){if(r===e)continue;let a=i[r],c=new W({name:_(`cum_eq_act_${r}_${e}`),type:`Binary`,lb:0,ub:1});o.push(c),O(c,new l(`and`,[new R(a.start.sub(t.start),`<=`,0,`${n}_eq_le_${r}_${e}`),new R(t.start.sub(a.start),`<=`,a.duration-1,`${n}_eq_ge_${r}_${e}`)]),n),s.push([c,a.demand])}a.push(new R($(s,0),`<=`,r.capacity-t.demand,`${n}_ev_${e}`))}O(e,new l(`and`,a),n);return}case`allowed`:{let t=r.vars.map(e=>b(e,n));if(r.tuples.length===0){v(new R($([[e,1]],0),`==`,0,`${n}_allowed_empty`),n);return}O(e,new l(`or`,r.tuples.map((e,r)=>new l(`and`,e.map((e,i)=>new R(t[i],`==`,e,`${n}_eq_tbl_${r}_${i}`))))),n);return}}}function re(e){return e instanceof R||e instanceof l&&e.children.some(e=>re(e))}function ie(e,t){if(e instanceof R){if((e.lhs.terms.get(t)??0)!==0)return!0;for(let n of e.lhs.nonlinearTerms){if(n.coeff===0)continue;let e=n.atom;if(e.kind===`abs`&&(e.arg.terms.get(t)??0)!==0||(e.kind===`max`||e.kind===`min`)&&e.args.some(e=>(e.terms.get(t)??0)!==0)||e.kind===`at`&&((e.index.terms.get(t)??0)!==0||e.array.some(e=>(e.terms.get(t)??0)!==0)))return!0}return!1}return e instanceof l&&e.children.some(e=>ie(e,t))}function j(e,t,n,r){if(t instanceof R){oe(e,E(t,n),1,r,n);return}if(t instanceof c||t instanceof h){v(new R($([[D(t,n),1],[e,-1]],0),`>=`,0,r),n);return}if(t instanceof l){if(t.op===`and`){for(let i=0;i<t.children.length;i++)j(e,t.children[i],n,`${r}_and_${i}`);return}if(t.op===`not`){let i=t.children[0];if(i instanceof R){I(e,E(i,n),1,r,n);return}if(i instanceof l){if(i.op===`not`){j(e,i.children[0],n,r);return}if(i.op===`or`){for(let t=0;t<i.children.length;t++)j(e,new l(`not`,[i.children[t]]),n,`${r}_not_or_${t}`);return}if(i.op===`and`){j(e,new l(`or`,i.children.map(e=>new l(`not`,[e]))),n,r);return}if(i.op===`implies`){j(e,i.children[0],n,`${r}_not_imp_0`),j(e,new l(`not`,[i.children[1]]),n,`${r}_not_imp_1`);return}}let a=D(i,n);v(new R($([[e,1],[a,1]],0),`<=`,1,r),n);return}if(t.op===`or`){if(t.children.length===0){v(new R($([[e,1]],0),`<=`,0,r),n);return}if(t.children.length===1){j(e,t.children[0],n,r);return}if(!t.children.some(e=>re(e))){let i=t.children.map(e=>D(e,n));v(new R($([[e,-1],...i.map(e=>[e,1])],0),`>=`,0,r),n);return}let i=[];for(let e=0;e<t.children.length;e++){let a=t.children[e];if(a instanceof c)i.push(D(a,n));else{let t=new W({name:_(`imp_or_${e}`),type:`Binary`,lb:0,ub:1});o.push(t),i.push(t),j(t,a,n,`${r}_or_${e}`)}}v(new R($([[e,-1],...i.map(e=>[e,1])],0),`>=`,0,r),n);return}if(t.op===`implies`){let[i,a]=t.children,s;if(i instanceof R){let e=E(i,n);s=new W({name:_(`ante`),type:`Binary`,lb:0,ub:1}),o.push(s),I(s,e,0,`${r}_ante_neg`,n)}else s=D(i,n);if(a instanceof c){v(new R($([[D(a,n),1],[e,-1],[s,-1]],0),`>=`,-1,r),n);return}let l=new W({name:_(`imp_joint`),type:`Binary`,lb:0,ub:1});o.push(l),v(new R($([[l,1],[e,-1],[s,-1]],0),`>=`,-1,`${r}_joint`),n),j(l,a,n,r);return}v(new R($([[D(t,n),1],[e,-1]],0),`>=`,0,r),n);return}throw Error(`Unsupported logical element in implication consequent "${n}": ${t}`)}function M(e,t,n=t){if(e instanceof R){T(e.lhs,e.sense,e.rhs,n,t);return}if(e instanceof h){te(e,!0,t);return}if(e instanceof c){v(new R($([[D(e,t),1]],0),`>=`,1,n),t);return}if(e instanceof l){if(e.op===`not`){let r=e.children[0];if(r instanceof c){v(new R($([[D(r,t),1]],0),`<=`,0,n),t);return}if(r instanceof h){te(r,!1,t);return}if(r instanceof R){se(E(r,t),t);return}if(r instanceof l){if(r.op===`not`){M(r.children[0],t,n);return}if(r.op===`or`){for(let e=0;e<r.children.length;e++)M(new l(`not`,[r.children[e]]),t,`${n}_not_or_${e}`);return}if(r.op===`and`){M(new l(`or`,r.children.map(e=>new l(`not`,[e]))),t,n);return}if(r.op===`implies`){M(r.children[0],t,`${n}_not_imp_0`),M(new l(`not`,[r.children[1]]),t,`${n}_not_imp_1`);return}}v(new R($([[D(r,t),1]],0),`<=`,0,n),t);return}if(e.op===`and`){for(let r=0;r<e.children.length;r++)M(e.children[r],t,`${n}_and_${r}`);return}if(e.op===`or`){if(e.children.length===0){P(t);return}if(e.children.length===1){M(e.children[0],t,n);return}if(!e.children.some(e=>re(e))){v(new R($(e.children.map(e=>D(e,t)).map(e=>[e,1]),0),`>=`,1,n),t);return}let r=[];for(let i=0;i<e.children.length;i++){let a=e.children[i];if(a instanceof c)r.push(D(a,t));else{let e=new W({name:_(`or_branch_${i}`),type:`Binary`,lb:0,ub:1});o.push(e),r.push(e),j(e,a,t,`${n}_or_${i}`)}}v(new R($(r.map(e=>[e,1]),0),`>=`,1,n),t);return}if(e.op===`xor`){if(e.children.length===0){P(t);return}if(e.children.length===1){M(e.children[0],t,n);return}let r=e.children.map(e=>D(e,t));if(r.length===2){v(new R($([[r[0],1],[r[1],1]],0),`==`,1,n),t);return}let i=r[0];for(let e=1;e<r.length-1;e++){let t=new W({name:_(`xor_fold_${e}`),type:`Binary`,lb:0,ub:1});o.push(t),ee(t,i,r[e],`${n}_xor_fold_${e}`),i=t}let a=r[r.length-1];v(new R($([[i,1],[a,1]],0),`==`,1,n),t);return}if(e.op===`implies`){let[r,i]=e.children,a=r instanceof R?un(r):null;if(a!==null){if(i instanceof R){let e=E(i,t);if((e.lhs.terms.get(a.binVar)??0)===0){oe(a.binVar,e,a.activeVal,n,t);return}}if(i instanceof c){let e=D(i,t);v(a.activeVal===1?new R($([[e,1],[a.binVar,-1]],0),`>=`,0,n):new R($([[e,1],[a.binVar,1]],0),`>=`,1,n),t);return}if(i instanceof l&&i.op===`not`){let e=i.children[0];if(e instanceof c){let r=D(e,t);v(a.activeVal===1?new R($([[r,1],[a.binVar,1]],0),`<=`,1,n):new R($([[r,1],[a.binVar,-1]],0),`<=`,0,n),t);return}if(e instanceof R){let r=E(e,t);if((r.lhs.terms.get(a.binVar)??0)===0){I(a.binVar,r,a.activeVal,n,t);return}}}if(a.activeVal===1&&!ie(i,a.binVar)){j(a.binVar,i,t,n);return}}let s;if(r instanceof R){let e=E(r,t);s=new W({name:_(`ante`),type:`Binary`,lb:0,ub:1}),o.push(s),I(s,e,0,`${n}_ante_neg`,t)}else s=D(r,t);j(s,i,t,n);return}}throw Error(`Unsupported top-level logical constraint "${t}": ${e}`)}function ae(e,t,n,r,i,a,o){let s=an(e,t,n,r,i,n===`<=`?nn(t,r,a):rn(t,r,a),a);s.lhs.terms.size>0&&v(new R(s.lhs,n,s.rhs,a),o)}function N(e){return new R(e.lhs,`==`,e.rhs,e.name)}function oe(e,t,n,r,i){let a=E(t,i);if(a.sense===`!=`){I(e,N(a),n,r,i);return}let{lhs:o,sense:s,rhs:c}=a;s===`==`?(ae(e,o,`<=`,c,n,`${r}_le`,i),ae(e,o,`>=`,c,n,`${r}_ge`,i)):ae(e,o,s,c,n,r,i)}function P(e){let t=new W({name:_(`unsat`),type:`Binary`,lb:0,ub:1});o.push(t),v(new R($([[t,1]],0),`>=`,2,e),e)}function F(e,t){let n=E(e,t),{lhs:r,sense:i,rhs:a}=n;if(i===`!=`){se(N(n),t);return}let o=r.constant??0,s=a-o;if(!Number.isFinite(o)||!Number.isFinite(a)||!Number.isFinite(s))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: constraint "${e.name}" contains non-finite constant or right-hand side.`);let c=[];for(let[n,i]of r.terms){if(!Number.isFinite(i))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: variable "${n.name}" in constraint "${e.name}" has non-finite coefficient (${i}).`);i!==0&&c.push([n,i])}if(c.length===0){(i===`<=`?0<=s:i===`>=`?0>=s:s===0)||P(t);return}v(new R($(c,0),i,s,e.name||t),t)}function se(e,t){let n=E(e,t);if(n.sense===`!=`){F(N(n),t);return}let r=dn(n,t);if(r.kind===`always_true`)return;if(r.kind===`always_false`){P(t);return}if(r.kind===`single`){v(new R(r.lhs,r.sense,r.rhs,n.name||t),t);return}let i=new W({name:_(`neq_dir`),type:`Binary`,lb:0,ub:1});o.push(i);let a=n.name||t;ae(i,r.lhs,`<=`,r.ltRhs,1,`${a}_lt`,t),ae(i,r.lhs,`>=`,r.gtRhs,0,`${a}_gt`,t)}function I(e,t,n,r,i){let a=E(t,i);if(a.sense===`!=`){oe(e,N(a),n,r,i);return}let s=dn(a,i);if(s.kind===`always_true`)return;if(s.kind===`always_false`){v(new R($([[e,1]],0),n===0?`>=`:`<=`,+(n===0),r),i);return}if(s.kind===`single`){ae(e,s.lhs,s.sense,s.rhs,n,r,i);return}let c=new W({name:_(`neq_lt`),type:`Binary`,lb:0,ub:1}),l=new W({name:_(`neq_gt`),type:`Binary`,lb:0,ub:1});o.push(c,l),ae(c,s.lhs,`<=`,s.ltRhs,1,`${r}_lt`,i),ae(l,s.lhs,`>=`,s.gtRhs,1,`${r}_gt`,i),v(new R($([[c,1],[l,1],[e,n===0?1:-1]],0),`>=`,+(n===0),`${r}_disj`),i)}for(let e of p)T(e.lhs,e.sense,e.rhs,e.name,e.name);let L;if(a&&a.expr.hasNonlinearTerms()){let e=i(a.sense)===`Minimize`,t=a.expr,n=new Map(t instanceof w?t.linearTerms:t.terms),r=t.constant;for(let i of t.nonlinearTerms){if(i.coeff===0)continue;let t=(e?i.coeff>0:i.coeff<0)?`upper`:`lower`,a=S(i.atom,t,`__objective`);r+=i.coeff*a.constant;for(let[e,t]of a.terms.entries()){let r=(n.get(e)??0)+i.coeff*t;r===0?n.delete(e):n.set(e,r)}}L=t instanceof w?new w(n,t.quadTerms,r,[]):new V(n,r,[])}else a&&(L=a.expr);for(let e of r){let t=e.name,n=e.expr;M(n,t)}return{variables:o,constraints:s,boolVarToBinary:u,constraintToOriginalName:d,...L===void 0?{}:{objective:L}}}function un(e){if(e.lhs.hasNonlinearTerms()||e.lhs.terms.size!==1||(e.lhs.constant??0)!==0)return null;let[[t,n]]=Array.from(e.lhs.terms.entries());return t.type!==`Binary`&&t.type!==`Integer`||t.lb!==0||t.ub!==1||n!==1?null:e.sense===`==`&&e.rhs===1||e.sense===`>=`&&e.rhs===1||e.sense===`!=`&&e.rhs===0?{binVar:t,activeVal:1}:e.sense===`==`&&e.rhs===0||e.sense===`<=`&&e.rhs===0||e.sense===`!=`&&e.rhs===1?{binVar:t,activeVal:0}:null}function dn(e,t){let{lhs:n,sense:r,rhs:i}=e;if(n.hasNonlinearTerms())throw Error(`Cannot negate unlowered nonlinear constraint "${e.name}" in "${t}".`);let a=n.constant??0,o=i-a;if(!Number.isFinite(a)||!Number.isFinite(i)||!Number.isFinite(o))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: constraint "${e.name}" contains non-finite constant or right-hand side.`);if(r!==`<=`&&r!==`>=`&&r!==`==`)throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: unsupported comparison sense "${String(r)}" in constraint "${e.name}".`);let s=[];for(let[r,i]of n.terms){if(!Number.isFinite(i))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: variable "${r.name}" in constraint "${e.name}" has non-finite coefficient (${i}).`);if(i!==0){if(r.type!==`Integer`&&r.type!==`Binary`)throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: negating constraint "${e.name}" involves Continuous variable "${r.name}", whose strict-inequality negation creates an open half-space not representable in MIP. Use { solver: "z3" }, rewrite explicitly with a closed tolerance such as or(expr\`... >= ... + eps\`, ...), or model the proposition with m.bool().`);if(!Number.isSafeInteger(i))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: negating constraint "${e.name}" requires safe integer coefficients, but variable "${r.name}" has coefficient ${i}. Scale to integer coefficients, use { solver: "z3" }, or rewrite explicitly with or(expr\`... >= ... + eps\`, ...) / m.bool().`);s.push([r,i])}}if(s.length===0)return(r===`<=`?0<=o:r===`>=`?0>=o:o===0)?{kind:`always_false`}:{kind:`always_true`};if(!Number.isInteger(o))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: negating constraint "${e.name}" requires an integer right-hand side and constant, received effective right-hand side ${o}. Scale or round the threshold to an integer, use { solver: "z3" }, or rewrite explicitly with or(expr\`... >= ... + eps\`, ...) / m.bool().`);if(Math.abs(o)>=2**53-1)throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: effective right-hand side (${o}) of constraint "${e.name}" exceeds safe integer precision for exact +/-1 negation. Please rescale coefficients/constants or solve with { solver: "z3" }.`);let c=$(s,0);if(r===`<=`)return{kind:`single`,lhs:c,sense:`>=`,rhs:o+1};if(r===`>=`)return{kind:`single`,lhs:c,sense:`<=`,rhs:o-1};let l=o-1,u=o+1,d=0,f=0,p=!0,m=!0;for(let[e,t]of s){if(!(e.lb<=e.ub)){p=!1,m=!1;break}let n=t>0?e.lb:e.ub,r=t>0?e.ub:e.lb,i=t*n,a=t*r;d+=i,f+=a,p&&=Number.isSafeInteger(n)&&Number.isSafeInteger(i)&&Number.isSafeInteger(d),m&&=Number.isSafeInteger(r)&&Number.isSafeInteger(a)&&Number.isSafeInteger(f)}let h=!(p&&d>l),g=!(m&&f<u);return!h&&!g?{kind:`always_false`}:g?h?{kind:`disjunction`,lhs:c,ltRhs:l,gtRhs:u}:{kind:`single`,lhs:c,sense:`>=`,rhs:u}:{kind:`single`,lhs:c,sense:`<=`,rhs:l}}async function fn(e){let t=e.master;if(!t)throw Error(`A master Model must be provided for solveColumnGeneration.`);let{pricing:n,maxIterations:r=100,reducedCostTolerance:i=1e-6,finalizeAsMIP:a=!0,solver:o,solverOptions:s,onIteration:c}=e,l=t.sense.toLowerCase()===`maximize`,u=n;if(!u)throw Error(`The 'pricing' callback must be provided in ColumnGenerationOptions.`);let d=[],f=null,p=0,m=t.status;for(let e=1;e<=r;e++){p=e;let n=await t.relax(o,s);if(m=n,n!==`Optimal`&&n!==`Feasible`||!t.solution)break;f=t.objectiveValue;let r=t.solution,a=r.duals||{},h=e=>typeof e==`string`?a[e]??0:e.dual??(e.name?a[e.name]??0:0),g=await u({iteration:e,duals:a,getDual:h,masterSolution:r,reducedCostTolerance:i,master:t}),_=[];g&&(Array.isArray(g)?_.push(...g):_.push(g));let v=[];for(let e of _){let t=e.reducedCost;if(typeof t!=`number`||!Number.isFinite(t)){let n=0,r=e.coefficients;if(Array.isArray(r))for(let e of r)Array.isArray(e)?n+=e[1]*h(e[0]):e&&typeof e==`object`&&(n+=e.coeff*h(e.constraint));else if(r instanceof Map)for(let[e,t]of r.entries())n+=t*h(e);else if(r&&typeof r==`object`)for(let[e,t]of Object.entries(r))n+=t*h(e);t=e.cost-n}(l?t>i:t<-i)&&v.push(e)}if(c&&c({iteration:e,relaxationObjective:f,columnsAdded:d.length+v.length,proposedColumns:v}),v.length===0)break;for(let e of v){let n=t.column({name:e.name,type:e.type||`Continuous`,lb:e.lb,ub:e.ub,cost:e.cost,coefficients:e.coefficients});d.push({variable:n,proposal:e})}}let h=f;a&&(m===`Optimal`||m===`Feasible`)&&(m=await t.solve(o,s),h=t.objectiveValue);let g={};for(let e of t.variables.values())e instanceof W&&e.value!==null&&(g[e.name]=e.value);let _={status:m,objectiveValue:h,relaxationObjectiveValue:f,iterations:p,columnsAdded:d.length,generatedColumns:d,master:t,values:g};return t.decomposition=_,_}function pn(e,t){let n=e;if(n instanceof R||typeof n==`object`&&n&&`sense`in n&&`lhs`in n&&`rhs`in n)throw Error(`Cannot use a Constraint as an objective in ${t}(). Use m.constraint(expr\`... <= ...\`) for constraints, or supply an unconstrained arithmetic expression to ${t}(), e.g. m.objective(${t}(expr\`30 * \${x}\`)).`);if(typeof n==`string`&&/(<=|>=|==|!=|=<|=>|<|>|=)/.test(n))throw Error(`Cannot use a comparison constraint as an objective in ${t}(). Use m.constraint(expr\`... <= ...\`) for constraints, or supply an unconstrained arithmetic expression to ${t}(), e.g. m.objective(${t}(expr\`30 * \${x}\`)).`);if(typeof n==`number`){if(!Number.isFinite(n))throw Error(`Invalid non-finite objective constant "${n}" passed to ${t}().`);return n}if(typeof n==`string`||n instanceof V||n instanceof w||n instanceof W||typeof n==`object`&&n&&(`terms`in n&&n.terms instanceof Map&&typeof n.constant==`number`||`quadTerms`in n&&n.quadTerms instanceof Map&&`linearTerms`in n&&n.linearTerms instanceof Map&&typeof n.constant==`number`||`id`in n&&`name`in n&&`lb`in n&&`ub`in n))return n;throw Error(`Invalid expression passed to ${t}(): expected a finite number, Var, LinExpr, QuadExpr, or arithmetic expression string.`)}function mn(e){return{expr:pn(e,`maximize`),sense:`Maximize`}}function hn(e){return{expr:pn(e,`minimize`),sense:`Minimize`}}var gn=new WeakSet;function _n(e){return!!(e&&typeof e==`object`&&`constraints`in e&&`variables`in e&&typeof e.solve==`function`)}async function vn(e,t,n,r,i,a,o,s,c=1){let l=[];for(let r=0;r<t.length;r++){let a=t[r],o=a.lhs,s=a.sense,u=a.rhs-(o.constant||0),d=[],f=[],p=0;for(let[e,t]of o.terms.entries()){let r=n.variables.get(e.name);if(e.ownerModel===n||r instanceof W){f.push([e,t]);let n=i[e.name]??0;p+=t*n}else d.push([e,t])}let m=u-p,h=new V;for(let[e,t]of d)h.addTerm(e,t);let g=new R(h,s,m,`__benders_link_${c}_${r}`);e.constraint(g),l.push({origConstraint:a,subConstr:g,masterTerms:f,baseRhs:u})}let u=await e.solve(o,{...s,relax:!0});if(u!==`Optimal`&&u!==`Feasible`)throw Error(`Benders subproblem failed at iteration ${c} with status "${u}". Auto-cut generation requires an Optimal or Feasible subproblem (expected Optimal or Feasible).`);let d=e.objectiveValue;if(typeof d!=`number`||!Number.isFinite(d))throw Error(`Benders subproblem returned invalid objectiveValue (${String(d)}) at iteration ${c}.`);if(gn.has(r)&&d<r.lb-1e-6)throw Error(`Benders auto-created "__benders_theta" (lb: ${r.lb}) cannot represent negative subproblem cost (${d}) at iteration ${c}. Define an explicit theta variable with a negative lower bound and pass options.theta.`);let f=i[r.name]??0,p=1e-4;if(!(a?f<d-p:f>d+p))return null;let m=0,h=new Map,g=new Set(l.map(e=>e.subConstr.name));for(let t of e.constraints.values()){if(!(t instanceof R)||g.has(t.name))continue;let n=e.solution?.duals[t.name]??t.dual??0;if(Math.abs(n)>1e-12){let e=t.rhs-(t.lhs.constant||0);m+=n*e}}for(let t of l){let n=e.solution?.duals[t.subConstr.name]??t.subConstr.dual??0;if(Math.abs(n)>1e-12){m+=n*t.baseRhs;for(let[e,r]of t.masterTerms){let t=h.get(e)??0;h.set(e,t+n*r)}}}let _=new V;_.addTerm(r,1);for(let[e,t]of h.entries())Math.abs(t)>1e-12&&_.addTerm(e,t);let v=new R(_,a?`>=`:`<=`,m,`__benders_opt_cut_${c}`),y=(n.objectiveValue??0)-f+d;return{kind:`optimality`,constraint:v,name:v.name,subproblemObjective:y}}async function yn(e){let t=e.master;if(!t)throw Error(`A master Model must be provided for solveBenders.`);let{subproblem:n,maxIterations:r=100,gapTolerance:i=1e-4,solver:a,solverOptions:o,onIteration:s}=e,c;if(e.theta!==void 0){if(typeof e.theta==`string`){let n=t.variables.get(e.theta);if(!(n instanceof W))throw Error(`Benders option "theta" references variable "${e.theta}", which was not found on the master model.`);c=n}else c=e.theta}if(!c){for(let e of t.variables.values())if(e instanceof W&&(e.name===`theta`||e.name===`__benders_theta`)){c=e;break}}let l=0,u=0,d=t.status,f,p,m,h={},g=null;for(let e=1;e<=r;e++){u=e;let r=await t.solve(a,o);if(d=r,r!==`Optimal`&&r!==`Feasible`)break;let _=t.objectiveValue,v=t.sense.toLowerCase()===`minimize`;v?f=_===null?f:_:p=_===null?p:_;let y={};for(let e of t.variables.values())e instanceof W&&e.value!==null&&(y[e.name]=e.value);let b=await n({iteration:e,masterValues:y,getMasterValue:e=>typeof e==`string`?y[e]??0:e.value??(e.name?y[e.name]??0:0),masterObjective:_,lowerBound:f,upperBound:p,master:t}),x=[];if(b){if(_n(b)){let n=b,r=n.linkingConstraints;if(!c){if(!v)throw Error(`Benders auto-cut generation requires an explicit options.theta variable for Maximize master models.`);c=t.continuous(`__benders_theta`,{lb:0}),t.objective(hn(t.objective().add(c))),gn.add(c)}let i=await vn(n,r,t,c,y,v,a,o,e);i&&x.push(i)}else Array.isArray(b)?x.push(...b):x.push(b)}for(let e of x)if(typeof e.subproblemObjective==`number`&&Number.isFinite(e.subproblemObjective)){if(v){let t=e.subproblemObjective;(p===void 0||t<p)&&(p=t,g=t,h={...y})}else{let t=e.subproblemObjective;(f===void 0||t>f)&&(f=t,g=t,h={...y})}}if(f!==void 0&&p!==void 0){let e=Math.abs(p)+1e-10;m=Math.abs(p-f)/e}if(s&&s({iteration:e,masterObjective:_,lowerBound:f,upperBound:p,cutsAdded:l+x.length,proposedCuts:x}),x.length===0){g=_,h={...y};break}if(m!==void 0&&m<=i)break;for(let e of x)t.constraint(e.constraint,e.name),l++}let _=d===`Optimal`||d===`Feasible`,v=Object.keys(h).length>0?h:_?(()=>{let e={};for(let n of t.variables.values())n instanceof W&&n.value!==null&&(e[n.name]=n.value);return e})():{},y=g===null?_?t.objectiveValue:null:g,b={status:d,objectiveValue:y,lowerBound:f,upperBound:p,gap:m,iterations:u,cutsAdded:l,master:t,values:v};return t.decomposition=b,b}function bn(e,t){return e.hasNonlinearTerms()?!0:xn(t)}function xn(e){for(let t of e)if(t.sense===`!=`||t.lhs.hasNonlinearTerms())return!0;return!1}function Sn(e){let t=Object.freeze({get size(){return e.size},get(t){return e.get(t)},has(t){return e.has(t)},forEach(n,r){e.forEach((e,i)=>{n.call(r,e,i,t)})},entries(){return e.entries()},keys(){return e.keys()},values(){return e.values()},[Symbol.iterator](){return e[Symbol.iterator]()}});return t}function Cn(e){return Array.isArray(e)||typeof e==`object`&&!!e&&!(e instanceof String)&&typeof e[Symbol.iterator]==`function`}function wn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof String)&&typeof e[Symbol.iterator]!=`function`}function Tn(e){return e instanceof W||typeof e==`object`&&!!e&&!(e instanceof s)&&!(e instanceof R)&&`id`in e&&`name`in e&&`lb`in e&&`ub`in e&&!(`terms`in e)&&!(`quadTerms`in e)&&!(`sense`in e)}function En(e,t){if(!Number.isInteger(e)||e<0)throw Error(`Invalid count (${e}) for ${t} variable creation: count must be a non-negative integer.`)}var Dn=class{name;_sense;_objectiveExpr;_variables=[];_constraints=[];_boolVars=[];_logicalConstraints=[];unsatCore=void 0;_conflicts=void 0;_values=new Map;varMapByName=new Map;varPrefixCounters=new Map;boolVarMapByName=new Map;boolVarPrefixCounters=new Map;constrMapByName=new Map;constrPrefixCounters=new Map;logicalConstrMapByName=new Map;logicalConstrCounter=0;allVarsMap=new Map;allConstrsMap=new Map;variables;constraints;values;status=`NotSolved`;terminationStatus=`NotSolved`;hasPrimalSolution=!1;objectiveValue=null;objectiveBound=void 0;relativeGap=void 0;absoluteGap=void 0;runTime=0;solution=null;solver=null;decomposition;_linkingConstraints;hasSolutionState=!1;modelRevision=0;activeOperationId=0;batchDepth=0;batchMutated=!1;batchUndoActions=[];constructor(e={},t){let n;n=typeof e==`string`?{...t,name:e}:e,this.name=n.name||`OptimizationModel`,this._sense=i(n.sense),this._objectiveExpr=new V,this.variables=Sn(this.allVarsMap),this.constraints=Sn(this.allConstrsMap),this.values=Sn(this._values),O(this,()=>this.recordModelMutation()),n.solver&&(this.solver=$e(n.solver))}get sense(){return this._sense}set sense(e){let t=i(e);this._sense!==t&&(this._sense=t,this.recordModelMutation())}get conflicts(){return this._conflicts??this.unsatCore}set conflicts(e){this._conflicts=e}clearSolutionFields(){if(this.hasSolutionState||this.status!==`NotSolved`||this.terminationStatus!==`NotSolved`||this.hasPrimalSolution||this.solution!==null||this.unsatCore!==void 0){this.hasSolutionState=!1,this.status=`NotSolved`,this.terminationStatus=`NotSolved`,this.hasPrimalSolution=!1,this.objectiveValue=null,this.objectiveBound=void 0,this.relativeGap=void 0,this.absoluteGap=void 0,this.solution=null,this.runTime=0,this.unsatCore=void 0,this._conflicts=void 0,this._values.clear();for(let e of this._variables)e.value=null,e.reducedCost=null;for(let e of this._boolVars)e.value=null;for(let e of this._constraints)e.dual=null,e.slack=null}}recordModelMutation(){if(this.batchDepth>0){this.batchMutated=!0;return}this.modelRevision++,this.clearSolutionFields()}runTransactionalBatch(e){if(this.batchDepth>0)return e();let t=this._variables.length,n=this._boolVars.length,r=this._constraints.length,i=this._logicalConstraints.length,a=new Map(this.varPrefixCounters),o=new Map(this.boolVarPrefixCounters),s=new Map(this.constrPrefixCounters),c=this.logicalConstrCounter;this.batchDepth=1,this.batchMutated=!1,this.batchUndoActions=[];try{let t=e();this.batchDepth=0;let n=this.batchMutated;return this.batchMutated=!1,this.batchUndoActions=[],n&&this.recordModelMutation(),t}catch(e){this.batchDepth=0,this.batchMutated=!1;for(let e=t;e<this._variables.length;e++){let t=this._variables[e];this.varMapByName.delete(t.name),this.allVarsMap.delete(t.name),t.ownerModel=null,re(t,this)}this._variables.length=t;for(let e=n;e<this._boolVars.length;e++){let t=this._boolVars[e];this.boolVarMapByName.delete(t.name),this.allVarsMap.delete(t.name)}this._boolVars.length=n;for(let e=r;e<this._constraints.length;e++){let t=this._constraints[e];this.constrMapByName.delete(t.name),this.allConstrsMap.delete(t.name)}this._constraints.length=r;for(let e=i;e<this._logicalConstraints.length;e++){let t=this._logicalConstraints[e];this.logicalConstrMapByName.delete(t.name),this.allConstrsMap.delete(t.name)}this._logicalConstraints.length=i;for(let e=this.batchUndoActions.length-1;e>=0;e--)this.batchUndoActions[e]();throw this.batchUndoActions=[],this.varPrefixCounters=a,this.boolVarPrefixCounters=o,this.constrPrefixCounters=s,this.logicalConstrCounter=c,e}}createDomainVars(e,t,n,r){let i=e.toLowerCase(),a=typeof t==`number`,o=typeof n==`number`,s=Cn(t),c=Cn(n);if(o||c){if(a&&En(t,i),o&&En(n,i),!a&&!s||r!==void 0&&!wn(r))throw Error(`Invalid arguments provided for ${i} variable creation`);let c=a?Array.from({length:t},(e,t)=>t):Array.from(t),l=o?Array.from({length:n},(e,t)=>t):n===t?c:Array.from(n),u=r||{},d=u.prefix||u.name||`x`;return this.runTransactionalBatch(()=>{let t=a?[]:{};for(let n of c){let r=o?[]:{};for(let t of l)r[t]=this.addVar({...u,type:e,name:`${d}_${n}_${t}`});t[n]=r}return t})}if(typeof t==`string`||t===void 0){if(n!==void 0&&!wn(n))throw Error(`Invalid arguments provided for ${i} variable creation`);let r=n||{},a=typeof t==`string`?t:r.name;return this.addVar({...r,type:e,name:a})}if(wn(t)){if(n!==void 0)throw Error(`Invalid arguments provided for ${i} variable creation`);let r=t;return this.addVar({...r,type:e})}if(n!==void 0&&!wn(n))throw Error(`Invalid arguments provided for ${i} variable creation`);let l=n||{},u=l.prefix||l.name;if(typeof t==`number`)return En(t,i),this.runTransactionalBatch(()=>{let n=[],r=u||`x`;for(let i=0;i<t;i++)n.push(this.addVar({...l,type:e,name:void 0,prefix:r}));return n});if(Cn(t))return this.runTransactionalBatch(()=>{let n={};for(let r of t){let t=u?`${u}_${r}`:`${r}`;n[r]=this.addVar({...l,type:e,name:t})}return n});throw Error(`Invalid arguments provided for ${i} variable creation`)}binary(e,t,n){return this.createDomainVars(`Binary`,e,t,n)}integer(e,t,n){return this.createDomainVars(`Integer`,e,t,n)}continuous(e,t,n){return this.createDomainVars(`Continuous`,e,t,n)}column(e){let t=e.type||`Continuous`,n=this.addVar({name:e.name,type:t,lb:e.lb,ub:e.ub});if(typeof e.cost==`number`&&e.cost!==0&&(this._objectiveExpr=this._objectiveExpr.add(n.mul(e.cost)),this.recordModelMutation()),e.coefficients){if(Array.isArray(e.coefficients)){for(let t of e.coefficients)if(Array.isArray(t)){let[e,r]=t,i=typeof e==`string`?this.constrMapByName.get(e):e;if(!i)throw Error(`Constraint '${String(e)}' not found in model when adding column`);i.addTerm(n,r)}else if(typeof t==`object`&&t){let e=typeof t.constraint==`string`?this.constrMapByName.get(t.constraint):t.constraint;if(!e)throw Error(`Constraint '${String(t.constraint)}' not found in model when adding column`);e.addTerm(n,t.coeff)}}else if(e.coefficients instanceof Map)for(let[t,r]of e.coefficients.entries()){let e=typeof t==`string`?this.constrMapByName.get(t):t;if(!e)throw Error(`Constraint '${String(t)}' not found in model when adding column`);e.addTerm(n,r)}else if(typeof e.coefficients==`object`)for(let[t,r]of Object.entries(e.coefficients)){let e=this.constrMapByName.get(t);if(!e)throw Error(`Constraint '${t}' not found in model when adding column`);e.addTerm(n,r)}}return n}bool(e,t,n){let r=typeof e==`number`,i=typeof t==`number`,a=Cn(e),o=Cn(t);if(i||o){if(r&&En(e,`boolean`),i&&En(t,`boolean`),!r&&!a||n!==void 0&&!wn(n))throw Error(`Invalid arguments provided for boolean variable creation`);let o=r?Array.from({length:e},(e,t)=>t):Array.from(e),s=i?Array.from({length:t},(e,t)=>t):t===e?o:Array.from(t),c=n||{},l=c.prefix||c.name||`p`;return this.runTransactionalBatch(()=>{let e=r?[]:{};for(let t of o){let n=i?[]:{};for(let e of s)n[e]=this.createBoolVar(`${l}_${t}_${e}`);e[t]=n}return e})}if(typeof e==`string`||e===void 0){if(t!==void 0&&!wn(t))throw Error(`Invalid arguments provided for boolean variable creation`);let n=t||{},r=typeof e==`string`?e:n.name;return this.createBoolVar(r,n.prefix)}if(wn(e)){if(t!==void 0)throw Error(`Invalid arguments provided for boolean variable creation`);let n=e;return this.createBoolVar(n.name,n.prefix)}if(t!==void 0&&!wn(t))throw Error(`Invalid arguments provided for boolean variable creation`);let s=t||{},c=s.prefix||s.name;if(typeof e==`number`)return En(e,`boolean`),this.runTransactionalBatch(()=>{let t=[],n=c||`p`;for(let r=0;r<e;r++)t.push(this.createBoolVar(void 0,n));return t});if(Cn(e))return this.runTransactionalBatch(()=>{let t={};for(let n of e){let e=c?`${c}_${n}`:`${n}`;t[n]=this.createBoolVar(e)}return t});throw Error(`Invalid arguments provided for boolean variable creation`)}hasVarName(e){return this.varMapByName.has(e)||this.boolVarMapByName.has(e)}getNextVarName(e){let t=this.varPrefixCounters.get(e)??0,n=`${e}_${t}`;for(;this.hasVarName(n);)t++,n=`${e}_${t}`;return this.varPrefixCounters.set(e,t+1),n}getNextBoolVarName(e){let t=this.boolVarPrefixCounters.get(e)??0,n=`${e}_${t}`;for(;this.hasVarName(n)||this.hasConstraintName(n);)t++,n=`${e}_${t}`;return this.boolVarPrefixCounters.set(e,t+1),n}hasConstraintName(e){return this.constrMapByName.has(e)||this.logicalConstrMapByName.has(e)}hasBoolVarName(e){return this.boolVarMapByName.has(e)}getNextConstrName(e=`c`){let t=this.constrPrefixCounters.get(e)??1,n=`${e}_${t}`;for(;this.hasConstraintName(n)||this.hasBoolVarName(n);)t++,n=`${e}_${t}`;return this.constrPrefixCounters.set(e,t+1),n}getNextLogicalConstrName(){let e=this.logicalConstrCounter+1,t=`lc_${e}`;for(;this.hasConstraintName(t)||this.hasBoolVarName(t);)e++,t=`lc_${e}`;return this.logicalConstrCounter=e,t}createBoolVar(e,t){let n=typeof e==`string`?e.trim():void 0,r=typeof t==`string`?t.trim():``,i=r.length>0?r:`p`,a=n&&n.length>0?n:this.getNextBoolVarName(i);if(this.hasVarName(a))throw Error(`Variable with name '${a}' already exists in model`);if(this.hasConstraintName(a))throw Error(`Boolean variable name '${a}' conflicts with an existing constraint in model`);let o=new c(a);return this._boolVars.push(o),this.boolVarMapByName.set(o.name,o),this.allVarsMap.set(o.name,o),this.recordModelMutation(),o}addVar(e){let t=e||{},n=typeof t.name==`string`?t.name.trim():void 0,r=n&&n.length>0?n:void 0,i=typeof t.prefix==`string`?t.prefix.trim():``,a=i.length>0?i:`x`,o=this.varPrefixCounters.get(a),s=r??this.getNextVarName(a);try{if(this.hasVarName(s))throw Error(`Variable with name '${s}' already exists in model`);let e=new W({...t,name:s,prefix:a});return e.hasExplicitName=r!==void 0,M(e),te(e,this),e.ownerModel=this,this._variables.push(e),this.varMapByName.set(e.name,e),this.allVarsMap.set(e.name,e),this.recordModelMutation(),e}catch(e){throw r===void 0&&(o===void 0?this.varPrefixCounters.delete(a):this.varPrefixCounters.set(a,o)),e}}objective(e){if(arguments.length===0)return this._objectiveExpr.clone();let t=e;if(t instanceof R||typeof t==`object`&&t&&`sense`in t&&`lhs`in t&&`rhs`in t||typeof t==`string`&&/(<=|>=|==|!=|=<|=>|<|>|=)/.test(t))throw Error("Cannot use a Constraint as an objective. Did you mean to use m.constraint(expr`... <= ...`)? To set an objective, wrap an unconstrained expression with maximize(...) or minimize(...), e.g. m.objective(maximize(expr`30 * ${x}`)).");if(typeof t!=`object`||!t||!(`expr`in t)||!(`sense`in t))throw Error("m.objective(...) expects an ObjectiveSpec created with maximize(...) or minimize(...), e.g. m.objective(maximize(expr`30 * ${x}`)).");return this.applyObjective(t.expr,t.sense),this}applyObjective(e,t){if(e instanceof R||typeof e==`object`&&e&&`sense`in e&&`lhs`in e&&`rhs`in e||typeof e==`string`&&/(<=|>=|==|!=|=<|=>|<|>|=)/.test(e))throw Error(typeof e==`string`?"Cannot use a comparison constraint as an objective. Did you mean to use m.constraint(expr`... <= ...`)? To set an objective, wrap an unconstrained expression with maximize(...) or minimize(...), e.g. m.objective(maximize(expr`30 * ${x}`)).":"Cannot use a Constraint as an objective. Did you mean to use m.constraint(expr`... <= ...`)? To set an objective, wrap an unconstrained expression with maximize(...) or minimize(...), e.g. m.objective(maximize(expr`30 * ${x}`)).");let n=t===void 0?this.sense:i(t),r;if(typeof e==`string`)r=Ie(e,e=>this.varMapByName.get(e));else if(typeof e==`number`)r=new V(new Map,e);else if(e instanceof w)r=e.clone();else if(e instanceof V)r=e.clone();else if(typeof e==`object`&&e&&`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map&&typeof e.constant==`number`){let t=e;r=new w(t.linearTerms,t.quadTerms,t.constant,t.nonlinearTerms)}else if(typeof e==`object`&&e&&`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`){let t=e;r=new V(t.terms,t.constant,t.nonlinearTerms)}else if(e instanceof W||typeof e==`object`&&e&&`id`in e&&`name`in e&&`lb`in e&&`ub`in e)r=new V(new Map([[e,1]]),0);else throw Error(`Invalid objective expression: expected a finite number, Var, LinExpr, QuadExpr, or arithmetic expression string.`);F(r,this.name,e=>this.varMapByName.get(e.name)===e),this._sense=n,this._objectiveExpr=r,this.recordModelMutation()}constraint(e,t){if(Array.isArray(e))return this.runTransactionalBatch(()=>{let t=[];for(let n of e)t.push(this.constraint(n));return t});if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e)throw Error(`Constraint must contain a comparison operator (<=, >=, ==): cannot add a quadratic expression as a constraint.`);if(e instanceof V||typeof e==`object`&&e&&`terms`in e)throw Error("Constraint must contain a comparison operator (<=, >=, ==): cannot add a linear expression without a comparison operator. Use expr`... <= ...` or .le(), .ge(), .eq().");if(Tn(e))throw Error(`Cannot add numeric variable "${e.name}" directly as a constraint without a comparison operator (<=, >=, ==). Numeric variables require a comparison such as expr\`\${x} <= 10\` or x.le(10), whereas propositional BoolVar variables must be created with m.bool().`);return this.addConstraint(e,t)}addConstraint(e,t){if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e)throw Error(`Constraint must contain a comparison operator (<=, >=, ==): cannot add a quadratic expression as a constraint.`);if(e instanceof V||typeof e==`object`&&e&&`terms`in e)throw Error("Constraint must contain a comparison operator (<=, >=, ==): cannot add a linear expression without a comparison operator. Use expr`... <= ...` or .le(), .ge(), .eq().");if(Tn(e))throw Error(`Cannot add numeric variable "${e.name}" directly as a constraint without a comparison operator (<=, >=, ==). Numeric variables require a comparison such as expr\`\${x} <= 10\` or x.le(10), whereas propositional BoolVar variables must be created with m.bool().`);if(e instanceof s){let n=typeof t==`string`&&t.trim().length>0?t.trim():void 0;if(n!==void 0){if(this.hasConstraintName(n))throw Error(`Constraint with name '${n}' already exists in model`);if(this.hasBoolVarName(n))throw Error(`Constraint name '${n}' conflicts with an existing Boolean variable in model`)}let r=this.logicalConstrCounter,i=n??this.getNextLogicalConstrName();try{I(e,i,this.name,e=>this.varMapByName.get(e.name)===e,e=>this.boolVarMapByName.get(e.name)===e,this)}catch(e){throw n===void 0&&(this.logicalConstrCounter=r),e}A(e,this,this.batchDepth>0?this.batchUndoActions:void 0);let a=Object.freeze({kind:`logical`,name:i,expr:e,dual:null,slack:null});return this._logicalConstraints.push(a),this.logicalConstrMapByName.set(i,a),this.allConstrsMap.set(i,a),this.recordModelMutation(),e}let n=typeof e==`string`?Re(e,e=>this.varMapByName.get(e),t):e;if(typeof n!=`object`||!n||!(`sense`in n)||!(`lhs`in n)||!(`rhs`in n))throw Error("Invalid constraint passed to m.constraint(...): expected a linear Constraint (e.g. expr`${x} <= 10` or x.le(10)), a propositional BoolVar/BoolExpr (created with m.bool()), or an array of constraints.");n.ownerModel&&n.ownerModel!==this&&(se(n,this.name,e=>this.varMapByName.get(e.name)===e,n.name),ne(n,this));let r=typeof t==`string`&&t.trim().length>0?t.trim():n.hasExplicitName?n.name.trim():void 0;if(r!==void 0){if(this.hasConstraintName(r))throw Error(`Constraint with name '${r}' already exists in model`);if(this.hasBoolVarName(r))throw Error(`Constraint name '${r}' conflicts with an existing Boolean variable in model`)}let i=this.constrPrefixCounters.get(`c`),a=r??this.getNextConstrName(`c`),o;try{se(n,this.name,e=>this.varMapByName.get(e.name)===e,a),o=ne(n,this)}catch(e){throw r===void 0&&(i===void 0?this.constrPrefixCounters.delete(`c`):this.constrPrefixCounters.set(`c`,i)),e}let c=n.name,l=n.hasExplicitName,u=n.ownerModel,d=o;return this.batchUndoActions.push(()=>{n.ownerModel=u,n._assignModelName(c,l),ie(n,this,d)}),this.batchDepth===0&&(this.batchUndoActions=[]),n._assignModelName(a,!0),n.ownerModel=this,this._constraints.push(n),this.constrMapByName.set(n.name,n),this.allConstrsMap.set(n.name,n),this.recordModelMutation(),n}indicator(e,t,n={}){if(e instanceof s)throw Error("Invalid binary variable passed to indicator(): received a propositional BoolVar/BoolExpr, but m.indicator() requires a 0-1 numeric binary Var created with m.binary(). For general boolean logic with m.bool(), use m.constraint(implies(flag, expr`${x} <= 10`)) with the Z3 solver.");if(!(e instanceof W))throw Error(`Invalid binary variable passed to indicator(). Expected a 0-1 binary Var instance created with m.binary() (or use implies(flag, ...) with m.bool() and the Z3 solver for general boolean logic).`);if(!(e.type===`Binary`||e.type===`Integer`&&e.lb===0&&e.ub===1))throw Error(`Invalid variable "${e.name}" passed to indicator(): variable has type "${e.type}" with bounds [${e.lb}, ${e.ub}]. Indicator activation variable must be a Binary variable created with m.binary() (or Integer variable with bounds [0, 1]).`);if(t instanceof w||typeof t==`object`&&t&&`quadTerms`in t)throw Error("Quadratic expressions or constraints are not supported in indicator constraints (only linear Constraints with <=, >=, or == such as expr`${x} <= 10` are allowed).");if(typeof t!=`object`||!t||!(`sense`in t)||!(`lhs`in t)||!(`rhs`in t))throw Error("Invalid constraint expression passed to indicator(). Expression must include a comparison operator (<=, >=, ==), e.g. m.indicator(b, expr`${x} <= 10`). For general boolean logic (such as BoolVar or implies/and/or/not), use m.constraint(implies(flag, ...)) with the Z3 solver.");let r=t;if(r.sense===`!=`)throw Error(`Constraint "${r.name}" uses discrete "!=", which is not supported in m.indicator(). Use m.constraint(implies(${e.name}.eq(1), ...)) instead.`);if(r.lhs.hasNonlinearTerms())throw Error(`Constraint "${r.name}" contains nonlinear terms (max/min/abs/at), which are not supported in m.indicator().`);let i=n.activeValue===void 0?1:n.activeValue;if(i!==0&&i!==1)throw Error(`Invalid activeValue: ${i}. Indicator activeValue must be 0 or 1.`);if(this.varMapByName.get(e.name)!==e)throw Error(`Variable "${e.name}" passed to indicator() does not belong to model "${this.name}". All variables must belong to the model by object identity.`);let a=typeof n.name==`string`&&n.name.trim().length>0?n.name.trim():void 0,o=this.constrPrefixCounters.get(`c`),{lhs:c,sense:l,rhs:u}=r,d,f,p;if(a!==void 0)d=a,f=l===`==`?`${d}_le`:d,p=l===`==`?`${d}_ge`:d;else if(r.hasExplicitName)d=`ind_${e.name}_${r.name.trim()}`,f=l===`==`?`${d}_le`:d,p=l===`==`?`${d}_ge`:d;else do{let t=this.getNextConstrName(`c`);d=`ind_${e.name}_${t}`,f=l===`==`?`${d}_le`:d,p=l===`==`?`${d}_ge`:d}while((l===`<=`||l===`==`)&&(this.hasConstraintName(f)||this.hasBoolVarName(f))||(l===`>=`||l===`==`)&&(this.hasConstraintName(p)||this.hasBoolVarName(p)));let m=[];try{if((l===`<=`||l===`==`)&&(this.hasConstraintName(f)||this.hasBoolVarName(f)))throw Error(this.hasBoolVarName(f)?`Constraint name '${f}' conflicts with an existing Boolean variable in model`:`Constraint with name '${f}' already exists in model`);if((l===`>=`||l===`==`)&&(this.hasConstraintName(p)||this.hasBoolVarName(p)))throw Error(this.hasBoolVarName(p)?`Constraint name '${p}' conflicts with an existing Boolean variable in model`:`Constraint with name '${p}' already exists in model`);n.M!==void 0&&en(n.M,d);let t=e=>this.varMapByName.get(e.name)===e;for(let[e]of c.terms)if(!t(e))throw Error(`Variable "${e.name}" in constraint "${d}" does not belong to model "${this.name}". All variables must belong to the model by object identity.`);if(l===`<=`||l===`==`){let t=n.M===void 0?nn(c,u,f):n.M,r=an(e,c,`<=`,u,i,t,f),a=new R(r.lhs,`<=`,r.rhs,f);n.M===void 0&&a._setIndicatorOrigin({binVar:e,activeValue:i,targetLhs:c.clone(),targetSense:`<=`,targetRhs:u,derivedM:t}),m.push([a,f])}if(l===`>=`||l===`==`){let t=n.M===void 0?rn(c,u,p):n.M,r=an(e,c,`>=`,u,i,t,p),a=new R(r.lhs,`>=`,r.rhs,p);n.M===void 0&&a._setIndicatorOrigin({binVar:e,activeValue:i,targetLhs:c.clone(),targetSense:`>=`,targetRhs:u,derivedM:t}),m.push([a,p])}for(let[e,n]of m)se(e,this.name,t,n)}catch(e){throw o===void 0?this.constrPrefixCounters.delete(`c`):this.constrPrefixCounters.set(`c`,o),e}return this.runTransactionalBatch(()=>m.map(([e,t])=>this.addConstraint(e,t)))}toLpString(){if(this.validateIntegrityInternal(),bn(this._objectiveExpr,this._constraints)){let e=ln(this._variables,[],this._constraints,[],{expr:this._objectiveExpr,sense:this.sense}),{lpString:t}=Ke({name:this.name,sense:this.sense,objective:e.objective??this._objectiveExpr,constraints:e.constraints,variables:e.variables});return t}let{lpString:e}=Ke({name:this.name,sense:this.sense,objective:this._objectiveExpr.clone(),constraints:this._constraints,variables:this._variables});return e}validateIntegrityInternal(){L({model:this,name:this.name,variables:this._variables,boolVars:this._boolVars,constraints:this._constraints,logicalConstraints:this._logicalConstraints,objectiveExpr:this._objectiveExpr,getVarByName:e=>this.varMapByName.get(e),getBoolVarByName:e=>this.boolVarMapByName.get(e),getConstraintByName:e=>this.constrMapByName.get(e),getLogicalConstraintByName:e=>this.logicalConstrMapByName.get(e)})}ensureExecutionValid(e,t,n){if(this.modelRevision!==e)throw this.activeOperationId===t&&this.clearSolutionFields(),Error(`Model "${this.name}" was modified while ${n}() was in progress; stale solver result was discarded.`);if(this.activeOperationId!==t)throw Error(`Stale ${n}() result discarded because a newer solve or check operation was started on model "${this.name}".`)}wrapSolveOptions(e,t,n){let r=e.onProgress;return r?{...e,onProgress:e=>{this.activeOperationId===n&&this.modelRevision===t&&r(e)}}:e}hasPrimalFromResult(e){if(typeof e.hasPrimalSolution==`boolean`)return e.hasPrimalSolution;let t=e.status,n=e.terminationStatus??t,r=e.values||{},i=e.boolValues||{};return t!==`Infeasible`&&t!==`Unsat`&&t!==`Unbounded`&&t!==`Error`&&t!==`NotSolved`&&n!==`Infeasible`&&n!==`Unsat`&&n!==`Unbounded`&&n!==`InfeasibleOrUnbounded`&&n!==`Error`&&n!==`NotSolved`&&(t===`Optimal`||t===`Feasible`||t===`Sat`||n===`Optimal`||n===`Feasible`||n===`Sat`||typeof e.objectiveValue==`number`&&Number.isFinite(e.objectiveValue)||Object.values(r).some(e=>typeof e==`number`&&Number.isFinite(e)||typeof e==`boolean`)||Object.values(i).some(e=>typeof e==`boolean`))}normalizePrimalValue(e,t,n,r){return(r.relax??n.options?.relax)!==!0&&(e.type===`Integer`||e.type===`Binary`)&&Math.abs(t-Math.round(t))<=1e-5?Math.round(t)+0:t}resolveSolverAndOptions(e,t){if(e&&typeof e==`object`&&`solve`in e&&typeof e.solve==`function`){let{solver:n,...r}=t||{};return{activeSolver:e,activeOptions:r}}if(typeof e==`function`){let{solver:n,...r}=t||{};return{activeSolver:new e(r),activeOptions:r}}if(typeof e==`string`){let{solver:n,...r}=t||{};return{activeSolver:$e(e,r),activeOptions:r}}let{solver:n,...r}=e||{};return n?{activeSolver:$e(n,r),activeOptions:r}:{activeSolver:this.solver||$e(),activeOptions:r}}async relax(e,t){let n=typeof e==`object`&&!!e&&!(`solve`in e),r=n?{...e,relax:!0}:{...t||{},relax:!0},i=n?void 0:e;return i?this.solve(i,r):this.solve(r)}async solve(e,t){let n=++this.activeOperationId,r=this.modelRevision;this.clearSolutionFields(),this.validateIntegrityInternal();let{activeSolver:i,activeOptions:a}=this.resolveSolverAndOptions(e,t);if(this._objectiveExpr instanceof w&&this._objectiveExpr.quadTerms.size>0&&i.capabilities?.supportsQP===!1)throw Error(`Solver "${i.name}" does not support quadratic objectives (QP). Please use a QP-capable solver such as HiGHS or Clarabel.`);let o,s=null;if(i.capabilities?.supportsLogicalConstraints!==!0&&i.capabilities?.supportsSMT!==!0&&(this._logicalConstraints.length>0||this._boolVars.length>0||bn(this._objectiveExpr,this._constraints))?(s=ln(this._variables,this._boolVars,this._constraints,this._logicalConstraints,{expr:this._objectiveExpr,sense:this.sense}),o={name:this.name,sense:this.sense,objective:s.objective??this._objectiveExpr,constraints:s.constraints,variables:s.variables,logicalConstraints:[],boolVars:[]}):o={name:this.name,sense:this.sense,objective:this._objectiveExpr,constraints:this._constraints,variables:this._variables,logicalConstraints:this._logicalConstraints,boolVars:this._boolVars},this._variables.some(e=>e.initialValue!==void 0)&&i.capabilities?.supportsWarmStart!==!0)throw Error(`Solver "${i.name}" does not support primal initial values (initialValue). Please use a solver with warm-start support such as HiGHS or Pumpkin.`);let c=this.wrapSolveOptions(a,r,n),l;try{l=await i.solve(o,c)}catch(e){throw this.activeOperationId===n&&this.clearSolutionFields(),e}this.ensureExecutionValid(r,n,`solve`),this.runTime=l.runTime??0,this.status=l.status,this.terminationStatus=l.terminationStatus??l.status;let u=this.hasPrimalFromResult(l);this.hasPrimalSolution=u,this.objectiveValue=u&&typeof l.objectiveValue==`number`&&Number.isFinite(l.objectiveValue)?l.objectiveValue:null,this.objectiveBound=typeof l.objectiveBound==`number`&&Number.isFinite(l.objectiveBound)?l.objectiveBound:void 0;let d=typeof l.relativeGap==`number`&&Number.isFinite(l.relativeGap)?l.relativeGap:void 0;this.relativeGap=d,this.absoluteGap=typeof l.absoluteGap==`number`&&Number.isFinite(l.absoluteGap)?l.absoluteGap:this.objectiveValue!==null&&this.objectiveBound!==void 0?Math.abs(this.objectiveValue-this.objectiveBound):void 0;let f=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})},p={},m={},h={},g={};if(this._values.clear(),u&&l.values){for(let[e,t]of Object.entries(l.values))if(typeof t==`number`&&Number.isFinite(t)){let n=this.varMapByName.get(e),r=this.boolVarMapByName.get(e);if(n){let e=this.normalizePrimalValue(n,t,i,a);n.value=e,f(p,n.name,e),this._values.set(n.name,e)}r&&(r.value=!!t,this._values.set(r.name,t)),!n&&!r&&!s&&this._values.set(e,t)}else if(typeof t==`boolean`){let n=t,r=this.boolVarMapByName.get(e);r?(r.value=n,f(p,r.name,+!!n),this._values.set(r.name,n)):this._values.set(e,n)}if(s)for(let e of this._boolVars){let t=s.boolVarToBinary.get(e);if(t&&l.values){let n=l.values[t.name];if(typeof n==`number`&&Number.isFinite(n)){let t=Math.round(n)===1;e.value=t,f(p,e.name,+!!t),this._values.set(e.name,t)}}}}if(u&&l.boolValues)for(let[e,t]of Object.entries(l.boolValues)){if(typeof t!=`boolean`)continue;let n=this.boolVarMapByName.get(e);n?(n.value=t,this._values.has(n.name)||this._values.set(n.name,t)):this._values.has(e)||this._values.set(e,t)}if(u&&l.reducedCosts)for(let[e,t]of Object.entries(l.reducedCosts)){if(typeof t!=`number`||!Number.isFinite(t))continue;let n=this.varMapByName.get(e);n&&(n.reducedCost=t,f(h,n.name,t))}if(l.duals)for(let[e,t]of Object.entries(l.duals)){if(typeof t!=`number`||!Number.isFinite(t))continue;let n=this.constrMapByName.get(e);n&&(n.dual=t,f(m,n.name,t))}if(l.slacks)for(let[e,t]of Object.entries(l.slacks)){if(typeof t!=`number`||!Number.isFinite(t))continue;let n=this.constrMapByName.get(e);n&&(n.slack=t,f(g,n.name,t))}return this.solution={status:this.status,terminationStatus:this.terminationStatus,hasPrimalSolution:this.hasPrimalSolution,objectiveValue:this.objectiveValue,...this.objectiveBound===void 0?{}:{objectiveBound:this.objectiveBound},...this.relativeGap===void 0?{}:{relativeGap:this.relativeGap},...this.absoluteGap===void 0?{}:{absoluteGap:this.absoluteGap},values:p,duals:m,reducedCosts:h,slacks:g,runTime:this.runTime,raw:l.raw},this.hasSolutionState=!0,this.status}async check(e,t){let n=++this.activeOperationId,r=this.modelRevision;this.clearSolutionFields(),this.validateIntegrityInternal();let{activeSolver:i,activeOptions:a}=this.resolveSolverAndOptions(e,t);if(this._variables.some(e=>e.initialValue!==void 0)&&i.capabilities?.supportsWarmStart!==!0)throw Error(`Solver "${i.name}" does not support primal initial values (initialValue). Please use a solver with warm-start support such as HiGHS or Pumpkin.`);let o=this.wrapSolveOptions(a,r,n),s=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})},c={name:this.name,variables:this._variables,boolVars:this._boolVars,constraints:this._constraints,logicalConstraints:this._logicalConstraints};if(typeof i.check==`function`){let e;try{e=await i.check(c,o)}catch(e){throw this.activeOperationId===n&&this.clearSolutionFields(),e}this.ensureExecutionValid(r,n,`check`),this.status=e.status,this.terminationStatus=a.signal?.aborted?`Interrupted`:e.status,this.hasPrimalSolution=e.status===`Sat`,this.runTime=e.runTime??0,this.unsatCore=e.unsatCore===void 0?void 0:Object.freeze([...e.unsatCore]),this.conflicts=e.conflicts===void 0?this.unsatCore:Object.freeze([...e.conflicts]);let t={};if(e.values&&e.status===`Sat`){for(let[n,r]of Object.entries(e.values))if(typeof r==`number`){if(!Number.isFinite(r))continue;let e=this.varMapByName.get(n),o=this.boolVarMapByName.get(n);if(e){let n=this.normalizePrimalValue(e,r,i,a);e.value=n,this._values.set(e.name,n),s(t,e.name,n)}o&&(o.value=!!r,this._values.set(o.name,o.value),s(t,o.name,o.value)),!e&&!o&&(this._values.set(n,r),s(t,n,r))}else if(typeof r==`boolean`){let e=this.boolVarMapByName.get(n);e?(e.value=r,this._values.set(e.name,r),s(t,e.name,r)):(this._values.set(n,r),s(t,n,r))}}return this.hasSolutionState=!0,{status:e.status,values:t,unsatCore:this.unsatCore,conflicts:this.conflicts,runTime:this.runTime}}let l=this._logicalConstraints.length>0||this._boolVars.length>0||xn(this._constraints)?ln(this._variables,this._boolVars,this._constraints,this._logicalConstraints):{variables:[...this._variables],constraints:[...this._constraints],boolVarToBinary:new Map,constraintToOriginalName:new Map(this._constraints.map(e=>[e,e.name]))},u=[],d=[],f=[],p=new Map,m=0;for(let e of l.constraints){let t=l.constraintToOriginalName.get(e)??e.name,{lhs:n,sense:r,rhs:i}=e;if(r===`<=`){let r=new W({name:`__slack_${++m}`,type:`Continuous`,lb:0,ub:1/0});d.push(r),f.push([r,1]),p.set(r,t);let a=n.clone().add(new V(new Map([[r,-1]]),0));u.push(new R(a,`<=`,i,`${e.name}_slack`))}else if(r===`>=`){let r=new W({name:`__slack_${++m}`,type:`Continuous`,lb:0,ub:1/0});d.push(r),f.push([r,1]),p.set(r,t);let a=n.clone().add(new V(new Map([[r,1]]),0));u.push(new R(a,`>=`,i,`${e.name}_slack`))}else{let r=new W({name:`__slack_${++m}_p`,type:`Continuous`,lb:0,ub:1/0}),a=new W({name:`__slack_${++m}_n`,type:`Continuous`,lb:0,ub:1/0});d.push(r,a),f.push([r,1],[a,1]),p.set(r,t),p.set(a,t);let o=n.clone().add(new V(new Map([[r,-1],[a,1]]),0));u.push(new R(o,`==`,i,`${e.name}_slack`))}}let h={name:`${this.name}_elastic_check`,sense:`Minimize`,objective:new V(new Map(f),0),constraints:u,variables:[...l.variables,...d]},g;try{g=await i.solve(h,o)}catch(e){throw this.activeOperationId===n&&this.clearSolutionFields(),e}this.ensureExecutionValid(r,n,`check`),this.runTime=g.runTime??0;let _=g.status,v=g.terminationStatus??_,y=this.hasPrimalFromResult(g),b=typeof g.objectiveValue==`number`&&Number.isFinite(g.objectiveValue)?g.objectiveValue:1/0,x=(_===`Optimal`||_===`Feasible`||y)&&b<=1e-5,S=typeof g.objectiveBound==`number`&&Number.isFinite(g.objectiveBound)&&g.objectiveBound>1e-5,C=!x&&(_===`Infeasible`||_===`Optimal`&&b>1e-5||S),w=x?`Sat`:C?`Unsat`:`Unknown`;this.status=w,this.terminationStatus=a.signal?.aborted||v===`Interrupted`?`Interrupted`:v===`Optimal`||v===`Feasible`||v===`Infeasible`?w:v,this.hasPrimalSolution=x,this.objectiveValue=null,this.objectiveBound=void 0,this.relativeGap=void 0,this.absoluteGap=void 0,this.solution=null,this._values.clear();let T={};if(x&&g.values){for(let e of this._variables){let t=g.values[e.name];if(typeof t==`number`&&Number.isFinite(t)){let n=this.normalizePrimalValue(e,t,i,a);e.value=n,this._values.set(e.name,n),s(T,e.name,n)}}for(let e of this._boolVars){let t=l.boolVarToBinary.get(e),n=t?g.values[t.name]:g.values[e.name];if(typeof n==`number`&&Number.isFinite(n)){let t=Math.round(n)===1;e.value=t,this._values.set(e.name,t),s(T,e.name,t)}}}let E=new Set;if(C&&g.values)for(let[e,t]of p.entries()){let n=g.values[e.name];typeof n==`number`&&n>1e-5&&E.add(t)}return this.conflicts=C?Object.freeze(Array.from(E)):void 0,this.unsatCore=void 0,this.hasSolutionState=!0,{status:w,values:T,conflicts:this.conflicts,unsatCore:this.unsatCore,runTime:this.runTime}}verify(e={}){return $t(this,e)}link(e){if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e)throw Error(`Linking constraint cannot be a quadratic expression.`);if(!(e instanceof R)&&(typeof e!=`object`||!e||!(`sense`in e)||!(`lhs`in e)||!(`rhs`in e)))throw Error("Linking constraint must contain a comparison operator (<=, >=, ==). Use expr`... <= ...` or .le(), .ge(), .eq().");this._linkingConstraints||=[];let t=e;return this._linkingConstraints.push(t),t}get linkingConstraints(){return this._linkingConstraints??[]}async solveBenders(e){let t=await yn({master:this,...e});return this.decomposition=t,t}async solveColumnGeneration(e){let t=await fn({master:this,...e});return this.decomposition=t,t}};return ht(),e.BoolExpr=s,e.BoolOp=l,e.BoolVar=c,e.Constraint=R,e.GlobalConstraint=h,e.HiGHS=Jt,e.Highs=mt,e.HighsSolver=qt,e.LinExpr=V,e.MockSolver=Xt,e.Model=Dn,e.QuadExpr=w,e.Var=W,e.abs=he,e.allowed=S,e.and=u,e.at=U,e.buildIndicatorLinearization=an,e.buildLpSymbolMaps=Ge,e.cumulative=x,e.deriveBigMForGe=rn,e.deriveBigMForLe=nn,e.disjoint=b,e.distinct=v,e.dot=me,e.expr=He,e.generateLpString=Ke,e.getHighs=jt,e.getHighsWasmUrl=Ot,e.getSolver=$e,e.implies=p,e.isLpExportResult=Ue,e.linearizeModelForMip=ln,e.listAvailableSolvers=et,e.max=ve,e.maximize=mn,e.min=ye,e.minimize=hn,e.normalizeSense=i,e.not=f,e.or=d,e.parseConstraint=Re,e.parseExpr=Ie,e.registerSolver=Ze,e.sanitizeIdentifier=We,e.setDefaultSolver=Qe,e.setHighsWasmUrl=Dt,e.solveBenders=yn,e.solveColumnGeneration=fn,e.solveLpWithHighs=Mt,e.sum=H,e.validateUserBigM=en,e.xor=m,e})({});
5
+ `)),!e)return null;Ee=ke(e,!0)}return Ee.shift()},U={ttys:[],init(){},shutdown(){},register(e,t){U.ttys[e]={input:[],output:[],ops:t},G.registerDevice(e,U.stream_ops)},stream_ops:{open(e){var t=U.ttys[e.node.rdev];if(!t)throw new G.ErrnoError(43);e.tty=t,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,t,n,r,i){if(!e.tty||!e.tty.ops.get_char)throw new G.ErrnoError(60);for(var a=0,o=0;o<r;o++){var s;try{s=e.tty.ops.get_char(e.tty)}catch{throw new G.ErrnoError(29)}if(s===void 0&&a===0)throw new G.ErrnoError(6);if(s==null)break;a++,t[n+o]=s}return a&&(e.node.timestamp=Date.now()),a},write(e,t,n,r,i){if(!e.tty||!e.tty.ops.put_char)throw new G.ErrnoError(60);try{for(var a=0;a<r;a++)e.tty.ops.put_char(e.tty,t[n+a])}catch{throw new G.ErrnoError(29)}return r&&(e.node.timestamp=Date.now()),a}},default_tty_ops:{get_char(e){return Ae()},put_char(e,t){t===null||t===10?(h(Te(e.output,0)),e.output=[]):t!=0&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(h(Te(e.output,0)),e.output=[])},ioctl_tcgets(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(e,t,n){return 0},ioctl_tiocgwinsz(e){return[24,80]}},default_tty1_ops:{put_char(e,t){t===null||t===10?(g(Te(e.output,0)),e.output=[]):t!=0&&e.output.push(t)},fsync(e){e.output&&e.output.length>0&&(g(Te(e.output,0)),e.output=[])}}},je=e=>{ue()},W={ops_table:null,mount(e){return W.createNode(null,`/`,16895,0)},createNode(e,t,n,r){if(G.isBlkdev(n)||G.isFIFO(n))throw new G.ErrnoError(63);W.ops_table||={dir:{node:{getattr:W.node_ops.getattr,setattr:W.node_ops.setattr,lookup:W.node_ops.lookup,mknod:W.node_ops.mknod,rename:W.node_ops.rename,unlink:W.node_ops.unlink,rmdir:W.node_ops.rmdir,readdir:W.node_ops.readdir,symlink:W.node_ops.symlink},stream:{llseek:W.stream_ops.llseek}},file:{node:{getattr:W.node_ops.getattr,setattr:W.node_ops.setattr},stream:{llseek:W.stream_ops.llseek,read:W.stream_ops.read,write:W.stream_ops.write,allocate:W.stream_ops.allocate,mmap:W.stream_ops.mmap,msync:W.stream_ops.msync}},link:{node:{getattr:W.node_ops.getattr,setattr:W.node_ops.setattr,readlink:W.node_ops.readlink},stream:{}},chrdev:{node:{getattr:W.node_ops.getattr,setattr:W.node_ops.setattr},stream:G.chrdev_stream_ops}};var i=G.createNode(e,t,n,r);return G.isDir(i.mode)?(i.node_ops=W.ops_table.dir.node,i.stream_ops=W.ops_table.dir.stream,i.contents={}):G.isFile(i.mode)?(i.node_ops=W.ops_table.file.node,i.stream_ops=W.ops_table.file.stream,i.usedBytes=0,i.contents=null):G.isLink(i.mode)?(i.node_ops=W.ops_table.link.node,i.stream_ops=W.ops_table.link.stream):G.isChrdev(i.mode)&&(i.node_ops=W.ops_table.chrdev.node,i.stream_ops=W.ops_table.chrdev.stream),i.timestamp=Date.now(),e&&(e.contents[t]=i,e.timestamp=i.timestamp),i},getFileDataAsTypedArray(e){return e.contents?e.contents.subarray?e.contents.subarray(0,e.usedBytes):new Uint8Array(e.contents):new Uint8Array},expandFileStorage(e,t){var n=e.contents?e.contents.length:0;if(!(n>=t)){t=Math.max(t,n*(n<1048576?2:1.125)>>>0),n!=0&&(t=Math.max(t,256));var r=e.contents;e.contents=new Uint8Array(t),e.usedBytes>0&&e.contents.set(r.subarray(0,e.usedBytes),0)}},resizeFileStorage(e,t){if(e.usedBytes!=t){if(t==0)e.contents=null,e.usedBytes=0;else{var n=e.contents;e.contents=new Uint8Array(t),n&&e.contents.set(n.subarray(0,Math.min(t,e.usedBytes))),e.usedBytes=t}}},node_ops:{getattr(e){var t={};return t.dev=G.isChrdev(e.mode)?e.id:1,t.ino=e.id,t.mode=e.mode,t.nlink=1,t.uid=0,t.gid=0,t.rdev=e.rdev,t.size=G.isDir(e.mode)?4096:G.isFile(e.mode)?e.usedBytes:G.isLink(e.mode)?e.link.length:0,t.atime=new Date(e.timestamp),t.mtime=new Date(e.timestamp),t.ctime=new Date(e.timestamp),t.blksize=4096,t.blocks=Math.ceil(t.size/t.blksize),t},setattr(e,t){t.mode!==void 0&&(e.mode=t.mode),t.timestamp!==void 0&&(e.timestamp=t.timestamp),t.size!==void 0&&W.resizeFileStorage(e,t.size)},lookup(e,t){throw G.genericErrors[44]},mknod(e,t,n,r){return W.createNode(e,t,n,r)},rename(e,t,n){if(G.isDir(e.mode)){var r;try{r=G.lookupNode(t,n)}catch{}if(r)for(var i in r.contents)throw new G.ErrnoError(55)}delete e.parent.contents[e.name],e.parent.timestamp=Date.now(),e.name=n,t.contents[n]=e,t.timestamp=e.parent.timestamp,e.parent=t},unlink(e,t){delete e.contents[t],e.timestamp=Date.now()},rmdir(e,t){for(var n in G.lookupNode(e,t).contents)throw new G.ErrnoError(55);delete e.contents[t],e.timestamp=Date.now()},readdir(e){var t=[`.`,`..`];for(var n in e.contents)e.contents.hasOwnProperty(n)&&t.push(n);return t},symlink(e,t,n){var r=W.createNode(e,t,41471,0);return r.link=n,r},readlink(e){if(!G.isLink(e.mode))throw new G.ErrnoError(28);return e.link}},stream_ops:{read(e,t,n,r,i){var a=e.node.contents;if(i>=e.node.usedBytes)return 0;var o=Math.min(e.node.usedBytes-i,r);if(o>8&&a.subarray)t.set(a.subarray(i,i+o),n);else for(var s=0;s<o;s++)t[n+s]=a[i+s];return o},write(e,t,n,r,i,a){if(t.buffer===x.buffer&&(a=!1),!r)return 0;var o=e.node;if(o.timestamp=Date.now(),t.subarray&&(!o.contents||o.contents.subarray)){if(a)return o.contents=t.subarray(n,n+r),o.usedBytes=r,r;if(o.usedBytes===0&&i===0)return o.contents=t.slice(n,n+r),o.usedBytes=r,r;if(i+r<=o.usedBytes)return o.contents.set(t.subarray(n,n+r),i),r}if(W.expandFileStorage(o,i+r),o.contents.subarray&&t.subarray)o.contents.set(t.subarray(n,n+r),i);else for(var s=0;s<r;s++)o.contents[i+s]=t[n+s];return o.usedBytes=Math.max(o.usedBytes,i+r),r},llseek(e,t,n){var r=t;if(n===1?r+=e.position:n===2&&G.isFile(e.node.mode)&&(r+=e.node.usedBytes),r<0)throw new G.ErrnoError(28);return r},allocate(e,t,n){W.expandFileStorage(e.node,t+n),e.node.usedBytes=Math.max(e.node.usedBytes,t+n)},mmap(e,t,n,r,i){if(!G.isFile(e.node.mode))throw new G.ErrnoError(43);var a,o,s=e.node.contents;if(!(i&2)&&s.buffer===x.buffer)o=!1,a=s.byteOffset;else{if((n>0||n+t<s.length)&&(s=s.subarray?s.subarray(n,n+t):Array.prototype.slice.call(s,n,n+t)),o=!0,a=je(t),!a)throw new G.ErrnoError(48);x.set(s,a)}return{ptr:a,allocated:o}},msync(e,t,n,r,i){return W.stream_ops.write(e,t,0,r,n,!1),0}}},Me=(e,t,n,r)=>{var i=r?``:P(`al ${e}`);p(e,n=>{b(n,`Loading data file "${e}" failed (no arrayBuffer).`),t(new Uint8Array(n)),i&&le(i)},t=>{if(n)n();else throw`Loading data file "${e}" failed.`}),i&&ce(i)},Ne=(e,t,n,r,i,a)=>{G.createDataFile(e,t,n,r,i,a)},Pe=n.preloadPlugins||[],Fe=(e,t,n,r)=>{typeof Browser<`u`&&Browser.init();var i=!1;return Pe.forEach(a=>{i||a.canHandle(t)&&(a.handle(e,t,n,r),i=!0)}),i},Ie=(e,t,n,r,i,a,o,s,c,l)=>{var u=t?V.resolve(B.join2(e,t)):e,d=P(`cp ${u}`);function f(n){function f(n){l&&l(),s||Ne(e,t,n,r,i,c),a&&a(),le(d)}Fe(n,u,f,()=>{o&&o(),le(d)})||f(n)}ce(d),typeof n==`string`?Me(n,e=>f(e),o):f(n)},Le=e=>{var t={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(t===void 0)throw Error(`Unknown file open mode: ${e}`);return t},Re=(e,t)=>{var n=0;return e&&(n|=365),t&&(n|=146),n},G={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:`/`,initialized:!1,ignorePermissions:!0,ErrnoError:null,genericErrors:{},filesystems:null,syncFSRequests:0,lookupPath(e,t={}){if(e=V.resolve(e),!e)return{path:``,node:null};if(t=Object.assign({follow_mount:!0,recurse_count:0},t),t.recurse_count>8)throw new G.ErrnoError(32);for(var n=e.split(`/`).filter(e=>!!e),r=G.root,i=`/`,a=0;a<n.length;a++){var o=a===n.length-1;if(o&&t.parent)break;if(r=G.lookupNode(r,n[a]),i=B.join2(i,n[a]),G.isMountpoint(r)&&(!o||o&&t.follow_mount)&&(r=r.mounted.root),!o||t.follow)for(var s=0;G.isLink(r.mode);){var c=G.readlink(i);if(i=V.resolve(B.dirname(i),c),r=G.lookupPath(i,{recurse_count:t.recurse_count+1}).node,s++>40)throw new G.ErrnoError(32)}}return{path:i,node:r}},getPath(e){for(var t;;){if(G.isRoot(e)){var n=e.mount.mountpoint;return t?n[n.length-1]===`/`?n+t:`${n}/${t}`:n}t=t?`${e.name}/${t}`:e.name,e=e.parent}},hashName(e,t){for(var n=0,r=0;r<t.length;r++)n=(n<<5)-n+t.charCodeAt(r)|0;return(e+n>>>0)%G.nameTable.length},hashAddNode(e){var t=G.hashName(e.parent.id,e.name);e.name_next=G.nameTable[t],G.nameTable[t]=e},hashRemoveNode(e){var t=G.hashName(e.parent.id,e.name);if(G.nameTable[t]===e)G.nameTable[t]=e.name_next;else for(var n=G.nameTable[t];n;){if(n.name_next===e){n.name_next=e.name_next;break}n=n.name_next}},lookupNode(e,t){var n=G.mayLookup(e);if(n)throw new G.ErrnoError(n,e);for(var r=G.hashName(e.id,t),i=G.nameTable[r];i;i=i.name_next){var a=i.name;if(i.parent.id===e.id&&a===t)return i}return G.lookup(e,t)},createNode(e,t,n,r){var i=new G.FSNode(e,t,n,r);return G.hashAddNode(i),i},destroyNode(e){G.hashRemoveNode(e)},isRoot(e){return e===e.parent},isMountpoint(e){return!!e.mounted},isFile(e){return(e&61440)==32768},isDir(e){return(e&61440)==16384},isLink(e){return(e&61440)==40960},isChrdev(e){return(e&61440)==8192},isBlkdev(e){return(e&61440)==24576},isFIFO(e){return(e&61440)==4096},isSocket(e){return(e&49152)==49152},flagsToPermissionString(e){var t=[`r`,`w`,`rw`][e&3];return e&512&&(t+=`w`),t},nodePermissions(e,t){return G.ignorePermissions?0:t.includes(`r`)&&!(e.mode&292)||t.includes(`w`)&&!(e.mode&146)||t.includes(`x`)&&!(e.mode&73)?2:0},mayLookup(e){return G.nodePermissions(e,`x`)||(e.node_ops.lookup?0:2)},mayCreate(e,t){try{return G.lookupNode(e,t),20}catch{}return G.nodePermissions(e,`wx`)},mayDelete(e,t,n){var r;try{r=G.lookupNode(e,t)}catch(e){return e.errno}var i=G.nodePermissions(e,`wx`);if(i)return i;if(n){if(!G.isDir(r.mode))return 54;if(G.isRoot(r)||G.getPath(r)===G.cwd())return 10}else if(G.isDir(r.mode))return 31;return 0},mayOpen(e,t){return e?G.isLink(e.mode)?32:G.isDir(e.mode)&&(G.flagsToPermissionString(t)!==`r`||t&512)?31:G.nodePermissions(e,G.flagsToPermissionString(t)):44},MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=G.MAX_OPEN_FDS;e++)if(!G.streams[e])return e;throw new G.ErrnoError(33)},getStreamChecked(e){var t=G.getStream(e);if(!t)throw new G.ErrnoError(8);return t},getStream:e=>G.streams[e],createStream(e,t=-1){return G.FSStream||(G.FSStream=function(){this.shared={}},G.FSStream.prototype={},Object.defineProperties(G.FSStream.prototype,{object:{get(){return this.node},set(e){this.node=e}},isRead:{get(){return(this.flags&2097155)!=1}},isWrite:{get(){return!!(this.flags&2097155)}},isAppend:{get(){return this.flags&1024}},flags:{get(){return this.shared.flags},set(e){this.shared.flags=e}},position:{get(){return this.shared.position},set(e){this.shared.position=e}}})),e=Object.assign(new G.FSStream,e),t==-1&&(t=G.nextfd()),e.fd=t,G.streams[t]=e,e},closeStream(e){G.streams[e]=null},chrdev_stream_ops:{open(e){e.stream_ops=G.getDevice(e.node.rdev).stream_ops,e.stream_ops.open&&e.stream_ops.open(e)},llseek(){throw new G.ErrnoError(70)}},major:e=>e>>8,minor:e=>e&255,makedev:(e,t)=>e<<8|t,registerDevice(e,t){G.devices[e]={stream_ops:t}},getDevice:e=>G.devices[e],getMounts(e){for(var t=[],n=[e];n.length;){var r=n.pop();t.push(r),n.push.apply(n,r.mounts)}return t},syncfs(e,t){typeof e==`function`&&(t=e,e=!1),G.syncFSRequests++,G.syncFSRequests>1&&g(`warning: ${G.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var n=G.getMounts(G.root.mount),r=0;function i(e){return G.syncFSRequests--,t(e)}function a(e){if(e)return a.errored?void 0:(a.errored=!0,i(e));++r>=n.length&&i(null)}n.forEach(t=>{if(!t.type.syncfs)return a(null);t.type.syncfs(t,e,a)})},mount(e,t,n){var r=n===`/`,i=!n,a;if(r&&G.root)throw new G.ErrnoError(10);if(!r&&!i){var o=G.lookupPath(n,{follow_mount:!1});if(n=o.path,a=o.node,G.isMountpoint(a))throw new G.ErrnoError(10);if(!G.isDir(a.mode))throw new G.ErrnoError(54)}var s={type:e,opts:t,mountpoint:n,mounts:[]},c=e.mount(s);return c.mount=s,s.root=c,r?G.root=c:a&&(a.mounted=s,a.mount&&a.mount.mounts.push(s)),c},unmount(e){var t=G.lookupPath(e,{follow_mount:!1});if(!G.isMountpoint(t.node))throw new G.ErrnoError(28);var n=t.node,r=n.mounted,i=G.getMounts(r);Object.keys(G.nameTable).forEach(e=>{for(var t=G.nameTable[e];t;){var n=t.name_next;i.includes(t.mount)&&G.destroyNode(t),t=n}}),n.mounted=null;var a=n.mount.mounts.indexOf(r);n.mount.mounts.splice(a,1)},lookup(e,t){return e.node_ops.lookup(e,t)},mknod(e,t,n){var r=G.lookupPath(e,{parent:!0}).node,i=B.basename(e);if(!i||i===`.`||i===`..`)throw new G.ErrnoError(28);var a=G.mayCreate(r,i);if(a)throw new G.ErrnoError(a);if(!r.node_ops.mknod)throw new G.ErrnoError(63);return r.node_ops.mknod(r,i,t,n)},create(e,t){return t=t===void 0?438:t,t&=4095,t|=32768,G.mknod(e,t,0)},mkdir(e,t){return t=t===void 0?511:t,t&=1023,t|=16384,G.mknod(e,t,0)},mkdirTree(e,t){for(var n=e.split(`/`),r=``,i=0;i<n.length;++i)if(n[i]){r+=`/`+n[i];try{G.mkdir(r,t)}catch(e){if(e.errno!=20)throw e}}},mkdev(e,t,n){return n===void 0&&(n=t,t=438),t|=8192,G.mknod(e,t,n)},symlink(e,t){if(!V.resolve(e))throw new G.ErrnoError(44);var n=G.lookupPath(t,{parent:!0}).node;if(!n)throw new G.ErrnoError(44);var r=B.basename(t),i=G.mayCreate(n,r);if(i)throw new G.ErrnoError(i);if(!n.node_ops.symlink)throw new G.ErrnoError(63);return n.node_ops.symlink(n,r,e)},rename(e,t){var n=B.dirname(e),r=B.dirname(t),i=B.basename(e),a=B.basename(t),o=G.lookupPath(e,{parent:!0}),s=o.node,c;if(o=G.lookupPath(t,{parent:!0}),c=o.node,!s||!c)throw new G.ErrnoError(44);if(s.mount!==c.mount)throw new G.ErrnoError(75);var l=G.lookupNode(s,i),u=V.relative(e,r);if(u.charAt(0)!==`.`)throw new G.ErrnoError(28);if(u=V.relative(t,n),u.charAt(0)!==`.`)throw new G.ErrnoError(55);var d;try{d=G.lookupNode(c,a)}catch{}if(l!==d){var f=G.isDir(l.mode),p=G.mayDelete(s,i,f);if(p||(p=d?G.mayDelete(c,a,f):G.mayCreate(c,a),p))throw new G.ErrnoError(p);if(!s.node_ops.rename)throw new G.ErrnoError(63);if(G.isMountpoint(l)||d&&G.isMountpoint(d))throw new G.ErrnoError(10);if(c!==s&&(p=G.nodePermissions(s,`w`),p))throw new G.ErrnoError(p);G.hashRemoveNode(l);try{s.node_ops.rename(l,c,a)}catch(e){throw e}finally{G.hashAddNode(l)}}},rmdir(e){var t=G.lookupPath(e,{parent:!0}).node,n=B.basename(e),r=G.lookupNode(t,n),i=G.mayDelete(t,n,!0);if(i)throw new G.ErrnoError(i);if(!t.node_ops.rmdir)throw new G.ErrnoError(63);if(G.isMountpoint(r))throw new G.ErrnoError(10);t.node_ops.rmdir(t,n),G.destroyNode(r)},readdir(e){var t=G.lookupPath(e,{follow:!0}).node;if(!t.node_ops.readdir)throw new G.ErrnoError(54);return t.node_ops.readdir(t)},unlink(e){var t=G.lookupPath(e,{parent:!0}).node;if(!t)throw new G.ErrnoError(44);var n=B.basename(e),r=G.lookupNode(t,n),i=G.mayDelete(t,n,!1);if(i)throw new G.ErrnoError(i);if(!t.node_ops.unlink)throw new G.ErrnoError(63);if(G.isMountpoint(r))throw new G.ErrnoError(10);t.node_ops.unlink(t,n),G.destroyNode(r)},readlink(e){var t=G.lookupPath(e).node;if(!t)throw new G.ErrnoError(44);if(!t.node_ops.readlink)throw new G.ErrnoError(28);return V.resolve(G.getPath(t.parent),t.node_ops.readlink(t))},stat(e,t){var n=G.lookupPath(e,{follow:!t}).node;if(!n)throw new G.ErrnoError(44);if(!n.node_ops.getattr)throw new G.ErrnoError(63);return n.node_ops.getattr(n)},lstat(e){return G.stat(e,!0)},chmod(e,t,n){var r=typeof e==`string`?G.lookupPath(e,{follow:!n}).node:e;if(!r.node_ops.setattr)throw new G.ErrnoError(63);r.node_ops.setattr(r,{mode:t&4095|r.mode&-4096,timestamp:Date.now()})},lchmod(e,t){G.chmod(e,t,!0)},fchmod(e,t){var n=G.getStreamChecked(e);G.chmod(n.node,t)},chown(e,t,n,r){var i=typeof e==`string`?G.lookupPath(e,{follow:!r}).node:e;if(!i.node_ops.setattr)throw new G.ErrnoError(63);i.node_ops.setattr(i,{timestamp:Date.now()})},lchown(e,t,n){G.chown(e,t,n,!0)},fchown(e,t,n){var r=G.getStreamChecked(e);G.chown(r.node,t,n)},truncate(e,t){if(t<0)throw new G.ErrnoError(28);var n=typeof e==`string`?G.lookupPath(e,{follow:!0}).node:e;if(!n.node_ops.setattr)throw new G.ErrnoError(63);if(G.isDir(n.mode))throw new G.ErrnoError(31);if(!G.isFile(n.mode))throw new G.ErrnoError(28);var r=G.nodePermissions(n,`w`);if(r)throw new G.ErrnoError(r);n.node_ops.setattr(n,{size:t,timestamp:Date.now()})},ftruncate(e,t){var n=G.getStreamChecked(e);if(!(n.flags&2097155))throw new G.ErrnoError(28);G.truncate(n.node,t)},utime(e,t,n){var r=G.lookupPath(e,{follow:!0}).node;r.node_ops.setattr(r,{timestamp:Math.max(t,n)})},open(e,t,r){if(e===``)throw new G.ErrnoError(44);t=typeof t==`string`?Le(t):t,r=r===void 0?438:r,r=t&64?r&4095|32768:0;var i;if(typeof e==`object`)i=e;else{e=B.normalize(e);try{i=G.lookupPath(e,{follow:!(t&131072)}).node}catch{}}var a=!1;if(t&64){if(i){if(t&128)throw new G.ErrnoError(20)}else i=G.mknod(e,r,0),a=!0}if(!i)throw new G.ErrnoError(44);if(G.isChrdev(i.mode)&&(t&=-513),t&65536&&!G.isDir(i.mode))throw new G.ErrnoError(54);if(!a){var o=G.mayOpen(i,t);if(o)throw new G.ErrnoError(o)}t&512&&!a&&G.truncate(i,0),t&=-131713;var s=G.createStream({node:i,path:G.getPath(i),flags:t,seekable:!0,position:0,stream_ops:i.stream_ops,ungotten:[],error:!1});return s.stream_ops.open&&s.stream_ops.open(s),n.logReadFiles&&!(t&1)&&(G.readFiles||={},e in G.readFiles||(G.readFiles[e]=1)),s},close(e){if(G.isClosed(e))throw new G.ErrnoError(8);e.getdents&&=null;try{e.stream_ops.close&&e.stream_ops.close(e)}catch(e){throw e}finally{G.closeStream(e.fd)}e.fd=null},isClosed(e){return e.fd===null},llseek(e,t,n){if(G.isClosed(e))throw new G.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new G.ErrnoError(70);if(n!=0&&n!=1&&n!=2)throw new G.ErrnoError(28);return e.position=e.stream_ops.llseek(e,t,n),e.ungotten=[],e.position},read(e,t,n,r,i){if(r<0||i<0)throw new G.ErrnoError(28);if(G.isClosed(e)||(e.flags&2097155)==1)throw new G.ErrnoError(8);if(G.isDir(e.node.mode))throw new G.ErrnoError(31);if(!e.stream_ops.read)throw new G.ErrnoError(28);var a=i!==void 0;if(!a)i=e.position;else if(!e.seekable)throw new G.ErrnoError(70);var o=e.stream_ops.read(e,t,n,r,i);return a||(e.position+=o),o},write(e,t,n,r,i,a){if(r<0||i<0)throw new G.ErrnoError(28);if(G.isClosed(e)||!(e.flags&2097155))throw new G.ErrnoError(8);if(G.isDir(e.node.mode))throw new G.ErrnoError(31);if(!e.stream_ops.write)throw new G.ErrnoError(28);e.seekable&&e.flags&1024&&G.llseek(e,0,2);var o=i!==void 0;if(!o)i=e.position;else if(!e.seekable)throw new G.ErrnoError(70);var s=e.stream_ops.write(e,t,n,r,i,a);return o||(e.position+=s),s},allocate(e,t,n){if(G.isClosed(e))throw new G.ErrnoError(8);if(t<0||n<=0)throw new G.ErrnoError(28);if(!(e.flags&2097155))throw new G.ErrnoError(8);if(!G.isFile(e.node.mode)&&!G.isDir(e.node.mode))throw new G.ErrnoError(43);if(!e.stream_ops.allocate)throw new G.ErrnoError(138);e.stream_ops.allocate(e,t,n)},mmap(e,t,n,r,i){if(r&2&&!(i&2)&&(e.flags&2097155)!=2||(e.flags&2097155)==1)throw new G.ErrnoError(2);if(!e.stream_ops.mmap)throw new G.ErrnoError(43);return e.stream_ops.mmap(e,t,n,r,i)},msync(e,t,n,r,i){return e.stream_ops.msync?e.stream_ops.msync(e,t,n,r,i):0},munmap:e=>0,ioctl(e,t,n){if(!e.stream_ops.ioctl)throw new G.ErrnoError(59);return e.stream_ops.ioctl(e,t,n)},readFile(e,t={}){if(t.flags=t.flags||0,t.encoding=t.encoding||`binary`,t.encoding!==`utf8`&&t.encoding!==`binary`)throw Error(`Invalid encoding type "${t.encoding}"`);var n,r=G.open(e,t.flags),i=G.stat(e).size,a=new Uint8Array(i);return G.read(r,a,0,i,0),t.encoding===`utf8`?n=Te(a,0):t.encoding===`binary`&&(n=a),G.close(r),n},writeFile(e,t,n={}){n.flags=n.flags||577;var r=G.open(e,n.flags,n.mode);if(typeof t==`string`){var i=new Uint8Array(De(t)+1),a=Oe(t,i,0,i.length);G.write(r,i,0,a,void 0,n.canOwn)}else if(ArrayBuffer.isView(t))G.write(r,t,0,t.byteLength,void 0,n.canOwn);else throw Error(`Unsupported data type`);G.close(r)},cwd:()=>G.currentPath,chdir(e){var t=G.lookupPath(e,{follow:!0});if(t.node===null)throw new G.ErrnoError(44);if(!G.isDir(t.node.mode))throw new G.ErrnoError(54);var n=G.nodePermissions(t.node,`x`);if(n)throw new G.ErrnoError(n);G.currentPath=t.path},createDefaultDirectories(){G.mkdir(`/tmp`),G.mkdir(`/home`),G.mkdir(`/home/web_user`)},createDefaultDevices(){G.mkdir(`/dev`),G.registerDevice(G.makedev(1,3),{read:()=>0,write:(e,t,n,r,i)=>r}),G.mkdev(`/dev/null`,G.makedev(1,3)),U.register(G.makedev(5,0),U.default_tty_ops),U.register(G.makedev(6,0),U.default_tty1_ops),G.mkdev(`/dev/tty`,G.makedev(5,0)),G.mkdev(`/dev/tty1`,G.makedev(6,0));var e=new Uint8Array(1024),t=0,n=()=>(t===0&&(t=we(e).byteLength),e[--t]);G.createDevice(`/dev`,`random`,n),G.createDevice(`/dev`,`urandom`,n),G.mkdir(`/dev/shm`),G.mkdir(`/dev/shm/tmp`)},createSpecialDirectories(){G.mkdir(`/proc`);var e=G.mkdir(`/proc/self`);G.mkdir(`/proc/self/fd`),G.mount({mount(){var t=G.createNode(e,`fd`,16895,73);return t.node_ops={lookup(e,t){var n=+t,r=G.getStreamChecked(n),i={parent:null,mount:{mountpoint:`fake`},node_ops:{readlink:()=>r.path}};return i.parent=i,i}},t}},{},`/proc/self/fd`)},createStandardStreams(){n.stdin?G.createDevice(`/dev`,`stdin`,n.stdin):G.symlink(`/dev/tty`,`/dev/stdin`),n.stdout?G.createDevice(`/dev`,`stdout`,null,n.stdout):G.symlink(`/dev/tty`,`/dev/stdout`),n.stderr?G.createDevice(`/dev`,`stderr`,null,n.stderr):G.symlink(`/dev/tty1`,`/dev/stderr`),G.open(`/dev/stdin`,0),G.open(`/dev/stdout`,1),G.open(`/dev/stderr`,1)},ensureErrnoError(){G.ErrnoError||(G.ErrnoError=function(e,t){this.name=`ErrnoError`,this.node=t,this.setErrno=function(e){this.errno=e},this.setErrno(e),this.message=`FS error`},G.ErrnoError.prototype=Error(),G.ErrnoError.prototype.constructor=G.ErrnoError,[44].forEach(e=>{G.genericErrors[e]=new G.ErrnoError(e),G.genericErrors[e].stack=`<generic error, no stack>`}))},staticInit(){G.ensureErrnoError(),G.nameTable=Array(4096),G.mount(W,{},`/`),G.createDefaultDirectories(),G.createDefaultDevices(),G.createSpecialDirectories(),G.filesystems={MEMFS:W}},init(e,t,r){G.init.initialized=!0,G.ensureErrnoError(),n.stdin=e||n.stdin,n.stdout=t||n.stdout,n.stderr=r||n.stderr,G.createStandardStreams()},quit(){G.init.initialized=!1;for(var e=0;e<G.streams.length;e++){var t=G.streams[e];t&&G.close(t)}},findObject(e,t){var n=G.analyzePath(e,t);return n.exists?n.object:null},analyzePath(e,t){try{var n=G.lookupPath(e,{follow:!t});e=n.path}catch{}var r={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var n=G.lookupPath(e,{parent:!0});r.parentExists=!0,r.parentPath=n.path,r.parentObject=n.node,r.name=B.basename(e),n=G.lookupPath(e,{follow:!t}),r.exists=!0,r.path=n.path,r.object=n.node,r.name=n.node.name,r.isRoot=n.path===`/`}catch(e){r.error=e.errno}return r},createPath(e,t,n,r){e=typeof e==`string`?e:G.getPath(e);for(var i=t.split(`/`).reverse();i.length;){var a=i.pop();if(a){var o=B.join2(e,a);try{G.mkdir(o)}catch{}e=o}}return o},createFile(e,t,n,r,i){var a=B.join2(typeof e==`string`?e:G.getPath(e),t),o=Re(r,i);return G.create(a,o)},createDataFile(e,t,n,r,i,a){var o=t;e&&(e=typeof e==`string`?e:G.getPath(e),o=t?B.join2(e,t):e);var s=Re(r,i),c=G.create(o,s);if(n){if(typeof n==`string`){for(var l=Array(n.length),u=0,d=n.length;u<d;++u)l[u]=n.charCodeAt(u);n=l}G.chmod(c,s|146);var f=G.open(c,577);G.write(f,n,0,n.length,0,a),G.close(f),G.chmod(c,s)}},createDevice(e,t,n,r){var i=B.join2(typeof e==`string`?e:G.getPath(e),t),a=Re(!!n,!!r);G.createDevice.major||(G.createDevice.major=64);var o=G.makedev(G.createDevice.major++,0);return G.registerDevice(o,{open(e){e.seekable=!1},close(e){r&&r.buffer&&r.buffer.length&&r(10)},read(e,t,r,i,a){for(var o=0,s=0;s<i;s++){var c;try{c=n()}catch{throw new G.ErrnoError(29)}if(c===void 0&&o===0)throw new G.ErrnoError(6);if(c==null)break;o++,t[r+s]=c}return o&&(e.node.timestamp=Date.now()),o},write(e,t,n,i,a){for(var o=0;o<i;o++)try{r(t[n+o])}catch{throw new G.ErrnoError(29)}return i&&(e.node.timestamp=Date.now()),o}}),G.mkdev(i,a,o)},forceLoadFile(e){if(e.isDevice||e.isFolder||e.link||e.contents)return!0;if(typeof XMLHttpRequest<`u`)throw Error(`Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers. Use --embed-file or --preload-file in emcc on the main thread.`);if(f)try{e.contents=ke(f(e.url),!0),e.usedBytes=e.contents.length}catch{throw new G.ErrnoError(29)}else throw Error(`Cannot load without read() or XMLHttpRequest.`)},createLazyFile(e,t,n,r,i){function a(){this.lengthKnown=!1,this.chunks=[]}if(a.prototype.get=function(e){if(!(e>this.length-1||e<0)){var t=e%this.chunkSize,n=e/this.chunkSize|0;return this.getter(n)[t]}},a.prototype.setDataGetter=function(e){this.getter=e},a.prototype.cacheLength=function(){var e=new XMLHttpRequest;if(e.open(`HEAD`,n,!1),e.send(null),!(e.status>=200&&e.status<300||e.status===304))throw Error(`Couldn't load `+n+`. Status: `+e.status);var t=Number(e.getResponseHeader(`Content-length`)),r,i=(r=e.getResponseHeader(`Accept-Ranges`))&&r===`bytes`,a=(r=e.getResponseHeader(`Content-Encoding`))&&r===`gzip`,o=1048576;i||(o=t);var s=(e,r)=>{if(e>r)throw Error(`invalid range (`+e+`, `+r+`) or no bytes requested!`);if(r>t-1)throw Error(`only `+t+` bytes available! programmer error!`);var i=new XMLHttpRequest;if(i.open(`GET`,n,!1),t!==o&&i.setRequestHeader(`Range`,`bytes=`+e+`-`+r),i.responseType=`arraybuffer`,i.overrideMimeType&&i.overrideMimeType(`text/plain; charset=x-user-defined`),i.send(null),!(i.status>=200&&i.status<300||i.status===304))throw Error(`Couldn't load `+n+`. Status: `+i.status);return i.response===void 0?ke(i.responseText||``,!0):new Uint8Array(i.response||[])},c=this;c.setDataGetter(e=>{var n=e*o,r=(e+1)*o-1;if(r=Math.min(r,t-1),c.chunks[e]===void 0&&(c.chunks[e]=s(n,r)),c.chunks[e]===void 0)throw Error(`doXHR failed!`);return c.chunks[e]}),(a||!t)&&(o=t=1,t=this.getter(0).length,o=t,h(`LazyFiles on gzip forces download of the whole file when length is accessed`)),this._length=t,this._chunkSize=o,this.lengthKnown=!0},typeof XMLHttpRequest<`u`){if(!l)throw`Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc`;var o=new a;Object.defineProperties(o,{length:{get:function(){return this.lengthKnown||this.cacheLength(),this._length}},chunkSize:{get:function(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}});var s={isDevice:!1,contents:o}}else var s={isDevice:!1,url:n};var c=G.createFile(e,t,s,r,i);s.contents?c.contents=s.contents:s.url&&(c.contents=null,c.url=s.url),Object.defineProperties(c,{usedBytes:{get:function(){return this.contents.length}}});var u={};Object.keys(c.stream_ops).forEach(e=>{var t=c.stream_ops[e];u[e]=function(){return G.forceLoadFile(c),t.apply(null,arguments)}});function d(e,t,n,r,i){var a=e.node.contents;if(i>=a.length)return 0;var o=Math.min(a.length-i,r);if(a.slice)for(var s=0;s<o;s++)t[n+s]=a[i+s];else for(var s=0;s<o;s++)t[n+s]=a.get(i+s);return o}return u.read=(e,t,n,r,i)=>(G.forceLoadFile(c),d(e,t,n,r,i)),u.mmap=(e,t,n,r,i)=>{G.forceLoadFile(c);var a=je(t);if(!a)throw new G.ErrnoError(48);return d(e,x,a,t,n),{ptr:a,allocated:!0}},c.stream_ops=u,c}},ze=(e,t)=>e?Te(S,e,t):``,K={DEFAULT_POLLMASK:5,calculateAt(e,t,n){if(B.isAbs(t))return t;var r=e===-100?G.cwd():K.getStreamFromFD(e).path;if(t.length==0){if(!n)throw new G.ErrnoError(44);return r}return B.join2(r,t)},doStat(e,t,n){try{var r=e(t)}catch(e){if(e&&e.node&&B.normalize(t)!==B.normalize(G.getPath(e.node)))return-54;throw e}w[n>>2]=r.dev,w[n+4>>2]=r.mode,T[n+8>>2]=r.nlink,w[n+12>>2]=r.uid,w[n+16>>2]=r.gid,w[n+20>>2]=r.rdev,z=[r.size>>>0,(R=r.size,+Math.abs(R)>=1?R>0?Math.floor(R/4294967296)>>>0:~~+Math.ceil((R-+(~~R>>>0))/4294967296)>>>0:0)],w[n+24>>2]=z[0],w[n+28>>2]=z[1],w[n+32>>2]=4096,w[n+36>>2]=r.blocks;var i=r.atime.getTime(),a=r.mtime.getTime(),o=r.ctime.getTime();return z=[Math.floor(i/1e3)>>>0,(R=Math.floor(i/1e3),+Math.abs(R)>=1?R>0?Math.floor(R/4294967296)>>>0:~~+Math.ceil((R-+(~~R>>>0))/4294967296)>>>0:0)],w[n+40>>2]=z[0],w[n+44>>2]=z[1],T[n+48>>2]=i%1e3*1e3,z=[Math.floor(a/1e3)>>>0,(R=Math.floor(a/1e3),+Math.abs(R)>=1?R>0?Math.floor(R/4294967296)>>>0:~~+Math.ceil((R-+(~~R>>>0))/4294967296)>>>0:0)],w[n+56>>2]=z[0],w[n+60>>2]=z[1],T[n+64>>2]=a%1e3*1e3,z=[Math.floor(o/1e3)>>>0,(R=Math.floor(o/1e3),+Math.abs(R)>=1?R>0?Math.floor(R/4294967296)>>>0:~~+Math.ceil((R-+(~~R>>>0))/4294967296)>>>0:0)],w[n+72>>2]=z[0],w[n+76>>2]=z[1],T[n+80>>2]=o%1e3*1e3,z=[r.ino>>>0,(R=r.ino,+Math.abs(R)>=1?R>0?Math.floor(R/4294967296)>>>0:~~+Math.ceil((R-+(~~R>>>0))/4294967296)>>>0:0)],w[n+88>>2]=z[0],w[n+92>>2]=z[1],0},doMsync(e,t,n,r,i){if(!G.isFile(t.node.mode))throw new G.ErrnoError(43);if(r&2)return 0;var a=S.slice(e,e+n);G.msync(t,a,i,n,r)},varargs:void 0,get(){var e=w[K.varargs>>2];return K.varargs+=4,e},getp(){return K.get()},getStr(e){return ze(e)},getStreamFromFD(e){return G.getStreamChecked(e)}};function Be(e,t,n){K.varargs=n;try{var r=K.getStreamFromFD(e);switch(t){case 0:var i=K.get();if(i<0)return-28;for(;G.streams[i];)i++;return G.createStream(r,i).fd;case 1:case 2:return 0;case 3:return r.flags;case 4:var i=K.get();return r.flags|=i,0;case 5:var i=K.getp(),a=0;return C[i+a>>1]=2,0;case 6:case 7:return 0;case 16:case 8:return-28;case 9:return Se(28),-1;default:return-28}}catch(e){if(G===void 0||e.name!==`ErrnoError`)throw e;return-e.errno}}function Ve(e,t,n){K.varargs=n;try{var r=K.getStreamFromFD(e);switch(t){case 21509:return r.tty?0:-59;case 21505:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcgets){var i=r.tty.ops.ioctl_tcgets(r),a=K.getp();w[a>>2]=i.c_iflag||0,w[a+4>>2]=i.c_oflag||0,w[a+8>>2]=i.c_cflag||0,w[a+12>>2]=i.c_lflag||0;for(var o=0;o<32;o++)x[a+o+17>>0]=i.c_cc[o]||0;return 0}return 0;case 21510:case 21511:case 21512:return r.tty?0:-59;case 21506:case 21507:case 21508:if(!r.tty)return-59;if(r.tty.ops.ioctl_tcsets){for(var a=K.getp(),s=w[a>>2],c=w[a+4>>2],l=w[a+8>>2],u=w[a+12>>2],d=[],o=0;o<32;o++)d.push(x[a+o+17>>0]);return r.tty.ops.ioctl_tcsets(r.tty,t,{c_iflag:s,c_oflag:c,c_cflag:l,c_lflag:u,c_cc:d})}return 0;case 21519:if(!r.tty)return-59;var a=K.getp();return w[a>>2]=0,0;case 21520:return r.tty?-28:-59;case 21531:var a=K.getp();return G.ioctl(r,t,a);case 21523:if(!r.tty)return-59;if(r.tty.ops.ioctl_tiocgwinsz){var f=r.tty.ops.ioctl_tiocgwinsz(r.tty),a=K.getp();C[a>>1]=f[0],C[a+2>>1]=f[1]}return 0;case 21524:return r.tty?0:-59;case 21515:return r.tty?0:-59;default:return-28}}catch(e){if(G===void 0||e.name!==`ErrnoError`)throw e;return-e.errno}}function He(e,t,n,r){K.varargs=r;try{t=K.getStr(t),t=K.calculateAt(e,t);var i=r?K.get():0;return G.open(t,n,i).fd}catch(e){if(G===void 0||e.name!==`ErrnoError`)throw e;return-e.errno}}var q=1,Ue=()=>q,We=()=>{ue(``)},Ge=()=>Date.now(),Ke=()=>2147483648,qe=()=>Ke(),Je=()=>performance.now(),Ye=(e,t,n)=>S.copyWithin(e,t,t+n),Xe=e=>{var t=(e-v.buffer.byteLength+65535)/65536;try{return v.grow(t),ee(),1}catch{}},Ze=e=>{var t=S.length;e>>>=0;var n=Ke();if(e>n)return!1;for(var r=(e,t)=>e+(t-e%t)%t,i=1;i<=4;i*=2){var a=t*(1+.2/i);if(a=Math.min(a,e+100663296),Xe(Math.min(n,r(Math.max(e,a),65536))))return!0}return!1},Qe={},$e=()=>o||`./this.program`,et=()=>{if(!et.strings){var e={USER:`web_user`,LOGNAME:`web_user`,PATH:`/`,PWD:`/`,HOME:`/home/web_user`,LANG:(typeof navigator==`object`&&navigator.languages&&navigator.languages[0]||`C`).replace(`-`,`_`)+`.UTF-8`,_:$e()};for(var t in Qe)Qe[t]===void 0?delete e[t]:e[t]=Qe[t];var n=[];for(var t in e)n.push(`${t}=${e[t]}`);et.strings=n}return et.strings},tt=(e,t)=>{for(var n=0;n<e.length;++n)x[t++>>0]=e.charCodeAt(n);x[t>>0]=0},nt=(e,t)=>{var n=0;return et().forEach((r,i)=>{var a=t+n;T[e+i*4>>2]=a,tt(r,a),n+=r.length+1}),0},rt=(e,t)=>{var n=et();T[e>>2]=n.length;var r=0;return n.forEach(e=>r+=e.length+1),T[t>>2]=r,0},it=0,at=()=>be||it>0,ot=e=>{at()||(n.onExit&&n.onExit(e),y=!0),s(e,new _e(e))},st=(e,t)=>{ot(e)};function ct(e){try{var t=K.getStreamFromFD(e);return G.close(t),0}catch(e){if(G===void 0||e.name!==`ErrnoError`)throw e;return e.errno}}var lt=(e,t,n,r)=>{for(var i=0,a=0;a<n;a++){var o=T[t>>2],s=T[t+4>>2];t+=8;var c=G.read(e,x,o,s,r);if(c<0)return-1;if(i+=c,c<s)break;r!==void 0&&(r+=c)}return i};function ut(e,t,n,r){try{var i=lt(K.getStreamFromFD(e),t,n);return T[r>>2]=i,0}catch(e){if(G===void 0||e.name!==`ErrnoError`)throw e;return e.errno}}var dt=(e,t)=>t+2097152>>>0<4194305-!!e?(e>>>0)+t*4294967296:NaN;function ft(e,t,n,r,i){var a=dt(t,n);try{if(isNaN(a))return 61;var o=K.getStreamFromFD(e);return G.llseek(o,a,r),z=[o.position>>>0,(R=o.position,+Math.abs(R)>=1?R>0?Math.floor(R/4294967296)>>>0:~~+Math.ceil((R-+(~~R>>>0))/4294967296)>>>0:0)],w[i>>2]=z[0],w[i+4>>2]=z[1],o.getdents&&a===0&&r===0&&(o.getdents=null),0}catch(e){if(G===void 0||e.name!==`ErrnoError`)throw e;return e.errno}}var pt=(e,t,n,r)=>{for(var i=0,a=0;a<n;a++){var o=T[t>>2],s=T[t+4>>2];t+=8;var c=G.write(e,x,o,s,r);if(c<0)return-1;i+=c,r!==void 0&&(r+=c)}return i};function mt(e,t,n,r){try{var i=pt(K.getStreamFromFD(e),t,n);return T[r>>2]=i,0}catch(e){if(G===void 0||e.name!==`ErrnoError`)throw e;return e.errno}}var ht=e=>e%4==0&&(e%100!=0||e%400==0),gt=(e,t)=>{for(var n=0,r=0;r<=t;n+=e[r++]);return n},_t=[31,29,31,30,31,30,31,31,30,31,30,31],vt=[31,28,31,30,31,30,31,31,30,31,30,31],yt=(e,t)=>{for(var n=new Date(e.getTime());t>0;){var r=ht(n.getFullYear()),i=n.getMonth(),a=(r?_t:vt)[i];if(t>a-n.getDate())t-=a-n.getDate()+1,n.setDate(1),i<11?n.setMonth(i+1):(n.setMonth(0),n.setFullYear(n.getFullYear()+1));else return n.setDate(n.getDate()+t),n}return n},bt=(e,t)=>{x.set(e,t)},xt=(e,t,n,r)=>{var i=T[r+40>>2],a={tm_sec:w[r>>2],tm_min:w[r+4>>2],tm_hour:w[r+8>>2],tm_mday:w[r+12>>2],tm_mon:w[r+16>>2],tm_year:w[r+20>>2],tm_wday:w[r+24>>2],tm_yday:w[r+28>>2],tm_isdst:w[r+32>>2],tm_gmtoff:w[r+36>>2],tm_zone:i?ze(i):``},o=ze(n),s={"%c":`%a %b %d %H:%M:%S %Y`,"%D":`%m/%d/%y`,"%F":`%Y-%m-%d`,"%h":`%b`,"%r":`%I:%M:%S %p`,"%R":`%H:%M`,"%T":`%H:%M:%S`,"%x":`%m/%d/%y`,"%X":`%H:%M:%S`,"%Ec":`%c`,"%EC":`%C`,"%Ex":`%m/%d/%y`,"%EX":`%H:%M:%S`,"%Ey":`%y`,"%EY":`%Y`,"%Od":`%d`,"%Oe":`%e`,"%OH":`%H`,"%OI":`%I`,"%Om":`%m`,"%OM":`%M`,"%OS":`%S`,"%Ou":`%u`,"%OU":`%U`,"%OV":`%V`,"%Ow":`%w`,"%OW":`%W`,"%Oy":`%y`};for(var c in s)o=o.replace(new RegExp(c,`g`),s[c]);var l=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],u=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`];function d(e,t,n){for(var r=typeof e==`number`?e.toString():e||``;r.length<t;)r=n[0]+r;return r}function f(e,t){return d(e,t,`0`)}function p(e,t){function n(e){return e<0?-1:+(e>0)}var r;return(r=n(e.getFullYear()-t.getFullYear()))===0&&(r=n(e.getMonth()-t.getMonth()))===0&&(r=n(e.getDate()-t.getDate())),r}function m(e){switch(e.getDay()){case 0:return new Date(e.getFullYear()-1,11,29);case 1:return e;case 2:return new Date(e.getFullYear(),0,3);case 3:return new Date(e.getFullYear(),0,2);case 4:return new Date(e.getFullYear(),0,1);case 5:return new Date(e.getFullYear()-1,11,31);case 6:return new Date(e.getFullYear()-1,11,30)}}function h(e){var t=yt(new Date(e.tm_year+1900,0,1),e.tm_yday),n=new Date(t.getFullYear(),0,4),r=new Date(t.getFullYear()+1,0,4),i=m(n),a=m(r);return p(i,t)<=0?p(a,t)<=0?t.getFullYear()+1:t.getFullYear():t.getFullYear()-1}var g={"%a":e=>l[e.tm_wday].substring(0,3),"%A":e=>l[e.tm_wday],"%b":e=>u[e.tm_mon].substring(0,3),"%B":e=>u[e.tm_mon],"%C":e=>f((e.tm_year+1900)/100|0,2),"%d":e=>f(e.tm_mday,2),"%e":e=>d(e.tm_mday,2,` `),"%g":e=>h(e).toString().substring(2),"%G":e=>h(e),"%H":e=>f(e.tm_hour,2),"%I":e=>{var t=e.tm_hour;return t==0?t=12:t>12&&(t-=12),f(t,2)},"%j":e=>f(e.tm_mday+gt(ht(e.tm_year+1900)?_t:vt,e.tm_mon-1),3),"%m":e=>f(e.tm_mon+1,2),"%M":e=>f(e.tm_min,2),"%n":()=>`
6
+ `,"%p":e=>e.tm_hour>=0&&e.tm_hour<12?`AM`:`PM`,"%S":e=>f(e.tm_sec,2),"%t":()=>` `,"%u":e=>e.tm_wday||7,"%U":e=>{var t=e.tm_yday+7-e.tm_wday;return f(Math.floor(t/7),2)},"%V":e=>{var t=Math.floor((e.tm_yday+7-(e.tm_wday+6)%7)/7);if((e.tm_wday+371-e.tm_yday-2)%7<=2&&t++,!t){t=52;var n=(e.tm_wday+7-e.tm_yday-1)%7;(n==4||n==5&&ht(e.tm_year%400-1))&&t++}else if(t==53){var r=(e.tm_wday+371-e.tm_yday)%7;r!=4&&(r!=3||!ht(e.tm_year))&&(t=1)}return f(t,2)},"%w":e=>e.tm_wday,"%W":e=>{var t=e.tm_yday+7-(e.tm_wday+6)%7;return f(Math.floor(t/7),2)},"%y":e=>(e.tm_year+1900).toString().substring(2),"%Y":e=>e.tm_year+1900,"%z":e=>{var t=e.tm_gmtoff,n=t>=0;return t=Math.abs(t)/60,t=t/60*100+t%60,(n?`+`:`-`)+String(`0000`+t).slice(-4)},"%Z":e=>e.tm_zone,"%%":()=>`%`};for(var c in o=o.replace(/%%/g,`\0\0`),g)o.includes(c)&&(o=o.replace(new RegExp(c,`g`),g[c](a)));o=o.replace(/\0\0/g,`%`);var _=ke(o,!1);return _.length>t?0:(bt(_,e),_.length-1)},St=(e,t,n,r,i)=>xt(e,t,n,r),Ct=e=>n[`_`+e],wt=(e,t,n)=>Oe(e,S,t,n),Tt=e=>{var t=De(e)+1,n=Dn(t);return wt(e,n,t),n},Et=(e,t,n,r,i)=>{var a={string:e=>{var t=0;return e!=null&&e!==0&&(t=Tt(e)),t},array:e=>{var t=Dn(e.length);return bt(e,t),t}};function o(e){return t===`string`?ze(e):t===`boolean`?!!e:e}var s=Ct(e),c=[],l=0;if(r)for(var u=0;u<r.length;u++){var d=a[n[u]];d?(l===0&&(l=Tn()),c[u]=d(r[u])):c[u]=r[u]}var f=s.apply(null,c);function p(e){return l!==0&&En(l),o(e)}return f=p(f),f},Dt=(e,t,n,r)=>{var i=!n||n.every(e=>e===`number`||e===`boolean`);return t!==`string`&&i&&!r?Ct(e):function(){return Et(e,t,n,arguments,r)}},Ot=(e,t)=>{e<128?t.push(e):t.push(e%128|128,e>>7)},kt=e=>{for(var t={i:`i32`,j:`i64`,f:`f32`,d:`f64`,e:`externref`,p:`i32`},n={parameters:[],results:e[0]==`v`?[]:[t[e[0]]]},r=1;r<e.length;++r)n.parameters.push(t[e[r]]);return n},At=(e,t)=>{var n=e.slice(0,1),r=e.slice(1),i={i:127,p:127,j:126,f:125,d:124,e:111};t.push(96),Ot(r.length,t);for(var a=0;a<r.length;++a)t.push(i[r[a]]);n==`v`?t.push(0):t.push(1,i[n])},jt=(e,t)=>{if(typeof WebAssembly.Function==`function`)return new WebAssembly.Function(kt(t),e);var n=[1];At(t,n);var r=[0,97,115,109,1,0,0,0,1];Ot(n.length,r),r.push.apply(r,n),r.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var i=new WebAssembly.Module(new Uint8Array(r));return new WebAssembly.Instance(i,{e:{f:e}}).exports.f},Mt=[],Nt,Pt=e=>{var t=Mt[e];return t||(e>=Mt.length&&(Mt.length=e+1),Mt[e]=t=Nt.get(e)),t},Ft=(e,t)=>{if(J)for(var n=e;n<e+t;n++){var r=Pt(n);r&&J.set(r,n)}},J,It=e=>(J||(J=new WeakMap,Ft(0,Nt.length)),J.get(e)||0),Y=[],Lt=()=>{if(Y.length)return Y.pop();try{Nt.grow(1)}catch(e){throw e instanceof RangeError?`Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.`:e}return Nt.length-1},Rt=(e,t)=>{Nt.set(e,t),Mt[e]=Nt.get(e)},zt=(e,t)=>{var n=It(e);if(n)return n;var r=Lt();try{Rt(r,e)}catch(n){if(!(n instanceof TypeError))throw n;Rt(r,jt(e,t))}return J.set(e,r),r},Bt=e=>{J.delete(Pt(e)),Rt(e,null),Y.push(e)},Vt=function(e,t,n,r){e||=this,this.parent=e,this.mount=e.mount,this.mounted=null,this.id=G.nextInode++,this.name=t,this.mode=n,this.node_ops={},this.stream_ops={},this.rdev=r},Ht=365,Ut=146;Object.defineProperties(Vt.prototype,{read:{get:function(){return(this.mode&Ht)===Ht},set:function(e){e?this.mode|=Ht:this.mode&=~Ht}},write:{get:function(){return(this.mode&Ut)===Ut},set:function(e){e?this.mode|=Ut:this.mode&=~Ut}},isFolder:{get:function(){return G.isDir(this.mode)}},isDevice:{get:function(){return G.isChrdev(this.mode)}}}),G.FSNode=Vt,G.createPreloadedFile=Ie,G.staticInit();var Wt={g:Be,p:Ve,h:He,i:Ue,c:We,e:Ge,j:qe,b:Je,q:Ye,r:Ze,m:nt,n:rt,a:st,f:ct,o:ut,k:ft,d:mt,l:St},X=ge(),Gt=n._Highs_create=()=>(Gt=n._Highs_create=X.u)(),Kt=n._Highs_destroy=e=>(Kt=n._Highs_destroy=X.v)(e),qt=n._Highs_version=()=>(qt=n._Highs_version=X.w)(),Jt=n._Highs_run=e=>(Jt=n._Highs_run=X.x)(e),Yt=n._Highs_readModel=(e,t)=>(Yt=n._Highs_readModel=X.y)(e,t),Xt=n._Highs_getNumCol=e=>(Xt=n._Highs_getNumCol=X.z)(e),Zt=n._Highs_clearModel=e=>(Zt=n._Highs_clearModel=X.A)(e),Qt=n._Highs_setBoolOptionValue=(e,t,r)=>(Qt=n._Highs_setBoolOptionValue=X.B)(e,t,r),$t=n._Highs_setIntOptionValue=(e,t,r)=>($t=n._Highs_setIntOptionValue=X.C)(e,t,r),en=n._Highs_setDoubleOptionValue=(e,t,r)=>(en=n._Highs_setDoubleOptionValue=X.D)(e,t,r),tn=n._Highs_setStringOptionValue=(e,t,r)=>(tn=n._Highs_setStringOptionValue=X.E)(e,t,r),nn=n._Highs_getIntInfoValue=(e,t,r)=>(nn=n._Highs_getIntInfoValue=X.F)(e,t,r),rn=n._Highs_getDoubleInfoValue=(e,t,r)=>(rn=n._Highs_getDoubleInfoValue=X.G)(e,t,r),an=n._Highs_getInt64InfoValue=(e,t,r)=>(an=n._Highs_getInt64InfoValue=X.H)(e,t,r),on=n._Highs_getSolution=(e,t,r,i,a)=>(on=n._Highs_getSolution=X.I)(e,t,r,i,a),sn=n._Highs_getModelStatus=e=>(sn=n._Highs_getModelStatus=X.J)(e),cn=n._Highs_getObjectiveValue=e=>(cn=n._Highs_getObjectiveValue=X.K)(e),ln=n._Highs_getNumRow=e=>(ln=n._Highs_getNumRow=X.L)(e),un=n._Highs_setSolution=(e,t,r,i,a)=>(un=n._Highs_setSolution=X.M)(e,t,r,i,a),dn=n._Highs_setSparseSolution=(e,t,r,i)=>(dn=n._Highs_setSparseSolution=X.N)(e,t,r,i),fn=n._Highs_setCallback=(e,t,r)=>(fn=n._Highs_setCallback=X.O)(e,t,r),pn=n._Highs_startCallback=(e,t)=>(pn=n._Highs_startCallback=X.P)(e,t),mn=n._Highs_stopCallback=(e,t)=>(mn=n._Highs_stopCallback=X.Q)(e,t),hn=n._Highs_changeObjectiveOffset=(e,t)=>(hn=n._Highs_changeObjectiveOffset=X.R)(e,t),gn=n._Highs_getObjectiveOffset=(e,t)=>(gn=n._Highs_getObjectiveOffset=X.S)(e,t),_n=n._Highs_getRowName=(e,t,r)=>(_n=n._Highs_getRowName=X.T)(e,t,r),vn=n._Highs_getColName=(e,t,r)=>(vn=n._Highs_getColName=X.U)(e,t,r),yn=n._Highs_getColIntegrality=(e,t,r)=>(yn=n._Highs_getColIntegrality=X.V)(e,t,r),bn=n._Highs_getNumNz=e=>(bn=n._Highs_getNumNz=X.W)(e),xn=()=>(xn=X.X)(),Sn=n._malloc=e=>(Sn=n._malloc=X.Y)(e),Cn=n._free=e=>(Cn=n._free=X.Z)(e),wn=()=>(wn=X._)(),Tn=()=>(Tn=X.$)(),En=e=>(En=X.aa)(e),Dn=e=>(Dn=X.ba)(e);n.wasmMemory=v,n.ccall=Et,n.cwrap=Dt,n.addFunction=zt,n.removeFunction=Bt,n.setValue=xe,n.getValue=ye,n.UTF8ToString=ze,n.stringToUTF8=wt,n.FS=G;var On;N=function e(){On||kn(),On||(N=e)};function kn(){if(oe>0||(ne(),oe>0))return;function e(){On||(On=!0,n.calledRun=!0,!y&&(re(),r(n),n.onRuntimeInitialized&&n.onRuntimeInitialized(),ie()))}n.setStatus?(n.setStatus(`Running...`),setTimeout(function(){setTimeout(function(){n.setStatus(``)},1),e()},1)):e()}if(n.preInit)for(typeof n.preInit==`function`&&(n.preInit=[n.preInit]);n.preInit.length>0;)n.preInit.pop()();return kn(),t.ready})})()})),Ct=r({default:()=>wt});async function wt(e={}){let t=await xt(e);return new yt(t)}var Tt=n((()=>{St(),bt()}));bt();var Et=[`mip_max_nodes`,`mip_max_improving_sols`,`mip_max_leaves`,`simplex_iteration_limit`,`ipm_iteration_limit`],Dt=new Set([`timeLimit`,`outputFlag`,`presolve`,`solver`,`relativeGap`,`absoluteGap`,`wasmUrl`,`signal`,`onProgress`,`onIncumbent`,`relax`,`useWorker`,`objectiveOffset`,`initialValues`,...Et]);function Ot(e={}){if(e.threads!==void 0)throw Error(`Solver "HiGHS" does not support option "threads" (HiGHS WebAssembly runs single-threaded).`);if(e.verbose!==void 0)throw Error(`Solver "HiGHS" does not support option "verbose"; use "outputFlag" instead.`);for(let[t,n]of Object.entries(e))if(n!==void 0&&!Dt.has(t))throw Error(`Solver "HiGHS" does not support option "${t}".`);if(e.useWorker!==void 0&&typeof e.useWorker!=`boolean`)throw Error(`Invalid HiGHS option "useWorker": expected boolean, got ${typeof e.useWorker}.`);if(e.outputFlag!==void 0&&typeof e.outputFlag!=`boolean`)throw Error(`Invalid HiGHS option "outputFlag": expected boolean, got ${typeof e.outputFlag}.`);if(e.relax!==void 0&&typeof e.relax!=`boolean`)throw Error(`Invalid HiGHS option "relax": expected boolean, got ${typeof e.relax}.`);if(e.presolve!==void 0&&e.presolve!==`on`&&e.presolve!==`off`&&e.presolve!==`choose`)throw Error(`Invalid HiGHS option "presolve" (${String(e.presolve)}): expected "on", "off", or "choose".`);if(e.timeLimit!==void 0&&(typeof e.timeLimit!=`number`||!Number.isFinite(e.timeLimit)||e.timeLimit<0))throw Error(`Invalid HiGHS option "timeLimit" (${String(e.timeLimit)}): expected a finite non-negative number of seconds.`);if(e.relativeGap!==void 0&&(typeof e.relativeGap!=`number`||!Number.isFinite(e.relativeGap)||e.relativeGap<0))throw Error(`Invalid HiGHS option "relativeGap" (${String(e.relativeGap)}): expected a finite non-negative number.`);if(e.absoluteGap!==void 0&&(typeof e.absoluteGap!=`number`||!Number.isFinite(e.absoluteGap)||e.absoluteGap<0))throw Error(`Invalid HiGHS option "absoluteGap" (${String(e.absoluteGap)}): expected a finite non-negative number.`);if(e.objectiveOffset!==void 0&&(typeof e.objectiveOffset!=`number`||!Number.isFinite(e.objectiveOffset)))throw Error(`Invalid HiGHS option "objectiveOffset" (${String(e.objectiveOffset)}): expected a finite number.`);if(e.wasmUrl!==void 0&&e.wasmUrl!==null&&(typeof e.wasmUrl!=`string`||e.wasmUrl===``))throw Error(`Invalid HiGHS option "wasmUrl": expected a non-empty string or null.`)}var kt=null,At=null;async function jt(e){return e||lt()}async function Mt(e={}){let t=await jt(e.wasmUrl);return{isNode:!1,wasmUrl:t,key:t??`node`}}async function Nt(e={}){let{isNode:t,wasmUrl:n,key:r}=await Mt(e);if(kt&&At===r)return kt;At=r;let i=null;return i=(async()=>{let e=t?await ut():(await Promise.resolve().then(()=>(Tt(),Ct))).default;return t?await e():await e({locateFile:e=>e.endsWith(`.wasm`)?n:e})})().then(e=>e).catch(e=>{kt===i&&(kt=null,At=null);let t=e instanceof Error?e.message:String(e);throw Error(`[WaSHI] Failed to initialize HiGHS${n?` from "${n}"`:``}. Deploy the package's WASM asset or explicitly set wasmUrl; no CDN fallback is attempted. ${t}`,{cause:e})}),kt=i,i}async function Pt(e,t={}){if(Ot(t),t.signal?.aborted)return{result:{Status:`Interrupted`,StatusCode:17,HasPrimalSolution:!1,ObjectiveValue:NaN,Columns:{},Rows:[]},runTime:0};let n=await Nt(t);if(t.signal?.aborted)return{result:{Status:`Interrupted`,StatusCode:17,HasPrimalSolution:!1,ObjectiveValue:NaN,Columns:{},Rows:[]},runTime:0};let r=performance.now(),i={output_flag:t.outputFlag??!1};t.timeLimit!==void 0&&(i.time_limit=t.timeLimit),t.presolve!==void 0&&(i.presolve=t.presolve),t.solver!==void 0&&(i.solver=t.solver),t.relativeGap!==void 0&&(i.mip_rel_gap=t.relativeGap),t.absoluteGap!==void 0&&(i.mip_abs_gap=t.absoluteGap);for(let e of Et)t[e]!==void 0&&(i[e]=t[e]);let a=t.objectiveOffset??0,o=t.initialValues,s=!1;if(o){for(let[e,t]of Object.entries(o))if(t!==void 0){if(typeof t!=`number`||!Number.isFinite(t))throw Error(`Invalid initial value for column "${e}": ${String(t)} (must be a finite number).`);s=!0}}if(typeof n.withModel!=`function`)throw Error(`[WaSHI] HiGHS runtime is missing required withModel() API (legacy highs.solve fallback has been removed).`);return{result:n.withModel({format:`lp`,data:e},e=>{let c=!1;if(a!==0){if(typeof e.changeObjectiveOffset!=`function`)throw Error(`[WaSHI] HiGHS runtime does not support changeObjectiveOffset() for non-zero objectiveOffset.`);let t=typeof e.getObjectiveOffset==`function`?e.getObjectiveOffset():0;e.changeObjectiveOffset(t+a),c=!0}for(let[t,n]of Object.entries(i))e.options.set(t,n);let l=e.getDimensions(),u=[],d=!1;for(let t=0;t<l.numCols;t++){let n=e.getColIntegrality(t);n!==0&&(d=!0),u.push({name:e.getColName(t),type:n===1?`Integer`:`Continuous`})}if(s&&o){if(typeof e.setSolution!=`function`)throw Error(`HiGHS runtime does not support setting primal initial values (setSolution is unavailable).`);let t=new Map;for(let e=0;e<l.numCols;e++)t.set(u[e].name,e);for(let[e,n]of Object.entries(o))if(n!==void 0&&!t.has(e))throw Error(`Unknown column "${e}" in initialValues (column does not exist in the HiGHS LP model).`);let n=[],r=[];for(let e=0;e<l.numCols;e++){let t=u[e].name;if(Object.prototype.hasOwnProperty.call(o,t)){let i=o[t];i!==void 0&&(n.push(e),r.push(i))}}n.length>0&&(n.length===l.numCols?e.setSolution({colValue:r}):e.setSolution({indices:n,values:r}))}let f=null,p=null,m=0,h=e=>{let t=e?.data??{},n=typeof t.running_time==`number`&&Number.isFinite(t.running_time)?t.running_time:(performance.now()-r)/1e3,i=typeof t.mip_primal_bound==`number`&&Number.isFinite(t.mip_primal_bound)?t.mip_primal_bound:typeof t.objective_function_value==`number`&&Number.isFinite(t.objective_function_value)?t.objective_function_value:void 0,a=typeof t.mip_dual_bound==`number`&&Number.isFinite(t.mip_dual_bound)?t.mip_dual_bound:void 0,o=typeof t.mip_gap==`number`&&Number.isFinite(t.mip_gap)?t.mip_gap:void 0,s=i!==void 0&&a!==void 0?Math.abs(i-a):void 0,c=typeof t.mip_node_count==`bigint`?Number(t.mip_node_count):typeof t.mip_node_count==`number`&&Number.isFinite(t.mip_node_count)?t.mip_node_count:void 0,l=typeof t.mip_total_lp_iterations==`bigint`?Number(t.mip_total_lp_iterations):typeof t.simplex_iteration_count==`number`&&Number.isFinite(t.simplex_iteration_count)?t.simplex_iteration_count:typeof t.ipm_iteration_count==`number`&&Number.isFinite(t.ipm_iteration_count)?t.ipm_iteration_count:void 0,u=typeof e?.message==`string`&&e.message.trim().length>0?e.message.trim():void 0,d={elapsedTime:n,elapsedSeconds:n,...i===void 0?{}:{objectiveValue:i},...a===void 0?{}:{objectiveBound:a},...o===void 0?{}:{relativeGap:o},...s===void 0?{}:{absoluteGap:s},...c===void 0?{}:{nodes:c},...l===void 0?{}:{iterations:l},...u===void 0?{}:{message:u}};return p=d,d},g=e=>{let n=e?.data;if(!n||!(n.mip_solution instanceof Float64Array))return;let r=n.mip_solution,i={};for(let e=0;e<u.length&&e<r.length;e++)Object.defineProperty(i,u[e].name,{value:{Index:e,Type:u[e].type,Name:u[e].name,Primal:r[e]},enumerable:!0,writable:!0,configurable:!0});let a=typeof n.objective_function_value==`number`&&Number.isFinite(n.objective_function_value)?n.objective_function_value:typeof n.mip_primal_bound==`number`&&Number.isFinite(n.mip_primal_bound)?n.mip_primal_bound:NaN;Number.isFinite(a)&&(f={objectiveValue:a,...typeof n.mip_dual_bound==`number`&&Number.isFinite(n.mip_dual_bound)?{mipDualBound:n.mip_dual_bound}:{},...typeof n.mip_gap==`number`&&Number.isFinite(n.mip_gap)?{mipGap:n.mip_gap}:{},columns:i},t.onIncumbent?.(f))},_=!1;if(t.signal||t.onProgress||t.onIncumbent){let r=n.constants?.callbackType??{logging:0,simplexInterrupt:1,ipmInterrupt:2,mipSolution:3,mipImprovingSolution:4,mipLogging:5,mipInterrupt:6},i=e=>{if(t.signal?.aborted){_=!0,e.interrupt();return}t.onProgress&&(m++,t.onProgress(h(e)),t.signal?.aborted&&(_=!0,e.interrupt()))},a={[r.simplexInterrupt]:i,[r.ipmInterrupt]:i,[r.mipInterrupt]:i,[r.mipImprovingSolution]:e=>{g(e),t.onProgress&&!t.signal?.aborted&&(m++,t.onProgress(h(e)))},[r.mipLogging]:e=>{t.onProgress&&!t.signal?.aborted&&(m++,t.onProgress(h(e)))}};e.run(a)}else e.run();let v=e.getModelStatus();_&&(v=17);let y=ht[v]??`Unknown`,b=0,x=0;try{b=Number(e.info.get(`primal_solution_status`))}catch{}try{x=Number(e.info.get(`dual_solution_status`))}catch{}let S=n.constants?.solutionStatus?.feasible??2,C=b===S,w=x===S,T=C||w?e.getSolution():null,E=C,D={};if(!C&&f!==null)E=!0,D=f.columns;else for(let e=0;e<l.numCols;e++){let t=u[e],n={Index:e,Type:t.type,Name:t.name};C&&T&&(n.Primal=T.colValue[e]),!d&&w&&T&&(n.Dual=T.colDual[e]),Object.defineProperty(D,t.name,{value:n,enumerable:!0,writable:!0,configurable:!0})}let ee=[];for(let t=0;t<l.numRows;t++){let n=e.getRowName(t),r={Index:t,Name:n};C&&T&&(r.Primal=T.rowValue[t]),!d&&w&&T&&(r.Dual=T.rowDual[t]),ee.push(r)}let O=C?e.getObjectiveValue():f===null?NaN:f.objectiveValue,k,A;if(d){try{let t=Number(e.info.get(`mip_dual_bound`));Number.isFinite(t)&&(k=t)}catch{}k===void 0&&p&&p.objectiveBound!==void 0&&(k=p.objectiveBound);try{let t=Number(e.info.get(`mip_gap`));Number.isFinite(t)&&(A=t)}catch{}A===void 0&&p&&p.relativeGap!==void 0&&(A=p.relativeGap)}return{Status:ht[v]??y,StatusCode:v,PrimalSolutionStatus:b,DualSolutionStatus:x,HasPrimalSolution:E,IsMip:d,ObjectiveValue:O,ObjectiveOffsetApplied:c,MipDualBound:k,MipGap:A,Columns:D,Rows:ee}}),runTime:(performance.now()-r)/1e3}}function Ft(){let e=ct(`solvers/highs-worker.js`),t=typeof window.origin==`string`?window.origin:window.location?.origin;if(new URL(e).origin===t)return new Worker(e,{type:`module`});let n=URL.createObjectURL(new Blob([`import `+JSON.stringify(e)+`;`],{type:`text/javascript`}));try{let e=new Worker(n,{type:`module`}),t=()=>URL.revokeObjectURL(n);return e.addEventListener(`message`,t,{once:!0}),e.addEventListener(`error`,t,{once:!0}),e}catch(e){throw URL.revokeObjectURL(n),e}}var J=null,It=0,Y=new Map;function Lt(e,t){return e?{Status:`Interrupted`,StatusCode:17,HasPrimalSolution:!0,IsMip:!0,ObjectiveValue:e.objectiveValue,ObjectiveOffsetApplied:!0,...t?.objectiveBound===void 0?e.mipDualBound===void 0?{}:{MipDualBound:e.mipDualBound}:{MipDualBound:t.objectiveBound},...t?.relativeGap===void 0?e.mipGap===void 0?{}:{MipGap:e.mipGap}:{MipGap:t.relativeGap},Columns:e.columns,Rows:[]}:{Status:`Interrupted`,StatusCode:17,HasPrimalSolution:!1,ObjectiveValue:NaN,ObjectiveOffsetApplied:!0,...t?.objectiveBound===void 0?{}:{MipDualBound:t.objectiveBound},...t?.relativeGap===void 0?{}:{MipGap:t.relativeGap},Columns:{},Rows:[]}}function Rt(e){let t=Y.values().next().value;if(t&&!t.dispatched){t.dispatched=!0;try{t.kind===`WARMUP`?e.postMessage({type:`WARMUP`,id:t.id,options:t.workerOptions}):e.postMessage({type:`SOLVE`,id:t.id,lpString:t.lpString,options:t.workerOptions,...t.reportProgress?{reportProgress:!0}:{}})}catch(n){Y.delete(t.id),t.cleanupAbort?.(),t.reject(n),Rt(e)}}}function zt(){let e=J;e&&(J=null,e.terminate());for(let e of Y.values())e.dispatched=!1;if(Y.size>0)try{let e=Vt();if(e)Rt(e);else{let e=Error(`[WaSHI] Failed to recreate HiGHS Worker after interruption.`);for(let t of Array.from(Y.values()))Y.delete(t.id),t.cleanupAbort?.(),t.reject(e)}}catch(e){for(let t of Array.from(Y.values()))Y.delete(t.id),t.cleanupAbort?.(),t.reject(e)}}function Bt(){return typeof window<`u`&&typeof Worker<`u`&&typeof Worker?.prototype?.unref!=`function`}function Vt(){if(!Bt())return null;if(!J){let e;try{e=Ft(),e.onmessage=t=>{let{type:n,id:r,result:i,runTime:a,error:o,progress:s,incumbent:c}=t.data,l=Y.get(r);if(l){if(n===`SOLVE_PROGRESS`){if(l.kind===`SOLVE`&&s){l.lastProgress=s;try{l.onProgress?.(s)}catch(e){let t=Y.get(r);if(t){let n=Y.keys().next().value;Y.delete(r),t.cleanupAbort?.(),n===r&&zt(),t.reject(e)}}}return}if(n===`SOLVE_INCUMBENT`){l.kind===`SOLVE`&&c&&(l.lastIncumbent=c);return}Y.delete(r),l.cleanupAbort?.(),l.kind===`WARMUP`?n===`WARMUP_SUCCESS`?(J===e&&l.wasmUrl,l.resolve()):l.reject(Error(o||`Worker warmup failed`)):n===`SOLVE_SUCCESS`?(J===e&&l.wasmUrl,l.resolve({result:i,runTime:a})):l.reject(Error(o||`Worker solve failed`)),J===e&&Rt(e)}};let t=t=>{if(J===e){J=null,e.terminate();for(let e of Y.values())e.cleanupAbort?.(),e.reject(t);Y.clear()}};e.onerror=e=>t(Error(`[WaSHI] HiGHS Worker failed to load or execute. Check Worker assets, CORS and CSP. ${e?.message||``}`)),e.onmessageerror=()=>t(Error(`[WaSHI] Could not deserialize the HiGHS Worker response.`)),J=e}catch(e){throw J=null,e}}return J}function Ht(e){let t=typeof window<`u`?typeof window.origin==`string`?window.origin:window.location?.origin:void 0;return e.useWorker??(typeof window<`u`&&t!==`null`&&!t?.startsWith(`file:`))}function Ut(e){if(e.useWorker===!0&&!Bt())throw Error(`[WaSHI] Web Worker execution was requested (useWorker: true), but browser Web Workers are unavailable in this environment.`);return Ht(e)?Vt():null}function Wt(e,t){let{signal:n,onProgress:r,onIncumbent:i,...a}=e,o={};for(let[e,t]of Object.entries(a)){if(typeof t==`function`)throw Error(`[WaSHI] HiGHS Worker option "${e}" cannot be a function (functions cannot be cloned across Web Worker boundaries).`);o[e]=t}return o.wasmUrl=t,o}function X(e,t,n){if(!e)return;let r=()=>{let e=Y.get(t.id);if(!e)return;let r=Y.keys().next().value;Y.delete(t.id),e.cleanupAbort?.(),r===t.id&&zt(),n()};e.addEventListener(`abort`,r,{once:!0}),t.cleanupAbort=()=>e.removeEventListener(`abort`,r)}async function Gt(e,t={}){if(Ot(t),t.signal?.aborted)return{result:Lt(),runTime:0};let n=await jt(t.wasmUrl);if(t.signal?.aborted)return{result:Lt(),runTime:0};let r=Ut(t);if(!r)return Pt(e,t);let{signal:i,onProgress:a}=t,o=Wt(t,n),s=!!(a||i),c=`req_${++It}`,l=performance.now();return new Promise((t,u)=>{let d={kind:`SOLVE`,id:c,lpString:e,workerOptions:o,wasmUrl:n,reportProgress:s,startTime:l,onProgress:a,resolve:t,reject:u};X(i,d,()=>{let e=(performance.now()-d.startTime)/1e3;d.resolve({result:Lt(d.lastIncumbent,d.lastProgress),runTime:e})}),Y.set(c,d),Rt(r)})}function Kt(e,t){if(typeof t==`number`)switch(t){case 0:return`NotSolved`;case 1:case 2:case 3:case 4:case 5:return`Error`;case 6:return`Unknown`;case 7:return`Optimal`;case 8:return`Infeasible`;case 9:return`InfeasibleOrUnbounded`;case 10:return`Unbounded`;case 11:return`ObjectiveBound`;case 12:return`ObjectiveTarget`;case 13:return`TimeLimit`;case 14:return`IterationLimit`;case 15:return`Unknown`;case 16:return`SolutionLimit`;case 17:return`Interrupted`;case 18:return`MemoryLimit`}if(typeof e!=`string`)return`Unknown`;let n=e.trim();if(!n)return`Unknown`;switch(n){case`Optimal`:return`Optimal`;case`Infeasible`:return`Infeasible`;case`Unbounded`:return`Unbounded`;case`Primal infeasible or unbounded`:case`InfeasibleOrUnbounded`:return`InfeasibleOrUnbounded`;case`Time limit reached`:case`TimeLimit`:return`TimeLimit`;case`Iteration limit reached`:case`IterationLimit`:return`IterationLimit`;case`Solution limit reached`:case`SolutionLimit`:return`SolutionLimit`;case`Memory limit reached`:case`MemoryLimit`:return`MemoryLimit`;case`Bound on objective reached`:case`ObjectiveBound`:return`ObjectiveBound`;case`Target for objective reached`:case`ObjectiveTarget`:return`ObjectiveTarget`;case`Interrupted`:case`User interrupt`:return`Interrupted`;case`Feasible`:return`Feasible`;case`Not Set`:return`NotSolved`;case`Load error`:case`Model error`:case`Presolve error`:case`Solve error`:case`Postsolve error`:case`Error`:return`Error`;case`Empty`:case`Unknown`:return`Unknown`}return`Unknown`}function qt(e,t,n){switch(Kt(e,t)){case`Optimal`:return`Optimal`;case`Infeasible`:return`Infeasible`;case`Unbounded`:return`Unbounded`;case`TimeLimit`:return`TimeLimit`;case`IterationLimit`:return`IterationLimit`;case`Feasible`:return`Feasible`;case`ObjectiveBound`:case`ObjectiveTarget`:case`SolutionLimit`:return n===!1?`Unknown`:`Feasible`;case`MemoryLimit`:case`Interrupted`:return n?`Feasible`:`Unknown`;case`NotSolved`:return`NotSolved`;case`Error`:return`Error`;default:return`Unknown`}}var Jt=class e{static capabilities={supportsMIP:!0,supportsQP:!0,supportsWarmStart:!0};name=`HiGHS`;version=`1.15.1`;capabilities=e.capabilities;options;constructor(e={}){this.options=e}async solve(e,t={},n={}){let r=Ke(t),i=r?n:t,a={...this.options,...i};Ot(a);let o=e.objective?.constant??0;if(typeof o!=`number`||!Number.isFinite(o))throw Error(`Solver "${this.name}" encountered non-finite objective constant: ${String(o)}.`);let s=o===0?0:o;for(let t of e.variables)M(t);let{lpString:c,nameToVar:l,nameToConstraint:u}=r?t:Ye(e,{relax:a.relax}),d=Object.create(null),f=!1,p=new Set;for(let[e,t]of l.entries()){p.add(t);let n=ae(t);n!==void 0&&(d[e]=n,f=!0)}for(let t of e.variables)if(!p.has(t))throw Error(`LP export symbol map (nameToVar) is missing model variable "${t.name}".`);let m=a;(s!==0||f||m.initialValues!==void 0)&&(m={...m,...s===0?{}:{objectiveOffset:s},...f?{initialValues:d}:{}});let{result:h,runTime:g}=await Gt(c,m),_=h?.ObjectiveOffsetApplied?0:s,v=Kt(h?.Status,h?.StatusCode),y=a.relax?!1:typeof h?.IsMip==`boolean`?h.IsMip:e.variables.some(e=>e.type===`Integer`||e.type===`Binary`),b=h?.HasPrimalSolution===!0,x=qt(h?.Status,h?.StatusCode,b),S=null;b&&typeof h?.ObjectiveValue==`number`&&Number.isFinite(h.ObjectiveValue)&&(S=h.ObjectiveValue+_);let C,w,T;if(typeof h?.MipDualBound==`number`&&Number.isFinite(h.MipDualBound)?C=h.MipDualBound+_:!y&&v===`Optimal`&&S!==null&&(C=S),S!==null&&C!==void 0&&Number.isFinite(C)&&(T=Math.abs(S-C)),_!==0&&y&&S!==null&&C!==void 0&&T!==void 0){if(T===0)w=0;else if(Math.abs(S)>0){let e=T/Math.abs(S);w=Number.isFinite(e)?e:void 0}else w=void 0}else typeof h?.MipGap==`number`&&Number.isFinite(h.MipGap)?w=h.MipGap:y&&v===`Optimal`&&b&&(T===void 0||T===0)&&(w=0);if(!b)return{status:x,terminationStatus:v,hasPrimalSolution:!1,objectiveValue:null,...C===void 0?{}:{objectiveBound:C},...w===void 0?{}:{relativeGap:w},...T===void 0?{}:{absoluteGap:T},values:{},reducedCosts:{},duals:{},slacks:{},runTime:g,raw:h};let E=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})},D={},ee={},O={},k={};if(h.Columns)for(let[e,t]of Object.entries(h.Columns)){let n=l.get(e);if(n){if(typeof t.Primal==`number`&&Number.isFinite(t.Primal)){let e=Math.abs(t.Primal)<1e-9?0:t.Primal;!a.relax&&(n.type===`Integer`||n.type===`Binary`)&&Math.abs(e-Math.round(e))<=1e-5&&(e=Math.round(e)+0),E(D,n.name,e)}typeof t.Dual==`number`&&Number.isFinite(t.Dual)&&E(O,n.name,Math.abs(t.Dual)<1e-9?0:t.Dual)}}if(h.Rows){let e=Array.isArray(h.Rows)?h.Rows:Object.values(h.Rows);for(let t of e){let e=t.Name,n=e?u.get(e):void 0;if(n&&(typeof t.Dual==`number`&&Number.isFinite(t.Dual)&&E(ee,n.name,Math.abs(t.Dual)<1e-9?0:t.Dual),typeof t.Primal==`number`&&Number.isFinite(t.Primal))){let e=n.rhs-t.Primal;E(k,n.name,Math.abs(e)<1e-9?0:e)}}}return{status:x,terminationStatus:v,hasPrimalSolution:!0,objectiveValue:S,...C===void 0?{}:{objectiveBound:C},...w===void 0?{}:{relativeGap:w},...T===void 0?{}:{absoluteGap:T},values:D,reducedCosts:O,duals:ee,slacks:k,runTime:g,raw:h}}};function Yt(){et(`highs`,e=>new Jt(e)),tt(e=>new Jt(e))}Yt(),bt();var Xt=typeof document<`u`?document.currentScript?.src:null,Zt=Xt?new URL(`.`,Xt).href:null;function Qt(e){if(!Zt)throw Error(`[WaSHI] Load the browser IIFE using an external script src, or use the browser ESM build.`);return new URL(e,Zt).href}function $t(){return Qt(`solvers/pumpkin.wasm`)}function en(){function e(e){let t,n;try{let r=d(e,_.__wbindgen_malloc,_.__wbindgen_realloc),i=g,a=_.check_json(r,i);return t=a[0],n=a[1],o(a[0],a[1])}finally{_.__wbindgen_free(t,n,1)}}function t(e,t){let n,r;try{let i=d(e,_.__wbindgen_malloc,_.__wbindgen_realloc),s=g,c=_.check_with_callback(i,s,u(t)?0:a(t));return n=c[0],r=c[1],o(c[0],c[1])}finally{_.__wbindgen_free(n,r,1)}}function n(e){let t,n;try{let r=d(e,_.__wbindgen_malloc,_.__wbindgen_realloc),i=g,a=_.solve_json(r,i);return t=a[0],n=a[1],o(a[0],a[1])}finally{_.__wbindgen_free(t,n,1)}}function r(e,t,n){let r,i;try{let s=d(e,_.__wbindgen_malloc,_.__wbindgen_realloc),c=g,l=_.solve_with_callback(s,c,u(t)?0:a(t),u(n)?0:a(n));return r=l[0],i=l[1],o(l[0],l[1])}finally{_.__wbindgen_free(r,i,1)}}function i(){return{__proto__:null,"./pumpkin_bg.js":{__proto__:null,__wbg___wbindgen_boolean_get_4f1baf9a00be3c74:function(e){let t=e,n=typeof t==`boolean`?t:void 0;return u(n)?16777215:+!!n},__wbg___wbindgen_is_undefined_be5b34249ff1fc15:function(e){return e===void 0},__wbg___wbindgen_throw_4c88d8bf264fd984:function(e,t){throw Error(o(e,t))},__wbg_call_40b008ba32f73991:function(){return l(function(e,t){return e.call(t)},arguments)},__wbg_call_a410eb4b59ed5965:function(){return l(function(e,t,n){return e.call(t,n)},arguments)},__wbg_now_e7c6795a7f81e10f:function(e){return e.now()},__wbg_performance_7e4e4494fdc9d07a:function(e){return e.performance},__wbg_static_accessor_GLOBAL_THIS_003ee833af9699fc:function(){let e=typeof globalThis>`u`?void 0:globalThis;return u(e)?0:a(e)},__wbg_static_accessor_GLOBAL_e4293fb22cbe77da:function(){let e=typeof globalThis>`u`?void 0:globalThis;return u(e)?0:a(e)},__wbg_static_accessor_SELF_53bb20457401453d:function(){let e=typeof self>`u`?void 0:self;return u(e)?0:a(e)},__wbg_static_accessor_WINDOW_b5e0810bfecb7feb:function(){let e=typeof window>`u`?void 0:window;return u(e)?0:a(e)},__wbindgen_generic_0000000000000001:function(e,t){return o(e,t)},__wbindgen_init_externref_table:function(){let e=_.__wbindgen_externrefs;e.set(0,void 0),e.set(1024,void 0),e.set(1025,null),e.set(1026,!0),e.set(1027,!1)}}}}function a(e){let t=_.__externref_table_alloc();return _.__wbindgen_externrefs.set(t,e),t}function o(e,t){return e>>>=0,m(c().subarray(e,e+t))}let s=null;function c(){return(s===null||s.byteLength===0)&&(s=new Uint8Array(_.memory.buffer)),s}function l(e,t){try{return e.apply(this,t)}catch(e){let t=a(e);_.__wbindgen_exn_store(t)}}function u(e){return e==null}function d(e,t,n){if(n===void 0){let n=h.encode(e),r=t(n.length,1)>>>0;return c().subarray(r,r+n.length).set(n),g=n.length,r}let r=e.length,i=t(r,1)>>>0,a=c(),o=0;for(;o<r;o++){let t=e.charCodeAt(o);if(t>127)break;a[i+o]=t}if(o!==r){o!==0&&(e=e.slice(o)),i=n(i,r,r=o+e.length*3,1)>>>0;let t=c().subarray(i+o,i+r),a=h.encodeInto(e,t);o+=a.written,i=n(i,r,o,1)>>>0}return g=o,i}let f=new TextDecoder(`utf-8`,{ignoreBOM:!0});f.decode();let p=0;function m(e){return p+=e.length,p>=2146435072&&(f=new TextDecoder(`utf-8`,{ignoreBOM:!0}),f.decode(),p=e.length),f.decode(e)}let h=new TextEncoder;`encodeInto`in h||(h.encodeInto=function(e,t){let n=h.encode(e);return t.set(n),{read:e.length,written:n.length}});let g=0,_;function v(e,t){if(_=e.exports,s=null,!_||!(_.memory instanceof WebAssembly.Memory)||typeof _.__wbindgen_start!=`function`||typeof _.__wbindgen_malloc!=`function`||typeof _.__wbindgen_free!=`function`||typeof _.check_json!=`function`||typeof _.check_with_callback!=`function`||typeof _.solve_json!=`function`||typeof _.solve_with_callback!=`function`)throw Error(`[WaSHI] Invalid Pumpkin WebAssembly module: missing expected solver exports.`);return _.__wbindgen_start(),_}async function y(e,t){if(typeof Response==`function`&&e instanceof Response){if(!e.ok)throw Error(`failed to fetch Wasm: ${e.status} ${e.statusText} fetching '${e.url}'`);if(typeof WebAssembly.instantiateStreaming==`function`)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if(n(e.type)&&e.headers.get(`Content-Type`)!==`application/wasm`)console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t);else throw t}let r=await e.arrayBuffer();return await WebAssembly.instantiate(r,t)}{let n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}function n(e){switch(e){case`basic`:case`cors`:case`default`:return!0}return!1}}let b;async function x(e){return _===void 0?(b===void 0&&(b=S(e),b.catch(()=>{b=void 0})),b):_}async function S(e){e!==void 0&&(Object.getPrototypeOf(e)===Object.prototype?{module_or_path:e}=e:console.warn(`using deprecated parameters for the initialization function; pass a single object instead`));let t=i();(typeof e==`string`||typeof Request==`function`&&e instanceof Request||typeof URL==`function`&&e instanceof URL)&&(e=fetch(e));let{instance:n,module:r}=await y(await e,t);return v(n,r)}return{check_json:e,check_with_callback:t,solve_json:n,solve_with_callback:r,__wbg_init:x}}async function tn(e){let t=en();return await t.__wbg_init({module_or_path:e}),{check_json:t.check_json,check_with_callback:t.check_with_callback,solve_json:t.solve_json,solve_with_callback:t.solve_with_callback}}var nn=r({readBundledPumpkinWasmBytes:()=>an,readPumpkinWasmFileUrl:()=>rn});async function rn(){throw Error(`This distribution is for browsers. Use the npm entry in Node.js.`)}async function an(){throw Error(`This distribution is for browsers. Use the npm entry in Node.js.`)}var on=n((()=>{})),sn=4,cn=null,ln=new Map,un=new Set,dn=0;function fn(){return!1}function pn(e){return e.byteLength>=8&&e[0]===0&&e[1]===97&&e[2]===115&&e[3]===109}function mn(){return cn}function hn(){if(typeof Worker>`u`||typeof window>`u`||typeof Worker.prototype.unref==`function`)return!1;let e=typeof window.origin==`string`?window.origin:(()=>{try{return window.location?.origin}catch{return}})();return!(!e||e===`null`||e.startsWith(`file:`))}async function gn(e){if(typeof fetch!=`function`)throw Error(`[WaSHI] Global fetch() is unavailable to load Pumpkin WebAssembly from "${e}"; no CDN fallback is attempted.`);let t;try{t=await fetch(e)}catch(t){throw Error(`[WaSHI] Failed to fetch pumpkin.wasm from "${e}" (no CDN fallback is attempted): ${t instanceof Error?t.message:String(t)}. Ensure pumpkin.wasm is hosted cleanly or call setPumpkinWasmUrl(url).`)}if(!t.ok)throw Error(`[WaSHI] Failed to fetch pumpkin.wasm from "${e}": HTTP ${t.status} ${t.statusText}; no CDN fallback is attempted.`);let n=t.headers?.get(`content-type`)?.toLowerCase()??``;if(n.includes(`text/html`))throw Error(`[WaSHI] Invalid response while loading pumpkin.wasm from "${e}": received HTML ("${n}") instead of a WebAssembly binary; no CDN fallback is attempted.`);let r=await t.arrayBuffer(),i=new Uint8Array(r);if(!pn(i))throw Error(`[WaSHI] Invalid WebAssembly binary loaded from "${e}": expected \\0asm magic header; no CDN fallback is attempted.`);return i}function _n(e){if(e===void 0)return cn;if(e!==null&&typeof e!=`string`)throw Error(`Invalid pumpkin.wasm URL: expected string or null, got ${typeof e}.`);if(e===``)throw Error(`Invalid pumpkin.wasm URL: expected non-empty string or null (received empty string "").`);return e}async function vn(e){if(e!==null){if(fn()&&e.startsWith(`file://`)){let{readPumpkinWasmFileUrl:t}=await Promise.resolve().then(()=>(on(),nn)),n=await t(new URL(e));if(!pn(n))throw Error(`[WaSHI] Invalid WebAssembly binary at "${e}": expected \\0asm magic header.`);return n}return gn(e)}if(fn()&&typeof window>`u`){let{readBundledPumpkinWasmBytes:e}=await Promise.resolve().then(()=>(on(),nn)),t=await e();if(!pn(t))throw Error(`[WaSHI] Bundled pumpkin.wasm on disk has an invalid WebAssembly magic header.`);return t}return gn($t())}async function yn(e){let t=_n(e),n=t??`__bundled__`,r=ln.get(n);if(r)return ln.delete(n),ln.set(n,r),r;let i=dn,a=null;for(a=(async()=>{try{let e=await tn(await vn(t));return dn===i&&ln.get(n)===a&&un.add(n),e}catch(e){throw dn===i&&(un.delete(n),ln.get(n)===a&&ln.delete(n)),t!==null&&e instanceof Error&&e.message.includes(`Invalid Pumpkin WebAssembly module`)?Error(`[WaSHI] Invalid Pumpkin WebAssembly module loaded from "${t}" (${e.message}); no CDN fallback is attempted.`):e}})();ln.size>=sn;){let e=ln.keys().next().value;if(e===void 0)break;ln.delete(e),un.delete(e)}return ln.set(n,a),a}function bn(){let e=Qt(`solvers/pumpkin-worker.js`),t=typeof window.origin==`string`?window.origin:window.location?.origin;if(new URL(e).origin===t)return new Worker(e,{type:`module`});let n=URL.createObjectURL(new Blob([`import `+JSON.stringify(e)+`;`],{type:`text/javascript`}));try{let e=new Worker(n,{type:`module`}),t=()=>URL.revokeObjectURL(n);return e.addEventListener(`message`,t,{once:!0}),e.addEventListener(`error`,t,{once:!0}),e}catch(e){throw URL.revokeObjectURL(n),e}}function xn(e){if(e===``)throw Error(`Invalid pumpkin.wasm URL: expected non-empty string or null (received empty string "").`);if(e!=null&&typeof e!=`string`)throw Error(`Invalid pumpkin.wasm URL: expected string or null, got ${typeof e}.`)}function Sn(e){return{status:`Unknown`,values:[],boolValues:[],runTime:Math.max((performance.now()-e)/1e3,1e-6)}}function Cn(e,t){let n=Math.max((performance.now()-e)/1e3,1e-6);return t?{status:`Feasible`,terminationStatus:`Interrupted`,objectiveValue:t.objectiveValue,values:t.values,boolValues:t.boolValues,runTime:n}:{status:`Unknown`,terminationStatus:`Interrupted`,objectiveValue:null,values:[],boolValues:[],runTime:n}}function wn(e={}){let t=e.workerFactory??bn,n=null,r=1,i=null,a=[],o=new Set,s=!1;xn(e.wasmUrl);let c=e=>(xn(e),typeof e==`string`?e:`__bundled__`),l=e=>{let t=c(e);for(o.delete(t),o.add(t);o.size>4;){let e=o.keys().next().value;if(e===void 0)break;o.delete(e)}},u=()=>{o.clear(),n&&=(n.onmessage=null,n.onerror=null,n.onmessageerror=null,n.terminate(),null)},d=e=>{i===e&&(i=null),e.cleanupAbort?.()},f=(e,t)=>{d(e),e.resolve(t),v()},p=(e,t)=>{d(e),e.resolve(t),v()},m=(e,t)=>{d(e),e.reject(t),v()},h=e=>{e.type===`check`?f(e,Sn(e.startTimeMs)):p(e,Cn(e.startTimeMs,e.lastIncumbent))},g=(e,t,n)=>{if(typeof e!=`string`)throw Error(`Pumpkin worker response is missing canonical responseJson string.`);let r=JSON.parse(e);if(!r)throw Error(`Pumpkin worker returned an empty success payload.`);if(r.error)throw Error(r.error);return{...r,runTime:typeof t==`number`?t:Math.max((performance.now()-n)/1e3,1e-6)}},_=()=>{if(n)return n;let e=t();return e.onmessage=t=>{let r=t.data,a=i;if(n===e&&r&&a&&r.id===a.id){if(r.type===`SOLVE_PROGRESS`){if(a.type!==`solve`)return;try{if(typeof r.payloadJson!=`string`)throw Error(`Pumpkin worker SOLVE_PROGRESS is missing canonical payloadJson string.`);let t=JSON.parse(r.payloadJson);if(!t)throw Error(`Pumpkin worker SOLVE_PROGRESS returned an empty incumbent payload.`);if(a.lastIncumbent=t,a.onProgress){let e=typeof r.elapsedTime==`number`?r.elapsedTime:Math.max((performance.now()-a.startTimeMs)/1e3,1e-6);a.onProgress({elapsedTime:e,elapsedSeconds:e,objectiveValue:t.objectiveValue})}if(n!==e||i!==a)return;a.signal?.aborted&&(u(),h(a))}catch(t){n===e&&i===a&&(u(),m(a,t))}return}if(r.type===`CHECK_SUCCESS`){if(a.type!==`check`){u(),m(a,Error(`Received "CHECK_SUCCESS" for a solve task.`));return}try{let e=g(r.responseJson,r.runTime,a.startTimeMs);l(a.wasmUrl),f(a,e)}catch(t){n===e&&i===a&&(u(),m(a,t))}return}if(r.type===`SOLVE_SUCCESS`){if(a.type!==`solve`){u(),m(a,Error(`Received "SOLVE_SUCCESS" for a check task.`));return}try{let e=g(r.responseJson,r.runTime,a.startTimeMs);l(a.wasmUrl),p(a,e)}catch(t){n===e&&i===a&&(u(),m(a,t))}return}if(r.type===`SOLVER_ERROR`){let e=typeof r.error==`string`?r.error:`Pumpkin worker execution failed.`;m(a,Error(e))}}},e.onerror=t=>{if(n!==e)return;let r=i;if(u(),r){let e=t?.message||`Pumpkin Web Worker encountered an unexpected error.`;m(r,Error(e))}},e.onmessageerror=()=>{if(n!==e)return;let t=i;u(),t&&m(t,Error(`Failed to deserialize message from Pumpkin Web Worker.`))},n=e,e},v=()=>{if(!(i||s))for(;a.length>0;){let e=a.shift();if(e.signal?.aborted){e.type===`check`?e.resolve(Sn(e.startTimeMs)):e.resolve(Cn(e.startTimeMs,e.lastIncumbent));continue}if(i=e,e.startTimeMs=performance.now(),e.signal){let t=()=>{i===e&&(u(),h(e))};e.signal.addEventListener(`abort`,t,{once:!0}),e.cleanupAbort=()=>e.signal?.removeEventListener(`abort`,t)}try{_().postMessage({id:e.id,type:e.type,requestJson:e.requestJson,wasmUrl:e.wasmUrl})}catch(t){i===e&&(u(),m(e,t))}return}},y=t=>{let n=t===void 0?e.wasmUrl===void 0?mn():e.wasmUrl:t;return xn(n),n??null},b=e=>new Promise((t,n)=>{a.push(e(t,n)),v()});return{check(e,t){if(s)return Promise.reject(Error(`[WaSHI] Pumpkin worker client has been disposed.`));if(t?.signal?.aborted)return Promise.resolve(Sn(performance.now()));let n=y(e.wasmUrl);return b((i,a)=>({id:r++,type:`check`,requestJson:e.requestJson,wasmUrl:n,signal:t?.signal,startTimeMs:performance.now(),lastIncumbent:null,resolve:i,reject:a}))},solve(e,t){if(s)return Promise.reject(Error(`[WaSHI] Pumpkin worker client has been disposed.`));if(t?.signal?.aborted)return Promise.resolve(Cn(performance.now(),null));let n=y(e.wasmUrl);return b((i,a)=>({id:r++,type:`solve`,requestJson:e.requestJson,wasmUrl:n,signal:t?.signal,onProgress:t?.onProgress,startTimeMs:performance.now(),lastIncumbent:null,resolve:i,reject:a}))},isWarmed(e){return!s&&n!==null&&o.has(c(y(e)))},dispose(){for(s=!0,u();a.length>0;){let e=a.shift();e.cleanupAbort?.(),e.reject(Error(`[WaSHI] Pumpkin worker client disposed.`))}if(i){let e=i;i=null,e.cleanupAbort?.(),e.reject(Error(`[WaSHI] Pumpkin worker client disposed.`))}}}}var Tn=null;function En(){return Tn||=wn(),Tn}var Dn=1073741823,On=2147483646,kn=1e-6;function Z(e){return Object.is(e,-0)||e===0?0:e}function An(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Q(e,t){if(typeof e!=`number`||Number.isNaN(e))throw Error(`PumpkinSolver encountered non-finite numeric value in ${t}.`);if(!Number.isFinite(e))throw Error(`PumpkinSolver only supports bounded finite integers (${t}: got ${e}).`);if(!Number.isInteger(e))throw Error(`PumpkinSolver only supports integer values (${t}: got ${e}).`);let n=Z(e);if(n<-1073741823||n>Dn)throw Error(`Value out of Pumpkin safe 32-bit integer range [-${Dn}, ${Dn}] (${t}: got ${n}).`);return n}function jn(e){if(e===void 0||e===1/0)return null;if(typeof e!=`number`||Number.isNaN(e)||e<0||!Number.isFinite(e))throw Error(`Invalid timeLimit (${String(e)}): expected a finite non-negative number of seconds.`);if(e===0)return 0;let t=Math.round(e*1e3);if(t>2**53-1)throw Error(`timeLimit (${e}s) exceeds safe millisecond range.`);return Math.max(1,t)}function Mn(e){return e instanceof w||typeof e==`object`&&!!e&&`quadTerms`in e}function Nn(e,t,n){if(e.initialValue===void 0)return;if(typeof e.initialValue!=`number`||!Number.isFinite(e.initialValue))throw Error(`Variable "${e.name}" has invalid initialValue: ${String(e.initialValue)} (initialValue must be a finite number).`);if(e.initialValue<t-kn||e.initialValue>n+kn)throw Error(`Variable "${e.name}" has initialValue (${e.initialValue}) outside its bounds [${t}, ${n}] (tolerance ${kn}).`);let r=Z(Math.round(e.initialValue));if(Math.abs(e.initialValue-r)>kn||r<t||r>n)throw Error(`Variable "${e.name}" of type "${e.type}" has non-integral or out-of-domain initialValue: ${e.initialValue} (must be within ${kn} of an integer in [${t}, ${n}]).`);return Q(r,`initialValue of variable "${e.name}"`)}function Pn(e){let t=[],n=new Map,r=!1;for(let i=0;i<e.length;i++){let a=e[i],o=String(a.type).toLowerCase();if(o===`continuous`||o===`cont`)throw Error(`PumpkinSolver does not support Continuous variable "${a.name}". Use an Integer or Binary variable, or select a MIP/SMT solver.`);if(n.set(a,i),o===`binary`||o===`bin`){if(typeof a.lb!=`number`||Number.isNaN(a.lb)||typeof a.ub!=`number`||Number.isNaN(a.ub))throw Error(`PumpkinSolver encountered non-finite numeric value in bounds of variable "${a.name}".`);if(a.lb===1/0||a.ub===-1/0||a.lb>a.ub)throw Error(`Variable "${a.name}" has invalid bounds lb (${a.lb}) > ub (${a.ub}).`);if(Number.isFinite(a.lb)&&!Number.isInteger(a.lb)||Number.isFinite(a.ub)&&!Number.isInteger(a.ub))throw Error(`PumpkinSolver only supports integer values (bounds of binary variable "${a.name}").`);let e=a.lb===-1/0?0:Math.max(0,Z(a.lb)),n=a.ub===1/0?1:Math.min(1,Z(a.ub)),i=Nn(a,e,n);e>n?(r=!0,t.push({name:a.name,lb:0,ub:1})):t.push(i===void 0?{name:a.name,lb:e,ub:n}:{name:a.name,lb:e,ub:n,initialValue:i});continue}let s=Q(a.lb,`lower bound of variable "${a.name}"`),c=Q(a.ub,`upper bound of variable "${a.name}"`);if(s>c)throw Error(`Variable "${a.name}" has invalid bounds lb (${s}) > ub (${c}).`);let l=Nn(a,s,c);t.push(l===void 0?{name:a.name,lb:s,ub:c}:{name:a.name,lb:s,ub:c,initialValue:l})}return{vars:t,varIndexMap:n,hasEmptyDomain:r}}function Fn(e,t,n){let r=0;function i(e,n,i){let a=Q(e,`internal ${i} lb`),o=Q(n,`internal ${i} ub`),s=t.length;return t.push({name:`__pumpkin_${i}_${++r}`,lb:a,ub:o,internal:!0}),s}function a(n,r,i){let a=new Map;for(let[t,r]of n.entries()){let n=e.get(t);if(n===void 0)throw Error(`Variable "${t.name}" in ${i} is not registered in the model.`);if(typeof r!=`number`||!Number.isFinite(r))throw Error(`Invalid non-finite coefficient for "${t.name}" in ${i}.`);if(!Number.isInteger(r))throw Error(`PumpkinSolver only supports integer coefficients (variable "${t.name}" in ${i} has ${r}).`);let o=(a.get(n)??0)+Z(r);if(!Number.isSafeInteger(o))throw Error(`Coefficient sum overflow for "${t.name}" in ${i}.`);a.set(n,o)}for(let e of r){let t=(a.get(e.varIndex)??0)+Z(e.coeff);if(!Number.isSafeInteger(t))throw Error(`Coefficient sum overflow in ${i}.`);a.set(e.varIndex,t)}let o=[],s=0;for(let[e,n]of a.entries()){let r=Z(n);if(r===0)continue;let a=t[e];Q(r,`coefficient of "${a.name}" in ${i}`);let c=r*a.lb,l=r*a.ub;if(Q(c,`scaled lower bound of "${a.name}" in ${i}`),Q(l,`scaled upper bound of "${a.name}" in ${i}`),s+=Math.max(Math.abs(c),Math.abs(l)),s>On)throw Error(`Linear expression magnitude in ${i} exceeds Pumpkin safe 32-bit propagator overflow limit.`);o.push({varIndex:e,coeff:r})}return{terms:o,sumMaxAbs:s}}function o(e,n,r){let i=n,a=n;for(let n of e){let e=t[n.varIndex],r=n.coeff*e.lb,o=n.coeff*e.ub;i+=Math.min(r,o),a+=Math.max(r,o)}return{lb:Q(Z(i),`lower bound of ${r}`),ub:Q(Z(a),`upper bound of ${r}`)}}function s(e,r,a){switch(e.kind){case`abs`:{let o=l(e.arg,r,`${a} abs()`),s=t[o],c=i(s.lb<=0&&s.ub>=0?0:Math.min(Math.abs(s.lb),Math.abs(s.ub)),Math.max(Math.abs(s.lb),Math.abs(s.ub)),`abs`);return n.push({kind:`abs`,argVar:o,outVar:c,owner:r}),c}case`max`:{let o=e.args.map((e,t)=>l(e,r,`${a} max()[${t}]`)),s=i(Math.max(...o.map(e=>t[e].lb)),Math.max(...o.map(e=>t[e].ub)),`max`);return n.push({kind:`max`,argVars:o,outVar:s,owner:r}),s}case`min`:{let o=e.args.map((e,t)=>l(e,r,`${a} min()[${t}]`)),s=i(Math.min(...o.map(e=>t[e].lb)),Math.min(...o.map(e=>t[e].ub)),`min`);return n.push({kind:`min`,argVars:o,outVar:s,owner:r}),s}case`at`:{let o=l(e.index,r,`${a} at() index`),s=e.array.map((e,t)=>l(e,r,`${a} at()[${t}]`)),c=i(Math.min(...s.map(e=>t[e].lb)),Math.max(...s.map(e=>t[e].ub)),`elem`);return n.push({kind:`element`,indexVar:o,arrayVars:s,outVar:c,owner:r}),c}}}function c(e,t,n,r=!1){if(typeof e.constant!=`number`||!Number.isFinite(e.constant))throw Error(`Invalid non-finite constant in ${n}.`);let i;if(r)i=Z(e.constant);else{if(!Number.isInteger(e.constant))throw Error(`PumpkinSolver only supports integer constants (${n}: got ${e.constant}).`);i=Q(Z(e.constant),`constant of ${n}`)}let o=[];if(Array.isArray(e.nonlinearTerms))for(let r of e.nonlinearTerms){if(r.coeff===0)continue;if(typeof r.coeff!=`number`||!Number.isFinite(r.coeff)||!Number.isInteger(r.coeff))throw Error(`PumpkinSolver only supports safe integer coefficients in ${n} (got ${r.coeff}).`);let e=Q(Z(r.coeff),`nonlinear coefficient in ${n}`),i=s(r.atom,t,n);o.push({varIndex:i,coeff:e})}let{terms:c,sumMaxAbs:l}=a(e.terms,o,n);return{terms:c,constant:i,sumMaxAbs:l}}function l(e,r,a){let{terms:s,constant:l}=c(e,r,a);if(s.length===1&&s[0].coeff===1&&l===0)return s[0].varIndex;let{lb:u,ub:d}=o(s,l,a),f=i(u,d,`expr`);if(s.length>0){let e=[...s,{varIndex:f,coeff:-1}],i=Q(Z(-l),`linearEq RHS in ${a}`),o=e.reduce((e,n)=>{let r=t[n.varIndex];return e+Math.max(Math.abs(n.coeff*r.lb),Math.abs(n.coeff*r.ub))},0);if(Math.abs(i)+o>On)throw Error(`Linear expression magnitude in ${a} exceeds Pumpkin safe 32-bit propagator overflow limit.`);n.push({kind:`linearEq`,terms:e,rhs:i,owner:r})}return f}function u(e,t,n,r){if(typeof t!=`number`||!Number.isFinite(t))throw Error(`Invalid non-finite RHS in ${r}.`);if(!Number.isInteger(t))throw Error(`PumpkinSolver only supports integer RHS (${r}: got ${t}).`);let{terms:i,constant:a,sumMaxAbs:o}=c(e,n,r),s=Q(Z(t-a),`RHS of ${r}`);if(Math.abs(s)+o>On)throw Error(`Linear expression magnitude in ${r} exceeds Pumpkin safe 32-bit propagator overflow limit.`);return{terms:i,rhs:s}}return{lowerLinExpr:c,materializeExprToVarIndex:l,serializeConstraintSide:u}}function In(e,t,n,r,i){if(r.has(e)||e instanceof c||typeof e==`object`&&e&&`name`in e&&`id`in e&&!(`op`in e)&&!(`lhs`in e)&&!(`spec`in e)){let t=e,n=r.get(t);if(n===void 0)throw Error(`Boolean variable "${t.name}" in ${i} is not registered in the model.`);return{kind:`boolVar`,index:n}}if(e instanceof F||`lhs`in e&&`sense`in e&&`rhs`in e){let r=e;if(Mn(r.lhs))throw Error(`PumpkinSolver does not support quadratic constraints inside ${i}.`);let{terms:a,rhs:o}=t.serializeConstraintSide(r.lhs,r.rhs,n,i);return{kind:`linear`,terms:a,sense:r.sense,rhs:o}}if(e instanceof h||typeof e==`object`&&e&&`spec`in e&&typeof e.spec==`object`){let r=e.spec;switch(r.kind){case`distinct`:return{kind:`allDifferent`,vars:r.args.map((e,r)=>t.materializeExprToVarIndex(e,n,`${i} distinct()[${r}]`))};case`disjoint`:return{kind:`disjunctive`,tasks:r.tasks.map((e,r)=>({startVar:t.materializeExprToVarIndex(e.start,n,`${i} disjoint()[${r}]`),duration:Q(e.duration,`duration of ${i} disjoint()[${r}]`)}))};case`cumulative`:return{kind:`cumulative`,tasks:r.tasks.map((e,r)=>({startVar:t.materializeExprToVarIndex(e.start,n,`${i} cumulative()[${r}]`),duration:Q(e.duration,`duration of ${i} cumulative()[${r}]`),demand:Q(e.demand,`demand of ${i} cumulative()[${r}]`)})),capacity:Q(r.capacity,`capacity of ${i} cumulative()`)};case`allowed`:return{kind:`table`,vars:r.vars.map((e,r)=>t.materializeExprToVarIndex(e,n,`${i} allowed() vars[${r}]`)),tuples:r.tuples.map((e,t)=>e.map((e,n)=>Q(e,`tuple[${t}][${n}] in ${i}`)))}}}if(e instanceof l||`op`in e&&`children`in e){let a=e;switch(a.op){case`and`:return{kind:`and`,children:a.children.map(e=>In(e,t,n,r,i))};case`or`:return{kind:`or`,children:a.children.map(e=>In(e,t,n,r,i))};case`not`:if(a.children.length!==1)throw Error(`Invalid 'not' operator arity in ${i}.`);return{kind:`not`,child:In(a.children[0],t,n,r,i)};case`implies`:if(a.children.length!==2)throw Error(`Invalid 'implies' operator arity in ${i}.`);return{kind:`implies`,left:In(a.children[0],t,n,r,i),right:In(a.children[1],t,n,r,i)};case`xor`:return{kind:`xor`,children:a.children.map(e=>In(e,t,n,r,i))};default:throw Error(`Unsupported logical operator "${String(a.op)}" in ${i}.`)}}throw Error(`Unsupported logical constraint node in ${i}.`)}function Ln(e){let{vars:t,varIndexMap:n,hasEmptyDomain:r}=Pn(e.variables),i=[],a=Fn(n,t,i),o=e.boolVars??[],s=new Map,c=[];for(let e=0;e<o.length;e++)s.set(o[e],e),c.push(o[e].name);let l=[];for(let t=0;t<e.constraints.length;t++){let r=e.constraints[t],i=`constraint "${r.name}"`,o={kind:`constraint`,index:t};if(r._indicatorMeta){let e=r._indicatorMeta,t=n.get(e.binVar);if(t===void 0)throw Error(`Indicator binary variable "${e.binVar.name}" in ${i} is not registered in the model.`);let{terms:s,rhs:c}=a.serializeConstraintSide(e.targetLhs,e.targetRhs,o,i);l.push({name:r.name,terms:s,sense:e.targetSense,rhs:c,indicator:{binVarIndex:t,activeValue:e.activeValue}});continue}if(Mn(r.lhs))throw Error(`PumpkinSolver does not support quadratic constraints (${i}).`);let{terms:s,rhs:c}=a.serializeConstraintSide(r.lhs,r.rhs,o,i);l.push({name:r.name,terms:s,sense:r.sense,rhs:c})}let u=[],d=e.logicalConstraints??[];for(let e=0;e<d.length;e++){let t=d[e],n=`logical constraint "${t.name}"`,r={kind:`logic`,index:e},i=In(t.expr,a,r,s,n);u.push({name:t.name,expr:i})}return{vars:t,boolVars:c,constraints:l,logicalConstraints:u,auxPropagators:i,varIndexMap:n,lowerer:a,hasEmptyDomain:r}}function Rn(e,t,n){let r={};if(e)for(let[t,n]of e)An(r,t,Z(n));let i;if(t&&t.length>0){i={};for(let[e,a]of t)An(i,e,a),n&&An(r,e,+!!a)}return{values:r,...i===void 0?{}:{boolValues:i}}}function zn(e,t){let n={};if(e)for(let[t,r]of e)An(n,t,Z(r));if(t)for(let[e,r]of t)An(n,e,r);return n}var Bn=new Set([`presolve`,`relativeGap`,`absoluteGap`,`threads`,`verbose`,`outputFlag`]),Vn=new Set([`timeLimit`,`wasmUrl`,`useWorker`,`signal`,`onProgress`,`relax`]);function Hn(e={}){if(e.relax!==void 0){if(typeof e.relax!=`boolean`)throw Error(`Invalid Pumpkin option "relax": expected boolean, got ${typeof e.relax}.`);if(e.relax===!0)throw Error(`PumpkinSolver does not support LP relaxation (relax: true). Use a simplex/IPM solver such as HiGHS or GLPK.`)}for(let t of Bn)if(e[t]!==void 0)throw Error(`PumpkinSolver does not support option "${t}".`);for(let[t,n]of Object.entries(e))if(n!==void 0&&!Vn.has(t))throw Error(`PumpkinSolver does not support option "${t}".`);if(e.useWorker!==void 0&&typeof e.useWorker!=`boolean`)throw Error(`Invalid Pumpkin option "useWorker": expected boolean, got ${typeof e.useWorker}.`);if(e.onProgress!==void 0&&typeof e.onProgress!=`function`)throw Error(`Invalid Pumpkin option "onProgress": expected function, got ${typeof e.onProgress}.`)}function Un(e){if(e.wasmUrl!==void 0&&e.wasmUrl!==null&&typeof e.wasmUrl!=`string`)throw Error(`Invalid pumpkin.wasm URL: expected string or null, got ${typeof e.wasmUrl}.`);if(e.wasmUrl===``)throw Error(`Invalid pumpkin.wasm URL: expected non-empty string or null (received empty string "").`);return e.wasmUrl===void 0?mn():e.wasmUrl}var Wn=class e{static capabilities={supportsMIP:!0,supportsQP:!1,supportsQCQP:!1,supportsSMT:!1,supportsLogicalConstraints:!0,supportsUnsatCore:!0,supportsWarmStart:!0};name=`pumpkin`;options;capabilities=e.capabilities;constructor(e={}){this.options=e}async check(e,t={}){let n={...this.options,...t};Hn(n);let r=Un(n),i=jn(n.timeLimit),a=Ln(e);if(n.signal?.aborted)return{status:`Unknown`,values:{},runTime:0};if(a.hasEmptyDomain)return{status:`Unsat`,values:{},unsatCore:[],conflicts:[],runTime:1e-6};let o=JSON.stringify({vars:a.vars,boolVars:a.boolVars,constraints:a.constraints,logicalConstraints:a.logicalConstraints,auxPropagators:a.auxPropagators,timeLimitMs:i}),s=n.useWorker??hn(),c;if(s)c=await En().check({requestJson:o,wasmUrl:r},{signal:n.signal});else{let e=await yn(r);if(n.signal?.aborted)return{status:`Unknown`,values:{},runTime:0};let t=performance.now(),i=e.check_with_callback(o,()=>!!n.signal?.aborted),a=Math.max((performance.now()-t)/1e3,1e-6);if(c=JSON.parse(i),c.runTime=a,c.error)throw Error(c.error)}let l=c.runTime??0;if(c.status===`Sat`)return{status:`Sat`,values:zn(c.values,c.boolValues),runTime:l};if(c.status===`Unsat`){let e=c.unsatCore?[...c.unsatCore]:[];return{status:`Unsat`,values:{},unsatCore:e,conflicts:e,runTime:l}}return{status:`Unknown`,values:{},runTime:l}}async solve(e,t={}){let n={...this.options,...t};Hn(n);let r=Un(n),a=jn(n.timeLimit),o=i(e.sense),s=Ln(e);if(Mn(e.objective))throw Error(`PumpkinSolver does not support quadratic objective expressions (QuadExpr). Use a QP solver such as HiGHS.`);let c=e.objective;if(typeof c.constant!=`number`||!Number.isFinite(c.constant))throw Error(`Invalid non-finite objective constant.`);let l=Z(c.constant),{terms:u,sumMaxAbs:d}=s.lowerer.lowerLinExpr(c,{kind:`objective`},`objective expression`,!0);if(d>Dn)throw Error(`Objective expression magnitude (${d}) exceeds Pumpkin safe 32-bit integer range [-${Dn}, ${Dn}].`);if(n.signal?.aborted)return{status:`Unknown`,terminationStatus:`Interrupted`,hasPrimalSolution:!1,objectiveValue:null,values:{},runTime:0};if(s.hasEmptyDomain)return{status:`Infeasible`,terminationStatus:`Infeasible`,hasPrimalSolution:!1,objectiveValue:null,values:{},runTime:1e-6};let f=JSON.stringify({vars:s.vars,boolVars:s.boolVars,constraints:s.constraints,logicalConstraints:s.logicalConstraints,auxPropagators:s.auxPropagators,sense:o,objectiveTerms:u,objectiveConstant:l,timeLimitMs:a}),p=n.useWorker??hn(),m=n.onProgress,h=0,g=m?e=>{h++,m(e)}:void 0,_;if(p)_=await En().solve({requestJson:f,wasmUrl:r},{signal:n.signal,onProgress:g});else{let e=await yn(r);if(n.signal?.aborted)return{status:`Unknown`,terminationStatus:`Interrupted`,hasPrimalSolution:!1,objectiveValue:null,values:{},runTime:0};let t=performance.now(),i=null,a=n.signal,o=g?e=>{try{let n=JSON.parse(e),r=Math.max((performance.now()-t)/1e3,1e-6);return g({elapsedTime:r,elapsedSeconds:r,objectiveValue:n.objectiveValue}),!!a?.aborted}catch(e){return i=e,!0}}:null,s=a?()=>!!a.aborted:null,c=e.solve_with_callback(f,o,s);if(i!==null)throw i;let l=Math.max((performance.now()-t)/1e3,1e-6);if(_=JSON.parse(c),_.runTime=l,_.error)throw Error(_.error)}let v=_.status===`Optimal`||_.status===`Feasible`,y=typeof _.objectiveValue==`number`?Z(_.objectiveValue):null,b=_.runTime??0;v&&h===0&&g&&g({elapsedTime:b,elapsedSeconds:b,...y===null?{}:{objectiveValue:y}});let x=v?Rn(_.values,_.boolValues,!0):{values:{}};return{status:_.status,terminationStatus:_.terminationStatus,hasPrimalSolution:v,objectiveValue:y,values:x.values,...x.boolValues===void 0?{}:{boolValues:x.boolValues},runTime:b}}};function Gn(e){et(`pumpkin`,t=>new Wn(t??e))}Gn();function Kn(e,t){if(e===void 0)return 1e-6;if(typeof e!=`number`||!Number.isFinite(e)||e<0)throw Error(`Invalid ${t}: expected a finite non-negative number, received ${String(e)}.`);return e}function qn(e,t={}){let n=Kn(t.feasibilityTolerance,`feasibilityTolerance`),r=Kn(t.integralityTolerance,`integralityTolerance`),i=t.evaluateLogicalConstraints===void 0||!!t.evaluateLogicalConstraints,a=t.values!==void 0&&t.values!==null;if(t.values!==void 0&&(typeof t.values!=`object`||t.values===null||Array.isArray(t.values)))throw Error(`Invalid values option: expected a plain object mapping variable names to values.`);let o=t.values,s=[],u=Object.create(null),d=[],f=[],p=0,m=e=>{typeof e==`number`&&!Number.isNaN(e)&&e>p&&(p=e)},g=e=>{s.push(e),Object.prototype.hasOwnProperty.call(u,e.name)||(u[e.name]=[]),u[e.name].push(e),e.type!==`missing_value`&&e.type!==`unchecked_constraint`&&m(e.violation)},_=[],v=[];for(let t of e.variables.values())t.type===`Boolean`?v.push(t):_.push(t);let y=[],b=[];for(let t of e.constraints.values())t instanceof F?y.push(t):b.push(t);let x=new Map,S=new Map,C=0,T=0,E=0,D=0;for(let e of _){let t=a?Object.prototype.hasOwnProperty.call(o,e.name)?o[e.name]:void 0:e.value;if(t==null){f.push(e.name),g({type:`missing_value`,target:`variable`,name:e.name,actual:t??null,violation:1/0,message:`Variable "${e.name}" has no assigned solution value.`});continue}if(typeof t!=`number`||!Number.isFinite(t)){g({type:`non_finite_value`,target:`variable`,name:e.name,actual:t,violation:1/0,message:`Variable "${e.name}" has non-finite or non-numeric value: ${String(t)}.`});continue}x.set(e,t),C++;let i=e.type===`Binary`||e.type===`BINARY`,s=i||e.type===`Integer`||e.type===`INTEGER`,c=i?Math.max(0,e.lb):e.lb,l=i?Math.min(1,e.ub):e.ub,u=typeof e.lb==`number`&&!Number.isNaN(e.lb)&&e.lb!==1/0,d=typeof e.ub==`number`&&!Number.isNaN(e.ub)&&e.ub!==-1/0;if(!u)g({type:`lower_bound`,target:`variable`,name:e.name,actual:t,limit:e.lb,violation:1/0,message:`Variable "${e.name}" has invalid lower bound (${String(e.lb)}).`});else if(c!==-1/0){let r=t-c,i=Math.max(0,c-t);m(i),i>n&&g({type:`lower_bound`,target:`variable`,name:e.name,actual:t,limit:c,violation:i,signedViolation:r,message:`Variable "${e.name}" value (${t}) violates lower bound (${c}) by ${i}.`})}if(!d)g({type:`upper_bound`,target:`variable`,name:e.name,actual:t,limit:e.ub,violation:1/0,message:`Variable "${e.name}" has invalid upper bound (${String(e.ub)}).`});else if(l!==1/0){let r=t-l,i=Math.max(0,t-l);m(i),i>n&&g({type:`upper_bound`,target:`variable`,name:e.name,actual:t,limit:l,violation:i,signedViolation:r,message:`Variable "${e.name}" value (${t}) violates upper bound (${l}) by ${i}.`})}if(u&&d&&c>l&&c-t<=n&&t-l<=n){let n=c-l;g({type:`lower_bound`,target:`variable`,name:e.name,actual:t,limit:c,violation:n,signedViolation:t-c,message:`Variable "${e.name}" has inverted bounds [${c}, ${l}].`})}if(s){let n=Math.round(t),a=t-n,o=Math.abs(a);m(o),o>r&&g({type:`integrality`,target:`variable`,name:e.name,varType:i?`Binary`:`Integer`,actual:t,nearestInteger:n,violation:o,signedViolation:a,message:`${i?`Binary`:`Integer`} variable "${e.name}" value (${t}) violates integrality by ${o} (nearest integer: ${n}).`})}}for(let e of v){let t=a?Object.prototype.hasOwnProperty.call(o,e.name)?o[e.name]:void 0:e.value;if(t==null){f.push(e.name),g({type:`missing_value`,target:`bool_variable`,name:e.name,actual:t??null,violation:1/0,message:`Boolean variable "${e.name}" has no assigned solution value.`});continue}if(typeof t!=`boolean`){g({type:`invalid_boolean_value`,target:`bool_variable`,name:e.name,actual:t,violation:1/0,message:`Boolean variable "${e.name}" has non-boolean value: ${String(t)}.`});continue}S.set(e,t),T++}let ee=e=>{switch(e.kind){case`abs`:{let t=O(e.arg);return t.ok?{ok:!0,value:Math.abs(t.value),...t.atDomainError?{atDomainError:t.atDomainError}:{}}:t}case`max`:{let t=-1/0,n;for(let r of e.args){let e=O(r);if(!e.ok)return e;!n&&e.atDomainError&&(n=e.atDomainError),e.value>t&&(t=e.value)}return{ok:!0,value:t,...n?{atDomainError:n}:{}}}case`min`:{let t=1/0,n;for(let r of e.args){let e=O(r);if(!e.ok)return e;!n&&e.atDomainError&&(n=e.atDomainError),e.value<t&&(t=e.value)}return{ok:!0,value:t,...n?{atDomainError:n}:{}}}case`at`:{let t=O(e.index);if(!t.ok)return t;let i=t.value,a=e.array.length-1,o=Math.max(0,-i),s=Math.max(0,i-a),c=Math.max(o,s),l=Math.abs(i-Math.round(i));if(c>n||l>r)return{ok:!0,value:0,atDomainError:{violation:Math.max(c,l),message:`at() index (${i}) violates valid integer range [0, ${a}].`}};let u=O(e.array[Math.round(i)]);return u.ok?{ok:!0,value:u.value,...t.atDomainError??u.atDomainError?{atDomainError:t.atDomainError??u.atDomainError}:{}}:u}}},O=e=>{let t=e.constant===void 0?0:e.constant;if(typeof t!=`number`||!Number.isFinite(t))return{ok:!1,reason:`non-finite constant (${String(t)})`};let n=t;for(let[t,r]of e.terms){if(typeof r!=`number`||!Number.isFinite(r))return{ok:!1,reason:`non-finite coefficient (${String(r)}) for variable "${t.name}"`};if(r!==0){if(!x.has(t))return{ok:!1,reason:`missing or invalid value for variable "${t.name}"`};if(n+=r*x.get(t),!Number.isFinite(n))return{ok:!1,reason:`linear expression evaluation overflowed finite range`}}}let r;for(let t of e.nonlinearTerms??[]){if(typeof t.coeff!=`number`||!Number.isFinite(t.coeff))return{ok:!1,reason:`non-finite nonlinear coefficient (${String(t.coeff)})`};let e=ee(t.atom);if(!e.ok)return e;if(!r&&e.atDomainError&&(r=e.atDomainError),t.coeff!==0&&(n+=t.coeff*e.value,!Number.isFinite(n)))return{ok:!1,reason:`expression evaluation overflowed finite range`}}return{ok:!0,value:n,...r?{atDomainError:r}:{}}},k=e=>{switch(e.kind){case`abs`:return A(e.arg);case`max`:case`min`:{let t=[];for(let n of e.args){let e=A(n);if(!e.ok)return e;t.push(...e.errors)}return{ok:!0,errors:t}}case`at`:{let t=[],i=A(e.index);if(!i.ok)return i;t.push(...i.errors);for(let n of e.array){let e=A(n);if(!e.ok)return e;t.push(...e.errors)}let a=O(e.index);if(!a.ok)return a;if(i.errors.length===0){let i=a.value,o=e.array.length-1,s=Math.max(0,-i),c=Math.max(0,i-o),l=Math.max(s,c),u=Math.abs(i-Math.round(i));if(l>n||u>r){let e=Math.max(l,u);t.push({violation:e,message:`at() index (${i}) violates valid integer range [0, ${o}].`})}}return{ok:!0,errors:t}}}},A=e=>{let t=[];for(let n of e.nonlinearTerms??[]){let e=k(n.atom);if(!e.ok)return e;t.push(...e.errors)}return{ok:!0,errors:t}},te=e=>{if(e instanceof c)return{ok:!0};if(e instanceof F){let t=A(e.lhs);return t.ok?{ok:!0,...t.errors.length>0?{firstError:t.errors[0]}:{}}:t}if(e instanceof h){let t=e.spec,n=t.kind===`distinct`?t.args:t.kind===`disjoint`||t.kind===`cumulative`?t.tasks.map(e=>e.start):t.vars;for(let e of n){let t=A(e);if(!t.ok)return t;if(t.errors.length>0)return{ok:!0,firstError:t.errors[0]}}return{ok:!0}}if(e instanceof l){let t;for(let n of e.children){let e=te(n);if(!e.ok)return e;!t&&e.firstError&&(t=e.firstError)}return{ok:!0,...t?{firstError:t}:{}}}return{ok:!0}},ne=(e,t=n)=>{if(typeof e.rhs!=`number`||!Number.isFinite(e.rhs))return{status:`unchecked`,reason:`non-finite right-hand side (${String(e.rhs)})`};let r=A(e.lhs);if(!r.ok)return{status:`unchecked`,reason:r.reason};let i=O(e.lhs);if(!i.ok)return{status:`unchecked`,reason:i.reason};if(r.errors.length>0||i.atDomainError){let t=r.errors[0]??i.atDomainError;return{status:`violated`,lhsVal:i.value,signed:i.value-e.rhs,violation:t.violation,message:`Constraint "${e.name}" invalid element lookup: ${t.message}`}}let a=i.value,o=a-e.rhs;if(!Number.isFinite(o))return{status:`unchecked`,reason:`constraint residual overflowed finite range`};let s=e.sense===`<=`?Math.max(0,o):e.sense===`>=`?Math.max(0,-o):e.sense===`!=`?Math.max(0,1-Math.abs(o)):Math.abs(o);return s>t?{status:`violated`,lhsVal:a,signed:o,violation:s,message:`Constraint "${e.name}" (${a} ${e.sense} ${e.rhs}) violated by ${s}.`}:{status:`satisfied`,lhsVal:a,signed:o,violation:s}},re=e.objective();if((re instanceof w||re instanceof R)&&re.nonlinearTerms.length>0){let e=A(new R(new Map,0,re.nonlinearTerms));if(e.ok)for(let t of e.errors)g({type:`linear_constraint`,target:`constraint`,name:`objective_at`,violation:t.violation,message:`Objective at() lookup failed: ${t.message}`})}for(let e of y){let t=ne(e);t.status===`unchecked`?(d.push(e.name),g({type:`unchecked_constraint`,target:`constraint`,name:e.name,sense:e.sense,limit:e.rhs,rhs:e.rhs,violation:1/0,message:`Constraint "${e.name}" could not be evaluated: ${t.reason}.`})):t.status===`violated`?(E++,g({type:`linear_constraint`,target:`constraint`,name:e.name,sense:e.sense,actual:t.lhsVal,limit:e.rhs,rhs:e.rhs,violation:t.violation,signedViolation:t.signed,message:t.message})):(E++,m(t.violation))}let ie=e=>{if(e instanceof c)return S.has(e)?{ok:!0,value:S.get(e),violation:0}:{ok:!1,reason:`missing or invalid value for Boolean variable "${e.name}"`};if(e instanceof F){if(e.sense===`!=`){let t=O(e.lhs);if(!t.ok)return{ok:!1,reason:t.reason};if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};let r=Math.abs(t.value-e.rhs);return r<=n?{ok:!0,value:!1,violation:0}:r>=1-n?{ok:!0,value:!0,violation:0}:{ok:!1,reason:`discrete comparison "${e.name}" lies between 0 and 1 (${t.value} != ${e.rhs})`}}let t=ne(e,0);if(t.status===`unchecked`)return{ok:!1,reason:t.reason};if(n>0){let r=Math.abs(t.lhsVal-e.rhs);if(r>0&&r<=n)return{ok:!1,reason:`numeric comparison "${e.name}" lies within feasibilityTolerance (${n}) of boundary (${t.lhsVal} vs ${e.rhs})`}}return{ok:!0,value:t.status===`satisfied`,violation:0}}if(e instanceof h){let t=e.spec;if(t.kind===`distinct`){let e=[];for(let n of t.args){let t=O(n);if(!t.ok)return t;if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};e.push(t.value)}for(let t=0;t<e.length;t++)for(let r=t+1;r<e.length;r++){let i=Math.abs(e[t]-e[r]);if(i<=n)return{ok:!0,value:!1,violation:0};if(i<1-n)return{ok:!1,reason:`distinct() operands at indices (${t}, ${r}) have fractional gap (${i})`}}return{ok:!0,value:!0,violation:0}}if(t.kind===`disjoint`){let e=[];for(let n of t.tasks){let t=O(n.start);if(!t.ok)return t;if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};e.push(t.value)}for(let r=0;r<t.tasks.length;r++)for(let i=r+1;i<t.tasks.length;i++){let a=e[r],o=t.tasks[r].duration,s=e[i],c=t.tasks[i].duration;if(!(a+o<=s+n||s+c<=a+n))return{ok:!0,value:!1,violation:0}}return{ok:!0,value:!0,violation:0}}if(t.kind===`cumulative`){let e=[];for(let n of t.tasks){let t=O(n.start);if(!t.ok)return t;if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};e.push(t.value)}let r=[];for(let n=0;n<t.tasks.length;n++){let i=t.tasks[n];if(i.duration>0&&i.demand>0){if(i.demand>t.capacity)return{ok:!0,value:!1,violation:0};r.push({start:e[n],duration:i.duration,demand:i.demand})}}for(let e=0;e<r.length;e++){let i=r[e].start,a=0;for(let e=0;e<r.length;e++){let t=r[e];t.start-n<=i&&i<t.start+t.duration-n&&(a+=t.demand)}if(a>t.capacity+n)return{ok:!0,value:!1,violation:0}}return{ok:!0,value:!0,violation:0}}if(t.kind===`allowed`){let e=[];for(let n of t.vars){let t=O(n);if(!t.ok)return t;if(t.atDomainError)return{ok:!1,reason:t.atDomainError.message};e.push(t.value)}return{ok:!0,value:t.tuples.some(t=>t.every((t,r)=>Math.abs(e[r]-t)<=n)),violation:0}}}if(e instanceof l)switch(e.op){case`not`:{let t=ie(e.children[0]);return t.ok?{ok:!0,value:!t.value,violation:0}:t}case`and`:{let t=0;for(let n of e.children){let e=ie(n);if(!e.ok)return e;if(!e.value)return{ok:!0,value:!1,violation:0};e.violation>t&&(t=e.violation)}return{ok:!0,value:!0,violation:t}}case`or`:{let t=!1,n=1/0;for(let r of e.children){let e=ie(r);if(!e.ok)return e;e.value&&(t=!0,e.violation<n&&(n=e.violation))}return{ok:!0,value:t,violation:t?n:0}}case`implies`:{let t=ie(e.children[0]);if(!t.ok)return t;if(!t.value)return{ok:!0,value:!0,violation:0};let n=ie(e.children[1]);return n.ok?{ok:!0,value:n.value,violation:n.value?n.violation:0}:n}case`xor`:{let t=!1,n=0;for(let r of e.children){let e=ie(r);if(!e.ok)return e;e.value&&(t=!t,e.violation>n&&(n=e.violation))}return{ok:!0,value:t,violation:t?n:0}}default:return{ok:!1,reason:`unsupported logical operator "${String(e.op)}"`}}return{ok:!1,reason:`unsupported logical expression node`}};for(let e=0;e<b.length;e++){let t=b[e],n=t.name||`lc_${e+1}`;if(!i){d.push(n),g({type:`unchecked_constraint`,target:`logical_constraint`,name:n,violation:1/0,message:`Logical constraint "${n}" was not evaluated because evaluateLogicalConstraints is false.`});continue}let r=te(t.expr);if(!r.ok){d.push(n),g({type:`unchecked_constraint`,target:`logical_constraint`,name:n,violation:1/0,message:`Logical constraint "${n}" could not be evaluated: ${r.reason}.`});continue}if(r.firstError){D++,g({type:`logical_constraint`,target:`logical_constraint`,name:n,actual:!1,limit:!0,violation:r.firstError.violation,signedViolation:-1,message:`Logical constraint "${n}" invalid element lookup: ${r.firstError.message}`});continue}let a=ie(t.expr);if(!a.ok){d.push(n),g({type:`unchecked_constraint`,target:`logical_constraint`,name:n,violation:1/0,message:`Logical constraint "${n}" could not be evaluated: ${a.reason}.`});continue}D++,a.value?m(a.violation):g({type:`logical_constraint`,target:`logical_constraint`,name:n,actual:!1,limit:!0,violation:1,signedViolation:-1,message:`Logical constraint "${n}" evaluated to false.`})}let j=C===_.length&&T===v.length&&E===y.length&&D===b.length&&d.length===0&&f.length===0;return{valid:j&&s.length===0,complete:j,violations:s,violationsByName:u,uncheckedConstraints:d,missingVariables:f,maxViolation:p,summary:{checkedVariables:C,totalVariables:_.length,checkedBoolVariables:T,totalBoolVariables:v.length,checkedLinearConstraints:E,totalLinearConstraints:y.length,checkedLogicalConstraints:D,totalLogicalConstraints:b.length}}}function Jn(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw Error(`Invalid Big-M value for indicator constraint "${t}": expected a finite positive number, received ${e}.`)}function Yn(e,t,n){let r=e.constant===void 0?0:e.constant;if(!Number.isFinite(t)||!Number.isFinite(r))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": constraint contains non-finite constant (${r}) or right-hand side (${t}).`);let i=t-r;if(!Number.isFinite(i))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": effective right-hand side (${t} - ${r}) overflows finite floating-point range. Please rescale coefficients/constants.`);for(let[t,r]of e.terms){if(!Number.isFinite(r))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" has non-finite coefficient (${r}).`);if(Number.isNaN(t.lb)||Number.isNaN(t.ub)||t.lb===1/0||t.ub===-1/0||t.lb>t.ub)throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" has invalid bounds [${t.lb}, ${t.ub}].`)}return i}function Xn(e,t,n){let r=Yn(e,t,n),i=0;for(let[t,r]of e.terms){if(r===0)continue;let e;if(r>0){if(!Number.isFinite(t.ub))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" lacks a finite upper bound (required because coefficient ${r} is positive in <= constraint). Please set an explicit finite upper bound on the variable or specify { M } explicitly in indicator options.`);e=t.ub}else{if(!Number.isFinite(t.lb))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" lacks a finite lower bound (required because coefficient ${r} is negative in <= constraint). Please set an explicit finite lower bound on the variable or specify { M } explicitly in indicator options.`);e=t.lb}let a=r*e;if(i+=a,!Number.isFinite(a)||!Number.isFinite(i))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": numeric overflow while bounding contribution of variable "${t.name}". Please rescale coefficients/bounds or specify a finite { M } explicitly.`)}let a=i-r;if(!Number.isFinite(a))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": numeric overflow while computing Big-M (${i} - ${r}). Please rescale coefficients/bounds or specify a finite { M } explicitly.`);let o=Math.max(0,a);if(!Number.isFinite(o)||!Number.isFinite(r+o))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": derived Big-M (${o}) or shifted right-hand side overflows finite floating-point range. Please rescale coefficients/bounds or specify a finite { M } explicitly.`);return o}function Zn(e,t,n){let r=Yn(e,t,n),i=0;for(let[t,r]of e.terms){if(r===0)continue;let e;if(r>0){if(!Number.isFinite(t.lb))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" lacks a finite lower bound (required because coefficient ${r} is positive in >= constraint). Please set an explicit finite lower bound on the variable or specify { M } explicitly in indicator options.`);e=t.lb}else{if(!Number.isFinite(t.ub))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": variable "${t.name}" lacks a finite upper bound (required because coefficient ${r} is negative in >= constraint). Please set an explicit finite upper bound on the variable or specify { M } explicitly in indicator options.`);e=t.ub}let a=r*e;if(i+=a,!Number.isFinite(a)||!Number.isFinite(i))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": numeric overflow while bounding contribution of variable "${t.name}". Please rescale coefficients/bounds or specify a finite { M } explicitly.`)}let a=r-i;if(!Number.isFinite(a))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": numeric overflow while computing Big-M (${r} - ${i}). Please rescale coefficients/bounds or specify a finite { M } explicitly.`);let o=Math.max(0,a);if(!Number.isFinite(o)||!Number.isFinite(r-o))throw Error(`Cannot derive safe Big-M for indicator constraint "${n}": derived Big-M (${o}) or shifted right-hand side overflows finite floating-point range. Please rescale coefficients/bounds or specify a finite { M } explicitly.`);return o}function Qn(e,t,n,r,i,a,o){if(!(e instanceof V&&(e.type===`Binary`||e.type===`Integer`&&e.lb===0&&e.ub===1)))throw Error(`Indicator variable "${e?.name??String(e)}" must be a Binary variable (or Integer variable with bounds [0, 1]), received "${e?.type??typeof e}" with bounds [${e?.lb}, ${e?.ub}].`);if(!Number.isFinite(e.lb)||!Number.isFinite(e.ub)||e.lb<0||e.ub>1||e.lb>e.ub)throw Error(`Binary indicator variable "${e.name}" has invalid bounds [${e.lb}, ${e.ub}]. Binary variables must stay within [0, 1] with lb <= ub.`);let s=Yn(t,r,o);if(i!==0&&i!==1)throw Error(`Invalid activeValue: ${i}. Indicator activation value must be 0 or 1.`);if(n!==`<=`&&n!==`>=`)throw Error(`Invalid indicator sense for "${o}": expected "<=" or ">=", received "${String(n)}".`);if(!Number.isFinite(a)||a<0)throw Error(`Invalid Big-M value for indicator constraint "${o}": expected a finite non-negative number, received ${a}.`);let c=t.terms.get(e);if(c!==void 0&&c!==0)throw Error(`Indicator constraint "${o}" cannot include its own binary activation variable "${e.name}" in the linear expression.`);let l,u;if(i===1?n===`<=`?(l=a,u=s+a):(l=-a,u=s-a):n===`<=`?(l=-a,u=s):(l=a,u=s),!Number.isFinite(u))throw Error(`Cannot construct finite indicator constraint "${o}": shifted right-hand side overflows finite floating-point range. Please rescale coefficients/bounds or specify a smaller finite { M }.`);let d=new Map;for(let[e,n]of t.terms)n!==0&&d.set(e,n);return l!==0&&d.set(e,l),{lhs:new R(d,0),rhs:u}}function $(e,t=0){let n=new Map;for(let[t,r]of e){if(r===0)continue;let e=(n.get(t)??0)+r;e===0?n.delete(t):n.set(t,e)}return new R(n,t)}function $n(e,t,n=1){if(n!==0){e.constant+=t.constant*n;for(let[r,i]of t.terms.entries())i!==0&&e.addTerm(r,i*n)}}var er=5e3,tr=25e3;function nr(e,t,n,r,a){let o=[...e],s=[],u=new Map,d=new Map,f=new Set,p=[];for(let e of n)if(e.sense===`!=`||e.lhs.hasNonlinearTerms())p.push(e);else{let t=e;if(f.has(t.name)){let n=1;for(;f.has(`${e.name}_${n}`);)n++;t=new F(e.lhs,e.sense,e.rhs,`${e.name}_${n}`)}f.add(t.name),s.push(t),d.set(t,e.name)}let m=new Set(e.map(e=>e.name)),g=0;function _(e){let t;do t=`__washi_${e}_${++g}`;while(m.has(t));return m.add(t),t}function v(e,t){let n=e.name||`c`,r=n;if(f.has(r)){let t=1;for(;f.has(`${n}_${t}`);)t++;r=`${n}_${t}`,e=new F(e.lhs,e.sense,e.rhs,r)}f.add(r),s.push(e),d.set(e,t)}for(let e of t){let t=e.name;m.has(t)?t=_(`bool_${e.name}`):m.add(t);let n=new V({name:t,type:`Binary`,lb:0,ub:1});u.set(e,n),o.push(n)}function y(e,t){if(!Number.isFinite(e.constant))throw Error(`Cannot linearize piecewise expression in "${t}": non-finite constant (${e.constant}).`);let n=e.constant,r=e.constant,i=Number.isSafeInteger(e.constant);for(let[a,o]of e.terms.entries()){if(!Number.isFinite(o))throw Error(`Cannot linearize piecewise expression in "${t}": variable "${a.name}" has non-finite coefficient (${o}).`);if(o===0)continue;if(typeof a.lb!=`number`||typeof a.ub!=`number`||Number.isNaN(a.lb)||Number.isNaN(a.ub)||a.lb===-1/0||a.ub===1/0||a.lb>a.ub)throw Error(`Cannot linearize non-convex piecewise expression in "${t}": variable "${a.name}" has unbounded or invalid domain [${a.lb}, ${a.ub}]. Finite bounds are required.`);let e=a.lb,s=a.ub;if(a.type===`Binary`){let t=Math.max(0,Math.ceil(a.lb)),n=Math.min(1,Math.floor(a.ub));t<=n&&(e=t,s=n)}else if(a.type===`Integer`){let t=Math.ceil(a.lb),n=Math.floor(a.ub);t<=n&&(e=t,s=n)}let c=o*e,l=o*s;if(n+=Math.min(c,l),r+=Math.max(c,l),!Number.isFinite(n)||!Number.isFinite(r))throw Error(`Cannot linearize non-convex piecewise expression in "${t}": bound calculation overflowed.`);i&&=(a.type===`Integer`||a.type===`Binary`)&&Number.isSafeInteger(o)&&Number.isSafeInteger(e)&&Number.isSafeInteger(s)}return{lb:Object.is(n,-0)?0:n,ub:Object.is(r,-0)?0:r,isDiscrete:i}}function b(e,t){if(!e.hasNonlinearTerms())return e.clone();let n=new R(e.terms,e.constant);for(let r of e.nonlinearTerms)r.coeff!==0&&$n(n,x(r.atom,t),r.coeff);return n}function x(e,t){switch(e.kind){case`abs`:{let n=b(e.arg,t),{lb:r,ub:i,isDiscrete:a}=y(n,t);if(r>=0)return n;if(i<=0)return n.mul(-1);let s=Math.max(-r,i),c=new V({name:_(`abs_t`),type:a?`Integer`:`Continuous`,lb:0,ub:s}),l=new V({name:_(`abs_z`),type:`Binary`,lb:0,ub:1});o.push(c,l);let u=$([[c,1]],0);return P(new F(n.sub(u),`<=`,0,`${t}_abs_pos`),t),P(new F(n.mul(-1).sub(u),`<=`,0,`${t}_abs_neg`),t),P(new F(u.sub(n).add($([[l,2*-r]],0)),`<=`,2*-r,`${t}_abs_hi_pos`),t),P(new F(u.add(n).sub($([[l,2*i]],0)),`<=`,0,`${t}_abs_hi_neg`),t),u}case`max`:{let n=e.args.map(e=>b(e,t));if(n.length===1)return n[0];let r=n.map(e=>y(e,t)),i=Math.max(...r.map(e=>e.lb)),a=Math.max(...r.map(e=>e.ub)),s=r.every(e=>e.isDiscrete),c=new V({name:_(`max_t`),type:s?`Integer`:`Continuous`,lb:i,ub:a});o.push(c);let l=$([[c,1]],0),u=[];for(let e=0;e<n.length;e++){let i=new V({name:_(`max_z_${e}`),type:`Binary`,lb:0,ub:1});o.push(i),u.push(i),P(new F(n[e].sub(l),`<=`,0,`${t}_max_lb_${e}`),t);let s=a-r[e].lb;P(new F(l.sub(n[e]).add($([[i,s]],0)),`<=`,s,`${t}_max_ub_${e}`),t)}return v(new F($(u.map(e=>[e,1]),0),`==`,1,`${t}_max_sos`),t),l}case`min`:{let n=e.args.map(e=>b(e,t));if(n.length===1)return n[0];let r=n.map(e=>y(e,t)),i=Math.min(...r.map(e=>e.lb)),a=Math.min(...r.map(e=>e.ub)),s=r.every(e=>e.isDiscrete),c=new V({name:_(`min_t`),type:s?`Integer`:`Continuous`,lb:i,ub:a});o.push(c);let l=$([[c,1]],0),u=[];for(let e=0;e<n.length;e++){let a=new V({name:_(`min_z_${e}`),type:`Binary`,lb:0,ub:1});o.push(a),u.push(a),P(new F(n[e].sub(l),`>=`,0,`${t}_min_ub_${e}`),t);let s=r[e].ub-i;P(new F(n[e].sub(l).add($([[a,s]],0)),`<=`,s,`${t}_min_lb_${e}`),t)}return v(new F($(u.map(e=>[e,1]),0),`==`,1,`${t}_min_sos`),t),l}case`at`:{let n=e.array.length,r=b(e.index,t),i=e.array.map(e=>b(e,t)),a=[];for(let e=0;e<n;e++){let t=new V({name:_(`at_lam_${e}`),type:`Binary`,lb:0,ub:1});o.push(t),a.push(t)}v(new F($(a.map(e=>[e,1]),0),`==`,1,`${t}_at_sos`),t);let s=r.clone();for(let e=1;e<n;e++)s.addTerm(a[e],-e);P(new F(s,`==`,0,`${t}_at_idx`),t);let c=new R(new Map,0);for(let e=0;e<n;e++){let n=i[e];if(n.terms.size===0)n.constant!==0&&c.addTerm(a[e],n.constant);else{let{lb:r,ub:i,isDiscrete:s}=y(n,t),l=new V({name:_(`at_w_${e}`),type:s?`Integer`:`Continuous`,lb:Math.min(0,r),ub:Math.max(0,i)});o.push(l);let u=$([[l,1]],0);P(new F($([[l,1],[a[e],-r]],0),`>=`,0,`${t}_at_mc1_${e}`),t),P(new F($([[l,1],[a[e],-i]],0),`<=`,0,`${t}_at_mc2_${e}`),t),P(new F(u.sub(n).add($([[a[e],-i]],0)),`>=`,-i,`${t}_at_mc3_${e}`),t),P(new F(u.sub(n).add($([[a[e],-r]],0)),`<=`,-r,`${t}_at_mc4_${e}`),t),c.addTerm(l,1)}}return c}}}function S(e,t,n){if(t===`upper`&&e.kind===`max`){let t=new V({name:_(`epi_max`),type:`Continuous`,lb:-1/0,ub:1/0});o.push(t);let r=$([[t,1]],0);for(let t=0;t<e.args.length;t++)T(e.args[t].sub(r),`<=`,0,`${n}_epi_max_${t}`,n);return r}if(t===`upper`&&e.kind===`abs`){let t=e.arg.hasNonlinearTerms()?b(e.arg,n):e.arg,r=new V({name:_(`epi_abs`),type:`Continuous`,lb:0,ub:1/0});o.push(r);let i=$([[r,1]],0);return P(new F(t.sub(i),`<=`,0,`${n}_epi_abs_pos`),n),P(new F(t.mul(-1).sub(i),`<=`,0,`${n}_epi_abs_neg`),n),i}if(t===`lower`&&e.kind===`min`){let t=new V({name:_(`epi_min`),type:`Continuous`,lb:-1/0,ub:1/0});o.push(t);let r=$([[t,1]],0);for(let t=0;t<e.args.length;t++)T(e.args[t].sub(r),`>=`,0,`${n}_epi_min_${t}`,n);return r}return x(e,n)}function C(e,t,n){if(!e.hasNonlinearTerms())return e;if(t===`==`||t===`!=`)return b(e,n);let r=new R(e.terms,e.constant);for(let i of e.nonlinearTerms){if(i.coeff===0)continue;let e=t===`<=`?i.coeff>0?`upper`:`lower`:i.coeff>0?`lower`:`upper`;$n(r,S(i.atom,e,n),i.coeff)}return r}function T(e,t,n,r,i){let a=C(e,t,i);if(t===`!=`){ce(new F(a,`==`,n,r),i);return}P(new F(a,t,n,r),i)}function E(e,t){return e.lhs.hasNonlinearTerms()?new F(b(e.lhs,t),e.sense,e.rhs,e.name):e}function D(e,t){if(e instanceof c){let n=u.get(e);if(!n)throw Error(`Unregistered BoolVar "${e.name}" in logical constraint "${t}".`);return n}let n=new V({name:_(`expr`),type:`Binary`,lb:0,ub:1});return o.push(n),O(n,e,t),n}function ee(e,t,n,r){v(new F($([[e,1],[t,-1],[n,-1]],0),`<=`,0,`${r}_xor_1`),r),v(new F($([[e,1],[t,-1],[n,1]],0),`>=`,0,`${r}_xor_2`),r),v(new F($([[e,1],[n,-1],[t,1]],0),`>=`,0,`${r}_xor_3`),r),v(new F($([[e,1],[t,1],[n,1]],0),`<=`,2,`${r}_xor_4`),r)}function O(e,t,n){if(t instanceof c){let r=u.get(t);v(new F($([[e,1],[r,-1]],0),`==`,0,`${n}_equiv`),n);return}if(t instanceof F){let r=E(t,n);le(e,r,0,`${n}_c_neg`,n),se(e,r,1,`${n}_c_pos`,n);return}if(t instanceof h){ne(e,t,n);return}if(t instanceof l){if(t.op===`not`){let r=D(t.children[0],n);v(new F($([[e,1],[r,1]],0),`==`,1,`${n}_not`),n);return}if(t.op===`and`){let r=t.children.map(e=>D(e,n));for(let t=0;t<r.length;t++)v(new F($([[e,1],[r[t],-1]],0),`<=`,0,`${n}_and_ub_${t}`),n);v(new F($([[e,1],...r.map(e=>[e,-1])],0),`>=`,1-r.length,`${n}_and_lb`),n);return}if(t.op===`or`){let r=t.children.map(e=>D(e,n));for(let t=0;t<r.length;t++)v(new F($([[e,1],[r[t],-1]],0),`>=`,0,`${n}_or_lb_${t}`),n);v(new F($([[e,1],...r.map(e=>[e,-1])],0),`<=`,0,`${n}_or_ub`),n);return}if(t.op===`implies`){let r=D(t.children[0],n),i=D(t.children[1],n);v(new F($([[e,1],[r,1]],0),`>=`,1,`${n}_imp_1`),n),v(new F($([[e,1],[i,-1]],0),`>=`,0,`${n}_imp_2`),n),v(new F($([[e,1],[r,1],[i,-1]],0),`<=`,1,`${n}_imp_3`),n);return}if(t.op===`xor`){if(t.children.length===0){v(new F($([[e,1]],0),`==`,0,`${n}_xor_empty`),n);return}if(t.children.length===1){let r=D(t.children[0],n);v(new F($([[e,1],[r,-1]],0),`==`,0,`${n}_xor_single`),n);return}let r=t.children.map(e=>D(e,n)),i=r[0];for(let e=1;e<r.length-1;e++){let t=new V({name:_(`xor_fold_${e}`),type:`Binary`,lb:0,ub:1});o.push(t),ee(t,i,r[e],`${n}_xor_fold_${e}`),i=t}ee(e,i,r[r.length-1],n);return}}throw Error(`Unsupported logical element in equivalence linearization: ${t}`)}function k(e,t){let n=e.map(e=>b(e.start,t)),r=[];for(let t=0;t<e.length;t++)for(let i=t+1;i<e.length;i++)(e[t].duration>0||e[i].duration>0)&&r.push({i:t,j:i,sI:n[t],dI:e[t].duration,sJ:n[i],dJ:e[i].duration});return r}function A(e,t,n){let r=e.map(e=>({start:b(e.start,n),duration:e.duration,demand:e.demand})).filter(e=>e.duration>0&&e.demand>0);if(r.length===0)return{kind:`constant`,value:!0};let i=[];for(let e of r){let t=e.start.constant??0;if(!Number.isSafeInteger(t))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: task start offset (${t}) must be a safe integer.`);let r=t,a=t;for(let[t,i]of e.start.terms.entries()){if(i===0)continue;if(typeof t.lb!=`number`||typeof t.ub!=`number`||Number.isNaN(t.lb)||Number.isNaN(t.ub)||t.lb===-1/0||t.ub===1/0||t.lb>t.ub)throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: variable "${t.name}" has unbounded or invalid domain [${t.lb}, ${t.ub}]. Finite bounds are required.`);if(!Number.isSafeInteger(i))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: variable "${t.name}" coefficient (${i}) exceeds safe integer precision.`);let e=t.type===`Binary`?Math.max(0,Math.ceil(t.lb)):Math.ceil(t.lb),o=t.type===`Binary`?Math.min(1,Math.floor(t.ub)):Math.floor(t.ub);if(e>o)return{kind:`empty_domain`};if(!Number.isSafeInteger(e)||!Number.isSafeInteger(o))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: variable "${t.name}" integer bounds [${e}, ${o}] exceed JavaScript safe integer precision.`);let s=i*e,c=i*o;if(r+=Math.min(s,c),a+=Math.max(s,c),!Number.isSafeInteger(s)||!Number.isSafeInteger(c)||!Number.isSafeInteger(r)||!Number.isSafeInteger(a))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: task start time bounds exceed JavaScript safe integer precision.`)}let o=r+e.duration,s=a+e.duration;if(!Number.isSafeInteger(o)||!Number.isSafeInteger(s))throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: task end time bounds [${r}, ${s}) exceed JavaScript safe integer precision.`);i.push({...e,est:Object.is(r,-0)?0:r,lst:Object.is(a,-0)?0:a})}return i.some(e=>e.demand>t)?{kind:`constant`,value:!1}:{kind:`tasks`,active:i}}function te(e,t,n){let r=e.spec;switch(r.kind){case`distinct`:{let e=r.args.map(e=>b(e,n));if(e.length<=1){t||N(n);return}if(t)for(let t=0;t<e.length;t++)for(let r=t+1;r<e.length;r++)T(e[t].sub(e[r]),`!=`,0,`${n}_neq_${t}_${r}`,n);else{let t=[];for(let r=0;r<e.length;r++)for(let i=r+1;i<e.length;i++)t.push(new F(e[r].sub(e[i]),`==`,0,`${n}_eq_${r}_${i}`));M(new l(`or`,t),n)}return}case`disjoint`:{let e=k(r.tasks,n);if(e.length===0){t||N(n);return}if(t)for(let{i:t,j:r,sI:i,dI:a,sJ:s,dJ:c}of e){let e=new V({name:_(`disj_${t}_${r}`),type:`Binary`,lb:0,ub:1});o.push(e),ae(e,i.sub(s),`<=`,-a,1,`${n}_p_${t}_${r}`,n),ae(e,s.sub(i),`<=`,-c,0,`${n}_q_${t}_${r}`,n)}else M(new l(`or`,e.map(({i:e,j:t,sI:r,dI:i,sJ:a,dJ:o})=>new l(`and`,[new F(r.sub(a),`>=`,1-i,`${n}_ov1_${e}_${t}`),new F(a.sub(r),`>=`,1-o,`${n}_ov2_${e}_${t}`)]))),n);return}case`cumulative`:{let e=A(r.tasks,r.capacity,n);if(e.kind===`empty_domain`){N(n);return}if(e.kind===`constant`){e.value!==t&&N(n);return}let{active:i}=e;if(t){let e=1/0,t=-1/0,a=0;for(let n of i)n.est<e&&(e=n.est),n.lst+n.duration>t&&(t=n.lst+n.duration),a+=Math.max(0,n.lst-n.est+1);let s=t-e;if(!Number.isSafeInteger(s)||s>er||a>tr)throw Error(`Cannot linearize cumulative() constraint "${n}" for MIP solver: time horizon [${e}, ${t}) (span ${s}, ${a} time-indexed variables) exceeds MIP limit. Tighten start bounds or use { solver: "pumpkin" }.`);let c=[];for(let e=0;e<i.length;e++){let t=i[e],r=new Map,a=[],s=t.start.clone();for(let n=t.est;n<=t.lst;n++){let t=new V({name:_(`cum_u_${e}_${n}`),type:`Binary`,lb:0,ub:1});o.push(t),r.set(n,t),a.push([t,1]),n!==0&&s.addTerm(t,-n)}if(a.length===0){N(n);return}v(new F($(a,0),`==`,1,`${n}_cum_sos_${e}`),n),P(new F(s,`==`,0,`${n}_cum_start_${e}`),n),c.push(r)}for(let a=e;a<t;a++){let e=[],t=0;for(let n=0;n<i.length;n++){let r=i[n],o=a<=r.est+r.duration-1?r.est:a-r.duration+1,s=Math.min(r.lst,a);if(o<=s){t+=r.demand;let i=c[n];for(let t=o;t<=s;t++){let n=i.get(t);n&&e.push([n,r.demand])}}}t>r.capacity&&e.length>0&&v(new F($(e,0),`<=`,r.capacity,`${n}_cum_t_${a}`),n)}return}let a=[];for(let e=0;e<i.length;e++){let t=i[e],s=[];for(let r=0;r<i.length;r++){if(r===e)continue;let a=i[r],c=new V({name:_(`cum_act_${r}_${e}`),type:`Binary`,lb:0,ub:1});o.push(c),O(c,new l(`and`,[new F(a.start.sub(t.start),`<=`,0,`${n}_act_le_${r}_${e}`),new F(t.start.sub(a.start),`<=`,a.duration-1,`${n}_act_ge_${r}_${e}`)]),n),s.push([c,a.demand])}let c=new F($(s,0),`>=`,r.capacity-t.demand+1,`${n}_overload_${e}`);a.push(new l(`and`,[c]))}M(new l(`or`,a),n);return}case`allowed`:{let e=r.vars.map(e=>b(e,n));if(r.tuples.length===0){t&&N(n);return}if(t){let t=[];for(let e=0;e<r.tuples.length;e++){let n=new V({name:_(`tbl_r_${e}`),type:`Binary`,lb:0,ub:1});o.push(n),t.push(n)}v(new F($(t.map(e=>[e,1]),0),`==`,1,`${n}_tbl_sos`),n);for(let i=0;i<e.length;i++){let a=e[i].clone();for(let e=0;e<r.tuples.length;e++){let n=r.tuples[e][i];n!==0&&a.addTerm(t[e],-n)}P(new F(a,`==`,0,`${n}_tbl_col_${i}`),n)}return}let i=e.map(e=>{let t=Array.from(e.terms.entries()).filter(([,e])=>e!==0);if(t.length!==1)return null;let[n,r]=t[0];if(Math.abs(r)!==1||!Number.isSafeInteger(n.lb)||!Number.isSafeInteger(n.ub)||n.ub-n.lb!==1)return null;let i=e.constant;if(!Number.isSafeInteger(i))return null;let a=r*n.lb+i,o=r*n.ub+i;return{expr:e,lo:Math.min(a,o),hi:Math.max(a,o)}});for(let t=0;t<r.tuples.length;t++){let a=r.tuples[t],o=!0,s=!1;for(let e=0;e<a.length;e++){let t=i[e];if(!t){o=!1;break}if(a[e]!==t.lo&&a[e]!==t.hi){s=!0;break}}if(!s){if(o){let e=new R(new Map,0);for(let t=0;t<a.length;t++){let n=i[t];a[t]===n.lo?$n(e,n.expr.sub(n.lo),1):$n(e,$([],n.hi).sub(n.expr),1)}P(new F(e,`>=`,1,`${n}_nogood_${t}`),n)}else M(new l(`or`,a.map((r,i)=>new F(e[i],`!=`,r,`${n}_ntbl_${t}_${i}`))),n,`${n}_ntbl_${t}`)}}return}}}function ne(e,t,n){let r=t.spec;switch(r.kind){case`distinct`:{let t=r.args.map(e=>b(e,n));if(t.length<=1){v(new F($([[e,1]],0),`==`,1,`${n}_distinct_triv`),n);return}let i=[];for(let e=0;e<t.length;e++)for(let r=e+1;r<t.length;r++)i.push(new F(t[e].sub(t[r]),`!=`,0,`${n}_d_${e}_${r}`));O(e,new l(`and`,i),n);return}case`disjoint`:{let t=k(r.tasks,n);if(t.length===0){v(new F($([[e,1]],0),`==`,1,`${n}_disjoint_triv`),n);return}O(e,new l(`and`,t.map(({i:e,j:t,sI:r,dI:i,sJ:a,dJ:o})=>new l(`or`,[new F(r.sub(a),`<=`,-i,`${n}_dj1_${e}_${t}`),new F(a.sub(r),`<=`,-o,`${n}_dj2_${e}_${t}`)]))),n);return}case`cumulative`:{let t=A(r.tasks,r.capacity,n);if(t.kind===`empty_domain`){N(n);return}if(t.kind===`constant`){v(new F($([[e,1]],0),`==`,+!!t.value,`${n}_cum_triv`),n);return}let{active:i}=t,a=[];for(let e=0;e<i.length;e++){let t=i[e],s=[];for(let r=0;r<i.length;r++){if(r===e)continue;let a=i[r],c=new V({name:_(`cum_eq_act_${r}_${e}`),type:`Binary`,lb:0,ub:1});o.push(c),O(c,new l(`and`,[new F(a.start.sub(t.start),`<=`,0,`${n}_eq_le_${r}_${e}`),new F(t.start.sub(a.start),`<=`,a.duration-1,`${n}_eq_ge_${r}_${e}`)]),n),s.push([c,a.demand])}a.push(new F($(s,0),`<=`,r.capacity-t.demand,`${n}_ev_${e}`))}O(e,new l(`and`,a),n);return}case`allowed`:{let t=r.vars.map(e=>b(e,n));if(r.tuples.length===0){v(new F($([[e,1]],0),`==`,0,`${n}_allowed_empty`),n);return}O(e,new l(`or`,r.tuples.map((e,r)=>new l(`and`,e.map((e,i)=>new F(t[i],`==`,e,`${n}_eq_tbl_${r}_${i}`))))),n);return}}}function re(e){return e instanceof F||e instanceof l&&e.children.some(e=>re(e))}function ie(e,t){if(e instanceof F){if((e.lhs.terms.get(t)??0)!==0)return!0;for(let n of e.lhs.nonlinearTerms){if(n.coeff===0)continue;let e=n.atom;if(e.kind===`abs`&&(e.arg.terms.get(t)??0)!==0||(e.kind===`max`||e.kind===`min`)&&e.args.some(e=>(e.terms.get(t)??0)!==0)||e.kind===`at`&&((e.index.terms.get(t)??0)!==0||e.array.some(e=>(e.terms.get(t)??0)!==0)))return!0}return!1}return e instanceof l&&e.children.some(e=>ie(e,t))}function j(e,t,n,r){if(t instanceof F){se(e,E(t,n),1,r,n);return}if(t instanceof c||t instanceof h){v(new F($([[D(t,n),1],[e,-1]],0),`>=`,0,r),n);return}if(t instanceof l){if(t.op===`and`){for(let i=0;i<t.children.length;i++)j(e,t.children[i],n,`${r}_and_${i}`);return}if(t.op===`not`){let i=t.children[0];if(i instanceof F){le(e,E(i,n),1,r,n);return}if(i instanceof l){if(i.op===`not`){j(e,i.children[0],n,r);return}if(i.op===`or`){for(let t=0;t<i.children.length;t++)j(e,new l(`not`,[i.children[t]]),n,`${r}_not_or_${t}`);return}if(i.op===`and`){j(e,new l(`or`,i.children.map(e=>new l(`not`,[e]))),n,r);return}if(i.op===`implies`){j(e,i.children[0],n,`${r}_not_imp_0`),j(e,new l(`not`,[i.children[1]]),n,`${r}_not_imp_1`);return}}let a=D(i,n);v(new F($([[e,1],[a,1]],0),`<=`,1,r),n);return}if(t.op===`or`){if(t.children.length===0){v(new F($([[e,1]],0),`<=`,0,r),n);return}if(t.children.length===1){j(e,t.children[0],n,r);return}if(!t.children.some(e=>re(e))){let i=t.children.map(e=>D(e,n));v(new F($([[e,-1],...i.map(e=>[e,1])],0),`>=`,0,r),n);return}let i=[];for(let e=0;e<t.children.length;e++){let a=t.children[e];if(a instanceof c)i.push(D(a,n));else{let t=new V({name:_(`imp_or_${e}`),type:`Binary`,lb:0,ub:1});o.push(t),i.push(t),j(t,a,n,`${r}_or_${e}`)}}v(new F($([[e,-1],...i.map(e=>[e,1])],0),`>=`,0,r),n);return}if(t.op===`implies`){let[i,a]=t.children,s;if(i instanceof F){let e=E(i,n);s=new V({name:_(`ante`),type:`Binary`,lb:0,ub:1}),o.push(s),le(s,e,0,`${r}_ante_neg`,n)}else s=D(i,n);if(a instanceof c){v(new F($([[D(a,n),1],[e,-1],[s,-1]],0),`>=`,-1,r),n);return}let l=new V({name:_(`imp_joint`),type:`Binary`,lb:0,ub:1});o.push(l),v(new F($([[l,1],[e,-1],[s,-1]],0),`>=`,-1,`${r}_joint`),n),j(l,a,n,r);return}v(new F($([[D(t,n),1],[e,-1]],0),`>=`,0,r),n);return}throw Error(`Unsupported logical element in implication consequent "${n}": ${t}`)}function M(e,t,n=t){if(e instanceof F){T(e.lhs,e.sense,e.rhs,n,t);return}if(e instanceof h){te(e,!0,t);return}if(e instanceof c){v(new F($([[D(e,t),1]],0),`>=`,1,n),t);return}if(e instanceof l){if(e.op===`not`){let r=e.children[0];if(r instanceof c){v(new F($([[D(r,t),1]],0),`<=`,0,n),t);return}if(r instanceof h){te(r,!1,t);return}if(r instanceof F){ce(E(r,t),t);return}if(r instanceof l){if(r.op===`not`){M(r.children[0],t,n);return}if(r.op===`or`){for(let e=0;e<r.children.length;e++)M(new l(`not`,[r.children[e]]),t,`${n}_not_or_${e}`);return}if(r.op===`and`){M(new l(`or`,r.children.map(e=>new l(`not`,[e]))),t,n);return}if(r.op===`implies`){M(r.children[0],t,`${n}_not_imp_0`),M(new l(`not`,[r.children[1]]),t,`${n}_not_imp_1`);return}}v(new F($([[D(r,t),1]],0),`<=`,0,n),t);return}if(e.op===`and`){for(let r=0;r<e.children.length;r++)M(e.children[r],t,`${n}_and_${r}`);return}if(e.op===`or`){if(e.children.length===0){N(t);return}if(e.children.length===1){M(e.children[0],t,n);return}if(!e.children.some(e=>re(e))){v(new F($(e.children.map(e=>D(e,t)).map(e=>[e,1]),0),`>=`,1,n),t);return}let r=[];for(let i=0;i<e.children.length;i++){let a=e.children[i];if(a instanceof c)r.push(D(a,t));else{let e=new V({name:_(`or_branch_${i}`),type:`Binary`,lb:0,ub:1});o.push(e),r.push(e),j(e,a,t,`${n}_or_${i}`)}}v(new F($(r.map(e=>[e,1]),0),`>=`,1,n),t);return}if(e.op===`xor`){if(e.children.length===0){N(t);return}if(e.children.length===1){M(e.children[0],t,n);return}let r=e.children.map(e=>D(e,t));if(r.length===2){v(new F($([[r[0],1],[r[1],1]],0),`==`,1,n),t);return}let i=r[0];for(let e=1;e<r.length-1;e++){let t=new V({name:_(`xor_fold_${e}`),type:`Binary`,lb:0,ub:1});o.push(t),ee(t,i,r[e],`${n}_xor_fold_${e}`),i=t}let a=r[r.length-1];v(new F($([[i,1],[a,1]],0),`==`,1,n),t);return}if(e.op===`implies`){let[r,i]=e.children,a=r instanceof F?rr(r):null;if(a!==null){if(i instanceof F){let e=E(i,t);if((e.lhs.terms.get(a.binVar)??0)===0){se(a.binVar,e,a.activeVal,n,t);return}}if(i instanceof c){let e=D(i,t);v(a.activeVal===1?new F($([[e,1],[a.binVar,-1]],0),`>=`,0,n):new F($([[e,1],[a.binVar,1]],0),`>=`,1,n),t);return}if(i instanceof l&&i.op===`not`){let e=i.children[0];if(e instanceof c){let r=D(e,t);v(a.activeVal===1?new F($([[r,1],[a.binVar,1]],0),`<=`,1,n):new F($([[r,1],[a.binVar,-1]],0),`<=`,0,n),t);return}if(e instanceof F){let r=E(e,t);if((r.lhs.terms.get(a.binVar)??0)===0){le(a.binVar,r,a.activeVal,n,t);return}}}if(a.activeVal===1&&!ie(i,a.binVar)){j(a.binVar,i,t,n);return}}let s;if(r instanceof F){let e=E(r,t);s=new V({name:_(`ante`),type:`Binary`,lb:0,ub:1}),o.push(s),le(s,e,0,`${n}_ante_neg`,t)}else s=D(r,t);j(s,i,t,n);return}}throw Error(`Unsupported top-level logical constraint "${t}": ${e}`)}function ae(e,t,n,r,i,a,o){let s=Qn(e,t,n,r,i,n===`<=`?Xn(t,r,a):Zn(t,r,a),a);s.lhs.terms.size>0&&v(new F(s.lhs,n,s.rhs,a),o)}function oe(e){return new F(e.lhs,`==`,e.rhs,e.name)}function se(e,t,n,r,i){let a=E(t,i);if(a.sense===`!=`){le(e,oe(a),n,r,i);return}let{lhs:o,sense:s,rhs:c}=a;s===`==`?(ae(e,o,`<=`,c,n,`${r}_le`,i),ae(e,o,`>=`,c,n,`${r}_ge`,i)):ae(e,o,s,c,n,r,i)}function N(e){let t=new V({name:_(`unsat`),type:`Binary`,lb:0,ub:1});o.push(t),v(new F($([[t,1]],0),`>=`,2,e),e)}function P(e,t){let n=E(e,t),{lhs:r,sense:i,rhs:a}=n;if(i===`!=`){ce(oe(n),t);return}let o=r.constant??0,s=a-o;if(!Number.isFinite(o)||!Number.isFinite(a)||!Number.isFinite(s))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: constraint "${e.name}" contains non-finite constant or right-hand side.`);let c=[];for(let[n,i]of r.terms){if(!Number.isFinite(i))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: variable "${n.name}" in constraint "${e.name}" has non-finite coefficient (${i}).`);i!==0&&c.push([n,i])}if(c.length===0){(i===`<=`?0<=s:i===`>=`?0>=s:s===0)||N(t);return}v(new F($(c,0),i,s,e.name||t),t)}function ce(e,t){let n=E(e,t);if(n.sense===`!=`){P(oe(n),t);return}let r=ir(n,t);if(r.kind===`always_true`)return;if(r.kind===`always_false`){N(t);return}if(r.kind===`single`){v(new F(r.lhs,r.sense,r.rhs,n.name||t),t);return}let i=new V({name:_(`neq_dir`),type:`Binary`,lb:0,ub:1});o.push(i);let a=n.name||t;ae(i,r.lhs,`<=`,r.ltRhs,1,`${a}_lt`,t),ae(i,r.lhs,`>=`,r.gtRhs,0,`${a}_gt`,t)}function le(e,t,n,r,i){let a=E(t,i);if(a.sense===`!=`){se(e,oe(a),n,r,i);return}let s=ir(a,i);if(s.kind===`always_true`)return;if(s.kind===`always_false`){v(new F($([[e,1]],0),n===0?`>=`:`<=`,+(n===0),r),i);return}if(s.kind===`single`){ae(e,s.lhs,s.sense,s.rhs,n,r,i);return}let c=new V({name:_(`neq_lt`),type:`Binary`,lb:0,ub:1}),l=new V({name:_(`neq_gt`),type:`Binary`,lb:0,ub:1});o.push(c,l),ae(c,s.lhs,`<=`,s.ltRhs,1,`${r}_lt`,i),ae(l,s.lhs,`>=`,s.gtRhs,1,`${r}_gt`,i),v(new F($([[c,1],[l,1],[e,n===0?1:-1]],0),`>=`,+(n===0),`${r}_disj`),i)}for(let e of p)T(e.lhs,e.sense,e.rhs,e.name,e.name);let ue;if(a&&a.expr.hasNonlinearTerms()){let e=i(a.sense)===`Minimize`,t=a.expr,n=new Map(t instanceof w?t.linearTerms:t.terms),r=t.constant;for(let i of t.nonlinearTerms){if(i.coeff===0)continue;let t=(e?i.coeff>0:i.coeff<0)?`upper`:`lower`,a=S(i.atom,t,`__objective`);r+=i.coeff*a.constant;for(let[e,t]of a.terms.entries()){let r=(n.get(e)??0)+i.coeff*t;r===0?n.delete(e):n.set(e,r)}}ue=t instanceof w?new w(n,t.quadTerms,r,[]):new R(n,r,[])}else a&&(ue=a.expr);for(let e of r){let t=e.name,n=e.expr;M(n,t)}return{variables:o,constraints:s,boolVarToBinary:u,constraintToOriginalName:d,...ue===void 0?{}:{objective:ue}}}function rr(e){if(e.lhs.hasNonlinearTerms()||e.lhs.terms.size!==1||(e.lhs.constant??0)!==0)return null;let[[t,n]]=Array.from(e.lhs.terms.entries());return t.type!==`Binary`&&t.type!==`Integer`||t.lb!==0||t.ub!==1||n!==1?null:e.sense===`==`&&e.rhs===1||e.sense===`>=`&&e.rhs===1||e.sense===`!=`&&e.rhs===0?{binVar:t,activeVal:1}:e.sense===`==`&&e.rhs===0||e.sense===`<=`&&e.rhs===0||e.sense===`!=`&&e.rhs===1?{binVar:t,activeVal:0}:null}function ir(e,t){let{lhs:n,sense:r,rhs:i}=e;if(n.hasNonlinearTerms())throw Error(`Cannot negate unlowered nonlinear constraint "${e.name}" in "${t}".`);let a=n.constant??0,o=i-a;if(!Number.isFinite(a)||!Number.isFinite(i)||!Number.isFinite(o))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: constraint "${e.name}" contains non-finite constant or right-hand side.`);if(r!==`<=`&&r!==`>=`&&r!==`==`)throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: unsupported comparison sense "${String(r)}" in constraint "${e.name}".`);let s=[];for(let[r,i]of n.terms){if(!Number.isFinite(i))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: variable "${r.name}" in constraint "${e.name}" has non-finite coefficient (${i}).`);if(i!==0){if(r.type!==`Integer`&&r.type!==`Binary`)throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: negating constraint "${e.name}" involves Continuous variable "${r.name}", whose strict-inequality negation creates an open half-space not representable in MIP. Use { solver: "z3" }, rewrite explicitly with a closed tolerance such as or(expr\`... >= ... + eps\`, ...), or model the proposition with m.bool().`);if(!Number.isSafeInteger(i))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: negating constraint "${e.name}" requires safe integer coefficients, but variable "${r.name}" has coefficient ${i}. Scale to integer coefficients, use { solver: "z3" }, or rewrite explicitly with or(expr\`... >= ... + eps\`, ...) / m.bool().`);s.push([r,i])}}if(s.length===0)return(r===`<=`?0<=o:r===`>=`?0>=o:o===0)?{kind:`always_false`}:{kind:`always_true`};if(!Number.isInteger(o))throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: negating constraint "${e.name}" requires an integer right-hand side and constant, received effective right-hand side ${o}. Scale or round the threshold to an integer, use { solver: "z3" }, or rewrite explicitly with or(expr\`... >= ... + eps\`, ...) / m.bool().`);if(Math.abs(o)>=2**53-1)throw Error(`Cannot linearize logical constraint "${t}" for MIP solver: effective right-hand side (${o}) of constraint "${e.name}" exceeds safe integer precision for exact +/-1 negation. Please rescale coefficients/constants or solve with { solver: "z3" }.`);let c=$(s,0);if(r===`<=`)return{kind:`single`,lhs:c,sense:`>=`,rhs:o+1};if(r===`>=`)return{kind:`single`,lhs:c,sense:`<=`,rhs:o-1};let l=o-1,u=o+1,d=0,f=0,p=!0,m=!0;for(let[e,t]of s){if(!(e.lb<=e.ub)){p=!1,m=!1;break}let n=t>0?e.lb:e.ub,r=t>0?e.ub:e.lb,i=t*n,a=t*r;d+=i,f+=a,p&&=Number.isSafeInteger(n)&&Number.isSafeInteger(i)&&Number.isSafeInteger(d),m&&=Number.isSafeInteger(r)&&Number.isSafeInteger(a)&&Number.isSafeInteger(f)}let h=!(p&&d>l),g=!(m&&f<u);return!h&&!g?{kind:`always_false`}:g?h?{kind:`disjunction`,lhs:c,ltRhs:l,gtRhs:u}:{kind:`single`,lhs:c,sense:`>=`,rhs:u}:{kind:`single`,lhs:c,sense:`<=`,rhs:l}}async function ar(e){let t=e.master;if(!t)throw Error(`A master Model must be provided for solveColumnGeneration.`);let{pricing:n,maxIterations:r=100,reducedCostTolerance:i=1e-6,finalizeAsMIP:a=!0,solver:o,solverOptions:s,onIteration:c}=e,l=t.sense.toLowerCase()===`maximize`,u=n;if(!u)throw Error(`The 'pricing' callback must be provided in ColumnGenerationOptions.`);let d=[],f=null,p=0,m=t.status;for(let e=1;e<=r;e++){p=e;let n=await t.relax(o,s);if(m=n,n!==`Optimal`&&n!==`Feasible`||!t.solution)break;f=t.objectiveValue;let r=t.solution,a=r.duals||{},h=e=>typeof e==`string`?a[e]??0:e.dual??(e.name?a[e.name]??0:0),g=await u({iteration:e,duals:a,getDual:h,masterSolution:r,reducedCostTolerance:i,master:t}),_=[];g&&(Array.isArray(g)?_.push(...g):_.push(g));let v=[];for(let e of _){let t=e.reducedCost;if(typeof t!=`number`||!Number.isFinite(t)){let n=0,r=e.coefficients;if(Array.isArray(r))for(let e of r)Array.isArray(e)?n+=e[1]*h(e[0]):e&&typeof e==`object`&&(n+=e.coeff*h(e.constraint));else if(r instanceof Map)for(let[e,t]of r.entries())n+=t*h(e);else if(r&&typeof r==`object`)for(let[e,t]of Object.entries(r))n+=t*h(e);t=e.cost-n}(l?t>i:t<-i)&&v.push(e)}if(c&&c({iteration:e,relaxationObjective:f,columnsAdded:d.length+v.length,proposedColumns:v}),v.length===0)break;for(let e of v){let n=t.column({name:e.name,type:e.type||`Continuous`,lb:e.lb,ub:e.ub,cost:e.cost,coefficients:e.coefficients});d.push({variable:n,proposal:e})}}let h=f;a&&(m===`Optimal`||m===`Feasible`)&&(m=await t.solve(o,s),h=t.objectiveValue);let g={};for(let e of t.variables.values())e instanceof V&&e.value!==null&&(g[e.name]=e.value);let _={status:m,objectiveValue:h,relaxationObjectiveValue:f,iterations:p,columnsAdded:d.length,generatedColumns:d,master:t,values:g};return t.decomposition=_,_}function or(e,t){let n=e;if(n instanceof F||typeof n==`object`&&n&&`sense`in n&&`lhs`in n&&`rhs`in n)throw Error(`Cannot use a Constraint as an objective in ${t}(). Use m.constraint(expr\`... <= ...\`) for constraints, or supply an unconstrained arithmetic expression to ${t}(), e.g. m.objective(${t}(expr\`30 * \${x}\`)).`);if(typeof n==`string`&&/(<=|>=|==|!=|=<|=>|<|>|=)/.test(n))throw Error(`Cannot use a comparison constraint as an objective in ${t}(). Use m.constraint(expr\`... <= ...\`) for constraints, or supply an unconstrained arithmetic expression to ${t}(), e.g. m.objective(${t}(expr\`30 * \${x}\`)).`);if(typeof n==`number`){if(!Number.isFinite(n))throw Error(`Invalid non-finite objective constant "${n}" passed to ${t}().`);return n}if(typeof n==`string`||n instanceof R||n instanceof w||n instanceof V||typeof n==`object`&&n&&(`terms`in n&&n.terms instanceof Map&&typeof n.constant==`number`||`quadTerms`in n&&n.quadTerms instanceof Map&&`linearTerms`in n&&n.linearTerms instanceof Map&&typeof n.constant==`number`||`id`in n&&`name`in n&&`lb`in n&&`ub`in n))return n;throw Error(`Invalid expression passed to ${t}(): expected a finite number, Var, LinExpr, QuadExpr, or arithmetic expression string.`)}function sr(e){return{expr:or(e,`maximize`),sense:`Maximize`}}function cr(e){return{expr:or(e,`minimize`),sense:`Minimize`}}var lr=new WeakSet;function ur(e){return!!(e&&typeof e==`object`&&`constraints`in e&&`variables`in e&&typeof e.solve==`function`)}async function dr(e,t,n,r,i,a,o,s,c=1){let l=[];for(let r=0;r<t.length;r++){let a=t[r],o=a.lhs,s=a.sense,u=a.rhs-(o.constant||0),d=[],f=[],p=0;for(let[e,t]of o.terms.entries()){let r=n.variables.get(e.name);if(e.ownerModel===n||r instanceof V){f.push([e,t]);let n=i[e.name]??0;p+=t*n}else d.push([e,t])}let m=u-p,h=new R;for(let[e,t]of d)h.addTerm(e,t);let g=new F(h,s,m,`__benders_link_${c}_${r}`);e.constraint(g),l.push({origConstraint:a,subConstr:g,masterTerms:f,baseRhs:u})}let u=await e.solve(o,{...s,relax:!0});if(u!==`Optimal`&&u!==`Feasible`)throw Error(`Benders subproblem failed at iteration ${c} with status "${u}". Auto-cut generation requires an Optimal or Feasible subproblem (expected Optimal or Feasible).`);let d=e.objectiveValue;if(typeof d!=`number`||!Number.isFinite(d))throw Error(`Benders subproblem returned invalid objectiveValue (${String(d)}) at iteration ${c}.`);if(lr.has(r)&&d<r.lb-1e-6)throw Error(`Benders auto-created "__benders_theta" (lb: ${r.lb}) cannot represent negative subproblem cost (${d}) at iteration ${c}. Define an explicit theta variable with a negative lower bound and pass options.theta.`);let f=i[r.name]??0,p=1e-4;if(!(a?f<d-p:f>d+p))return null;let m=0,h=new Map,g=new Set(l.map(e=>e.subConstr.name));for(let t of e.constraints.values()){if(!(t instanceof F)||g.has(t.name))continue;let n=e.solution?.duals[t.name]??t.dual??0;if(Math.abs(n)>1e-12){let e=t.rhs-(t.lhs.constant||0);m+=n*e}}for(let t of l){let n=e.solution?.duals[t.subConstr.name]??t.subConstr.dual??0;if(Math.abs(n)>1e-12){m+=n*t.baseRhs;for(let[e,r]of t.masterTerms){let t=h.get(e)??0;h.set(e,t+n*r)}}}let _=new R;_.addTerm(r,1);for(let[e,t]of h.entries())Math.abs(t)>1e-12&&_.addTerm(e,t);let v=new F(_,a?`>=`:`<=`,m,`__benders_opt_cut_${c}`),y=(n.objectiveValue??0)-f+d;return{kind:`optimality`,constraint:v,name:v.name,subproblemObjective:y}}async function fr(e){let t=e.master;if(!t)throw Error(`A master Model must be provided for solveBenders.`);let{subproblem:n,maxIterations:r=100,gapTolerance:i=1e-4,solver:a,solverOptions:o,onIteration:s}=e,c;if(e.theta!==void 0){if(typeof e.theta==`string`){let n=t.variables.get(e.theta);if(!(n instanceof V))throw Error(`Benders option "theta" references variable "${e.theta}", which was not found on the master model.`);c=n}else c=e.theta}if(!c){for(let e of t.variables.values())if(e instanceof V&&(e.name===`theta`||e.name===`__benders_theta`)){c=e;break}}let l=0,u=0,d=t.status,f,p,m,h={},g=null;for(let e=1;e<=r;e++){u=e;let r=await t.solve(a,o);if(d=r,r!==`Optimal`&&r!==`Feasible`)break;let _=t.objectiveValue,v=t.sense.toLowerCase()===`minimize`;v?f=_===null?f:_:p=_===null?p:_;let y={};for(let e of t.variables.values())e instanceof V&&e.value!==null&&(y[e.name]=e.value);let b=await n({iteration:e,masterValues:y,getMasterValue:e=>typeof e==`string`?y[e]??0:e.value??(e.name?y[e.name]??0:0),masterObjective:_,lowerBound:f,upperBound:p,master:t}),x=[];if(b){if(ur(b)){let n=b,r=n.linkingConstraints;if(!c){if(!v)throw Error(`Benders auto-cut generation requires an explicit options.theta variable for Maximize master models.`);c=t.continuous(`__benders_theta`,{lb:0}),t.objective(cr(t.objective().add(c))),lr.add(c)}let i=await dr(n,r,t,c,y,v,a,o,e);i&&x.push(i)}else Array.isArray(b)?x.push(...b):x.push(b)}for(let e of x)if(typeof e.subproblemObjective==`number`&&Number.isFinite(e.subproblemObjective)){if(v){let t=e.subproblemObjective;(p===void 0||t<p)&&(p=t,g=t,h={...y})}else{let t=e.subproblemObjective;(f===void 0||t>f)&&(f=t,g=t,h={...y})}}if(f!==void 0&&p!==void 0){let e=Math.abs(p)+1e-10;m=Math.abs(p-f)/e}if(s&&s({iteration:e,masterObjective:_,lowerBound:f,upperBound:p,cutsAdded:l+x.length,proposedCuts:x}),x.length===0){g=_,h={...y};break}if(m!==void 0&&m<=i)break;for(let e of x)t.constraint(e.constraint,e.name),l++}let _=d===`Optimal`||d===`Feasible`,v=Object.keys(h).length>0?h:_?(()=>{let e={};for(let n of t.variables.values())n instanceof V&&n.value!==null&&(e[n.name]=n.value);return e})():{},y=g===null?_?t.objectiveValue:null:g,b={status:d,objectiveValue:y,lowerBound:f,upperBound:p,gap:m,iterations:u,cutsAdded:l,master:t,values:v};return t.decomposition=b,b}function pr(e,t){return e.hasNonlinearTerms()?!0:mr(t)}function mr(e){for(let t of e)if(t.sense===`!=`||t.lhs.hasNonlinearTerms())return!0;return!1}function hr(e){let t=Object.freeze({get size(){return e.size},get(t){return e.get(t)},has(t){return e.has(t)},forEach(n,r){e.forEach((e,i)=>{n.call(r,e,i,t)})},entries(){return e.entries()},keys(){return e.keys()},values(){return e.values()},[Symbol.iterator](){return e[Symbol.iterator]()}});return t}function gr(e){return Array.isArray(e)||typeof e==`object`&&!!e&&!(e instanceof String)&&typeof e[Symbol.iterator]==`function`}function _r(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&!(e instanceof String)&&typeof e[Symbol.iterator]!=`function`}function vr(e){return e instanceof V||typeof e==`object`&&!!e&&!(e instanceof s)&&!(e instanceof F)&&`id`in e&&`name`in e&&`lb`in e&&`ub`in e&&!(`terms`in e)&&!(`quadTerms`in e)&&!(`sense`in e)}function yr(e,t){if(!Number.isInteger(e)||e<0)throw Error(`Invalid count (${e}) for ${t} variable creation: count must be a non-negative integer.`)}var br=class{name;_sense;_objectiveExpr;_variables=[];_constraints=[];_boolVars=[];_logicalConstraints=[];unsatCore=void 0;_conflicts=void 0;_values=new Map;varMapByName=new Map;varPrefixCounters=new Map;boolVarMapByName=new Map;boolVarPrefixCounters=new Map;constrMapByName=new Map;constrPrefixCounters=new Map;logicalConstrMapByName=new Map;logicalConstrCounter=0;allVarsMap=new Map;allConstrsMap=new Map;variables;constraints;values;status=`NotSolved`;terminationStatus=`NotSolved`;hasPrimalSolution=!1;objectiveValue=null;objectiveBound=void 0;relativeGap=void 0;absoluteGap=void 0;runTime=0;solution=null;solver=null;decomposition;_linkingConstraints;hasSolutionState=!1;modelRevision=0;activeOperationId=0;batchDepth=0;batchMutated=!1;batchUndoActions=[];constructor(e={},t){let n;n=typeof e==`string`?{...t,name:e}:e,this.name=n.name||`OptimizationModel`,this._sense=i(n.sense),this._objectiveExpr=new R,this.variables=hr(this.allVarsMap),this.constraints=hr(this.allConstrsMap),this.values=hr(this._values),O(this,()=>this.recordModelMutation()),n.solver&&(this.solver=nt(n.solver))}get sense(){return this._sense}set sense(e){let t=i(e);this._sense!==t&&(this._sense=t,this.recordModelMutation())}get conflicts(){return this._conflicts??this.unsatCore}set conflicts(e){this._conflicts=e}clearSolutionFields(){if(this.hasSolutionState||this.status!==`NotSolved`||this.terminationStatus!==`NotSolved`||this.hasPrimalSolution||this.solution!==null||this.unsatCore!==void 0){this.hasSolutionState=!1,this.status=`NotSolved`,this.terminationStatus=`NotSolved`,this.hasPrimalSolution=!1,this.objectiveValue=null,this.objectiveBound=void 0,this.relativeGap=void 0,this.absoluteGap=void 0,this.solution=null,this.runTime=0,this.unsatCore=void 0,this._conflicts=void 0,this._values.clear();for(let e of this._variables)e.value=null,e.reducedCost=null;for(let e of this._boolVars)e.value=null;for(let e of this._constraints)e.dual=null,e.slack=null}}recordModelMutation(){if(this.batchDepth>0){this.batchMutated=!0;return}this.modelRevision++,this.clearSolutionFields()}runTransactionalBatch(e){if(this.batchDepth>0)return e();let t=this._variables.length,n=this._boolVars.length,r=this._constraints.length,i=this._logicalConstraints.length,a=new Map(this.varPrefixCounters),o=new Map(this.boolVarPrefixCounters),s=new Map(this.constrPrefixCounters),c=this.logicalConstrCounter;this.batchDepth=1,this.batchMutated=!1,this.batchUndoActions=[];try{let t=e();this.batchDepth=0;let n=this.batchMutated;return this.batchMutated=!1,this.batchUndoActions=[],n&&this.recordModelMutation(),t}catch(e){this.batchDepth=0,this.batchMutated=!1;for(let e=t;e<this._variables.length;e++){let t=this._variables[e];this.varMapByName.delete(t.name),this.allVarsMap.delete(t.name),t.ownerModel=null,re(t,this)}this._variables.length=t;for(let e=n;e<this._boolVars.length;e++){let t=this._boolVars[e];this.boolVarMapByName.delete(t.name),this.allVarsMap.delete(t.name)}this._boolVars.length=n;for(let e=r;e<this._constraints.length;e++){let t=this._constraints[e];this.constrMapByName.delete(t.name),this.allConstrsMap.delete(t.name)}this._constraints.length=r;for(let e=i;e<this._logicalConstraints.length;e++){let t=this._logicalConstraints[e];this.logicalConstrMapByName.delete(t.name),this.allConstrsMap.delete(t.name)}this._logicalConstraints.length=i;for(let e=this.batchUndoActions.length-1;e>=0;e--)this.batchUndoActions[e]();throw this.batchUndoActions=[],this.varPrefixCounters=a,this.boolVarPrefixCounters=o,this.constrPrefixCounters=s,this.logicalConstrCounter=c,e}}createDomainVars(e,t,n,r){let i=e.toLowerCase(),a=typeof t==`number`,o=typeof n==`number`,s=gr(t),c=gr(n);if(o||c){if(a&&yr(t,i),o&&yr(n,i),!a&&!s||r!==void 0&&!_r(r))throw Error(`Invalid arguments provided for ${i} variable creation`);let c=a?Array.from({length:t},(e,t)=>t):Array.from(t),l=o?Array.from({length:n},(e,t)=>t):n===t?c:Array.from(n),u=r||{},d=u.prefix||u.name||`x`;return this.runTransactionalBatch(()=>{let t=a?[]:{};for(let n of c){let r=o?[]:{};for(let t of l)r[t]=this.addVar({...u,type:e,name:`${d}_${n}_${t}`});t[n]=r}return t})}if(typeof t==`string`||t===void 0){if(n!==void 0&&!_r(n))throw Error(`Invalid arguments provided for ${i} variable creation`);let r=n||{},a=typeof t==`string`?t:r.name;return this.addVar({...r,type:e,name:a})}if(_r(t)){if(n!==void 0)throw Error(`Invalid arguments provided for ${i} variable creation`);let r=t;return this.addVar({...r,type:e})}if(n!==void 0&&!_r(n))throw Error(`Invalid arguments provided for ${i} variable creation`);let l=n||{},u=l.prefix||l.name;if(typeof t==`number`)return yr(t,i),this.runTransactionalBatch(()=>{let n=[],r=u||`x`;for(let i=0;i<t;i++)n.push(this.addVar({...l,type:e,name:void 0,prefix:r}));return n});if(gr(t))return this.runTransactionalBatch(()=>{let n={};for(let r of t){let t=u?`${u}_${r}`:`${r}`;n[r]=this.addVar({...l,type:e,name:t})}return n});throw Error(`Invalid arguments provided for ${i} variable creation`)}binary(e,t,n){return this.createDomainVars(`Binary`,e,t,n)}integer(e,t,n){return this.createDomainVars(`Integer`,e,t,n)}continuous(e,t,n){return this.createDomainVars(`Continuous`,e,t,n)}column(e){let t=e.type||`Continuous`,n=this.addVar({name:e.name,type:t,lb:e.lb,ub:e.ub});if(typeof e.cost==`number`&&e.cost!==0&&(this._objectiveExpr=this._objectiveExpr.add(n.mul(e.cost)),this.recordModelMutation()),e.coefficients){if(Array.isArray(e.coefficients)){for(let t of e.coefficients)if(Array.isArray(t)){let[e,r]=t,i=typeof e==`string`?this.constrMapByName.get(e):e;if(!i)throw Error(`Constraint '${String(e)}' not found in model when adding column`);i.addTerm(n,r)}else if(typeof t==`object`&&t){let e=typeof t.constraint==`string`?this.constrMapByName.get(t.constraint):t.constraint;if(!e)throw Error(`Constraint '${String(t.constraint)}' not found in model when adding column`);e.addTerm(n,t.coeff)}}else if(e.coefficients instanceof Map)for(let[t,r]of e.coefficients.entries()){let e=typeof t==`string`?this.constrMapByName.get(t):t;if(!e)throw Error(`Constraint '${String(t)}' not found in model when adding column`);e.addTerm(n,r)}else if(typeof e.coefficients==`object`)for(let[t,r]of Object.entries(e.coefficients)){let e=this.constrMapByName.get(t);if(!e)throw Error(`Constraint '${t}' not found in model when adding column`);e.addTerm(n,r)}}return n}bool(e,t,n){let r=typeof e==`number`,i=typeof t==`number`,a=gr(e),o=gr(t);if(i||o){if(r&&yr(e,`boolean`),i&&yr(t,`boolean`),!r&&!a||n!==void 0&&!_r(n))throw Error(`Invalid arguments provided for boolean variable creation`);let o=r?Array.from({length:e},(e,t)=>t):Array.from(e),s=i?Array.from({length:t},(e,t)=>t):t===e?o:Array.from(t),c=n||{},l=c.prefix||c.name||`p`;return this.runTransactionalBatch(()=>{let e=r?[]:{};for(let t of o){let n=i?[]:{};for(let e of s)n[e]=this.createBoolVar(`${l}_${t}_${e}`);e[t]=n}return e})}if(typeof e==`string`||e===void 0){if(t!==void 0&&!_r(t))throw Error(`Invalid arguments provided for boolean variable creation`);let n=t||{},r=typeof e==`string`?e:n.name;return this.createBoolVar(r,n.prefix)}if(_r(e)){if(t!==void 0)throw Error(`Invalid arguments provided for boolean variable creation`);let n=e;return this.createBoolVar(n.name,n.prefix)}if(t!==void 0&&!_r(t))throw Error(`Invalid arguments provided for boolean variable creation`);let s=t||{},c=s.prefix||s.name;if(typeof e==`number`)return yr(e,`boolean`),this.runTransactionalBatch(()=>{let t=[],n=c||`p`;for(let r=0;r<e;r++)t.push(this.createBoolVar(void 0,n));return t});if(gr(e))return this.runTransactionalBatch(()=>{let t={};for(let n of e){let e=c?`${c}_${n}`:`${n}`;t[n]=this.createBoolVar(e)}return t});throw Error(`Invalid arguments provided for boolean variable creation`)}hasVarName(e){return this.varMapByName.has(e)||this.boolVarMapByName.has(e)}getNextVarName(e){let t=this.varPrefixCounters.get(e)??0,n=`${e}_${t}`;for(;this.hasVarName(n);)t++,n=`${e}_${t}`;return this.varPrefixCounters.set(e,t+1),n}getNextBoolVarName(e){let t=this.boolVarPrefixCounters.get(e)??0,n=`${e}_${t}`;for(;this.hasVarName(n)||this.hasConstraintName(n);)t++,n=`${e}_${t}`;return this.boolVarPrefixCounters.set(e,t+1),n}hasConstraintName(e){return this.constrMapByName.has(e)||this.logicalConstrMapByName.has(e)}hasBoolVarName(e){return this.boolVarMapByName.has(e)}getNextConstrName(e=`c`){let t=this.constrPrefixCounters.get(e)??1,n=`${e}_${t}`;for(;this.hasConstraintName(n)||this.hasBoolVarName(n);)t++,n=`${e}_${t}`;return this.constrPrefixCounters.set(e,t+1),n}getNextLogicalConstrName(){let e=this.logicalConstrCounter+1,t=`lc_${e}`;for(;this.hasConstraintName(t)||this.hasBoolVarName(t);)e++,t=`lc_${e}`;return this.logicalConstrCounter=e,t}createBoolVar(e,t){let n=typeof e==`string`?e.trim():void 0,r=typeof t==`string`?t.trim():``,i=r.length>0?r:`p`,a=n&&n.length>0?n:this.getNextBoolVarName(i);if(this.hasVarName(a))throw Error(`Variable with name '${a}' already exists in model`);if(this.hasConstraintName(a))throw Error(`Boolean variable name '${a}' conflicts with an existing constraint in model`);let o=new c(a);return this._boolVars.push(o),this.boolVarMapByName.set(o.name,o),this.allVarsMap.set(o.name,o),this.recordModelMutation(),o}addVar(e){let t=e||{},n=typeof t.name==`string`?t.name.trim():void 0,r=n&&n.length>0?n:void 0,i=typeof t.prefix==`string`?t.prefix.trim():``,a=i.length>0?i:`x`,o=this.varPrefixCounters.get(a),s=r??this.getNextVarName(a);try{if(this.hasVarName(s))throw Error(`Variable with name '${s}' already exists in model`);let e=new V({...t,name:s,prefix:a});return e.hasExplicitName=r!==void 0,M(e),te(e,this),e.ownerModel=this,this._variables.push(e),this.varMapByName.set(e.name,e),this.allVarsMap.set(e.name,e),this.recordModelMutation(),e}catch(e){throw r===void 0&&(o===void 0?this.varPrefixCounters.delete(a):this.varPrefixCounters.set(a,o)),e}}objective(e){if(arguments.length===0)return this._objectiveExpr.clone();let t=e;if(t instanceof F||typeof t==`object`&&t&&`sense`in t&&`lhs`in t&&`rhs`in t||typeof t==`string`&&/(<=|>=|==|!=|=<|=>|<|>|=)/.test(t))throw Error("Cannot use a Constraint as an objective. Did you mean to use m.constraint(expr`... <= ...`)? To set an objective, wrap an unconstrained expression with maximize(...) or minimize(...), e.g. m.objective(maximize(expr`30 * ${x}`)).");if(typeof t!=`object`||!t||!(`expr`in t)||!(`sense`in t))throw Error("m.objective(...) expects an ObjectiveSpec created with maximize(...) or minimize(...), e.g. m.objective(maximize(expr`30 * ${x}`)).");return this.applyObjective(t.expr,t.sense),this}applyObjective(e,t){if(e instanceof F||typeof e==`object`&&e&&`sense`in e&&`lhs`in e&&`rhs`in e||typeof e==`string`&&/(<=|>=|==|!=|=<|=>|<|>|=)/.test(e))throw Error(typeof e==`string`?"Cannot use a comparison constraint as an objective. Did you mean to use m.constraint(expr`... <= ...`)? To set an objective, wrap an unconstrained expression with maximize(...) or minimize(...), e.g. m.objective(maximize(expr`30 * ${x}`)).":"Cannot use a Constraint as an objective. Did you mean to use m.constraint(expr`... <= ...`)? To set an objective, wrap an unconstrained expression with maximize(...) or minimize(...), e.g. m.objective(maximize(expr`30 * ${x}`)).");let n=t===void 0?this.sense:i(t),r;if(typeof e==`string`)r=ze(e,e=>this.varMapByName.get(e));else if(typeof e==`number`)r=new R(new Map,e);else if(e instanceof w)r=e.clone();else if(e instanceof R)r=e.clone();else if(typeof e==`object`&&e&&`quadTerms`in e&&e.quadTerms instanceof Map&&`linearTerms`in e&&e.linearTerms instanceof Map&&typeof e.constant==`number`){let t=e;r=new w(t.linearTerms,t.quadTerms,t.constant,t.nonlinearTerms)}else if(typeof e==`object`&&e&&`terms`in e&&e.terms instanceof Map&&typeof e.constant==`number`){let t=e;r=new R(t.terms,t.constant,t.nonlinearTerms)}else if(e instanceof V||typeof e==`object`&&e&&`id`in e&&`name`in e&&`lb`in e&&`ub`in e)r=new R(new Map([[e,1]]),0);else throw Error(`Invalid objective expression: expected a finite number, Var, LinExpr, QuadExpr, or arithmetic expression string.`);P(r,this.name,e=>this.varMapByName.get(e.name)===e),this._sense=n,this._objectiveExpr=r,this.recordModelMutation()}constraint(e,t){if(Array.isArray(e))return this.runTransactionalBatch(()=>{let t=[];for(let n of e)t.push(this.constraint(n));return t});if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e)throw Error(`Constraint must contain a comparison operator (<=, >=, ==): cannot add a quadratic expression as a constraint.`);if(e instanceof R||typeof e==`object`&&e&&`terms`in e)throw Error("Constraint must contain a comparison operator (<=, >=, ==): cannot add a linear expression without a comparison operator. Use expr`... <= ...` or .le(), .ge(), .eq().");if(vr(e))throw Error(`Cannot add numeric variable "${e.name}" directly as a constraint without a comparison operator (<=, >=, ==). Numeric variables require a comparison such as expr\`\${x} <= 10\` or x.le(10), whereas propositional BoolVar variables must be created with m.bool().`);return this.addConstraint(e,t)}addConstraint(e,t){if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e)throw Error(`Constraint must contain a comparison operator (<=, >=, ==): cannot add a quadratic expression as a constraint.`);if(e instanceof R||typeof e==`object`&&e&&`terms`in e)throw Error("Constraint must contain a comparison operator (<=, >=, ==): cannot add a linear expression without a comparison operator. Use expr`... <= ...` or .le(), .ge(), .eq().");if(vr(e))throw Error(`Cannot add numeric variable "${e.name}" directly as a constraint without a comparison operator (<=, >=, ==). Numeric variables require a comparison such as expr\`\${x} <= 10\` or x.le(10), whereas propositional BoolVar variables must be created with m.bool().`);if(e instanceof s){let n=typeof t==`string`&&t.trim().length>0?t.trim():void 0;if(n!==void 0){if(this.hasConstraintName(n))throw Error(`Constraint with name '${n}' already exists in model`);if(this.hasBoolVarName(n))throw Error(`Constraint name '${n}' conflicts with an existing Boolean variable in model`)}let r=this.logicalConstrCounter,i=n??this.getNextLogicalConstrName();try{le(e,i,this.name,e=>this.varMapByName.get(e.name)===e,e=>this.boolVarMapByName.get(e.name)===e,this)}catch(e){throw n===void 0&&(this.logicalConstrCounter=r),e}A(e,this,this.batchDepth>0?this.batchUndoActions:void 0);let a=Object.freeze({kind:`logical`,name:i,expr:e,dual:null,slack:null});return this._logicalConstraints.push(a),this.logicalConstrMapByName.set(i,a),this.allConstrsMap.set(i,a),this.recordModelMutation(),e}let n=typeof e==`string`?Ve(e,e=>this.varMapByName.get(e),t):e;if(typeof n!=`object`||!n||!(`sense`in n)||!(`lhs`in n)||!(`rhs`in n))throw Error("Invalid constraint passed to m.constraint(...): expected a linear Constraint (e.g. expr`${x} <= 10` or x.le(10)), a propositional BoolVar/BoolExpr (created with m.bool()), or an array of constraints.");n.ownerModel&&n.ownerModel!==this&&(ce(n,this.name,e=>this.varMapByName.get(e.name)===e,n.name),ne(n,this));let r=typeof t==`string`&&t.trim().length>0?t.trim():n.hasExplicitName?n.name.trim():void 0;if(r!==void 0){if(this.hasConstraintName(r))throw Error(`Constraint with name '${r}' already exists in model`);if(this.hasBoolVarName(r))throw Error(`Constraint name '${r}' conflicts with an existing Boolean variable in model`)}let i=this.constrPrefixCounters.get(`c`),a=r??this.getNextConstrName(`c`),o;try{ce(n,this.name,e=>this.varMapByName.get(e.name)===e,a),o=ne(n,this)}catch(e){throw r===void 0&&(i===void 0?this.constrPrefixCounters.delete(`c`):this.constrPrefixCounters.set(`c`,i)),e}let c=n.name,l=n.hasExplicitName,u=n.ownerModel,d=o;return this.batchUndoActions.push(()=>{n.ownerModel=u,n._assignModelName(c,l),ie(n,this,d)}),this.batchDepth===0&&(this.batchUndoActions=[]),n._assignModelName(a,!0),n.ownerModel=this,this._constraints.push(n),this.constrMapByName.set(n.name,n),this.allConstrsMap.set(n.name,n),this.recordModelMutation(),n}indicator(e,t,n={}){if(e instanceof s)throw Error("Invalid binary variable passed to indicator(): received a propositional BoolVar/BoolExpr, but m.indicator() requires a 0-1 numeric binary Var created with m.binary(). For general boolean logic with m.bool(), use m.constraint(implies(flag, expr`${x} <= 10`)) with the Z3 solver.");if(!(e instanceof V))throw Error(`Invalid binary variable passed to indicator(). Expected a 0-1 binary Var instance created with m.binary() (or use implies(flag, ...) with m.bool() and the Z3 solver for general boolean logic).`);if(!(e.type===`Binary`||e.type===`Integer`&&e.lb===0&&e.ub===1))throw Error(`Invalid variable "${e.name}" passed to indicator(): variable has type "${e.type}" with bounds [${e.lb}, ${e.ub}]. Indicator activation variable must be a Binary variable created with m.binary() (or Integer variable with bounds [0, 1]).`);if(t instanceof w||typeof t==`object`&&t&&`quadTerms`in t)throw Error("Quadratic expressions or constraints are not supported in indicator constraints (only linear Constraints with <=, >=, or == such as expr`${x} <= 10` are allowed).");if(typeof t!=`object`||!t||!(`sense`in t)||!(`lhs`in t)||!(`rhs`in t))throw Error("Invalid constraint expression passed to indicator(). Expression must include a comparison operator (<=, >=, ==), e.g. m.indicator(b, expr`${x} <= 10`). For general boolean logic (such as BoolVar or implies/and/or/not), use m.constraint(implies(flag, ...)) with the Z3 solver.");let r=t;if(r.sense===`!=`)throw Error(`Constraint "${r.name}" uses discrete "!=", which is not supported in m.indicator(). Use m.constraint(implies(${e.name}.eq(1), ...)) instead.`);if(r.lhs.hasNonlinearTerms())throw Error(`Constraint "${r.name}" contains nonlinear terms (max/min/abs/at), which are not supported in m.indicator().`);let i=n.activeValue===void 0?1:n.activeValue;if(i!==0&&i!==1)throw Error(`Invalid activeValue: ${i}. Indicator activeValue must be 0 or 1.`);if(this.varMapByName.get(e.name)!==e)throw Error(`Variable "${e.name}" passed to indicator() does not belong to model "${this.name}". All variables must belong to the model by object identity.`);let a=typeof n.name==`string`&&n.name.trim().length>0?n.name.trim():void 0,o=this.constrPrefixCounters.get(`c`),{lhs:c,sense:l,rhs:u}=r,d,f,p;if(a!==void 0)d=a,f=l===`==`?`${d}_le`:d,p=l===`==`?`${d}_ge`:d;else if(r.hasExplicitName)d=`ind_${e.name}_${r.name.trim()}`,f=l===`==`?`${d}_le`:d,p=l===`==`?`${d}_ge`:d;else do{let t=this.getNextConstrName(`c`);d=`ind_${e.name}_${t}`,f=l===`==`?`${d}_le`:d,p=l===`==`?`${d}_ge`:d}while((l===`<=`||l===`==`)&&(this.hasConstraintName(f)||this.hasBoolVarName(f))||(l===`>=`||l===`==`)&&(this.hasConstraintName(p)||this.hasBoolVarName(p)));let m=[];try{if((l===`<=`||l===`==`)&&(this.hasConstraintName(f)||this.hasBoolVarName(f)))throw Error(this.hasBoolVarName(f)?`Constraint name '${f}' conflicts with an existing Boolean variable in model`:`Constraint with name '${f}' already exists in model`);if((l===`>=`||l===`==`)&&(this.hasConstraintName(p)||this.hasBoolVarName(p)))throw Error(this.hasBoolVarName(p)?`Constraint name '${p}' conflicts with an existing Boolean variable in model`:`Constraint with name '${p}' already exists in model`);n.M!==void 0&&Jn(n.M,d);let t=e=>this.varMapByName.get(e.name)===e;for(let[e]of c.terms)if(!t(e))throw Error(`Variable "${e.name}" in constraint "${d}" does not belong to model "${this.name}". All variables must belong to the model by object identity.`);if(l===`<=`||l===`==`){let t=n.M===void 0?Xn(c,u,f):n.M,r=Qn(e,c,`<=`,u,i,t,f),a=new F(r.lhs,`<=`,r.rhs,f);n.M===void 0&&a._setIndicatorOrigin({binVar:e,activeValue:i,targetLhs:c.clone(),targetSense:`<=`,targetRhs:u,derivedM:t}),m.push([a,f])}if(l===`>=`||l===`==`){let t=n.M===void 0?Zn(c,u,p):n.M,r=Qn(e,c,`>=`,u,i,t,p),a=new F(r.lhs,`>=`,r.rhs,p);n.M===void 0&&a._setIndicatorOrigin({binVar:e,activeValue:i,targetLhs:c.clone(),targetSense:`>=`,targetRhs:u,derivedM:t}),m.push([a,p])}for(let[e,n]of m)ce(e,this.name,t,n)}catch(e){throw o===void 0?this.constrPrefixCounters.delete(`c`):this.constrPrefixCounters.set(`c`,o),e}return this.runTransactionalBatch(()=>m.map(([e,t])=>this.addConstraint(e,t)))}toLpString(){if(this.validateIntegrityInternal(),pr(this._objectiveExpr,this._constraints)){let e=nr(this._variables,[],this._constraints,[],{expr:this._objectiveExpr,sense:this.sense}),{lpString:t}=Ye({name:this.name,sense:this.sense,objective:e.objective??this._objectiveExpr,constraints:e.constraints,variables:e.variables});return t}let{lpString:e}=Ye({name:this.name,sense:this.sense,objective:this._objectiveExpr.clone(),constraints:this._constraints,variables:this._variables});return e}validateIntegrityInternal(){ue({model:this,name:this.name,variables:this._variables,boolVars:this._boolVars,constraints:this._constraints,logicalConstraints:this._logicalConstraints,objectiveExpr:this._objectiveExpr,getVarByName:e=>this.varMapByName.get(e),getBoolVarByName:e=>this.boolVarMapByName.get(e),getConstraintByName:e=>this.constrMapByName.get(e),getLogicalConstraintByName:e=>this.logicalConstrMapByName.get(e)})}ensureExecutionValid(e,t,n){if(this.modelRevision!==e)throw this.activeOperationId===t&&this.clearSolutionFields(),Error(`Model "${this.name}" was modified while ${n}() was in progress; stale solver result was discarded.`);if(this.activeOperationId!==t)throw Error(`Stale ${n}() result discarded because a newer solve or check operation was started on model "${this.name}".`)}wrapSolveOptions(e,t,n){let r=e.onProgress;return r?{...e,onProgress:e=>{this.activeOperationId===n&&this.modelRevision===t&&r(e)}}:e}hasPrimalFromResult(e){if(typeof e.hasPrimalSolution==`boolean`)return e.hasPrimalSolution;let t=e.status,n=e.terminationStatus??t,r=e.values||{},i=e.boolValues||{};return t!==`Infeasible`&&t!==`Unsat`&&t!==`Unbounded`&&t!==`Error`&&t!==`NotSolved`&&n!==`Infeasible`&&n!==`Unsat`&&n!==`Unbounded`&&n!==`InfeasibleOrUnbounded`&&n!==`Error`&&n!==`NotSolved`&&(t===`Optimal`||t===`Feasible`||t===`Sat`||n===`Optimal`||n===`Feasible`||n===`Sat`||typeof e.objectiveValue==`number`&&Number.isFinite(e.objectiveValue)||Object.values(r).some(e=>typeof e==`number`&&Number.isFinite(e)||typeof e==`boolean`)||Object.values(i).some(e=>typeof e==`boolean`))}normalizePrimalValue(e,t,n,r){return(r.relax??n.options?.relax)!==!0&&(e.type===`Integer`||e.type===`Binary`)&&Math.abs(t-Math.round(t))<=1e-5?Math.round(t)+0:t}resolveSolverAndOptions(e,t){if(e&&typeof e==`object`&&`solve`in e&&typeof e.solve==`function`){let{solver:n,...r}=t||{};return{activeSolver:e,activeOptions:r}}if(typeof e==`function`){let{solver:n,...r}=t||{};return{activeSolver:new e(r),activeOptions:r}}if(typeof e==`string`){let{solver:n,...r}=t||{};return{activeSolver:nt(e,r),activeOptions:r}}let{solver:n,...r}=e||{};return n?{activeSolver:nt(n,r),activeOptions:r}:{activeSolver:this.solver||nt(),activeOptions:r}}async relax(e,t){let n=typeof e==`object`&&!!e&&!(`solve`in e),r=n?{...e,relax:!0}:{...t||{},relax:!0},i=n?void 0:e;return i?this.solve(i,r):this.solve(r)}async solve(e,t){let n=++this.activeOperationId,r=this.modelRevision;this.clearSolutionFields(),this.validateIntegrityInternal();let{activeSolver:i,activeOptions:a}=this.resolveSolverAndOptions(e,t);if(this._objectiveExpr instanceof w&&this._objectiveExpr.quadTerms.size>0&&i.capabilities?.supportsQP===!1)throw Error(`Solver "${i.name}" does not support quadratic objectives (QP). Please use a QP-capable solver such as HiGHS or Clarabel.`);let o,s=null;if(i.capabilities?.supportsLogicalConstraints!==!0&&i.capabilities?.supportsSMT!==!0&&(this._logicalConstraints.length>0||this._boolVars.length>0||pr(this._objectiveExpr,this._constraints))?(s=nr(this._variables,this._boolVars,this._constraints,this._logicalConstraints,{expr:this._objectiveExpr,sense:this.sense}),o={name:this.name,sense:this.sense,objective:s.objective??this._objectiveExpr,constraints:s.constraints,variables:s.variables,logicalConstraints:[],boolVars:[]}):o={name:this.name,sense:this.sense,objective:this._objectiveExpr,constraints:this._constraints,variables:this._variables,logicalConstraints:this._logicalConstraints,boolVars:this._boolVars},this._variables.some(e=>e.initialValue!==void 0)&&i.capabilities?.supportsWarmStart!==!0)throw Error(`Solver "${i.name}" does not support primal initial values (initialValue). Please use a solver with warm-start support such as HiGHS or Pumpkin.`);let c=this.wrapSolveOptions(a,r,n),l;try{l=await i.solve(o,c)}catch(e){throw this.activeOperationId===n&&this.clearSolutionFields(),e}this.ensureExecutionValid(r,n,`solve`),this.runTime=l.runTime??0,this.status=l.status,this.terminationStatus=l.terminationStatus??l.status;let u=this.hasPrimalFromResult(l);this.hasPrimalSolution=u,this.objectiveValue=u&&typeof l.objectiveValue==`number`&&Number.isFinite(l.objectiveValue)?l.objectiveValue:null,this.objectiveBound=typeof l.objectiveBound==`number`&&Number.isFinite(l.objectiveBound)?l.objectiveBound:void 0;let d=typeof l.relativeGap==`number`&&Number.isFinite(l.relativeGap)?l.relativeGap:void 0;this.relativeGap=d,this.absoluteGap=typeof l.absoluteGap==`number`&&Number.isFinite(l.absoluteGap)?l.absoluteGap:this.objectiveValue!==null&&this.objectiveBound!==void 0?Math.abs(this.objectiveValue-this.objectiveBound):void 0;let f=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})},p={},m={},h={},g={};if(this._values.clear(),u&&l.values){for(let[e,t]of Object.entries(l.values))if(typeof t==`number`&&Number.isFinite(t)){let n=this.varMapByName.get(e),r=this.boolVarMapByName.get(e);if(n){let e=this.normalizePrimalValue(n,t,i,a);n.value=e,f(p,n.name,e),this._values.set(n.name,e)}r&&(r.value=!!t,this._values.set(r.name,t)),!n&&!r&&!s&&this._values.set(e,t)}else if(typeof t==`boolean`){let n=t,r=this.boolVarMapByName.get(e);r?(r.value=n,f(p,r.name,+!!n),this._values.set(r.name,n)):this._values.set(e,n)}if(s)for(let e of this._boolVars){let t=s.boolVarToBinary.get(e);if(t&&l.values){let n=l.values[t.name];if(typeof n==`number`&&Number.isFinite(n)){let t=Math.round(n)===1;e.value=t,f(p,e.name,+!!t),this._values.set(e.name,t)}}}}if(u&&l.boolValues)for(let[e,t]of Object.entries(l.boolValues)){if(typeof t!=`boolean`)continue;let n=this.boolVarMapByName.get(e);n?(n.value=t,this._values.has(n.name)||this._values.set(n.name,t)):this._values.has(e)||this._values.set(e,t)}if(u&&l.reducedCosts)for(let[e,t]of Object.entries(l.reducedCosts)){if(typeof t!=`number`||!Number.isFinite(t))continue;let n=this.varMapByName.get(e);n&&(n.reducedCost=t,f(h,n.name,t))}if(l.duals)for(let[e,t]of Object.entries(l.duals)){if(typeof t!=`number`||!Number.isFinite(t))continue;let n=this.constrMapByName.get(e);n&&(n.dual=t,f(m,n.name,t))}if(l.slacks)for(let[e,t]of Object.entries(l.slacks)){if(typeof t!=`number`||!Number.isFinite(t))continue;let n=this.constrMapByName.get(e);n&&(n.slack=t,f(g,n.name,t))}return this.solution={status:this.status,terminationStatus:this.terminationStatus,hasPrimalSolution:this.hasPrimalSolution,objectiveValue:this.objectiveValue,...this.objectiveBound===void 0?{}:{objectiveBound:this.objectiveBound},...this.relativeGap===void 0?{}:{relativeGap:this.relativeGap},...this.absoluteGap===void 0?{}:{absoluteGap:this.absoluteGap},values:p,duals:m,reducedCosts:h,slacks:g,runTime:this.runTime,raw:l.raw},this.hasSolutionState=!0,this.status}async check(e,t){let n=++this.activeOperationId,r=this.modelRevision;this.clearSolutionFields(),this.validateIntegrityInternal();let{activeSolver:i,activeOptions:a}=this.resolveSolverAndOptions(e,t);if(this._variables.some(e=>e.initialValue!==void 0)&&i.capabilities?.supportsWarmStart!==!0)throw Error(`Solver "${i.name}" does not support primal initial values (initialValue). Please use a solver with warm-start support such as HiGHS or Pumpkin.`);let o=this.wrapSolveOptions(a,r,n),s=(e,t,n)=>{Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0})},c={name:this.name,variables:this._variables,boolVars:this._boolVars,constraints:this._constraints,logicalConstraints:this._logicalConstraints};if(typeof i.check==`function`){let e;try{e=await i.check(c,o)}catch(e){throw this.activeOperationId===n&&this.clearSolutionFields(),e}this.ensureExecutionValid(r,n,`check`),this.status=e.status,this.terminationStatus=a.signal?.aborted?`Interrupted`:e.status,this.hasPrimalSolution=e.status===`Sat`,this.runTime=e.runTime??0,this.unsatCore=e.unsatCore===void 0?void 0:Object.freeze([...e.unsatCore]),this.conflicts=e.conflicts===void 0?this.unsatCore:Object.freeze([...e.conflicts]);let t={};if(e.values&&e.status===`Sat`){for(let[n,r]of Object.entries(e.values))if(typeof r==`number`){if(!Number.isFinite(r))continue;let e=this.varMapByName.get(n),o=this.boolVarMapByName.get(n);if(e){let n=this.normalizePrimalValue(e,r,i,a);e.value=n,this._values.set(e.name,n),s(t,e.name,n)}o&&(o.value=!!r,this._values.set(o.name,o.value),s(t,o.name,o.value)),!e&&!o&&(this._values.set(n,r),s(t,n,r))}else if(typeof r==`boolean`){let e=this.boolVarMapByName.get(n);e?(e.value=r,this._values.set(e.name,r),s(t,e.name,r)):(this._values.set(n,r),s(t,n,r))}}return this.hasSolutionState=!0,{status:e.status,values:t,unsatCore:this.unsatCore,conflicts:this.conflicts,runTime:this.runTime}}let l=this._logicalConstraints.length>0||this._boolVars.length>0||mr(this._constraints)?nr(this._variables,this._boolVars,this._constraints,this._logicalConstraints):{variables:[...this._variables],constraints:[...this._constraints],boolVarToBinary:new Map,constraintToOriginalName:new Map(this._constraints.map(e=>[e,e.name]))},u=[],d=[],f=[],p=new Map,m=0;for(let e of l.constraints){let t=l.constraintToOriginalName.get(e)??e.name,{lhs:n,sense:r,rhs:i}=e;if(r===`<=`){let r=new V({name:`__slack_${++m}`,type:`Continuous`,lb:0,ub:1/0});d.push(r),f.push([r,1]),p.set(r,t);let a=n.clone().add(new R(new Map([[r,-1]]),0));u.push(new F(a,`<=`,i,`${e.name}_slack`))}else if(r===`>=`){let r=new V({name:`__slack_${++m}`,type:`Continuous`,lb:0,ub:1/0});d.push(r),f.push([r,1]),p.set(r,t);let a=n.clone().add(new R(new Map([[r,1]]),0));u.push(new F(a,`>=`,i,`${e.name}_slack`))}else{let r=new V({name:`__slack_${++m}_p`,type:`Continuous`,lb:0,ub:1/0}),a=new V({name:`__slack_${++m}_n`,type:`Continuous`,lb:0,ub:1/0});d.push(r,a),f.push([r,1],[a,1]),p.set(r,t),p.set(a,t);let o=n.clone().add(new R(new Map([[r,-1],[a,1]]),0));u.push(new F(o,`==`,i,`${e.name}_slack`))}}let h={name:`${this.name}_elastic_check`,sense:`Minimize`,objective:new R(new Map(f),0),constraints:u,variables:[...l.variables,...d]},g;try{g=await i.solve(h,o)}catch(e){throw this.activeOperationId===n&&this.clearSolutionFields(),e}this.ensureExecutionValid(r,n,`check`),this.runTime=g.runTime??0;let _=g.status,v=g.terminationStatus??_,y=this.hasPrimalFromResult(g),b=typeof g.objectiveValue==`number`&&Number.isFinite(g.objectiveValue)?g.objectiveValue:1/0,x=(_===`Optimal`||_===`Feasible`||y)&&b<=1e-5,S=typeof g.objectiveBound==`number`&&Number.isFinite(g.objectiveBound)&&g.objectiveBound>1e-5,C=!x&&(_===`Infeasible`||_===`Optimal`&&b>1e-5||S),w=x?`Sat`:C?`Unsat`:`Unknown`;this.status=w,this.terminationStatus=a.signal?.aborted||v===`Interrupted`?`Interrupted`:v===`Optimal`||v===`Feasible`||v===`Infeasible`?w:v,this.hasPrimalSolution=x,this.objectiveValue=null,this.objectiveBound=void 0,this.relativeGap=void 0,this.absoluteGap=void 0,this.solution=null,this._values.clear();let T={};if(x&&g.values){for(let e of this._variables){let t=g.values[e.name];if(typeof t==`number`&&Number.isFinite(t)){let n=this.normalizePrimalValue(e,t,i,a);e.value=n,this._values.set(e.name,n),s(T,e.name,n)}}for(let e of this._boolVars){let t=l.boolVarToBinary.get(e),n=t?g.values[t.name]:g.values[e.name];if(typeof n==`number`&&Number.isFinite(n)){let t=Math.round(n)===1;e.value=t,this._values.set(e.name,t),s(T,e.name,t)}}}let E=new Set;if(C&&g.values)for(let[e,t]of p.entries()){let n=g.values[e.name];typeof n==`number`&&n>1e-5&&E.add(t)}return this.conflicts=C?Object.freeze(Array.from(E)):void 0,this.unsatCore=void 0,this.hasSolutionState=!0,{status:w,values:T,conflicts:this.conflicts,unsatCore:this.unsatCore,runTime:this.runTime}}verify(e={}){return qn(this,e)}link(e){if(e instanceof w||typeof e==`object`&&e&&`quadTerms`in e)throw Error(`Linking constraint cannot be a quadratic expression.`);if(!(e instanceof F)&&(typeof e!=`object`||!e||!(`sense`in e)||!(`lhs`in e)||!(`rhs`in e)))throw Error("Linking constraint must contain a comparison operator (<=, >=, ==). Use expr`... <= ...` or .le(), .ge(), .eq().");this._linkingConstraints||=[];let t=e;return this._linkingConstraints.push(t),t}get linkingConstraints(){return this._linkingConstraints??[]}async solveBenders(e){let t=await fr({master:this,...e});return this.decomposition=t,t}async solveColumnGeneration(e){let t=await ar({master:this,...e});return this.decomposition=t,t}};return e.BoolExpr=s,e.BoolOp=l,e.BoolVar=c,e.Constraint=F,e.GlobalConstraint=h,e.LinExpr=R,e.MockSolver=it,e.Model=br,e.QuadExpr=w,e.Var=V,e.abs=ve,e.allowed=S,e.and=u,e.at=B,e.buildIndicatorLinearization=Qn,e.buildLpSymbolMaps=Je,e.cumulative=x,e.deriveBigMForGe=Zn,e.deriveBigMForLe=Xn,e.disjoint=b,e.distinct=v,e.dot=_e,e.expr=Ge,e.generateLpString=Ye,e.getSolver=nt,e.implies=p,e.isLpExportResult=Ke,e.linearizeModelForMip=nr,e.listAvailableSolvers=rt,e.max=xe,e.maximize=sr,e.min=Se,e.minimize=cr,e.normalizeSense=i,e.not=f,e.or=d,e.parseConstraint=Ve,e.parseExpr=ze,e.registerSolver=et,e.sanitizeIdentifier=qe,e.setDefaultSolver=tt,e.solveBenders=fr,e.solveColumnGeneration=ar,e.sum=z,e.validateUserBigM=Jn,e.xor=m,e})({});